]> wimlib.net Git - wimlib/blob - src/lzx-compress.c
Dynamically load Find{Find,Next}StreamW()
[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, 2013 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 position_slot;
140         unsigned position_footer = 0;
141         u32 match;
142         u32 len_header;
143         u32 len_pos_header;
144         unsigned len_footer;
145         unsigned adjusted_match_len;
146
147         wimlib_assert(match_len >= LZX_MIN_MATCH && match_len <= LZX_MAX_MATCH);
148         wimlib_assert(match_offset != 0);
149
150         /* If possible, encode this offset as a repeated offset. */
151         if (match_offset == queue->R0) {
152                 position_slot = 0;
153         } else if (match_offset == queue->R1) {
154                 swap(queue->R0, queue->R1);
155                 position_slot = 1;
156         } else if (match_offset == queue->R2) {
157                 swap(queue->R0, queue->R2);
158                 position_slot = 2;
159         } else {
160                 /* Not a repeated offset. */
161
162                 /* offsets of 0, 1, and 2 are reserved for the repeated offset
163                  * codes, so non-repeated offsets must be encoded as 3+.  The
164                  * minimum offset is 1, so encode the offsets offset by 2. */
165                 unsigned formatted_offset = match_offset + LZX_MIN_MATCH;
166
167                 queue->R2 = queue->R1;
168                 queue->R1 = queue->R0;
169                 queue->R0 = match_offset;
170
171                 /* The (now-formatted) offset will actually be encoded as a
172                  * small position slot number that maps to a certain hard-coded
173                  * offset (position base), followed by a number of extra bits---
174                  * the position footer--- that are added to the position base to
175                  * get the original formatted offset. */
176
177                 position_slot = lzx_get_position_slot(formatted_offset);
178                 position_footer = formatted_offset &
179                                   ((1 << lzx_get_num_extra_bits(position_slot)) - 1);
180         }
181
182         adjusted_match_len = match_len - LZX_MIN_MATCH;
183
184         /* Pack the position slot, position footer, and match length into an
185          * intermediate representation.
186          *
187          * bits    description
188          * ----    -----------------------------------------------------------
189          *
190          * 31      1 if a match, 0 if a literal.
191          *
192          * 30-25   position slot.  This can be at most 50, so it will fit in 6
193          *         bits.
194          *
195          * 8-24    position footer.  This is the offset of the real formatted
196          *         offset from the position base.  This can be at most 17 bits
197          *         (since lzx_extra_bits[LZX_NUM_POSITION_SLOTS - 1] is 17).
198          *
199          * 0-7     length of match, offset by 2.  This can be at most
200          *         (LZX_MAX_MATCH - 2) == 255, so it will fit in 8 bits.  */
201         match = 0x80000000 |
202                 (position_slot << 25) |
203                 (position_footer << 8) |
204                 (adjusted_match_len);
205
206         /* The match length must be at least 2, so let the adjusted match length
207          * be the match length minus 2.
208          *
209          * If it is less than 7, the adjusted match length is encoded as a 3-bit
210          * number offset by 2.  Otherwise, the 3-bit length header is all 1's
211          * and the actual adjusted length is given as a symbol encoded with the
212          * length tree, offset by 7.
213          */
214         if (adjusted_match_len < LZX_NUM_PRIMARY_LENS) {
215                 len_header = adjusted_match_len;
216         } else {
217                 len_header = LZX_NUM_PRIMARY_LENS;
218                 len_footer = adjusted_match_len - LZX_NUM_PRIMARY_LENS;
219                 freq_tabs->len_freq_table[len_footer]++;
220         }
221         len_pos_header = (position_slot << 3) | len_header;
222
223         wimlib_assert(len_pos_header < LZX_MAINTREE_NUM_SYMBOLS - LZX_NUM_CHARS);
224
225         freq_tabs->main_freq_table[len_pos_header + LZX_NUM_CHARS]++;
226
227         /* Equivalent to:
228          * if (lzx_extra_bits[position_slot] >= 3) */
229         if (position_slot >= 8)
230                 freq_tabs->aligned_freq_table[position_footer & 7]++;
231
232         return match;
233 }
234
235 /*
236  * Writes a compressed literal match to the output.
237  *
238  * @out:         The output bitstream.
239  * @block_type:  The type of the block (LZX_BLOCKTYPE_ALIGNED or LZX_BLOCKTYPE_VERBATIM)
240  * @match:       The match, encoded as a 32-bit number.
241  * @codes:      Pointer to a structure that contains the codewords for the
242  *                      main, length, and aligned offset Huffman codes.
243  */
244 static int lzx_write_match(struct output_bitstream *out, int block_type,
245                            u32 match, const struct lzx_codes *codes)
246 {
247         /* low 8 bits are the match length minus 2 */
248         unsigned match_len_minus_2 = match & 0xff;
249         /* Next 17 bits are the position footer */
250         unsigned position_footer = (match >> 8) & 0x1ffff;      /* 17 bits */
251         /* Next 6 bits are the position slot. */
252         unsigned position_slot = (match >> 25) & 0x3f;  /* 6 bits */
253         unsigned len_header;
254         unsigned len_footer;
255         unsigned len_pos_header;
256         unsigned main_symbol;
257         unsigned num_extra_bits;
258         unsigned verbatim_bits;
259         unsigned aligned_bits;
260         int ret;
261
262         /* If the match length is less than MIN_MATCH (= 2) +
263          * NUM_PRIMARY_LENS (= 7), the length header contains
264          * the match length minus MIN_MATCH, and there is no
265          * length footer.
266          *
267          * Otherwise, the length header contains
268          * NUM_PRIMARY_LENS, and the length footer contains
269          * the match length minus NUM_PRIMARY_LENS minus
270          * MIN_MATCH. */
271         if (match_len_minus_2 < LZX_NUM_PRIMARY_LENS) {
272                 len_header = match_len_minus_2;
273                 /* No length footer-- mark it with a special
274                  * value. */
275                 len_footer = (unsigned)(-1);
276         } else {
277                 len_header = LZX_NUM_PRIMARY_LENS;
278                 len_footer = match_len_minus_2 - LZX_NUM_PRIMARY_LENS;
279         }
280
281         /* Combine the position slot with the length header into
282          * a single symbol that will be encoded with the main
283          * tree. */
284         len_pos_header = (position_slot << 3) | len_header;
285
286         /* The actual main symbol is offset by LZX_NUM_CHARS because
287          * values under LZX_NUM_CHARS are used to indicate a literal
288          * byte rather than a match. */
289         main_symbol = len_pos_header + LZX_NUM_CHARS;
290
291         /* Output main symbol. */
292         ret = bitstream_put_bits(out, codes->main_codewords[main_symbol],
293                                  codes->main_lens[main_symbol]);
294         if (ret != 0)
295                 return ret;
296
297         /* If there is a length footer, output it using the
298          * length Huffman code. */
299         if (len_footer != (unsigned)(-1)) {
300                 ret = bitstream_put_bits(out, codes->len_codewords[len_footer],
301                                          codes->len_lens[len_footer]);
302                 if (ret != 0)
303                         return ret;
304         }
305
306         wimlib_assert(position_slot < LZX_NUM_POSITION_SLOTS);
307
308         num_extra_bits = lzx_get_num_extra_bits(position_slot);
309
310         /* For aligned offset blocks with at least 3 extra bits, output the
311          * verbatim bits literally, then the aligned bits encoded using the
312          * aligned offset tree.  Otherwise, only the verbatim bits need to be
313          * output. */
314         if ((block_type == LZX_BLOCKTYPE_ALIGNED) && (num_extra_bits >= 3)) {
315
316                 verbatim_bits = position_footer >> 3;
317                 ret = bitstream_put_bits(out, verbatim_bits,
318                                          num_extra_bits - 3);
319                 if (ret != 0)
320                         return ret;
321
322                 aligned_bits = (position_footer & 7);
323                 ret = bitstream_put_bits(out,
324                                          codes->aligned_codewords[aligned_bits],
325                                          codes->aligned_lens[aligned_bits]);
326                 if (ret != 0)
327                         return ret;
328         } else {
329                 /* verbatim bits is the same as the position
330                  * footer, in this case. */
331                 ret = bitstream_put_bits(out, position_footer, num_extra_bits);
332                 if (ret != 0)
333                         return ret;
334         }
335         return 0;
336 }
337
338 /*
339  * Writes all compressed literals in a block, both matches and literal bytes, to
340  * the output bitstream.
341  *
342  * @out:         The output bitstream.
343  * @block_type:  The type of the block (LZX_BLOCKTYPE_ALIGNED or LZX_BLOCKTYPE_VERBATIM)
344  * @match_tab[]:   The array of matches that will be output.  It has length
345  *                      of @num_compressed_literals.
346  * @num_compressed_literals:  Number of compressed literals to be output.
347  * @codes:      Pointer to a structure that contains the codewords for the
348  *                      main, length, and aligned offset Huffman codes.
349  */
350 static int lzx_write_compressed_literals(struct output_bitstream *ostream,
351                                          int block_type,
352                                          const u32 match_tab[],
353                                          unsigned  num_compressed_literals,
354                                          const struct lzx_codes *codes)
355 {
356         unsigned i;
357         u32 match;
358         int ret;
359
360         for (i = 0; i < num_compressed_literals; i++) {
361                 match = match_tab[i];
362
363                 /* High bit of the match indicates whether the match is an
364                  * actual match (1) or a literal uncompressed byte (0) */
365                 if (match & 0x80000000) {
366                         /* match */
367                         ret = lzx_write_match(ostream, block_type, match,
368                                               codes);
369                         if (ret != 0)
370                                 return ret;
371                 } else {
372                         /* literal byte */
373                         wimlib_assert(match < LZX_NUM_CHARS);
374                         ret = bitstream_put_bits(ostream,
375                                                  codes->main_codewords[match],
376                                                  codes->main_lens[match]);
377                         if (ret != 0)
378                                 return ret;
379                 }
380         }
381         return 0;
382 }
383
384 /*
385  * Writes a compressed Huffman tree to the output, preceded by the pretree for
386  * it.
387  *
388  * The Huffman tree is represented in the output as a series of path lengths
389  * from which the canonical Huffman code can be reconstructed.  The path lengths
390  * themselves are compressed using a separate Huffman code, the pretree, which
391  * consists of LZX_PRETREE_NUM_SYMBOLS (= 20) symbols that cover all possible code
392  * lengths, plus extra codes for repeated lengths.  The path lengths of the
393  * pretree precede the path lengths of the larger code and are uncompressed,
394  * consisting of 20 entries of 4 bits each.
395  *
396  * @out:        The bitstream for the compressed output.
397  * @lens:       The code lengths for the Huffman tree, indexed by symbol.
398  * @num_symbols:        The number of symbols in the code.
399  */
400 static int lzx_write_compressed_tree(struct output_bitstream *out,
401                                      const u8 lens[], unsigned num_symbols)
402 {
403         /* Frequencies of the length symbols, including the RLE symbols (NOT the
404          * actual lengths themselves). */
405         freq_t pretree_freqs[LZX_PRETREE_NUM_SYMBOLS];
406         u8 pretree_lens[LZX_PRETREE_NUM_SYMBOLS];
407         u16 pretree_codewords[LZX_PRETREE_NUM_SYMBOLS];
408         u8 output_syms[num_symbols * 2];
409         unsigned output_syms_idx;
410         unsigned cur_run_len;
411         unsigned i;
412         unsigned len_in_run;
413         unsigned additional_bits;
414         char delta;
415         u8 pretree_sym;
416
417         ZERO_ARRAY(pretree_freqs);
418
419         /* Since the code word lengths use a form of RLE encoding, the goal here
420          * is to find each run of identical lengths when going through them in
421          * symbol order (including runs of length 1).  For each run, as many
422          * lengths are encoded using RLE as possible, and the rest are output
423          * literally.
424          *
425          * output_syms[] will be filled in with the length symbols that will be
426          * output, including RLE codes, not yet encoded using the pre-tree.
427          *
428          * cur_run_len keeps track of how many code word lengths are in the
429          * current run of identical lengths.
430          */
431         output_syms_idx = 0;
432         cur_run_len = 1;
433         for (i = 1; i <= num_symbols; i++) {
434
435                 if (i != num_symbols && lens[i] == lens[i - 1]) {
436                         /* Still in a run--- keep going. */
437                         cur_run_len++;
438                         continue;
439                 }
440
441                 /* Run ended! Check if it is a run of zeroes or a run of
442                  * nonzeroes. */
443
444                 /* The symbol that was repeated in the run--- not to be confused
445                  * with the length *of* the run (cur_run_len) */
446                 len_in_run = lens[i - 1];
447
448                 if (len_in_run == 0) {
449                         /* A run of 0's.  Encode it in as few length
450                          * codes as we can. */
451
452                         /* The magic length 18 indicates a run of 20 + n zeroes,
453                          * where n is an uncompressed literal 5-bit integer that
454                          * follows the magic length. */
455                         while (cur_run_len >= 20) {
456
457                                 additional_bits = min(cur_run_len - 20, 0x1f);
458                                 pretree_freqs[18]++;
459                                 output_syms[output_syms_idx++] = 18;
460                                 output_syms[output_syms_idx++] = additional_bits;
461                                 cur_run_len -= 20 + additional_bits;
462                         }
463
464                         /* The magic length 17 indicates a run of 4 + n zeroes,
465                          * where n is an uncompressed literal 4-bit integer that
466                          * follows the magic length. */
467                         while (cur_run_len >= 4) {
468                                 additional_bits = min(cur_run_len - 4, 0xf);
469                                 pretree_freqs[17]++;
470                                 output_syms[output_syms_idx++] = 17;
471                                 output_syms[output_syms_idx++] = additional_bits;
472                                 cur_run_len -= 4 + additional_bits;
473                         }
474
475                 } else {
476
477                         /* A run of nonzero lengths. */
478
479                         /* The magic length 19 indicates a run of 4 + n
480                          * nonzeroes, where n is a literal bit that follows the
481                          * magic length, and where the value of the lengths in
482                          * the run is given by an extra length symbol, encoded
483                          * with the pretree, that follows the literal bit.
484                          *
485                          * The extra length symbol is encoded as a difference
486                          * from the length of the codeword for the first symbol
487                          * in the run in the previous tree.
488                          * */
489                         while (cur_run_len >= 4) {
490                                 additional_bits = (cur_run_len > 4);
491                                 delta = -(char)len_in_run;
492                                 if (delta < 0)
493                                         delta += 17;
494                                 pretree_freqs[19]++;
495                                 pretree_freqs[(unsigned char)delta]++;
496                                 output_syms[output_syms_idx++] = 19;
497                                 output_syms[output_syms_idx++] = additional_bits;
498                                 output_syms[output_syms_idx++] = delta;
499                                 cur_run_len -= 4 + additional_bits;
500                         }
501                 }
502
503                 /* Any remaining lengths in the run are outputted without RLE,
504                  * as a difference from the length of that codeword in the
505                  * previous tree. */
506                 while (cur_run_len--) {
507                         delta = -(char)len_in_run;
508                         if (delta < 0)
509                                 delta += 17;
510
511                         pretree_freqs[(unsigned char)delta]++;
512                         output_syms[output_syms_idx++] = delta;
513                 }
514
515                 cur_run_len = 1;
516         }
517
518         wimlib_assert(output_syms_idx < ARRAY_LEN(output_syms));
519
520         /* Build the pretree from the frequencies of the length symbols. */
521
522         make_canonical_huffman_code(LZX_PRETREE_NUM_SYMBOLS,
523                                     LZX_MAX_CODEWORD_LEN,
524                                     pretree_freqs, pretree_lens,
525                                     pretree_codewords);
526
527         /* Write the lengths of the pretree codes to the output. */
528         for (i = 0; i < LZX_PRETREE_NUM_SYMBOLS; i++)
529                 bitstream_put_bits(out, pretree_lens[i],
530                                    LZX_PRETREE_ELEMENT_SIZE);
531
532         /* Write the length symbols, encoded with the pretree, to the output. */
533
534         i = 0;
535         while (i < output_syms_idx) {
536                 pretree_sym = output_syms[i++];
537
538                 bitstream_put_bits(out, pretree_codewords[pretree_sym],
539                                    pretree_lens[pretree_sym]);
540                 switch (pretree_sym) {
541                 case 17:
542                         bitstream_put_bits(out, output_syms[i++], 4);
543                         break;
544                 case 18:
545                         bitstream_put_bits(out, output_syms[i++], 5);
546                         break;
547                 case 19:
548                         bitstream_put_bits(out, output_syms[i++], 1);
549                         bitstream_put_bits(out,
550                                            pretree_codewords[output_syms[i]],
551                                            pretree_lens[output_syms[i]]);
552                         i++;
553                         break;
554                 default:
555                         break;
556                 }
557         }
558         return 0;
559 }
560
561 /* Builds the canonical Huffman code for the main tree, the length tree, and the
562  * aligned offset tree. */
563 static void lzx_make_huffman_codes(const struct lzx_freq_tables *freq_tabs,
564                                 struct lzx_codes *codes)
565 {
566         make_canonical_huffman_code(LZX_MAINTREE_NUM_SYMBOLS,
567                                         LZX_MAX_CODEWORD_LEN,
568                                         freq_tabs->main_freq_table,
569                                         codes->main_lens,
570                                         codes->main_codewords);
571
572         make_canonical_huffman_code(LZX_LENTREE_NUM_SYMBOLS,
573                                         LZX_MAX_CODEWORD_LEN,
574                                         freq_tabs->len_freq_table,
575                                         codes->len_lens,
576                                         codes->len_codewords);
577
578         make_canonical_huffman_code(LZX_ALIGNEDTREE_NUM_SYMBOLS, 8,
579                                         freq_tabs->aligned_freq_table,
580                                         codes->aligned_lens,
581                                         codes->aligned_codewords);
582 }
583
584 static void do_call_insn_translation(u32 *call_insn_target, int input_pos,
585                                      int32_t file_size)
586 {
587         int32_t abs_offset;
588         int32_t rel_offset;
589
590         rel_offset = le32_to_cpu(*call_insn_target);
591         if (rel_offset >= -input_pos && rel_offset < file_size) {
592                 if (rel_offset < file_size - input_pos) {
593                         /* "good translation" */
594                         abs_offset = rel_offset + input_pos;
595                 } else {
596                         /* "compensating translation" */
597                         abs_offset = rel_offset - file_size;
598                 }
599                 *call_insn_target = cpu_to_le32(abs_offset);
600         }
601 }
602
603 /* This is the reverse of undo_call_insn_preprocessing() in lzx-decompress.c.
604  * See the comment above that function for more information. */
605 static void do_call_insn_preprocessing(u8 uncompressed_data[],
606                                        int uncompressed_data_len)
607 {
608         for (int i = 0; i < uncompressed_data_len - 10; i++) {
609                 if (uncompressed_data[i] == 0xe8) {
610                         do_call_insn_translation((u32*)&uncompressed_data[i + 1],
611                                                  i,
612                                                  LZX_WIM_MAGIC_FILESIZE);
613                         i += 4;
614                 }
615         }
616 }
617
618
619 static const struct lz_params lzx_lz_params = {
620
621          /* LZX_MIN_MATCH == 2, but 2-character matches are rarely useful; the
622           * minimum match for compression is set to 3 instead. */
623         .min_match      = 3,
624
625         .max_match      = LZX_MAX_MATCH,
626         .good_match     = LZX_MAX_MATCH,
627         .nice_match     = LZX_MAX_MATCH,
628         .max_chain_len  = LZX_MAX_MATCH,
629         .max_lazy_match = LZX_MAX_MATCH,
630         .too_far        = 4096,
631 };
632
633 /*
634  * Performs LZX compression on a block of data.
635  *
636  * @__uncompressed_data:  Pointer to the data to be compressed.
637  * @uncompressed_len:     Length, in bytes, of the data to be compressed.
638  * @compressed_data:      Pointer to a location at least (@uncompressed_len - 1)
639  *                              bytes long into which the compressed data may be
640  *                              written.
641  * @compressed_len_ret:   A pointer to an unsigned int into which the length of
642  *                              the compressed data may be returned.
643  *
644  * Returns zero if compression was successfully performed.  In that case
645  * @compressed_data and @compressed_len_ret will contain the compressed data and
646  * its length.  A return value of nonzero means that compressing the data did
647  * not reduce its size, and @compressed_data will not contain the full
648  * compressed data.
649  */
650 int lzx_compress(const void *__uncompressed_data, unsigned uncompressed_len,
651                  void *compressed_data, unsigned *compressed_len_ret)
652 {
653         struct output_bitstream ostream;
654         u8 uncompressed_data[uncompressed_len + 8];
655         struct lzx_freq_tables freq_tabs;
656         struct lzx_codes codes;
657         u32 match_tab[uncompressed_len];
658         struct lru_queue queue;
659         unsigned num_matches;
660         unsigned compressed_len;
661         unsigned i;
662         int ret;
663         int block_type = LZX_BLOCKTYPE_ALIGNED;
664
665         if (uncompressed_len < 100)
666                 return 1;
667
668         memset(&freq_tabs, 0, sizeof(freq_tabs));
669         queue.R0 = 1;
670         queue.R1 = 1;
671         queue.R2 = 1;
672
673         /* The input data must be preprocessed. To avoid changing the original
674          * input, copy it to a temporary buffer. */
675         memcpy(uncompressed_data, __uncompressed_data, uncompressed_len);
676
677         /* Before doing any actual compression, do the call instruction (0xe8
678          * byte) translation on the uncompressed data. */
679         do_call_insn_preprocessing(uncompressed_data, uncompressed_len);
680
681         /* Determine the sequence of matches and literals that will be output,
682          * and in the process, keep counts of the number of times each symbol
683          * will be output, so that the Huffman trees can be made. */
684
685         num_matches = lz_analyze_block(uncompressed_data, uncompressed_len,
686                                        match_tab, lzx_record_match,
687                                        lzx_record_literal, &freq_tabs,
688                                        &queue, freq_tabs.main_freq_table,
689                                        &lzx_lz_params);
690
691         lzx_make_huffman_codes(&freq_tabs, &codes);
692
693         /* Initialize the output bitstream. */
694         init_output_bitstream(&ostream, compressed_data, uncompressed_len - 1);
695
696         /* The first three bits tell us what kind of block it is, and are one
697          * of the LZX_BLOCKTYPE_* values.  */
698         bitstream_put_bits(&ostream, block_type, 3);
699
700         /* The next bit indicates whether the block size is the default (32768),
701          * indicated by a 1 bit, or whether the block size is given by the next
702          * 16 bits, indicated by a 0 bit. */
703         if (uncompressed_len == 32768) {
704                 bitstream_put_bits(&ostream, 1, 1);
705         } else {
706                 bitstream_put_bits(&ostream, 0, 1);
707                 bitstream_put_bits(&ostream, uncompressed_len, 16);
708         }
709
710         /* Write out the aligned offset tree. Note that M$ lies and says that
711          * the aligned offset tree comes after the length tree, but that is
712          * wrong; it actually is before the main tree.  */
713         if (block_type == LZX_BLOCKTYPE_ALIGNED)
714                 for (i = 0; i < LZX_ALIGNEDTREE_NUM_SYMBOLS; i++)
715                         bitstream_put_bits(&ostream, codes.aligned_lens[i],
716                                            LZX_ALIGNEDTREE_ELEMENT_SIZE);
717
718         /* Write the pre-tree and lengths for the first LZX_NUM_CHARS symbols in the
719          * main tree. */
720         ret = lzx_write_compressed_tree(&ostream, codes.main_lens,
721                                         LZX_NUM_CHARS);
722         if (ret != 0)
723                 return ret;
724
725         /* Write the pre-tree and symbols for the rest of the main tree. */
726         ret = lzx_write_compressed_tree(&ostream, codes.main_lens +
727                                         LZX_NUM_CHARS,
728                                         LZX_MAINTREE_NUM_SYMBOLS -
729                                                 LZX_NUM_CHARS);
730         if (ret != 0)
731                 return ret;
732
733         /* Write the pre-tree and symbols for the length tree. */
734         ret = lzx_write_compressed_tree(&ostream, codes.len_lens,
735                                         LZX_LENTREE_NUM_SYMBOLS);
736         if (ret != 0)
737                 return ret;
738
739         /* Write the compressed literals. */
740         ret = lzx_write_compressed_literals(&ostream, block_type,
741                                             match_tab, num_matches, &codes);
742         if (ret != 0)
743                 return ret;
744
745         ret = flush_output_bitstream(&ostream);
746         if (ret != 0)
747                 return ret;
748
749         compressed_len = ostream.bit_output - (u8*)compressed_data;
750
751         *compressed_len_ret = compressed_len;
752
753 #ifdef ENABLE_VERIFY_COMPRESSION
754         /* Verify that we really get the same thing back when decompressing. */
755         u8 buf[uncompressed_len];
756         ret = lzx_decompress(compressed_data, compressed_len, buf,
757                              uncompressed_len);
758         if (ret != 0) {
759                 ERROR("lzx_compress(): Failed to decompress data we compressed");
760                 abort();
761         }
762
763         for (i = 0; i < uncompressed_len; i++) {
764                 if (buf[i] != *((u8*)__uncompressed_data + i)) {
765                         ERROR("lzx_compress(): Data we compressed didn't "
766                               "decompress to the original data (difference at "
767                               "byte %u of %u)", i + 1, uncompressed_len);
768                         abort();
769                 }
770         }
771 #endif
772         return 0;
773 }