]> wimlib.net Git - wimlib/blob - src/lzx-compress.c
effe656bf20fcd14f65c780e13b7fc78c1d31483
[wimlib] / src / lzx-compress.c
1 /*
2  * lzx-compress.c
3  *
4  * LZX compression routines, originally based on code written by Matthew T.
5  * Russotto (liblzxcomp), but heavily modified.
6  */
7
8 /*
9  * Copyright (C) 2002 Matthew T. Russotto
10  * Copyright (C) 2012 Eric Biggers
11  *
12  * This file is part of wimlib, a library for working with WIM files.
13  *
14  * wimlib is free software; you can redistribute it and/or modify it under the
15  * terms of the GNU General Public License as published by the Free
16  * Software Foundation; either version 3 of the License, or (at your option)
17  * any later version.
18  *
19  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
20  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
21  * A PARTICULAR PURPOSE. See the GNU General Public License for more
22  * details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with wimlib; if not, see http://www.gnu.org/licenses/.
26  */
27
28
29 /*
30  * This file provides lzx_compress(), a function to compress an in-memory buffer
31  * of data using LZX compression, as used in the WIM file format.
32  *
33  * Please see the comments in lzx-decompress.c for more information about this
34  * compression format.
35  *
36  * One thing to keep in mind is that there is no sliding window, since the
37  * window is always the entirety of a WIM chunk, which is at most WIM_CHUNK_SIZE
38  * ( = 32768) bytes.
39  *
40  * The basic compression algorithm used here should be familiar if you are
41  * familiar with Huffman trees and with other LZ77 and Huffman-based formats
42  * such as DEFLATE.  Otherwise it can be quite tricky to understand.  Basically
43  * it is the following:
44  *
45  * - Preprocess the input data (LZX-specific)
46  * - Go through the input data and determine matches.  This part is based on
47  *       code from zlib, and a hash table of 3-character strings is used to
48  *       accelerate the process of finding matches.
49  * - Build the Huffman trees based on the frequencies of symbols determined
50  *       while recording matches.
51  * - Output the block header, including the Huffman trees; then output the
52  *       compressed stream of matches and literal characters.
53  *
54  * It is possible for a WIM chunk to include multiple LZX blocks, since for some
55  * input data this will produce a better compression ratio (especially since
56  * each block can include new Huffman codes).  However, producing multiple LZX
57  * blocks from one input chunk is not yet implemented.
58  */
59
60 #include "lzx.h"
61 #include "compress.h"
62 #include <stdlib.h>
63 #include <string.h>
64
65
66 /* Structure to contain the Huffman codes for the main, length, and aligned
67  * offset trees. */
68 struct lzx_codes {
69         u16 main_codewords[LZX_MAINTREE_NUM_SYMBOLS];
70         u8  main_lens[LZX_MAINTREE_NUM_SYMBOLS];
71
72         u16 len_codewords[LZX_LENTREE_NUM_SYMBOLS];
73         u8  len_lens[LZX_LENTREE_NUM_SYMBOLS];
74
75         u16 aligned_codewords[LZX_ALIGNEDTREE_NUM_SYMBOLS];
76         u8  aligned_lens[LZX_ALIGNEDTREE_NUM_SYMBOLS];
77 };
78
79 struct lzx_freq_tables {
80         freq_t main_freq_table[LZX_MAINTREE_NUM_SYMBOLS];
81         freq_t len_freq_table[LZX_LENTREE_NUM_SYMBOLS];
82         freq_t aligned_freq_table[LZX_ALIGNEDTREE_NUM_SYMBOLS];
83 };
84
85 /* Returns the LZX position slot that corresponds to a given formatted offset.
86  *
87  * Logically, this returns the smallest i such that
88  * formatted_offset >= lzx_position_base[i].
89  *
90  * The actual implementation below takes advantage of the regularity of the
91  * numbers in the lzx_position_base array to calculate the slot directly from
92  * the formatted offset without actually looking at the array.
93  */
94 static inline unsigned lzx_get_position_slot(unsigned formatted_offset)
95 {
96 #if 0
97         /*
98          * Slots 36-49 (formatted_offset >= 262144) can be found by
99          * (formatted_offset/131072) + 34 == (formatted_offset >> 17) + 34;
100          * however, this check for formatted_offset >= 262144 is commented out
101          * because WIM chunks cannot be that large.
102          */
103         if (formatted_offset >= 262144) {
104                 return (formatted_offset >> 17) + 34;
105         } else
106 #endif
107         {
108                 /* Note: this part here only works if:
109                  *
110                  *    2 <= formatted_offset < 655360
111                  *
112                  * It is < 655360 because the frequency of the position bases
113                  * increases starting at the 655360 entry, and it is >= 2
114                  * because the below calculation fails if the most significant
115                  * bit is lower than the 2's place. */
116                 wimlib_assert(formatted_offset >= 2 && formatted_offset < 655360);
117                 unsigned mssb_idx = bsr32(formatted_offset);
118                 return (mssb_idx << 1) |
119                         ((formatted_offset >> (mssb_idx - 1)) & 1);
120         }
121 }
122
123 static u32 lzx_record_literal(u8 literal, void *__main_freq_tab)
124 {
125         freq_t *main_freq_tab = __main_freq_tab;
126         main_freq_tab[literal]++;
127         return literal;
128 }
129
130 /* Constructs a match from an offset and a length, and updates the LRU queue and
131  * the frequency of symbols in the main, length, and aligned offset alphabets.
132  * The return value is a 32-bit number that provides the match in an
133  * intermediate representation documented below. */
134 static u32 lzx_record_match(unsigned match_offset, unsigned match_len,
135                             void *__freq_tabs, void *__queue)
136 {
137         struct lzx_freq_tables *freq_tabs = __freq_tabs;
138         struct lru_queue *queue = __queue;
139         unsigned formatted_offset;
140         unsigned position_slot;
141         unsigned position_footer = 0;
142         u32 match;
143         u32 len_header;
144         u32 len_pos_header;
145         unsigned len_footer;
146         unsigned adjusted_match_len;
147
148         wimlib_assert(match_len >= LZX_MIN_MATCH && match_len <= LZX_MAX_MATCH);
149         wimlib_assert(match_offset != 0);
150
151         /* If possible, encode this offset as a repeated offset. */
152         if (match_offset == queue->R0) {
153                 formatted_offset = 0;
154                 position_slot    = 0;
155         } else if (match_offset == queue->R1) {
156                 swap(queue->R0, queue->R1);
157                 formatted_offset = 1;
158                 position_slot    = 1;
159         } else if (match_offset == queue->R2) {
160                 swap(queue->R0, queue->R2);
161                 formatted_offset = 2;
162                 position_slot    = 2;
163         } else {
164                 /* Not a repeated offset. */
165
166                 /* offsets of 0, 1, and 2 are reserved for the repeated offset
167                  * codes, so non-repeated offsets must be encoded as 3+.  The
168                  * minimum offset is 1, so encode the offsets offset by 2. */
169                 formatted_offset = match_offset + LZX_MIN_MATCH;
170
171                 queue->R2 = queue->R1;
172                 queue->R1 = queue->R0;
173                 queue->R0 = match_offset;
174
175                 /* The (now-formatted) offset will actually be encoded as a
176                  * small position slot number that maps to a certain hard-coded
177                  * offset (position base), followed by a number of extra bits---
178                  * the position footer--- that are added to the position base to
179                  * get the original formatted offset. */
180
181                 position_slot = lzx_get_position_slot(formatted_offset);
182                 position_footer = formatted_offset &
183                                   ((1 << lzx_get_num_extra_bits(position_slot)) - 1);
184         }
185
186         adjusted_match_len = match_len - LZX_MIN_MATCH;
187
188         /* Pack the position slot, position footer, and match length into an
189          * intermediate representation.
190          *
191          * bits    description
192          * ----    -----------------------------------------------------------
193          *
194          * 31      1 if a match, 0 if a literal.
195          *
196          * 30-25   position slot.  This can be at most 50, so it will fit in 6
197          *         bits.
198          *
199          * 8-24    position footer.  This is the offset of the real formatted
200          *         offset from the position base.  This can be at most 17 bits
201          *         (since lzx_extra_bits[LZX_NUM_POSITION_SLOTS - 1] is 17).
202          *
203          * 0-7     length of match, offset by 2.  This can be at most
204          *         (LZX_MAX_MATCH - 2) == 255, so it will fit in 8 bits.  */
205         match = 0x80000000 |
206                 (position_slot << 25) |
207                 (position_footer << 8) |
208                 (adjusted_match_len);
209
210         /* The match length must be at least 2, so let the adjusted match length
211          * be the match length minus 2.
212          *
213          * If it is less than 7, the adjusted match length is encoded as a 3-bit
214          * number offset by 2.  Otherwise, the 3-bit length header is all 1's
215          * and the actual adjusted length is given as a symbol encoded with the
216          * length tree, offset by 7.
217          */
218         if (adjusted_match_len < LZX_NUM_PRIMARY_LENS) {
219                 len_header = adjusted_match_len;
220         } else {
221                 len_header = LZX_NUM_PRIMARY_LENS;
222                 len_footer = adjusted_match_len - LZX_NUM_PRIMARY_LENS;
223                 freq_tabs->len_freq_table[len_footer]++;
224         }
225         len_pos_header = (position_slot << 3) | len_header;
226
227         wimlib_assert(len_pos_header < LZX_MAINTREE_NUM_SYMBOLS - LZX_NUM_CHARS);
228
229         freq_tabs->main_freq_table[len_pos_header + LZX_NUM_CHARS]++;
230
231         /* Equivalent to:
232          * if (lzx_extra_bits[position_slot] >= 3) */
233         if (position_slot >= 8)
234                 freq_tabs->aligned_freq_table[position_footer & 7]++;
235
236         return match;
237 }
238
239 /*
240  * Writes a compressed literal match to the output.
241  *
242  * @out:         The output bitstream.
243  * @block_type:  The type of the block (LZX_BLOCKTYPE_ALIGNED or LZX_BLOCKTYPE_VERBATIM)
244  * @match:       The match, encoded as a 32-bit number.
245  * @codes:      Pointer to a structure that contains the codewords for the
246  *                      main, length, and aligned offset Huffman codes.
247  */
248 static int lzx_write_match(struct output_bitstream *out, int block_type,
249                            u32 match, const struct lzx_codes *codes)
250 {
251         /* low 8 bits are the match length minus 2 */
252         unsigned match_len_minus_2 = match & 0xff;
253         /* Next 17 bits are the position footer */
254         unsigned position_footer = (match >> 8) & 0x1ffff;      /* 17 bits */
255         /* Next 6 bits are the position slot. */
256         unsigned position_slot = (match >> 25) & 0x3f;  /* 6 bits */
257         unsigned len_header;
258         unsigned len_footer;
259         unsigned len_pos_header;
260         unsigned main_symbol;
261         unsigned num_extra_bits;
262         unsigned verbatim_bits;
263         unsigned aligned_bits;
264         int ret;
265
266         /* If the match length is less than MIN_MATCH (= 2) +
267          * NUM_PRIMARY_LENS (= 7), the length header contains
268          * the match length minus MIN_MATCH, and there is no
269          * length footer.
270          *
271          * Otherwise, the length header contains
272          * NUM_PRIMARY_LENS, and the length footer contains
273          * the match length minus NUM_PRIMARY_LENS minus
274          * MIN_MATCH. */
275         if (match_len_minus_2 < LZX_NUM_PRIMARY_LENS) {
276                 len_header = match_len_minus_2;
277                 /* No length footer-- mark it with a special
278                  * value. */
279                 len_footer = (unsigned)(-1);
280         } else {
281                 len_header = LZX_NUM_PRIMARY_LENS;
282                 len_footer = match_len_minus_2 - LZX_NUM_PRIMARY_LENS;
283         }
284
285         /* Combine the position slot with the length header into
286          * a single symbol that will be encoded with the main
287          * tree. */
288         len_pos_header = (position_slot << 3) | len_header;
289
290         /* The actual main symbol is offset by LZX_NUM_CHARS because
291          * values under LZX_NUM_CHARS are used to indicate a literal
292          * byte rather than a match. */
293         main_symbol = len_pos_header + LZX_NUM_CHARS;
294
295         /* Output main symbol. */
296         ret = bitstream_put_bits(out, codes->main_codewords[main_symbol],
297                                  codes->main_lens[main_symbol]);
298         if (ret != 0)
299                 return ret;
300
301         /* If there is a length footer, output it using the
302          * length Huffman code. */
303         if (len_footer != (unsigned)(-1)) {
304                 ret = bitstream_put_bits(out, codes->len_codewords[len_footer],
305                                          codes->len_lens[len_footer]);
306                 if (ret != 0)
307                         return ret;
308         }
309
310         wimlib_assert(position_slot < LZX_NUM_POSITION_SLOTS);
311
312         num_extra_bits = lzx_get_num_extra_bits(position_slot);
313
314         /* For aligned offset blocks with at least 3 extra bits, output the
315          * verbatim bits literally, then the aligned bits encoded using the
316          * aligned offset tree.  Otherwise, only the verbatim bits need to be
317          * output. */
318         if ((block_type == LZX_BLOCKTYPE_ALIGNED) && (num_extra_bits >= 3)) {
319
320                 verbatim_bits = position_footer >> 3;
321                 ret = bitstream_put_bits(out, verbatim_bits,
322                                          num_extra_bits - 3);
323                 if (ret != 0)
324                         return ret;
325
326                 aligned_bits = (position_footer & 7);
327                 ret = bitstream_put_bits(out,
328                                          codes->aligned_codewords[aligned_bits],
329                                          codes->aligned_lens[aligned_bits]);
330                 if (ret != 0)
331                         return ret;
332         } else {
333                 /* verbatim bits is the same as the position
334                  * footer, in this case. */
335                 ret = bitstream_put_bits(out, position_footer, num_extra_bits);
336                 if (ret != 0)
337                         return ret;
338         }
339         return 0;
340 }
341
342 /*
343  * Writes all compressed literals in a block, both matches and literal bytes, to
344  * the output bitstream.
345  *
346  * @out:         The output bitstream.
347  * @block_type:  The type of the block (LZX_BLOCKTYPE_ALIGNED or LZX_BLOCKTYPE_VERBATIM)
348  * @match_tab[]:   The array of matches that will be output.  It has length
349  *                      of @num_compressed_literals.
350  * @num_compressed_literals:  Number of compressed literals to be output.
351  * @codes:      Pointer to a structure that contains the codewords for the
352  *                      main, length, and aligned offset Huffman codes.
353  */
354 static int lzx_write_compressed_literals(struct output_bitstream *ostream,
355                                          int block_type,
356                                          const u32 match_tab[],
357                                          unsigned  num_compressed_literals,
358                                          const struct lzx_codes *codes)
359 {
360         unsigned i;
361         u32 match;
362         int ret;
363
364         for (i = 0; i < num_compressed_literals; i++) {
365                 match = match_tab[i];
366
367                 /* High bit of the match indicates whether the match is an
368                  * actual match (1) or a literal uncompressed byte (0) */
369                 if (match & 0x80000000) {
370                         /* match */
371                         ret = lzx_write_match(ostream, block_type, match,
372                                               codes);
373                         if (ret != 0)
374                                 return ret;
375                 } else {
376                         /* literal byte */
377                         wimlib_assert(match < LZX_NUM_CHARS);
378                         ret = bitstream_put_bits(ostream,
379                                                  codes->main_codewords[match],
380                                                  codes->main_lens[match]);
381                         if (ret != 0)
382                                 return ret;
383                 }
384         }
385         return 0;
386 }
387
388 /*
389  * Writes a compressed Huffman tree to the output, preceded by the pretree for
390  * it.
391  *
392  * The Huffman tree is represented in the output as a series of path lengths
393  * from which the canonical Huffman code can be reconstructed.  The path lengths
394  * themselves are compressed using a separate Huffman code, the pretree, which
395  * consists of LZX_PRETREE_NUM_SYMBOLS (= 20) symbols that cover all possible code
396  * lengths, plus extra codes for repeated lengths.  The path lengths of the
397  * pretree precede the path lengths of the larger code and are uncompressed,
398  * consisting of 20 entries of 4 bits each.
399  *
400  * @out:        The bitstream for the compressed output.
401  * @lens:       The code lengths for the Huffman tree, indexed by symbol.
402  * @num_symbols:        The number of symbols in the code.
403  */
404 static int lzx_write_compressed_tree(struct output_bitstream *out,
405                                      const u8 lens[], unsigned num_symbols)
406 {
407         /* Frequencies of the length symbols, including the RLE symbols (NOT the
408          * actual lengths themselves). */
409         freq_t pretree_freqs[LZX_PRETREE_NUM_SYMBOLS];
410         u8 pretree_lens[LZX_PRETREE_NUM_SYMBOLS];
411         u16 pretree_codewords[LZX_PRETREE_NUM_SYMBOLS];
412         u8 output_syms[num_symbols * 2];
413         unsigned output_syms_idx;
414         unsigned cur_run_len;
415         unsigned i;
416         unsigned len_in_run;
417         unsigned additional_bits;
418         char delta;
419         u8 pretree_sym;
420
421         ZERO_ARRAY(pretree_freqs);
422
423         /* Since the code word lengths use a form of RLE encoding, the goal here
424          * is to find each run of identical lengths when going through them in
425          * symbol order (including runs of length 1).  For each run, as many
426          * lengths are encoded using RLE as possible, and the rest are output
427          * literally.
428          *
429          * output_syms[] will be filled in with the length symbols that will be
430          * output, including RLE codes, not yet encoded using the pre-tree.
431          *
432          * cur_run_len keeps track of how many code word lengths are in the
433          * current run of identical lengths.
434          */
435         output_syms_idx = 0;
436         cur_run_len = 1;
437         for (i = 1; i <= num_symbols; i++) {
438
439                 if (i != num_symbols && lens[i] == lens[i - 1]) {
440                         /* Still in a run--- keep going. */
441                         cur_run_len++;
442                         continue;
443                 }
444
445                 /* Run ended! Check if it is a run of zeroes or a run of
446                  * nonzeroes. */
447
448                 /* The symbol that was repeated in the run--- not to be confused
449                  * with the length *of* the run (cur_run_len) */
450                 len_in_run = lens[i - 1];
451
452                 if (len_in_run == 0) {
453                         /* A run of 0's.  Encode it in as few length
454                          * codes as we can. */
455
456                         /* The magic length 18 indicates a run of 20 + n zeroes,
457                          * where n is an uncompressed literal 5-bit integer that
458                          * follows the magic length. */
459                         while (cur_run_len >= 20) {
460
461                                 additional_bits = min(cur_run_len - 20, 0x1f);
462                                 pretree_freqs[18]++;
463                                 output_syms[output_syms_idx++] = 18;
464                                 output_syms[output_syms_idx++] = additional_bits;
465                                 cur_run_len -= 20 + additional_bits;
466                         }
467
468                         /* The magic length 17 indicates a run of 4 + n zeroes,
469                          * where n is an uncompressed literal 4-bit integer that
470                          * follows the magic length. */
471                         while (cur_run_len >= 4) {
472                                 additional_bits = min(cur_run_len - 4, 0xf);
473                                 pretree_freqs[17]++;
474                                 output_syms[output_syms_idx++] = 17;
475                                 output_syms[output_syms_idx++] = additional_bits;
476                                 cur_run_len -= 4 + additional_bits;
477                         }
478
479                 } else {
480
481                         /* A run of nonzero lengths. */
482
483                         /* The magic length 19 indicates a run of 4 + n
484                          * nonzeroes, where n is a literal bit that follows the
485                          * magic length, and where the value of the lengths in
486                          * the run is given by an extra length symbol, encoded
487                          * with the pretree, that follows the literal bit.
488                          *
489                          * The extra length symbol is encoded as a difference
490                          * from the length of the codeword for the first symbol
491                          * in the run in the previous tree.
492                          * */
493                         while (cur_run_len >= 4) {
494                                 additional_bits = (cur_run_len > 4);
495                                 delta = -(char)len_in_run;
496                                 if (delta < 0)
497                                         delta += 17;
498                                 pretree_freqs[19]++;
499                                 pretree_freqs[(unsigned char)delta]++;
500                                 output_syms[output_syms_idx++] = 19;
501                                 output_syms[output_syms_idx++] = additional_bits;
502                                 output_syms[output_syms_idx++] = delta;
503                                 cur_run_len -= 4 + additional_bits;
504                         }
505                 }
506
507                 /* Any remaining lengths in the run are outputted without RLE,
508                  * as a difference from the length of that codeword in the
509                  * previous tree. */
510                 while (cur_run_len--) {
511                         delta = -(char)len_in_run;
512                         if (delta < 0)
513                                 delta += 17;
514
515                         pretree_freqs[(unsigned char)delta]++;
516                         output_syms[output_syms_idx++] = delta;
517                 }
518
519                 cur_run_len = 1;
520         }
521
522         wimlib_assert(output_syms_idx < ARRAY_LEN(output_syms));
523
524         /* Build the pretree from the frequencies of the length symbols. */
525
526         make_canonical_huffman_code(LZX_PRETREE_NUM_SYMBOLS,
527                                     LZX_MAX_CODEWORD_LEN,
528                                     pretree_freqs, pretree_lens,
529                                     pretree_codewords);
530
531         /* Write the lengths of the pretree codes to the output. */
532         for (i = 0; i < LZX_PRETREE_NUM_SYMBOLS; i++)
533                 bitstream_put_bits(out, pretree_lens[i],
534                                    LZX_PRETREE_ELEMENT_SIZE);
535
536         /* Write the length symbols, encoded with the pretree, to the output. */
537
538         i = 0;
539         while (i < output_syms_idx) {
540                 pretree_sym = output_syms[i++];
541
542                 bitstream_put_bits(out, pretree_codewords[pretree_sym],
543                                    pretree_lens[pretree_sym]);
544                 switch (pretree_sym) {
545                 case 17:
546                         bitstream_put_bits(out, output_syms[i++], 4);
547                         break;
548                 case 18:
549                         bitstream_put_bits(out, output_syms[i++], 5);
550                         break;
551                 case 19:
552                         bitstream_put_bits(out, output_syms[i++], 1);
553                         bitstream_put_bits(out,
554                                            pretree_codewords[output_syms[i]],
555                                            pretree_lens[output_syms[i]]);
556                         i++;
557                         break;
558                 default:
559                         break;
560                 }
561         }
562         return 0;
563 }
564
565 /* Builds the canonical Huffman code for the main tree, the length tree, and the
566  * aligned offset tree. */
567 static void lzx_make_huffman_codes(const struct lzx_freq_tables *freq_tabs,
568                                 struct lzx_codes *codes)
569 {
570         make_canonical_huffman_code(LZX_MAINTREE_NUM_SYMBOLS,
571                                         LZX_MAX_CODEWORD_LEN,
572                                         freq_tabs->main_freq_table,
573                                         codes->main_lens,
574                                         codes->main_codewords);
575
576         make_canonical_huffman_code(LZX_LENTREE_NUM_SYMBOLS,
577                                         LZX_MAX_CODEWORD_LEN,
578                                         freq_tabs->len_freq_table,
579                                         codes->len_lens,
580                                         codes->len_codewords);
581
582         make_canonical_huffman_code(LZX_ALIGNEDTREE_NUM_SYMBOLS, 8,
583                                         freq_tabs->aligned_freq_table,
584                                         codes->aligned_lens,
585                                         codes->aligned_codewords);
586 }
587
588 static void do_call_insn_translation(u32 *call_insn_target, int input_pos,
589                                      int32_t file_size)
590 {
591         int32_t abs_offset;
592         int32_t rel_offset;
593
594         rel_offset = le32_to_cpu(*call_insn_target);
595         if (rel_offset >= -input_pos && rel_offset < file_size) {
596                 if (rel_offset < file_size - input_pos) {
597                         /* "good translation" */
598                         abs_offset = rel_offset + input_pos;
599                 } else {
600                         /* "compensating translation" */
601                         abs_offset = rel_offset - file_size;
602                 }
603                 *call_insn_target = cpu_to_le32(abs_offset);
604         }
605 }
606
607 /* This is the reverse of undo_call_insn_preprocessing() in lzx-decompress.c.
608  * See the comment above that function for more information. */
609 static void do_call_insn_preprocessing(u8 uncompressed_data[],
610                                        int uncompressed_data_len)
611 {
612         for (int i = 0; i < uncompressed_data_len - 10; i++) {
613                 if (uncompressed_data[i] == 0xe8) {
614                         do_call_insn_translation((u32*)&uncompressed_data[i + 1],
615                                                  i,
616                                                  LZX_WIM_MAGIC_FILESIZE);
617                         i += 4;
618                 }
619         }
620 }
621
622
623 static const struct lz_params lzx_lz_params = {
624
625          /* LZX_MIN_MATCH == 2, but 2-character matches are rarely useful; the
626           * minimum match for compression is set to 3 instead. */
627         .min_match      = 3,
628
629         .max_match      = LZX_MAX_MATCH,
630         .good_match     = LZX_MAX_MATCH,
631         .nice_match     = LZX_MAX_MATCH,
632         .max_chain_len  = LZX_MAX_MATCH,
633         .max_lazy_match = LZX_MAX_MATCH,
634         .too_far        = 4096,
635 };
636
637 /*
638  * Performs LZX compression on a block of data.
639  *
640  * @__uncompressed_data:  Pointer to the data to be compressed.
641  * @uncompressed_len:     Length, in bytes, of the data to be compressed.
642  * @compressed_data:      Pointer to a location at least (@uncompressed_len - 1)
643  *                              bytes long into which the compressed data may be
644  *                              written.
645  * @compressed_len_ret:   A pointer to an unsigned int into which the length of
646  *                              the compressed data may be returned.
647  *
648  * Returns zero if compression was successfully performed.  In that case
649  * @compressed_data and @compressed_len_ret will contain the compressed data and
650  * its length.  A return value of nonzero means that compressing the data did
651  * not reduce its size, and @compressed_data will not contain the full
652  * compressed data.
653  */
654 int lzx_compress(const void *__uncompressed_data, unsigned uncompressed_len,
655                  void *compressed_data, unsigned *compressed_len_ret)
656 {
657         struct output_bitstream ostream;
658         u8 uncompressed_data[uncompressed_len + 8];
659         struct lzx_freq_tables freq_tabs;
660         struct lzx_codes codes;
661         u32 match_tab[uncompressed_len];
662         struct lru_queue queue;
663         unsigned num_matches;
664         unsigned compressed_len;
665         unsigned i;
666         int ret;
667         int block_type = LZX_BLOCKTYPE_ALIGNED;
668
669         if (uncompressed_len < 100)
670                 return 1;
671
672         memset(&freq_tabs, 0, sizeof(freq_tabs));
673         queue.R0 = 1;
674         queue.R1 = 1;
675         queue.R2 = 1;
676
677         /* The input data must be preprocessed. To avoid changing the original
678          * input, copy it to a temporary buffer. */
679         memcpy(uncompressed_data, __uncompressed_data, uncompressed_len);
680
681         /* Before doing any actual compression, do the call instruction (0xe8
682          * byte) translation on the uncompressed data. */
683         do_call_insn_preprocessing(uncompressed_data, uncompressed_len);
684
685         /* Determine the sequence of matches and literals that will be output,
686          * and in the process, keep counts of the number of times each symbol
687          * will be output, so that the Huffman trees can be made. */
688
689         num_matches = lz_analyze_block(uncompressed_data, uncompressed_len,
690                                        match_tab, lzx_record_match,
691                                        lzx_record_literal, &freq_tabs,
692                                        &queue, freq_tabs.main_freq_table,
693                                        &lzx_lz_params);
694
695         lzx_make_huffman_codes(&freq_tabs, &codes);
696
697         /* Initialize the output bitstream. */
698         init_output_bitstream(&ostream, compressed_data, uncompressed_len - 1);
699
700         /* The first three bits tell us what kind of block it is, and are one
701          * of the LZX_BLOCKTYPE_* values.  */
702         bitstream_put_bits(&ostream, block_type, 3);
703
704         /* The next bit indicates whether the block size is the default (32768),
705          * indicated by a 1 bit, or whether the block size is given by the next
706          * 16 bits, indicated by a 0 bit. */
707         if (uncompressed_len == 32768) {
708                 bitstream_put_bits(&ostream, 1, 1);
709         } else {
710                 bitstream_put_bits(&ostream, 0, 1);
711                 bitstream_put_bits(&ostream, uncompressed_len, 16);
712         }
713
714         /* Write out the aligned offset tree. Note that M$ lies and says that
715          * the aligned offset tree comes after the length tree, but that is
716          * wrong; it actually is before the main tree.  */
717         if (block_type == LZX_BLOCKTYPE_ALIGNED)
718                 for (i = 0; i < LZX_ALIGNEDTREE_NUM_SYMBOLS; i++)
719                         bitstream_put_bits(&ostream, codes.aligned_lens[i],
720                                            LZX_ALIGNEDTREE_ELEMENT_SIZE);
721
722         /* Write the pre-tree and lengths for the first LZX_NUM_CHARS symbols in the
723          * main tree. */
724         ret = lzx_write_compressed_tree(&ostream, codes.main_lens,
725                                         LZX_NUM_CHARS);
726         if (ret != 0)
727                 return ret;
728
729         /* Write the pre-tree and symbols for the rest of the main tree. */
730         ret = lzx_write_compressed_tree(&ostream, codes.main_lens +
731                                         LZX_NUM_CHARS,
732                                         LZX_MAINTREE_NUM_SYMBOLS -
733                                                 LZX_NUM_CHARS);
734         if (ret != 0)
735                 return ret;
736
737         /* Write the pre-tree and symbols for the length tree. */
738         ret = lzx_write_compressed_tree(&ostream, codes.len_lens,
739                                         LZX_LENTREE_NUM_SYMBOLS);
740         if (ret != 0)
741                 return ret;
742
743         /* Write the compressed literals. */
744         ret = lzx_write_compressed_literals(&ostream, block_type,
745                                             match_tab, num_matches, &codes);
746         if (ret != 0)
747                 return ret;
748
749         ret = flush_output_bitstream(&ostream);
750         if (ret != 0)
751                 return ret;
752
753         compressed_len = ostream.bit_output - (u8*)compressed_data;
754
755         *compressed_len_ret = compressed_len;
756
757 #ifdef ENABLE_VERIFY_COMPRESSION
758         /* Verify that we really get the same thing back when decompressing. */
759         u8 buf[uncompressed_len];
760         ret = lzx_decompress(compressed_data, compressed_len, buf,
761                              uncompressed_len);
762         if (ret != 0) {
763                 ERROR("lzx_compress(): Failed to decompress data we compressed");
764                 abort();
765         }
766
767         for (i = 0; i < uncompressed_len; i++) {
768                 if (buf[i] != *((u8*)__uncompressed_data + i)) {
769                         ERROR("lzx_compress(): Data we compressed didn't "
770                               "decompress to the original data (difference at "
771                               "byte %u of %u)", i + 1, uncompressed_len);
772                         abort();
773                 }
774         }
775 #endif
776         return 0;
777 }