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