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