]> wimlib.net Git - wimlib/blob - src/lzms-common.c
41383f4c3f553286cbcf6213bab527fb6fc0bf20
[wimlib] / src / lzms-common.c
1 /*
2  * lzms-common.c
3  *
4  * Code shared between the compressor and decompressor for the LZMS compression
5  * format.
6  */
7
8 /*
9  * Copyright (C) 2013, 2014 Eric Biggers
10  *
11  * This file is free software; you can redistribute it and/or modify it under
12  * the terms of the GNU Lesser General Public License as published by the Free
13  * Software Foundation; either version 3 of the License, or (at your option) any
14  * later version.
15  *
16  * This file is distributed in the hope that it will be useful, but WITHOUT
17  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
19  * details.
20  *
21  * You should have received a copy of the GNU Lesser General Public License
22  * along with this file; if not, see http://www.gnu.org/licenses/.
23  */
24
25 #ifdef HAVE_CONFIG_H
26 #  include "config.h"
27 #endif
28
29 #include "wimlib/bitops.h"
30 #include "wimlib/endianness.h"
31 #include "wimlib/lzms.h"
32 #include "wimlib/unaligned.h"
33 #include "wimlib/util.h"
34
35 #include <pthread.h>
36
37 /***************************************************************
38  * Constant tables initialized by lzms_compute_slots():        *
39  ***************************************************************/
40
41 /* Table: offset slot => offset slot base value  */
42 u32 lzms_offset_slot_base[LZMS_MAX_NUM_OFFSET_SYMS + 1];
43
44 /* Table: offset slot => number of extra offset bits  */
45 u8 lzms_extra_offset_bits[LZMS_MAX_NUM_OFFSET_SYMS];
46
47 /* Table: length slot => length slot base value  */
48 u32 lzms_length_slot_base[LZMS_NUM_LEN_SYMS + 1];
49
50 /* Table: length slot => number of extra length bits  */
51 u8 lzms_extra_length_bits[LZMS_NUM_LEN_SYMS];
52
53 unsigned
54 lzms_get_slot(u32 value, const u32 slot_base_tab[], unsigned num_slots)
55 {
56         unsigned l = 0;
57         unsigned r = num_slots - 1;
58         for (;;) {
59                 LZMS_ASSERT(r >= l);
60                 unsigned slot = (l + r) / 2;
61                 if (value >= slot_base_tab[slot]) {
62                         if (value < slot_base_tab[slot + 1])
63                                 return slot;
64                         else
65                                 l = slot + 1;
66                 } else {
67                         r = slot - 1;
68                 }
69         }
70 }
71
72 static void
73 lzms_decode_delta_rle_slot_bases(u32 slot_bases[],
74                                  u8 extra_bits[],
75                                  const u8 delta_run_lens[],
76                                  unsigned num_run_lens,
77                                  u32 final,
78                                  unsigned expected_num_slots)
79 {
80         unsigned order = 0;
81         u32 delta = 1;
82         u32 base = 0;
83         unsigned slot = 0;
84         for (unsigned i = 0; i < num_run_lens; i++) {
85                 unsigned run_len = delta_run_lens[i];
86                 while (run_len--) {
87                         base += delta;
88                         if (slot > 0)
89                                 extra_bits[slot - 1] = order;
90                         slot_bases[slot] = base;
91                         slot++;
92                 }
93                 delta <<= 1;
94                 order++;
95         }
96         LZMS_ASSERT(slot == expected_num_slots);
97
98         slot_bases[slot] = final;
99         extra_bits[slot - 1] = fls32(slot_bases[slot] - slot_bases[slot - 1]);
100 }
101
102 /* Initialize the global offset and length slot tables.  */
103 static void
104 lzms_compute_slots(void)
105 {
106         /* If an explicit formula that maps LZMS offset and length slots to slot
107          * bases exists, then it could be used here.  But until one is found,
108          * the following code fills in the slots using the observation that the
109          * increase from one slot base to the next is an increasing power of 2.
110          * Therefore, run-length encoding of the delta of adjacent entries can
111          * be used.  */
112         static const u8 offset_slot_delta_run_lens[] = {
113                 9,   0,   9,   7,   10,  15,  15,  20,
114                 20,  30,  33,  40,  42,  45,  60,  73,
115                 80,  85,  95,  105, 6,
116         };
117
118         static const u8 length_slot_delta_run_lens[] = {
119                 27,  4,   6,   4,   5,   2,   1,   1,
120                 1,   1,   1,   0,   0,   0,   0,   0,
121                 1,
122         };
123
124         /* Offset slots  */
125         lzms_decode_delta_rle_slot_bases(lzms_offset_slot_base,
126                                          lzms_extra_offset_bits,
127                                          offset_slot_delta_run_lens,
128                                          ARRAY_LEN(offset_slot_delta_run_lens),
129                                          0x7fffffff,
130                                          LZMS_MAX_NUM_OFFSET_SYMS);
131
132         /* Length slots  */
133         lzms_decode_delta_rle_slot_bases(lzms_length_slot_base,
134                                          lzms_extra_length_bits,
135                                          length_slot_delta_run_lens,
136                                          ARRAY_LEN(length_slot_delta_run_lens),
137                                          0x400108ab,
138                                          LZMS_NUM_LEN_SYMS);
139 }
140
141 /* Initialize the global offset and length slot tables if not already done.  */
142 void
143 lzms_init_slots(void)
144 {
145         static pthread_once_t once = PTHREAD_ONCE_INIT;
146
147         pthread_once(&once, lzms_compute_slots);
148 }
149
150 static s32
151 lzms_maybe_do_x86_translation(u8 data[restrict], s32 i, s32 num_op_bytes,
152                               s32 * restrict closest_target_usage_p,
153                               s32 last_target_usages[restrict],
154                               s32 max_trans_offset, bool undo)
155 {
156         u16 pos;
157
158         if (undo) {
159                 if (i - *closest_target_usage_p <= max_trans_offset) {
160                         LZMS_DEBUG("Undid x86 translation at position %d "
161                                    "(opcode 0x%02x)", i, data[i]);
162                         void *p32 = &data[i + num_op_bytes];
163                         u32 n = get_unaligned_u32_le(p32);
164                         put_unaligned_u32_le(n - i, p32);
165                 }
166                 pos = i + get_unaligned_u16_le(&data[i + num_op_bytes]);
167         } else {
168                 pos = i + get_unaligned_u16_le(&data[i + num_op_bytes]);
169
170                 if (i - *closest_target_usage_p <= max_trans_offset) {
171                         LZMS_DEBUG("Did x86 translation at position %d "
172                                    "(opcode 0x%02x)", i, data[i]);
173                         void *p32 = &data[i + num_op_bytes];
174                         u32 n = get_unaligned_u32_le(p32);
175                         put_unaligned_u32_le(n + i, p32);
176                 }
177         }
178
179         i += num_op_bytes + sizeof(le32) - 1;
180
181         if (i - last_target_usages[pos] <= LZMS_X86_MAX_GOOD_TARGET_OFFSET)
182                 *closest_target_usage_p = i;
183
184         last_target_usages[pos] = i;
185
186         return i + 1;
187 }
188
189 static inline s32
190 lzms_may_x86_translate(const u8 p[restrict], s32 *restrict max_offset_ret)
191 {
192         /* Switch on first byte of the opcode, assuming it is really an x86
193          * instruction.  */
194         *max_offset_ret = LZMS_X86_MAX_TRANSLATION_OFFSET;
195         switch (p[0]) {
196         case 0x48:
197                 if (p[1] == 0x8b) {
198                         if (p[2] == 0x5 || p[2] == 0xd) {
199                                 /* Load relative (x86_64)  */
200                                 return 3;
201                         }
202                 } else if (p[1] == 0x8d) {
203                         if ((p[2] & 0x7) == 0x5) {
204                                 /* Load effective address relative (x86_64)  */
205                                 return 3;
206                         }
207                 }
208                 break;
209
210         case 0x4c:
211                 if (p[1] == 0x8d) {
212                         if ((p[2] & 0x7) == 0x5) {
213                                 /* Load effective address relative (x86_64)  */
214                                 return 3;
215                         }
216                 }
217                 break;
218
219         case 0xe8:
220                 /* Call relative  */
221                 *max_offset_ret = LZMS_X86_MAX_TRANSLATION_OFFSET / 2;
222                 return 1;
223
224         case 0xe9:
225                 /* Jump relative  */
226                 *max_offset_ret = 0;
227                 return 5;
228
229         case 0xf0:
230                 if (p[1] == 0x83 && p[2] == 0x05) {
231                         /* Lock add relative  */
232                         return 3;
233                 }
234                 break;
235
236         case 0xff:
237                 if (p[1] == 0x15) {
238                         /* Call indirect  */
239                         return 2;
240                 }
241                 break;
242         }
243         *max_offset_ret = 0;
244         return 1;
245 }
246
247 /*
248  * Translate relative addresses embedded in x86 instructions into absolute
249  * addresses (@undo == %false), or undo this translation (@undo == %true).
250  *
251  * Absolute addresses are usually more compressible by LZ factorization.
252  *
253  * @last_target_usages must be a temporary array of length >= 65536.
254  */
255 void
256 lzms_x86_filter(u8 data[restrict], s32 size,
257                 s32 last_target_usages[restrict], bool undo)
258 {
259         /*
260          * Note: this filter runs unconditionally and uses a custom algorithm to
261          * detect data regions that probably contain x86 code.
262          *
263          * 'closest_target_usage' tracks the most recent position that has a
264          * good chance of being an x86 instruction.  When the filter detects a
265          * likely x86 instruction, it updates this variable and considers the
266          * next 1023 bytes of data as valid for x86 translations.
267          *
268          * If part of the data does not, in fact, contain x86 machine code, then
269          * 'closest_target_usage' will, very likely, eventually fall more than
270          * 1023 bytes behind the current position.  This results in x86
271          * translations being disabled until the next likely x86 instruction is
272          * detected.
273          *
274          * Translations on relative call (e8 opcode) instructions are slightly
275          * more restricted.  They require that the most recent likely x86
276          * instruction was in the last 511 bytes, rather than the last 1023
277          * bytes.
278          *
279          * To identify "likely x86 instructions", the algorithm attempts to
280          * track the position of the most recent potential relative-addressing
281          * instruction that referenced each possible memory address.  If it
282          * finds two references to the same memory address within a 65535 byte
283          * window, the second reference is flagged as a likely x86 instruction.
284          * Since the instructions considered for translation necessarily use
285          * relative addressing, the algorithm does a tentative translation into
286          * absolute addresses.  In addition, so that memory addresses can be
287          * looked up in an array of reasonable size (in this code,
288          * 'last_target_usages'), only the low-order 2 bytes of each address are
289          * considered significant.
290          */
291
292         s32 closest_target_usage = -LZMS_X86_MAX_TRANSLATION_OFFSET - 1;
293
294         for (s32 i = 0; i < 65536; i++)
295                 last_target_usages[i] = -LZMS_X86_MAX_GOOD_TARGET_OFFSET - 1;
296
297         for (s32 i = 1; i < size - 16; ) {
298                 s32 max_trans_offset;
299                 s32 n;
300
301                 n = lzms_may_x86_translate(data + i, &max_trans_offset);
302
303                 if (max_trans_offset) {
304                         /* Recognized opcode.  */
305                         i = lzms_maybe_do_x86_translation(data, i, n,
306                                                           &closest_target_usage,
307                                                           last_target_usages,
308                                                           max_trans_offset,
309                                                           undo);
310                 } else {
311                         /* Not a recognized opcode.  */
312                         i += n;
313                 }
314         }
315 }
316
317 void
318 lzms_init_lz_lru_queues(struct lzms_lz_lru_queues *lz)
319 {
320         /* Recent offsets for LZ matches  */
321         for (u32 i = 0; i < LZMS_NUM_RECENT_OFFSETS + 1; i++)
322                 lz->recent_offsets[i] = i + 1;
323
324         lz->prev_offset = 0;
325         lz->upcoming_offset = 0;
326 }
327
328 void
329 lzms_init_delta_lru_queues(struct lzms_delta_lru_queues *delta)
330 {
331         /* Recent offsets and powers for LZ matches  */
332         for (u32 i = 0; i < LZMS_NUM_RECENT_OFFSETS + 1; i++) {
333                 delta->recent_offsets[i] = i + 1;
334                 delta->recent_powers[i] = 0;
335         }
336         delta->prev_offset = 0;
337         delta->prev_power = 0;
338         delta->upcoming_offset = 0;
339         delta->upcoming_power = 0;
340 }
341
342
343 void
344 lzms_init_lru_queues(struct lzms_lru_queues *lru)
345 {
346         lzms_init_lz_lru_queues(&lru->lz);
347         lzms_init_delta_lru_queues(&lru->delta);
348 }
349
350 void
351 lzms_update_lz_lru_queue(struct lzms_lz_lru_queues *lz)
352 {
353         if (lz->prev_offset != 0) {
354                 for (int i = LZMS_NUM_RECENT_OFFSETS - 1; i >= 0; i--)
355                         lz->recent_offsets[i + 1] = lz->recent_offsets[i];
356                 lz->recent_offsets[0] = lz->prev_offset;
357         }
358         lz->prev_offset = lz->upcoming_offset;
359 }
360
361 void
362 lzms_update_delta_lru_queues(struct lzms_delta_lru_queues *delta)
363 {
364         if (delta->prev_offset != 0) {
365                 for (int i = LZMS_NUM_RECENT_OFFSETS - 1; i >= 0; i--) {
366                         delta->recent_offsets[i + 1] = delta->recent_offsets[i];
367                         delta->recent_powers[i + 1] = delta->recent_powers[i];
368                 }
369                 delta->recent_offsets[0] = delta->prev_offset;
370                 delta->recent_powers[0] = delta->prev_power;
371         }
372
373         delta->prev_offset = delta->upcoming_offset;
374         delta->prev_power = delta->upcoming_power;
375 }
376
377 void
378 lzms_update_lru_queues(struct lzms_lru_queues *lru)
379 {
380         lzms_update_lz_lru_queue(&lru->lz);
381         lzms_update_delta_lru_queues(&lru->delta);
382 }