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