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