projects/linux·blob master · refs

1340 lines · 32.6 KiB

1// SPDX-License-Identifier: 0BSD
2
3/*
4 * LZMA2 decoder
5 *
6 * Authors: Lasse Collin <[email protected]>
7 * Igor Pavlov <https://7-zip.org/>
8 */
9
10#include "xz_private.h"
11#include "xz_lzma2.h"
12
13/*
14 * Range decoder initialization eats the first five bytes of each LZMA chunk.
15 */
16#define RC_INIT_BYTES 5
17
18/*
19 * Minimum number of usable input buffer to safely decode one LZMA symbol.
20 * The worst case is that we decode 22 bits using probabilities and 26
21 * direct bits. This may decode at maximum of 20 bytes of input. However,
22 * lzma_main() does an extra normalization before returning, thus we
23 * need to put 21 here.
24 */
25#define LZMA_IN_REQUIRED 21
26
27/*
28 * Dictionary (history buffer)
29 *
30 * These are always true:
31 * start <= pos <= full <= end
32 * pos <= limit <= end
33 *
34 * In multi-call mode, also these are true:
35 * end == size
36 * size <= size_max
37 * allocated <= size
38 *
39 * Most of these variables are size_t to support single-call mode,
40 * in which the dictionary variables address the actual output
41 * buffer directly.
42 */
43struct dictionary {
44 /* Beginning of the history buffer */
45 uint8_t *buf;
46
47 /* Old position in buf (before decoding more data) */
48 size_t start;
49
50 /* Position in buf */
51 size_t pos;
52
53 /*
54 * How full dictionary is. This is used to detect corrupt input that
55 * would read beyond the beginning of the uncompressed stream.
56 */
57 size_t full;
58
59 /* Write limit; we don't write to buf[limit] or later bytes. */
60 size_t limit;
61
62 /*
63 * End of the dictionary buffer. In multi-call mode, this is
64 * the same as the dictionary size. In single-call mode, this
65 * indicates the size of the output buffer.
66 */
67 size_t end;
68
69 /*
70 * Size of the dictionary as specified in Block Header. This is used
71 * together with "full" to detect corrupt input that would make us
72 * read beyond the beginning of the uncompressed stream.
73 */
74 uint32_t size;
75
76 /*
77 * Maximum allowed dictionary size in multi-call mode.
78 * This is ignored in single-call mode.
79 */
80 uint32_t size_max;
81
82 /*
83 * Amount of memory currently allocated for the dictionary.
84 * This is used only with XZ_DYNALLOC. (With XZ_PREALLOC,
85 * size_max is always the same as the allocated size.)
86 */
87 uint32_t allocated;
88
89 /* Operation mode */
90 enum xz_mode mode;
91};
92
93/* Range decoder */
94struct rc_dec {
95 uint32_t range;
96 uint32_t code;
97
98 /*
99 * Number of initializing bytes remaining to be read
100 * by rc_read_init().
101 */
102 uint32_t init_bytes_left;
103
104 /*
105 * Buffer from which we read our input. It can be either
106 * temp.buf or the caller-provided input buffer.
107 */
108 const uint8_t *in;
109 size_t in_pos;
110 size_t in_limit;
111};
112
113/* Probabilities for a length decoder. */
114struct lzma_len_dec {
115 /* Probability of match length being at least 10 */
116 uint16_t choice;
117
118 /* Probability of match length being at least 18 */
119 uint16_t choice2;
120
121 /* Probabilities for match lengths 2-9 */
122 uint16_t low[POS_STATES_MAX][LEN_LOW_SYMBOLS];
123
124 /* Probabilities for match lengths 10-17 */
125 uint16_t mid[POS_STATES_MAX][LEN_MID_SYMBOLS];
126
127 /* Probabilities for match lengths 18-273 */
128 uint16_t high[LEN_HIGH_SYMBOLS];
129};
130
131struct lzma_dec {
132 /* Distances of latest four matches */
133 uint32_t rep0;
134 uint32_t rep1;
135 uint32_t rep2;
136 uint32_t rep3;
137
138 /*
139 * Length of a match. This is updated so that dict_repeat can
140 * be called again to finish repeating the whole match. This is
141 * size_t because a pointer to this is passed to dict_repeat,
142 * and there it's nicer to have size_t instead of uint32_t.
143 */
144 size_t len;
145
146 /* Types of the most recently seen LZMA symbols */
147 enum lzma_state state;
148
149 /*
150 * LZMA properties or related bit masks (number of literal
151 * context bits, a mask derived from the number of literal
152 * position bits, and a mask derived from the number
153 * position bits)
154 */
155 uint32_t lc;
156 uint32_t literal_pos_mask; /* (1 << lp) - 1 */
157 uint32_t pos_mask; /* (1 << pb) - 1 */
158
159 /* If 1, it's a match. Otherwise it's a single 8-bit literal. */
160 uint16_t is_match[STATES][POS_STATES_MAX];
161
162 /* If 1, it's a repeated match. The distance is one of rep0 .. rep3. */
163 uint16_t is_rep[STATES];
164
165 /*
166 * If 0, distance of a repeated match is rep0.
167 * Otherwise check is_rep1.
168 */
169 uint16_t is_rep0[STATES];
170
171 /*
172 * If 0, distance of a repeated match is rep1.
173 * Otherwise check is_rep2.
174 */
175 uint16_t is_rep1[STATES];
176
177 /* If 0, distance of a repeated match is rep2. Otherwise it is rep3. */
178 uint16_t is_rep2[STATES];
179
180 /*
181 * If 1, the repeated match has length of one byte. Otherwise
182 * the length is decoded from rep_len_decoder.
183 */
184 uint16_t is_rep0_long[STATES][POS_STATES_MAX];
185
186 /*
187 * Probability tree for the highest two bits of the match
188 * distance. There is a separate probability tree for match
189 * lengths of 2 (i.e. MATCH_LEN_MIN), 3, 4, and [5, 273].
190 */
191 uint16_t dist_slot[DIST_STATES][DIST_SLOTS];
192
193 /*
194 * Probility trees for additional bits for match distance
195 * when the distance is in the range [4, 127].
196 */
197 uint16_t dist_special[FULL_DISTANCES - DIST_MODEL_END];
198
199 /*
200 * Probability tree for the lowest four bits of a match
201 * distance that is equal to or greater than 128.
202 */
203 uint16_t dist_align[ALIGN_SIZE];
204
205 /* Length of a normal match */
206 struct lzma_len_dec match_len_dec;
207
208 /* Length of a repeated match */
209 struct lzma_len_dec rep_len_dec;
210
211 /* Probabilities of literals */
212 uint16_t literal[LITERAL_CODERS_MAX][LITERAL_CODER_SIZE];
213};
214
215struct lzma2_dec {
216 /* Position in xz_dec_lzma2_run(). */
217 enum lzma2_seq {
218 SEQ_CONTROL,
219 SEQ_UNCOMPRESSED_1,
220 SEQ_UNCOMPRESSED_2,
221 SEQ_COMPRESSED_0,
222 SEQ_COMPRESSED_1,
223 SEQ_PROPERTIES,
224 SEQ_LZMA_PREPARE,
225 SEQ_LZMA_RUN,
226 SEQ_COPY
227 } sequence;
228
229 /* Next position after decoding the compressed size of the chunk. */
230 enum lzma2_seq next_sequence;
231
232 /* Uncompressed size of LZMA chunk (2 MiB at maximum) */
233 size_t uncompressed;
234
235 /*
236 * Compressed size of LZMA chunk or compressed/uncompressed
237 * size of uncompressed chunk (64 KiB at maximum)
238 */
239 size_t compressed;
240
241 /*
242 * True if dictionary reset is needed. This is false before
243 * the first chunk (LZMA or uncompressed).
244 */
245 bool need_dict_reset;
246
247 /*
248 * True if new LZMA properties are needed. This is false
249 * before the first LZMA chunk.
250 */
251 bool need_props;
252
253#ifdef XZ_DEC_MICROLZMA
254 bool pedantic_microlzma;
255#endif
256};
257
258struct xz_dec_lzma2 {
259 /*
260 * The order below is important on x86 to reduce code size and
261 * it shouldn't hurt on other platforms. Everything up to and
262 * including lzma.pos_mask are in the first 128 bytes on x86-32,
263 * which allows using smaller instructions to access those
264 * variables. On x86-64, fewer variables fit into the first 128
265 * bytes, but this is still the best order without sacrificing
266 * the readability by splitting the structures.
267 */
268 struct rc_dec rc;
269 struct dictionary dict;
270 struct lzma2_dec lzma2;
271 struct lzma_dec lzma;
272
273 /*
274 * Temporary buffer which holds a small number of input bytes between
275 * decoder calls. See lzma2_lzma() for details.
276 */
277 struct {
278 size_t size;
279 uint8_t buf[3 * LZMA_IN_REQUIRED];
280 } temp;
281};
282
283/**************
284 * Dictionary *
285 **************/
286
287/*
288 * Reset the dictionary state. When in single-call mode, set up the beginning
289 * of the dictionary to point to the actual output buffer.
290 */
291static void dict_reset(struct dictionary *dict, struct xz_buf *b)
292{
293 if (DEC_IS_SINGLE(dict->mode)) {
294 dict->buf = b->out + b->out_pos;
295 dict->end = b->out_size - b->out_pos;
296 }
297
298 dict->start = 0;
299 dict->pos = 0;
300 dict->limit = 0;
301 dict->full = 0;
302}
303
304/* Set dictionary write limit */
305static void dict_limit(struct dictionary *dict, size_t out_max)
306{
307 if (dict->end - dict->pos <= out_max)
308 dict->limit = dict->end;
309 else
310 dict->limit = dict->pos + out_max;
311}
312
313/* Return true if at least one byte can be written into the dictionary. */
314static inline bool dict_has_space(const struct dictionary *dict)
315{
316 return dict->pos < dict->limit;
317}
318
319/*
320 * Get a byte from the dictionary at the given distance. The distance is
321 * assumed to valid, or as a special case, zero when the dictionary is
322 * still empty. This special case is needed for single-call decoding to
323 * avoid writing a '\0' to the end of the destination buffer.
324 */
325static inline uint32_t dict_get(const struct dictionary *dict, size_t dist)
326{
327 size_t offset = dict->pos - dist - 1;
328
329 if (dist >= dict->pos)
330 offset += dict->end;
331
332 return dict->full > 0 ? dict->buf[offset] : 0;
333}
334
335/*
336 * Put one byte into the dictionary. It is assumed that there is space for it.
337 */
338static inline void dict_put(struct dictionary *dict, uint8_t byte)
339{
340 dict->buf[dict->pos++] = byte;
341
342 if (dict->full < dict->pos)
343 dict->full = dict->pos;
344}
345
346/*
347 * Repeat given number of bytes from the given distance. If the distance is
348 * invalid, false is returned. On success, true is returned and *len is
349 * updated to indicate how many bytes were left to be repeated.
350 */
351static bool dict_repeat(struct dictionary *dict, size_t *len, size_t dist)
352{
353 size_t back;
354 size_t left;
355
356 if (dist >= dict->full || dist >= dict->size)
357 return false;
358
359 left = min(dict->limit - dict->pos, *len);
360 *len -= left;
361
362 back = dict->pos - dist - 1;
363 if (dist >= dict->pos)
364 back += dict->end;
365
366 do {
367 dict->buf[dict->pos++] = dict->buf[back++];
368 if (back == dict->end)
369 back = 0;
370 } while (--left > 0);
371
372 if (dict->full < dict->pos)
373 dict->full = dict->pos;
374
375 return true;
376}
377
378/* Copy uncompressed data as is from input to dictionary and output buffers. */
379static void dict_uncompressed(struct dictionary *dict, struct xz_buf *b,
380 size_t *left)
381{
382 size_t copy_size;
383
384 while (*left > 0 && b->in_pos < b->in_size
385 && b->out_pos < b->out_size) {
386 copy_size = min(b->in_size - b->in_pos,
387 b->out_size - b->out_pos);
388 if (copy_size > dict->end - dict->pos)
389 copy_size = dict->end - dict->pos;
390 if (copy_size > *left)
391 copy_size = *left;
392
393 *left -= copy_size;
394
395 /*
396 * If doing in-place decompression in single-call mode and the
397 * uncompressed size of the file is larger than the caller
398 * thought (i.e. it is invalid input!), the buffers below may
399 * overlap and cause undefined behavior with memcpy().
400 * With valid inputs memcpy() would be fine here.
401 */
402 memmove(dict->buf + dict->pos, b->in + b->in_pos, copy_size);
403 dict->pos += copy_size;
404
405 if (dict->full < dict->pos)
406 dict->full = dict->pos;
407
408 if (DEC_IS_MULTI(dict->mode)) {
409 if (dict->pos == dict->end)
410 dict->pos = 0;
411
412 /*
413 * Like above but for multi-call mode: use memmove()
414 * to avoid undefined behavior with invalid input.
415 */
416 memmove(b->out + b->out_pos, b->in + b->in_pos,
417 copy_size);
418 }
419
420 dict->start = dict->pos;
421
422 b->out_pos += copy_size;
423 b->in_pos += copy_size;
424 }
425}
426
427#ifdef XZ_DEC_MICROLZMA
428# define DICT_FLUSH_SUPPORTS_SKIPPING true
429#else
430# define DICT_FLUSH_SUPPORTS_SKIPPING false
431#endif
432
433/*
434 * Flush pending data from dictionary to b->out. It is assumed that there is
435 * enough space in b->out. This is guaranteed because caller uses dict_limit()
436 * before decoding data into the dictionary.
437 */
438static size_t dict_flush(struct dictionary *dict, struct xz_buf *b)
439{
440 size_t copy_size = dict->pos - dict->start;
441
442 if (DEC_IS_MULTI(dict->mode)) {
443 if (dict->pos == dict->end)
444 dict->pos = 0;
445
446 /*
447 * These buffers cannot overlap even if doing in-place
448 * decompression because in multi-call mode dict->buf
449 * has been allocated by us in this file; it's not
450 * provided by the caller like in single-call mode.
451 *
452 * With MicroLZMA, b->out can be NULL to skip bytes that
453 * the caller doesn't need. This cannot be done with XZ
454 * because it would break BCJ filters.
455 */
456 if (!DICT_FLUSH_SUPPORTS_SKIPPING || b->out != NULL)
457 memcpy(b->out + b->out_pos, dict->buf + dict->start,
458 copy_size);
459 }
460
461 dict->start = dict->pos;
462 b->out_pos += copy_size;
463 return copy_size;
464}
465
466/*****************
467 * Range decoder *
468 *****************/
469
470/* Reset the range decoder. */
471static void rc_reset(struct rc_dec *rc)
472{
473 rc->range = (uint32_t)-1;
474 rc->code = 0;
475 rc->init_bytes_left = RC_INIT_BYTES;
476}
477
478/*
479 * Read the first five initial bytes into rc->code if they haven't been
480 * read already. (Yes, the first byte gets completely ignored.)
481 */
482static bool rc_read_init(struct rc_dec *rc, struct xz_buf *b)
483{
484 while (rc->init_bytes_left > 0) {
485 if (b->in_pos == b->in_size)
486 return false;
487
488 rc->code = (rc->code << 8) + b->in[b->in_pos++];
489 --rc->init_bytes_left;
490 }
491
492 return true;
493}
494
495/* Return true if there may not be enough input for the next decoding loop. */
496static inline bool rc_limit_exceeded(const struct rc_dec *rc)
497{
498 return rc->in_pos > rc->in_limit;
499}
500
501/*
502 * Return true if it is possible (from point of view of range decoder) that
503 * we have reached the end of the LZMA chunk.
504 */
505static inline bool rc_is_finished(const struct rc_dec *rc)
506{
507 return rc->code == 0;
508}
509
510/* Read the next input byte if needed. */
511static __always_inline void rc_normalize(struct rc_dec *rc)
512{
513 if (rc->range < RC_TOP_VALUE) {
514 rc->range <<= RC_SHIFT_BITS;
515 rc->code = (rc->code << RC_SHIFT_BITS) + rc->in[rc->in_pos++];
516 }
517}
518
519/*
520 * Decode one bit. In some versions, this function has been split in three
521 * functions so that the compiler is supposed to be able to more easily avoid
522 * an extra branch. In this particular version of the LZMA decoder, this
523 * doesn't seem to be a good idea (tested with GCC 3.3.6, 3.4.6, and 4.3.3
524 * on x86). Using a non-split version results in nicer looking code too.
525 *
526 * NOTE: This must return an int. Do not make it return a bool or the speed
527 * of the code generated by GCC 3.x decreases 10-15 %. (GCC 4.3 doesn't care,
528 * and it generates 10-20 % faster code than GCC 3.x from this file anyway.)
529 */
530static __always_inline int rc_bit(struct rc_dec *rc, uint16_t *prob)
531{
532 uint32_t bound;
533 int bit;
534
535 rc_normalize(rc);
536 bound = (rc->range >> RC_BIT_MODEL_TOTAL_BITS) * *prob;
537 if (rc->code < bound) {
538 rc->range = bound;
539 *prob += (RC_BIT_MODEL_TOTAL - *prob) >> RC_MOVE_BITS;
540 bit = 0;
541 } else {
542 rc->range -= bound;
543 rc->code -= bound;
544 *prob -= *prob >> RC_MOVE_BITS;
545 bit = 1;
546 }
547
548 return bit;
549}
550
551/* Decode a bittree starting from the most significant bit. */
552static __always_inline uint32_t rc_bittree(struct rc_dec *rc,
553 uint16_t *probs, uint32_t limit)
554{
555 uint32_t symbol = 1;
556
557 do {
558 if (rc_bit(rc, &probs[symbol]))
559 symbol = (symbol << 1) + 1;
560 else
561 symbol <<= 1;
562 } while (symbol < limit);
563
564 return symbol;
565}
566
567/* Decode a bittree starting from the least significant bit. */
568static __always_inline void rc_bittree_reverse(struct rc_dec *rc,
569 uint16_t *probs,
570 uint32_t *dest, uint32_t limit)
571{
572 uint32_t symbol = 1;
573 uint32_t i = 0;
574
575 do {
576 if (rc_bit(rc, &probs[symbol])) {
577 symbol = (symbol << 1) + 1;
578 *dest += 1 << i;
579 } else {
580 symbol <<= 1;
581 }
582 } while (++i < limit);
583}
584
585/* Decode direct bits (fixed fifty-fifty probability) */
586static inline void rc_direct(struct rc_dec *rc, uint32_t *dest, uint32_t limit)
587{
588 uint32_t mask;
589
590 do {
591 rc_normalize(rc);
592 rc->range >>= 1;
593 rc->code -= rc->range;
594 mask = (uint32_t)0 - (rc->code >> 31);
595 rc->code += rc->range & mask;
596 *dest = (*dest << 1) + (mask + 1);
597 } while (--limit > 0);
598}
599
600/********
601 * LZMA *
602 ********/
603
604/* Get pointer to literal coder probability array. */
605static uint16_t *lzma_literal_probs(struct xz_dec_lzma2 *s)
606{
607 uint32_t prev_byte = dict_get(&s->dict, 0);
608 uint32_t low = prev_byte >> (8 - s->lzma.lc);
609 uint32_t high = (s->dict.pos & s->lzma.literal_pos_mask) << s->lzma.lc;
610 return s->lzma.literal[low + high];
611}
612
613/* Decode a literal (one 8-bit byte) */
614static void lzma_literal(struct xz_dec_lzma2 *s)
615{
616 uint16_t *probs;
617 uint32_t symbol;
618 uint32_t match_byte;
619 uint32_t match_bit;
620 uint32_t offset;
621 uint32_t i;
622
623 probs = lzma_literal_probs(s);
624
625 if (lzma_state_is_literal(s->lzma.state)) {
626 symbol = rc_bittree(&s->rc, probs, 0x100);
627 } else {
628 symbol = 1;
629 match_byte = dict_get(&s->dict, s->lzma.rep0) << 1;
630 offset = 0x100;
631
632 do {
633 match_bit = match_byte & offset;
634 match_byte <<= 1;
635 i = offset + match_bit + symbol;
636
637 if (rc_bit(&s->rc, &probs[i])) {
638 symbol = (symbol << 1) + 1;
639 offset &= match_bit;
640 } else {
641 symbol <<= 1;
642 offset &= ~match_bit;
643 }
644 } while (symbol < 0x100);
645 }
646
647 dict_put(&s->dict, (uint8_t)symbol);
648 lzma_state_literal(&s->lzma.state);
649}
650
651/* Decode the length of the match into s->lzma.len. */
652static void lzma_len(struct xz_dec_lzma2 *s, struct lzma_len_dec *l,
653 uint32_t pos_state)
654{
655 uint16_t *probs;
656 uint32_t limit;
657
658 if (!rc_bit(&s->rc, &l->choice)) {
659 probs = l->low[pos_state];
660 limit = LEN_LOW_SYMBOLS;
661 s->lzma.len = MATCH_LEN_MIN;
662 } else {
663 if (!rc_bit(&s->rc, &l->choice2)) {
664 probs = l->mid[pos_state];
665 limit = LEN_MID_SYMBOLS;
666 s->lzma.len = MATCH_LEN_MIN + LEN_LOW_SYMBOLS;
667 } else {
668 probs = l->high;
669 limit = LEN_HIGH_SYMBOLS;
670 s->lzma.len = MATCH_LEN_MIN + LEN_LOW_SYMBOLS
671 + LEN_MID_SYMBOLS;
672 }
673 }
674
675 s->lzma.len += rc_bittree(&s->rc, probs, limit) - limit;
676}
677
678/* Decode a match. The distance will be stored in s->lzma.rep0. */
679static void lzma_match(struct xz_dec_lzma2 *s, uint32_t pos_state)
680{
681 uint16_t *probs;
682 uint32_t dist_slot;
683 uint32_t limit;
684
685 lzma_state_match(&s->lzma.state);
686
687 s->lzma.rep3 = s->lzma.rep2;
688 s->lzma.rep2 = s->lzma.rep1;
689 s->lzma.rep1 = s->lzma.rep0;
690
691 lzma_len(s, &s->lzma.match_len_dec, pos_state);
692
693 probs = s->lzma.dist_slot[lzma_get_dist_state(s->lzma.len)];
694 dist_slot = rc_bittree(&s->rc, probs, DIST_SLOTS) - DIST_SLOTS;
695
696 if (dist_slot < DIST_MODEL_START) {
697 s->lzma.rep0 = dist_slot;
698 } else {
699 limit = (dist_slot >> 1) - 1;
700 s->lzma.rep0 = 2 + (dist_slot & 1);
701
702 if (dist_slot < DIST_MODEL_END) {
703 s->lzma.rep0 <<= limit;
704 probs = s->lzma.dist_special + s->lzma.rep0
705 - dist_slot - 1;
706 rc_bittree_reverse(&s->rc, probs,
707 &s->lzma.rep0, limit);
708 } else {
709 rc_direct(&s->rc, &s->lzma.rep0, limit - ALIGN_BITS);
710 s->lzma.rep0 <<= ALIGN_BITS;
711 rc_bittree_reverse(&s->rc, s->lzma.dist_align,
712 &s->lzma.rep0, ALIGN_BITS);
713 }
714 }
715}
716
717/*
718 * Decode a repeated match. The distance is one of the four most recently
719 * seen matches. The distance will be stored in s->lzma.rep0.
720 */
721static void lzma_rep_match(struct xz_dec_lzma2 *s, uint32_t pos_state)
722{
723 uint32_t tmp;
724
725 if (!rc_bit(&s->rc, &s->lzma.is_rep0[s->lzma.state])) {
726 if (!rc_bit(&s->rc, &s->lzma.is_rep0_long[
727 s->lzma.state][pos_state])) {
728 lzma_state_short_rep(&s->lzma.state);
729 s->lzma.len = 1;
730 return;
731 }
732 } else {
733 if (!rc_bit(&s->rc, &s->lzma.is_rep1[s->lzma.state])) {
734 tmp = s->lzma.rep1;
735 } else {
736 if (!rc_bit(&s->rc, &s->lzma.is_rep2[s->lzma.state])) {
737 tmp = s->lzma.rep2;
738 } else {
739 tmp = s->lzma.rep3;
740 s->lzma.rep3 = s->lzma.rep2;
741 }
742
743 s->lzma.rep2 = s->lzma.rep1;
744 }
745
746 s->lzma.rep1 = s->lzma.rep0;
747 s->lzma.rep0 = tmp;
748 }
749
750 lzma_state_long_rep(&s->lzma.state);
751 lzma_len(s, &s->lzma.rep_len_dec, pos_state);
752}
753
754/* LZMA decoder core */
755static bool lzma_main(struct xz_dec_lzma2 *s)
756{
757 uint32_t pos_state;
758
759 /*
760 * If the dictionary write limit was reached during the previous call,
761 * try to finish the possibly pending repeat in the dictionary.
762 */
763 if (dict_has_space(&s->dict) && s->lzma.len > 0)
764 dict_repeat(&s->dict, &s->lzma.len, s->lzma.rep0);
765
766 /*
767 * Decode more LZMA symbols. One iteration may consume up to
768 * LZMA_IN_REQUIRED - 1 bytes.
769 */
770 while (dict_has_space(&s->dict) && !rc_limit_exceeded(&s->rc)) {
771 pos_state = s->dict.pos & s->lzma.pos_mask;
772
773 if (!rc_bit(&s->rc, &s->lzma.is_match[
774 s->lzma.state][pos_state])) {
775 lzma_literal(s);
776 } else {
777 if (rc_bit(&s->rc, &s->lzma.is_rep[s->lzma.state]))
778 lzma_rep_match(s, pos_state);
779 else
780 lzma_match(s, pos_state);
781
782 if (!dict_repeat(&s->dict, &s->lzma.len, s->lzma.rep0))
783 return false;
784 }
785 }
786
787 /*
788 * Having the range decoder always normalized when we are outside
789 * this function makes it easier to correctly handle end of the chunk.
790 */
791 rc_normalize(&s->rc);
792
793 return true;
794}
795
796/*
797 * Reset the LZMA decoder and range decoder state. Dictionary is not reset
798 * here, because LZMA state may be reset without resetting the dictionary.
799 */
800static void lzma_reset(struct xz_dec_lzma2 *s)
801{
802 uint16_t *probs;
803 size_t i;
804
805 s->lzma.state = STATE_LIT_LIT;
806 s->lzma.rep0 = 0;
807 s->lzma.rep1 = 0;
808 s->lzma.rep2 = 0;
809 s->lzma.rep3 = 0;
810 s->lzma.len = 0;
811
812 /*
813 * All probabilities are initialized to the same value. This hack
814 * makes the code smaller by avoiding a separate loop for each
815 * probability array.
816 *
817 * This could be optimized so that only that part of literal
818 * probabilities that are actually required. In the common case
819 * we would write 12 KiB less.
820 */
821 probs = s->lzma.is_match[0];
822 for (i = 0; i < PROBS_TOTAL; ++i)
823 probs[i] = RC_BIT_MODEL_TOTAL / 2;
824
825 rc_reset(&s->rc);
826}
827
828/*
829 * Decode and validate LZMA properties (lc/lp/pb) and calculate the bit masks
830 * from the decoded lp and pb values. On success, the LZMA decoder state is
831 * reset and true is returned.
832 */
833static bool lzma_props(struct xz_dec_lzma2 *s, uint8_t props)
834{
835 if (props > (4 * 5 + 4) * 9 + 8)
836 return false;
837
838 s->lzma.pos_mask = 0;
839 while (props >= 9 * 5) {
840 props -= 9 * 5;
841 ++s->lzma.pos_mask;
842 }
843
844 s->lzma.pos_mask = (1 << s->lzma.pos_mask) - 1;
845
846 s->lzma.literal_pos_mask = 0;
847 while (props >= 9) {
848 props -= 9;
849 ++s->lzma.literal_pos_mask;
850 }
851
852 s->lzma.lc = props;
853
854 if (s->lzma.lc + s->lzma.literal_pos_mask > 4)
855 return false;
856
857 s->lzma.literal_pos_mask = (1 << s->lzma.literal_pos_mask) - 1;
858
859 lzma_reset(s);
860
861 return true;
862}
863
864/*********
865 * LZMA2 *
866 *********/
867
868/*
869 * The LZMA decoder assumes that if the input limit (s->rc.in_limit) hasn't
870 * been exceeded, it is safe to read up to LZMA_IN_REQUIRED bytes. This
871 * wrapper function takes care of making the LZMA decoder's assumption safe.
872 *
873 * As long as there is plenty of input left to be decoded in the current LZMA
874 * chunk, we decode directly from the caller-supplied input buffer until
875 * there's LZMA_IN_REQUIRED bytes left. Those remaining bytes are copied into
876 * s->temp.buf, which (hopefully) gets filled on the next call to this
877 * function. We decode a few bytes from the temporary buffer so that we can
878 * continue decoding from the caller-supplied input buffer again.
879 */
880static bool lzma2_lzma(struct xz_dec_lzma2 *s, struct xz_buf *b)
881{
882 size_t in_avail;
883 size_t tmp;
884
885 in_avail = b->in_size - b->in_pos;
886 if (s->temp.size > 0 || s->lzma2.compressed == 0) {
887 tmp = 2 * LZMA_IN_REQUIRED - s->temp.size;
888 if (tmp > s->lzma2.compressed - s->temp.size)
889 tmp = s->lzma2.compressed - s->temp.size;
890 if (tmp > in_avail)
891 tmp = in_avail;
892
893 memcpy(s->temp.buf + s->temp.size, b->in + b->in_pos, tmp);
894
895 if (s->temp.size + tmp == s->lzma2.compressed) {
896 memzero(s->temp.buf + s->temp.size + tmp,
897 sizeof(s->temp.buf)
898 - s->temp.size - tmp);
899 s->rc.in_limit = s->temp.size + tmp;
900 } else if (s->temp.size + tmp < LZMA_IN_REQUIRED) {
901 s->temp.size += tmp;
902 b->in_pos += tmp;
903 return true;
904 } else {
905 s->rc.in_limit = s->temp.size + tmp - LZMA_IN_REQUIRED;
906 }
907
908 s->rc.in = s->temp.buf;
909 s->rc.in_pos = 0;
910
911 if (!lzma_main(s) || s->rc.in_pos > s->temp.size + tmp)
912 return false;
913
914 s->lzma2.compressed -= s->rc.in_pos;
915
916 if (s->rc.in_pos < s->temp.size) {
917 s->temp.size -= s->rc.in_pos;
918 memmove(s->temp.buf, s->temp.buf + s->rc.in_pos,
919 s->temp.size);
920 return true;
921 }
922
923 b->in_pos += s->rc.in_pos - s->temp.size;
924 s->temp.size = 0;
925 }
926
927 in_avail = b->in_size - b->in_pos;
928 if (in_avail >= LZMA_IN_REQUIRED) {
929 s->rc.in = b->in;
930 s->rc.in_pos = b->in_pos;
931
932 if (in_avail >= s->lzma2.compressed + LZMA_IN_REQUIRED)
933 s->rc.in_limit = b->in_pos + s->lzma2.compressed;
934 else
935 s->rc.in_limit = b->in_size - LZMA_IN_REQUIRED;
936
937 if (!lzma_main(s))
938 return false;
939
940 in_avail = s->rc.in_pos - b->in_pos;
941 if (in_avail > s->lzma2.compressed)
942 return false;
943
944 s->lzma2.compressed -= in_avail;
945 b->in_pos = s->rc.in_pos;
946 }
947
948 in_avail = b->in_size - b->in_pos;
949 if (in_avail < LZMA_IN_REQUIRED) {
950 if (in_avail > s->lzma2.compressed)
951 in_avail = s->lzma2.compressed;
952
953 memcpy(s->temp.buf, b->in + b->in_pos, in_avail);
954 s->temp.size = in_avail;
955 b->in_pos += in_avail;
956 }
957
958 return true;
959}
960
961/*
962 * Take care of the LZMA2 control layer, and forward the job of actual LZMA
963 * decoding or copying of uncompressed chunks to other functions.
964 */
965enum xz_ret xz_dec_lzma2_run(struct xz_dec_lzma2 *s, struct xz_buf *b)
966{
967 uint32_t tmp;
968
969 while (b->in_pos < b->in_size || s->lzma2.sequence == SEQ_LZMA_RUN) {
970 switch (s->lzma2.sequence) {
971 case SEQ_CONTROL:
972 /*
973 * LZMA2 control byte
974 *
975 * Exact values:
976 * 0x00 End marker
977 * 0x01 Dictionary reset followed by
978 * an uncompressed chunk
979 * 0x02 Uncompressed chunk (no dictionary reset)
980 *
981 * Highest three bits (tmp & 0xE0):
982 * 0xE0 Dictionary reset, new properties and state
983 * reset, followed by LZMA compressed chunk
984 * 0xC0 New properties and state reset, followed
985 * by LZMA compressed chunk (no dictionary
986 * reset)
987 * 0xA0 State reset using old properties,
988 * followed by LZMA compressed chunk (no
989 * dictionary reset)
990 * 0x80 LZMA chunk (no dictionary or state reset)
991 *
992 * For LZMA compressed chunks, the lowest five bits
993 * (tmp & 1F) are the highest bits of the
994 * uncompressed size (bits 16-20).
995 *
996 * A new LZMA2 stream must begin with a dictionary
997 * reset. The first LZMA chunk must set new
998 * properties and reset the LZMA state.
999 *
1000 * Values that don't match anything described above
1001 * are invalid and we return XZ_DATA_ERROR.
1002 */
1003 tmp = b->in[b->in_pos++];
1004
1005 if (tmp == 0x00)
1006 return XZ_STREAM_END;
1007
1008 if (tmp >= 0xE0 || tmp == 0x01) {
1009 s->lzma2.need_props = true;
1010 s->lzma2.need_dict_reset = false;
1011 dict_reset(&s->dict, b);
1012 } else if (s->lzma2.need_dict_reset) {
1013 return XZ_DATA_ERROR;
1014 }
1015
1016 if (tmp >= 0x80) {
1017 s->lzma2.uncompressed = (tmp & 0x1F) << 16;
1018 s->lzma2.sequence = SEQ_UNCOMPRESSED_1;
1019
1020 if (tmp >= 0xC0) {
1021 /*
1022 * When there are new properties,
1023 * state reset is done at
1024 * SEQ_PROPERTIES.
1025 */
1026 s->lzma2.need_props = false;
1027 s->lzma2.next_sequence
1028 = SEQ_PROPERTIES;
1029
1030 } else if (s->lzma2.need_props) {
1031 return XZ_DATA_ERROR;
1032
1033 } else {
1034 s->lzma2.next_sequence
1035 = SEQ_LZMA_PREPARE;
1036 if (tmp >= 0xA0)
1037 lzma_reset(s);
1038 }
1039 } else {
1040 if (tmp > 0x02)
1041 return XZ_DATA_ERROR;
1042
1043 s->lzma2.sequence = SEQ_COMPRESSED_0;
1044 s->lzma2.next_sequence = SEQ_COPY;
1045 }
1046
1047 break;
1048
1049 case SEQ_UNCOMPRESSED_1:
1050 s->lzma2.uncompressed
1051 += (size_t)b->in[b->in_pos++] << 8;
1052 s->lzma2.sequence = SEQ_UNCOMPRESSED_2;
1053 break;
1054
1055 case SEQ_UNCOMPRESSED_2:
1056 s->lzma2.uncompressed
1057 += (size_t)b->in[b->in_pos++] + 1;
1058 s->lzma2.sequence = SEQ_COMPRESSED_0;
1059 break;
1060
1061 case SEQ_COMPRESSED_0:
1062 s->lzma2.compressed = (size_t)b->in[b->in_pos++] << 8;
1063 s->lzma2.sequence = SEQ_COMPRESSED_1;
1064 break;
1065
1066 case SEQ_COMPRESSED_1:
1067 s->lzma2.compressed += (size_t)b->in[b->in_pos++] + 1;
1068 s->lzma2.sequence = s->lzma2.next_sequence;
1069 break;
1070
1071 case SEQ_PROPERTIES:
1072 if (!lzma_props(s, b->in[b->in_pos++]))
1073 return XZ_DATA_ERROR;
1074
1075 s->lzma2.sequence = SEQ_LZMA_PREPARE;
1076
1077 fallthrough;
1078
1079 case SEQ_LZMA_PREPARE:
1080 if (s->lzma2.compressed < RC_INIT_BYTES)
1081 return XZ_DATA_ERROR;
1082
1083 if (!rc_read_init(&s->rc, b))
1084 return XZ_OK;
1085
1086 s->lzma2.compressed -= RC_INIT_BYTES;
1087 s->lzma2.sequence = SEQ_LZMA_RUN;
1088
1089 fallthrough;
1090
1091 case SEQ_LZMA_RUN:
1092 /*
1093 * Set dictionary limit to indicate how much we want
1094 * to be decoded at maximum. Decode new data into the
1095 * dictionary. Flush the new data from dictionary to
1096 * b->out. Check if we finished decoding this chunk.
1097 * In case the dictionary got full but we didn't fill
1098 * the output buffer yet, we may run this loop
1099 * multiple times without changing s->lzma2.sequence.
1100 */
1101 dict_limit(&s->dict, min(b->out_size - b->out_pos,
1102 s->lzma2.uncompressed));
1103 if (!lzma2_lzma(s, b))
1104 return XZ_DATA_ERROR;
1105
1106 s->lzma2.uncompressed -= dict_flush(&s->dict, b);
1107
1108 if (s->lzma2.uncompressed == 0) {
1109 if (s->lzma2.compressed > 0 || s->lzma.len > 0
1110 || !rc_is_finished(&s->rc))
1111 return XZ_DATA_ERROR;
1112
1113 rc_reset(&s->rc);
1114 s->lzma2.sequence = SEQ_CONTROL;
1115
1116 } else if (b->out_pos == b->out_size
1117 || (b->in_pos == b->in_size
1118 && s->temp.size
1119 < s->lzma2.compressed)) {
1120 return XZ_OK;
1121 }
1122
1123 break;
1124
1125 case SEQ_COPY:
1126 dict_uncompressed(&s->dict, b, &s->lzma2.compressed);
1127 if (s->lzma2.compressed > 0)
1128 return XZ_OK;
1129
1130 s->lzma2.sequence = SEQ_CONTROL;
1131 break;
1132 }
1133 }
1134
1135 return XZ_OK;
1136}
1137
1138struct xz_dec_lzma2 *xz_dec_lzma2_create(enum xz_mode mode, uint32_t dict_max)
1139{
1140 struct xz_dec_lzma2 *s = kmalloc_obj(*s);
1141 if (s == NULL)
1142 return NULL;
1143
1144 s->dict.mode = mode;
1145 s->dict.size_max = dict_max;
1146
1147 if (DEC_IS_PREALLOC(mode)) {
1148 s->dict.buf = vmalloc(dict_max);
1149 if (s->dict.buf == NULL) {
1150 kfree(s);
1151 return NULL;
1152 }
1153 } else if (DEC_IS_DYNALLOC(mode)) {
1154 s->dict.buf = NULL;
1155 s->dict.allocated = 0;
1156 }
1157
1158 return s;
1159}
1160
1161enum xz_ret xz_dec_lzma2_reset(struct xz_dec_lzma2 *s, uint8_t props)
1162{
1163 /* This limits dictionary size to 3 GiB to keep parsing simpler. */
1164 if (props > 39)
1165 return XZ_OPTIONS_ERROR;
1166
1167 s->dict.size = 2 + (props & 1);
1168 s->dict.size <<= (props >> 1) + 11;
1169
1170 if (DEC_IS_MULTI(s->dict.mode)) {
1171 if (s->dict.size > s->dict.size_max)
1172 return XZ_MEMLIMIT_ERROR;
1173
1174 s->dict.end = s->dict.size;
1175
1176 if (DEC_IS_DYNALLOC(s->dict.mode)) {
1177 if (s->dict.allocated < s->dict.size) {
1178 s->dict.allocated = s->dict.size;
1179 vfree(s->dict.buf);
1180 s->dict.buf = vmalloc(s->dict.size);
1181 if (s->dict.buf == NULL) {
1182 s->dict.allocated = 0;
1183 return XZ_MEM_ERROR;
1184 }
1185 }
1186 }
1187 }
1188
1189 s->lzma2.sequence = SEQ_CONTROL;
1190 s->lzma2.need_dict_reset = true;
1191
1192 s->temp.size = 0;
1193
1194 return XZ_OK;
1195}
1196
1197void xz_dec_lzma2_end(struct xz_dec_lzma2 *s)
1198{
1199 if (DEC_IS_MULTI(s->dict.mode))
1200 vfree(s->dict.buf);
1201
1202 kfree(s);
1203}
1204
1205#ifdef XZ_DEC_MICROLZMA
1206/* This is a wrapper struct to have a nice struct name in the public API. */
1207struct xz_dec_microlzma {
1208 struct xz_dec_lzma2 s;
1209};
1210
1211enum xz_ret xz_dec_microlzma_run(struct xz_dec_microlzma *s_ptr,
1212 struct xz_buf *b)
1213{
1214 struct xz_dec_lzma2 *s = &s_ptr->s;
1215
1216 /*
1217 * sequence is SEQ_PROPERTIES before the first input byte,
1218 * SEQ_LZMA_PREPARE until a total of five bytes have been read,
1219 * and SEQ_LZMA_RUN for the rest of the input stream.
1220 */
1221 if (s->lzma2.sequence != SEQ_LZMA_RUN) {
1222 if (s->lzma2.sequence == SEQ_PROPERTIES) {
1223 /* One byte is needed for the props. */
1224 if (b->in_pos >= b->in_size)
1225 return XZ_OK;
1226
1227 /*
1228 * Don't increment b->in_pos here. The same byte is
1229 * also passed to rc_read_init() which will ignore it.
1230 */
1231 if (!lzma_props(s, ~b->in[b->in_pos]))
1232 return XZ_DATA_ERROR;
1233
1234 s->lzma2.sequence = SEQ_LZMA_PREPARE;
1235 }
1236
1237 /*
1238 * xz_dec_microlzma_reset() doesn't validate the compressed
1239 * size so we do it here. We have to limit the maximum size
1240 * to avoid integer overflows in lzma2_lzma(). 3 GiB is a nice
1241 * round number and much more than users of this code should
1242 * ever need.
1243 */
1244 if (s->lzma2.compressed < RC_INIT_BYTES
1245 || s->lzma2.compressed > (3U << 30))
1246 return XZ_DATA_ERROR;
1247
1248 if (!rc_read_init(&s->rc, b))
1249 return XZ_OK;
1250
1251 s->lzma2.compressed -= RC_INIT_BYTES;
1252 s->lzma2.sequence = SEQ_LZMA_RUN;
1253
1254 dict_reset(&s->dict, b);
1255 }
1256
1257 /* This is to allow increasing b->out_size between calls. */
1258 if (DEC_IS_SINGLE(s->dict.mode))
1259 s->dict.end = b->out_size - b->out_pos;
1260
1261 while (true) {
1262 dict_limit(&s->dict, min(b->out_size - b->out_pos,
1263 s->lzma2.uncompressed));
1264
1265 if (!lzma2_lzma(s, b))
1266 return XZ_DATA_ERROR;
1267
1268 s->lzma2.uncompressed -= dict_flush(&s->dict, b);
1269
1270 if (s->lzma2.uncompressed == 0) {
1271 if (s->lzma2.pedantic_microlzma) {
1272 if (s->lzma2.compressed > 0 || s->lzma.len > 0
1273 || !rc_is_finished(&s->rc))
1274 return XZ_DATA_ERROR;
1275 }
1276
1277 return XZ_STREAM_END;
1278 }
1279
1280 if (b->out_pos == b->out_size)
1281 return XZ_OK;
1282
1283 if (b->in_pos == b->in_size
1284 && s->temp.size < s->lzma2.compressed)
1285 return XZ_OK;
1286 }
1287}
1288
1289struct xz_dec_microlzma *xz_dec_microlzma_alloc(enum xz_mode mode,
1290 uint32_t dict_size)
1291{
1292 struct xz_dec_microlzma *s;
1293
1294 /* Restrict dict_size to the same range as in the LZMA2 code. */
1295 if (dict_size < 4096 || dict_size > (3U << 30))
1296 return NULL;
1297
1298 s = kmalloc_obj(*s);
1299 if (s == NULL)
1300 return NULL;
1301
1302 s->s.dict.mode = mode;
1303 s->s.dict.size = dict_size;
1304
1305 if (DEC_IS_MULTI(mode)) {
1306 s->s.dict.end = dict_size;
1307
1308 s->s.dict.buf = vmalloc(dict_size);
1309 if (s->s.dict.buf == NULL) {
1310 kfree(s);
1311 return NULL;
1312 }
1313 }
1314
1315 return s;
1316}
1317
1318void xz_dec_microlzma_reset(struct xz_dec_microlzma *s, uint32_t comp_size,
1319 uint32_t uncomp_size, int uncomp_size_is_exact)
1320{
1321 /*
1322 * comp_size is validated in xz_dec_microlzma_run().
1323 * uncomp_size can safely be anything.
1324 */
1325 s->s.lzma2.compressed = comp_size;
1326 s->s.lzma2.uncompressed = uncomp_size;
1327 s->s.lzma2.pedantic_microlzma = uncomp_size_is_exact;
1328
1329 s->s.lzma2.sequence = SEQ_PROPERTIES;
1330 s->s.temp.size = 0;
1331}
1332
1333void xz_dec_microlzma_end(struct xz_dec_microlzma *s)
1334{
1335 if (DEC_IS_MULTI(s->s.dict.mode))
1336 vfree(s->s.dict.buf);
1337
1338 kfree(s);
1339}
1340#endif