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