xz_dec_lzma2.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176
  1. /*
  2. * LZMA2 decoder
  3. *
  4. * Authors: Lasse Collin <lasse.collin@tukaani.org>
  5. * Igor Pavlov <http://7-zip.org/>
  6. *
  7. * This file has been put into the public domain.
  8. * You can do whatever you want with this file.
  9. */
  10. #include "xz_private.h"
  11. #include "xz_lzma2.h"
  12. /*
  13. * Range decoder initialization eats the first five bytes of each LZMA chunk.
  14. */
  15. #define RC_INIT_BYTES 5
  16. /*
  17. * Minimum number of usable input buffer to safely decode one LZMA symbol.
  18. * The worst case is that we decode 22 bits using probabilities and 26
  19. * direct bits. This may decode at maximum of 20 bytes of input. However,
  20. * lzma_main() does an extra normalization before returning, thus we
  21. * need to put 21 here.
  22. */
  23. #define LZMA_IN_REQUIRED 21
  24. /*
  25. * Dictionary (history buffer)
  26. *
  27. * These are always true:
  28. * start <= pos <= full <= end
  29. * pos <= limit <= end
  30. *
  31. * In multi-call mode, also these are true:
  32. * end == size
  33. * size <= size_max
  34. * allocated <= size
  35. *
  36. * Most of these variables are size_t to support single-call mode,
  37. * in which the dictionary variables address the actual output
  38. * buffer directly.
  39. */
  40. struct dictionary {
  41. /* Beginning of the history buffer */
  42. uint8_t *buf;
  43. /* Old position in buf (before decoding more data) */
  44. size_t start;
  45. /* Position in buf */
  46. size_t pos;
  47. /*
  48. * How full dictionary is. This is used to detect corrupt input that
  49. * would read beyond the beginning of the uncompressed stream.
  50. */
  51. size_t full;
  52. /* Write limit; we don't write to buf[limit] or later bytes. */
  53. size_t limit;
  54. /*
  55. * End of the dictionary buffer. In multi-call mode, this is
  56. * the same as the dictionary size. In single-call mode, this
  57. * indicates the size of the output buffer.
  58. */
  59. size_t end;
  60. /*
  61. * Size of the dictionary as specified in Block Header. This is used
  62. * together with "full" to detect corrupt input that would make us
  63. * read beyond the beginning of the uncompressed stream.
  64. */
  65. uint32_t size;
  66. /*
  67. * Maximum allowed dictionary size in multi-call mode.
  68. * This is ignored in single-call mode.
  69. */
  70. uint32_t size_max;
  71. /*
  72. * Amount of memory currently allocated for the dictionary.
  73. * This is used only with XZ_DYNALLOC. (With XZ_PREALLOC,
  74. * size_max is always the same as the allocated size.)
  75. */
  76. uint32_t allocated;
  77. /* Operation mode */
  78. enum xz_mode mode;
  79. };
  80. /* Range decoder */
  81. struct rc_dec {
  82. uint32_t range;
  83. uint32_t code;
  84. /*
  85. * Number of initializing bytes remaining to be read
  86. * by rc_read_init().
  87. */
  88. uint32_t init_bytes_left;
  89. /*
  90. * Buffer from which we read our input. It can be either
  91. * temp.buf or the caller-provided input buffer.
  92. */
  93. const uint8_t *in;
  94. size_t in_pos;
  95. size_t in_limit;
  96. };
  97. /* Probabilities for a length decoder. */
  98. struct lzma_len_dec {
  99. /* Probability of match length being at least 10 */
  100. uint16_t choice;
  101. /* Probability of match length being at least 18 */
  102. uint16_t choice2;
  103. /* Probabilities for match lengths 2-9 */
  104. uint16_t low[POS_STATES_MAX][LEN_LOW_SYMBOLS];
  105. /* Probabilities for match lengths 10-17 */
  106. uint16_t mid[POS_STATES_MAX][LEN_MID_SYMBOLS];
  107. /* Probabilities for match lengths 18-273 */
  108. uint16_t high[LEN_HIGH_SYMBOLS];
  109. };
  110. struct lzma_dec {
  111. /* Distances of latest four matches */
  112. uint32_t rep0;
  113. uint32_t rep1;
  114. uint32_t rep2;
  115. uint32_t rep3;
  116. /* Types of the most recently seen LZMA symbols */
  117. enum lzma_state state;
  118. /*
  119. * Length of a match. This is updated so that dict_repeat can
  120. * be called again to finish repeating the whole match.
  121. */
  122. uint32_t len;
  123. /*
  124. * LZMA properties or related bit masks (number of literal
  125. * context bits, a mask dervied from the number of literal
  126. * position bits, and a mask dervied from the number
  127. * position bits)
  128. */
  129. uint32_t lc;
  130. uint32_t literal_pos_mask; /* (1 << lp) - 1 */
  131. uint32_t pos_mask; /* (1 << pb) - 1 */
  132. /* If 1, it's a match. Otherwise it's a single 8-bit literal. */
  133. uint16_t is_match[STATES][POS_STATES_MAX];
  134. /* If 1, it's a repeated match. The distance is one of rep0 .. rep3. */
  135. uint16_t is_rep[STATES];
  136. /*
  137. * If 0, distance of a repeated match is rep0.
  138. * Otherwise check is_rep1.
  139. */
  140. uint16_t is_rep0[STATES];
  141. /*
  142. * If 0, distance of a repeated match is rep1.
  143. * Otherwise check is_rep2.
  144. */
  145. uint16_t is_rep1[STATES];
  146. /* If 0, distance of a repeated match is rep2. Otherwise it is rep3. */
  147. uint16_t is_rep2[STATES];
  148. /*
  149. * If 1, the repeated match has length of one byte. Otherwise
  150. * the length is decoded from rep_len_decoder.
  151. */
  152. uint16_t is_rep0_long[STATES][POS_STATES_MAX];
  153. /*
  154. * Probability tree for the highest two bits of the match
  155. * distance. There is a separate probability tree for match
  156. * lengths of 2 (i.e. MATCH_LEN_MIN), 3, 4, and [5, 273].
  157. */
  158. uint16_t dist_slot[DIST_STATES][DIST_SLOTS];
  159. /*
  160. * Probility trees for additional bits for match distance
  161. * when the distance is in the range [4, 127].
  162. */
  163. uint16_t dist_special[FULL_DISTANCES - DIST_MODEL_END];
  164. /*
  165. * Probability tree for the lowest four bits of a match
  166. * distance that is equal to or greater than 128.
  167. */
  168. uint16_t dist_align[ALIGN_SIZE];
  169. /* Length of a normal match */
  170. struct lzma_len_dec match_len_dec;
  171. /* Length of a repeated match */
  172. struct lzma_len_dec rep_len_dec;
  173. /* Probabilities of literals */
  174. uint16_t literal[LITERAL_CODERS_MAX][LITERAL_CODER_SIZE];
  175. };
  176. struct lzma2_dec {
  177. /* Position in xz_dec_lzma2_run(). */
  178. enum lzma2_seq {
  179. SEQ_CONTROL,
  180. SEQ_UNCOMPRESSED_1,
  181. SEQ_UNCOMPRESSED_2,
  182. SEQ_COMPRESSED_0,
  183. SEQ_COMPRESSED_1,
  184. SEQ_PROPERTIES,
  185. SEQ_LZMA_PREPARE,
  186. SEQ_LZMA_RUN,
  187. SEQ_COPY
  188. } sequence;
  189. /* Next position after decoding the compressed size of the chunk. */
  190. enum lzma2_seq next_sequence;
  191. /* Uncompressed size of LZMA chunk (2 MiB at maximum) */
  192. uint32_t uncompressed;
  193. /*
  194. * Compressed size of LZMA chunk or compressed/uncompressed
  195. * size of uncompressed chunk (64 KiB at maximum)
  196. */
  197. uint32_t compressed;
  198. /*
  199. * True if dictionary reset is needed. This is false before
  200. * the first chunk (LZMA or uncompressed).
  201. */
  202. bool need_dict_reset;
  203. /*
  204. * True if new LZMA properties are needed. This is false
  205. * before the first LZMA chunk.
  206. */
  207. bool need_props;
  208. };
  209. struct xz_dec_lzma2 {
  210. /*
  211. * The order below is important on x86 to reduce code size and
  212. * it shouldn't hurt on other platforms. Everything up to and
  213. * including lzma.pos_mask are in the first 128 bytes on x86-32,
  214. * which allows using smaller instructions to access those
  215. * variables. On x86-64, fewer variables fit into the first 128
  216. * bytes, but this is still the best order without sacrificing
  217. * the readability by splitting the structures.
  218. */
  219. struct rc_dec rc;
  220. struct dictionary dict;
  221. struct lzma2_dec lzma2;
  222. struct lzma_dec lzma;
  223. /*
  224. * Temporary buffer which holds small number of input bytes between
  225. * decoder calls. See lzma2_lzma() for details.
  226. */
  227. struct {
  228. uint32_t size;
  229. uint8_t buf[3 * LZMA_IN_REQUIRED];
  230. } temp;
  231. };
  232. /**************
  233. * Dictionary *
  234. **************/
  235. /*
  236. * Reset the dictionary state. When in single-call mode, set up the beginning
  237. * of the dictionary to point to the actual output buffer.
  238. */
  239. static void dict_reset(struct dictionary *dict, struct xz_buf *b)
  240. {
  241. if (DEC_IS_SINGLE(dict->mode)) {
  242. dict->buf = b->out + b->out_pos;
  243. dict->end = b->out_size - b->out_pos;
  244. }
  245. dict->start = 0;
  246. dict->pos = 0;
  247. dict->limit = 0;
  248. dict->full = 0;
  249. }
  250. /* Set dictionary write limit */
  251. static void dict_limit(struct dictionary *dict, size_t out_max)
  252. {
  253. if (dict->end - dict->pos <= out_max)
  254. dict->limit = dict->end;
  255. else
  256. dict->limit = dict->pos + out_max;
  257. }
  258. /* Return true if at least one byte can be written into the dictionary. */
  259. static inline bool dict_has_space(const struct dictionary *dict)
  260. {
  261. return dict->pos < dict->limit;
  262. }
  263. /*
  264. * Get a byte from the dictionary at the given distance. The distance is
  265. * assumed to valid, or as a special case, zero when the dictionary is
  266. * still empty. This special case is needed for single-call decoding to
  267. * avoid writing a '\0' to the end of the destination buffer.
  268. */
  269. static inline uint32_t dict_get(const struct dictionary *dict, uint32_t dist)
  270. {
  271. size_t offset = dict->pos - dist - 1;
  272. if (dist >= dict->pos)
  273. offset += dict->end;
  274. return dict->full > 0 ? dict->buf[offset] : 0;
  275. }
  276. /*
  277. * Put one byte into the dictionary. It is assumed that there is space for it.
  278. */
  279. static inline void dict_put(struct dictionary *dict, uint8_t byte)
  280. {
  281. dict->buf[dict->pos++] = byte;
  282. if (dict->full < dict->pos)
  283. dict->full = dict->pos;
  284. }
  285. /*
  286. * Repeat given number of bytes from the given distance. If the distance is
  287. * invalid, false is returned. On success, true is returned and *len is
  288. * updated to indicate how many bytes were left to be repeated.
  289. */
  290. static bool dict_repeat(struct dictionary *dict, uint32_t *len, uint32_t dist)
  291. {
  292. size_t back;
  293. uint32_t left;
  294. if (dist >= dict->full || dist >= dict->size)
  295. return false;
  296. left = min_t(size_t, dict->limit - dict->pos, *len);
  297. *len -= left;
  298. back = dict->pos - dist - 1;
  299. if (dist >= dict->pos)
  300. back += dict->end;
  301. do {
  302. dict->buf[dict->pos++] = dict->buf[back++];
  303. if (back == dict->end)
  304. back = 0;
  305. } while (--left > 0);
  306. if (dict->full < dict->pos)
  307. dict->full = dict->pos;
  308. return true;
  309. }
  310. /* Copy uncompressed data as is from input to dictionary and output buffers. */
  311. static void dict_uncompressed(struct dictionary *dict, struct xz_buf *b,
  312. uint32_t *left)
  313. {
  314. size_t copy_size;
  315. while (*left > 0 && b->in_pos < b->in_size
  316. && b->out_pos < b->out_size) {
  317. copy_size = min(b->in_size - b->in_pos,
  318. b->out_size - b->out_pos);
  319. if (copy_size > dict->end - dict->pos)
  320. copy_size = dict->end - dict->pos;
  321. if (copy_size > *left)
  322. copy_size = *left;
  323. *left -= copy_size;
  324. memcpy(dict->buf + dict->pos, b->in + b->in_pos, copy_size);
  325. dict->pos += copy_size;
  326. if (dict->full < dict->pos)
  327. dict->full = dict->pos;
  328. if (DEC_IS_MULTI(dict->mode)) {
  329. if (dict->pos == dict->end)
  330. dict->pos = 0;
  331. memcpy(b->out + b->out_pos, b->in + b->in_pos,
  332. copy_size);
  333. }
  334. dict->start = dict->pos;
  335. b->out_pos += copy_size;
  336. b->in_pos += copy_size;
  337. }
  338. }
  339. /*
  340. * Flush pending data from dictionary to b->out. It is assumed that there is
  341. * enough space in b->out. This is guaranteed because caller uses dict_limit()
  342. * before decoding data into the dictionary.
  343. */
  344. static uint32_t dict_flush(struct dictionary *dict, struct xz_buf *b)
  345. {
  346. size_t copy_size = dict->pos - dict->start;
  347. if (DEC_IS_MULTI(dict->mode)) {
  348. if (dict->pos == dict->end)
  349. dict->pos = 0;
  350. memcpy(b->out + b->out_pos, dict->buf + dict->start,
  351. copy_size);
  352. }
  353. dict->start = dict->pos;
  354. b->out_pos += copy_size;
  355. return copy_size;
  356. }
  357. /*****************
  358. * Range decoder *
  359. *****************/
  360. /* Reset the range decoder. */
  361. static void rc_reset(struct rc_dec *rc)
  362. {
  363. rc->range = (uint32_t)-1;
  364. rc->code = 0;
  365. rc->init_bytes_left = RC_INIT_BYTES;
  366. }
  367. /*
  368. * Read the first five initial bytes into rc->code if they haven't been
  369. * read already. (Yes, the first byte gets completely ignored.)
  370. */
  371. static bool rc_read_init(struct rc_dec *rc, struct xz_buf *b)
  372. {
  373. while (rc->init_bytes_left > 0) {
  374. if (b->in_pos == b->in_size)
  375. return false;
  376. rc->code = (rc->code << 8) + b->in[b->in_pos++];
  377. --rc->init_bytes_left;
  378. }
  379. return true;
  380. }
  381. /* Return true if there may not be enough input for the next decoding loop. */
  382. static inline bool rc_limit_exceeded(const struct rc_dec *rc)
  383. {
  384. return rc->in_pos > rc->in_limit;
  385. }
  386. /*
  387. * Return true if it is possible (from point of view of range decoder) that
  388. * we have reached the end of the LZMA chunk.
  389. */
  390. static inline bool rc_is_finished(const struct rc_dec *rc)
  391. {
  392. return rc->code == 0;
  393. }
  394. /* Read the next input byte if needed. */
  395. static __always_inline void rc_normalize(struct rc_dec *rc)
  396. {
  397. if (rc->range < RC_TOP_VALUE) {
  398. rc->range <<= RC_SHIFT_BITS;
  399. rc->code = (rc->code << RC_SHIFT_BITS) + rc->in[rc->in_pos++];
  400. }
  401. }
  402. /*
  403. * Decode one bit. In some versions, this function has been splitted in three
  404. * functions so that the compiler is supposed to be able to more easily avoid
  405. * an extra branch. In this particular version of the LZMA decoder, this
  406. * doesn't seem to be a good idea (tested with GCC 3.3.6, 3.4.6, and 4.3.3
  407. * on x86). Using a non-splitted version results in nicer looking code too.
  408. *
  409. * NOTE: This must return an int. Do not make it return a bool or the speed
  410. * of the code generated by GCC 3.x decreases 10-15 %. (GCC 4.3 doesn't care,
  411. * and it generates 10-20 % faster code than GCC 3.x from this file anyway.)
  412. */
  413. static __always_inline int rc_bit(struct rc_dec *rc, uint16_t *prob)
  414. {
  415. uint32_t bound;
  416. int bit;
  417. rc_normalize(rc);
  418. bound = (rc->range >> RC_BIT_MODEL_TOTAL_BITS) * *prob;
  419. if (rc->code < bound) {
  420. rc->range = bound;
  421. *prob += (RC_BIT_MODEL_TOTAL - *prob) >> RC_MOVE_BITS;
  422. bit = 0;
  423. } else {
  424. rc->range -= bound;
  425. rc->code -= bound;
  426. *prob -= *prob >> RC_MOVE_BITS;
  427. bit = 1;
  428. }
  429. return bit;
  430. }
  431. /* Decode a bittree starting from the most significant bit. */
  432. static __always_inline uint32_t rc_bittree(struct rc_dec *rc,
  433. uint16_t *probs, uint32_t limit)
  434. {
  435. uint32_t symbol = 1;
  436. do {
  437. if (rc_bit(rc, &probs[symbol]))
  438. symbol = (symbol << 1) + 1;
  439. else
  440. symbol <<= 1;
  441. } while (symbol < limit);
  442. return symbol;
  443. }
  444. /* Decode a bittree starting from the least significant bit. */
  445. static __always_inline void rc_bittree_reverse(struct rc_dec *rc,
  446. uint16_t *probs,
  447. uint32_t *dest, uint32_t limit)
  448. {
  449. uint32_t symbol = 1;
  450. uint32_t i = 0;
  451. do {
  452. if (rc_bit(rc, &probs[symbol])) {
  453. symbol = (symbol << 1) + 1;
  454. *dest += 1 << i;
  455. } else {
  456. symbol <<= 1;
  457. }
  458. } while (++i < limit);
  459. }
  460. /* Decode direct bits (fixed fifty-fifty probability) */
  461. static inline void rc_direct(struct rc_dec *rc, uint32_t *dest, uint32_t limit)
  462. {
  463. uint32_t mask;
  464. do {
  465. rc_normalize(rc);
  466. rc->range >>= 1;
  467. rc->code -= rc->range;
  468. mask = (uint32_t)0 - (rc->code >> 31);
  469. rc->code += rc->range & mask;
  470. *dest = (*dest << 1) + (mask + 1);
  471. } while (--limit > 0);
  472. }
  473. /********
  474. * LZMA *
  475. ********/
  476. /* Get pointer to literal coder probability array. */
  477. static uint16_t *lzma_literal_probs(struct xz_dec_lzma2 *s)
  478. {
  479. uint32_t prev_byte = dict_get(&s->dict, 0);
  480. uint32_t low = prev_byte >> (8 - s->lzma.lc);
  481. uint32_t high = (s->dict.pos & s->lzma.literal_pos_mask) << s->lzma.lc;
  482. return s->lzma.literal[low + high];
  483. }
  484. /* Decode a literal (one 8-bit byte) */
  485. static void lzma_literal(struct xz_dec_lzma2 *s)
  486. {
  487. uint16_t *probs;
  488. uint32_t symbol;
  489. uint32_t match_byte;
  490. uint32_t match_bit;
  491. uint32_t offset;
  492. uint32_t i;
  493. probs = lzma_literal_probs(s);
  494. if (lzma_state_is_literal(s->lzma.state)) {
  495. symbol = rc_bittree(&s->rc, probs, 0x100);
  496. } else {
  497. symbol = 1;
  498. match_byte = dict_get(&s->dict, s->lzma.rep0) << 1;
  499. offset = 0x100;
  500. do {
  501. match_bit = match_byte & offset;
  502. match_byte <<= 1;
  503. i = offset + match_bit + symbol;
  504. if (rc_bit(&s->rc, &probs[i])) {
  505. symbol = (symbol << 1) + 1;
  506. offset &= match_bit;
  507. } else {
  508. symbol <<= 1;
  509. offset &= ~match_bit;
  510. }
  511. } while (symbol < 0x100);
  512. }
  513. dict_put(&s->dict, (uint8_t)symbol);
  514. lzma_state_literal(&s->lzma.state);
  515. }
  516. /* Decode the length of the match into s->lzma.len. */
  517. static void lzma_len(struct xz_dec_lzma2 *s, struct lzma_len_dec *l,
  518. uint32_t pos_state)
  519. {
  520. uint16_t *probs;
  521. uint32_t limit;
  522. if (!rc_bit(&s->rc, &l->choice)) {
  523. probs = l->low[pos_state];
  524. limit = LEN_LOW_SYMBOLS;
  525. s->lzma.len = MATCH_LEN_MIN;
  526. } else {
  527. if (!rc_bit(&s->rc, &l->choice2)) {
  528. probs = l->mid[pos_state];
  529. limit = LEN_MID_SYMBOLS;
  530. s->lzma.len = MATCH_LEN_MIN + LEN_LOW_SYMBOLS;
  531. } else {
  532. probs = l->high;
  533. limit = LEN_HIGH_SYMBOLS;
  534. s->lzma.len = MATCH_LEN_MIN + LEN_LOW_SYMBOLS
  535. + LEN_MID_SYMBOLS;
  536. }
  537. }
  538. s->lzma.len += rc_bittree(&s->rc, probs, limit) - limit;
  539. }
  540. /* Decode a match. The distance will be stored in s->lzma.rep0. */
  541. static void lzma_match(struct xz_dec_lzma2 *s, uint32_t pos_state)
  542. {
  543. uint16_t *probs;
  544. uint32_t dist_slot;
  545. uint32_t limit;
  546. lzma_state_match(&s->lzma.state);
  547. s->lzma.rep3 = s->lzma.rep2;
  548. s->lzma.rep2 = s->lzma.rep1;
  549. s->lzma.rep1 = s->lzma.rep0;
  550. lzma_len(s, &s->lzma.match_len_dec, pos_state);
  551. probs = s->lzma.dist_slot[lzma_get_dist_state(s->lzma.len)];
  552. dist_slot = rc_bittree(&s->rc, probs, DIST_SLOTS) - DIST_SLOTS;
  553. if (dist_slot < DIST_MODEL_START) {
  554. s->lzma.rep0 = dist_slot;
  555. } else {
  556. limit = (dist_slot >> 1) - 1;
  557. s->lzma.rep0 = 2 + (dist_slot & 1);
  558. if (dist_slot < DIST_MODEL_END) {
  559. s->lzma.rep0 <<= limit;
  560. probs = s->lzma.dist_special + s->lzma.rep0
  561. - dist_slot - 1;
  562. rc_bittree_reverse(&s->rc, probs,
  563. &s->lzma.rep0, limit);
  564. } else {
  565. rc_direct(&s->rc, &s->lzma.rep0, limit - ALIGN_BITS);
  566. s->lzma.rep0 <<= ALIGN_BITS;
  567. rc_bittree_reverse(&s->rc, s->lzma.dist_align,
  568. &s->lzma.rep0, ALIGN_BITS);
  569. }
  570. }
  571. }
  572. /*
  573. * Decode a repeated match. The distance is one of the four most recently
  574. * seen matches. The distance will be stored in s->lzma.rep0.
  575. */
  576. static void lzma_rep_match(struct xz_dec_lzma2 *s, uint32_t pos_state)
  577. {
  578. uint32_t tmp;
  579. if (!rc_bit(&s->rc, &s->lzma.is_rep0[s->lzma.state])) {
  580. if (!rc_bit(&s->rc, &s->lzma.is_rep0_long[
  581. s->lzma.state][pos_state])) {
  582. lzma_state_short_rep(&s->lzma.state);
  583. s->lzma.len = 1;
  584. return;
  585. }
  586. } else {
  587. if (!rc_bit(&s->rc, &s->lzma.is_rep1[s->lzma.state])) {
  588. tmp = s->lzma.rep1;
  589. } else {
  590. if (!rc_bit(&s->rc, &s->lzma.is_rep2[s->lzma.state])) {
  591. tmp = s->lzma.rep2;
  592. } else {
  593. tmp = s->lzma.rep3;
  594. s->lzma.rep3 = s->lzma.rep2;
  595. }
  596. s->lzma.rep2 = s->lzma.rep1;
  597. }
  598. s->lzma.rep1 = s->lzma.rep0;
  599. s->lzma.rep0 = tmp;
  600. }
  601. lzma_state_long_rep(&s->lzma.state);
  602. lzma_len(s, &s->lzma.rep_len_dec, pos_state);
  603. }
  604. /* LZMA decoder core */
  605. static bool lzma_main(struct xz_dec_lzma2 *s)
  606. {
  607. uint32_t pos_state;
  608. /*
  609. * If the dictionary was reached during the previous call, try to
  610. * finish the possibly pending repeat in the dictionary.
  611. */
  612. if (dict_has_space(&s->dict) && s->lzma.len > 0)
  613. dict_repeat(&s->dict, &s->lzma.len, s->lzma.rep0);
  614. /*
  615. * Decode more LZMA symbols. One iteration may consume up to
  616. * LZMA_IN_REQUIRED - 1 bytes.
  617. */
  618. while (dict_has_space(&s->dict) && !rc_limit_exceeded(&s->rc)) {
  619. pos_state = s->dict.pos & s->lzma.pos_mask;
  620. if (!rc_bit(&s->rc, &s->lzma.is_match[
  621. s->lzma.state][pos_state])) {
  622. lzma_literal(s);
  623. } else {
  624. if (rc_bit(&s->rc, &s->lzma.is_rep[s->lzma.state]))
  625. lzma_rep_match(s, pos_state);
  626. else
  627. lzma_match(s, pos_state);
  628. if (!dict_repeat(&s->dict, &s->lzma.len, s->lzma.rep0))
  629. return false;
  630. }
  631. }
  632. /*
  633. * Having the range decoder always normalized when we are outside
  634. * this function makes it easier to correctly handle end of the chunk.
  635. */
  636. rc_normalize(&s->rc);
  637. return true;
  638. }
  639. /*
  640. * Reset the LZMA decoder and range decoder state. Dictionary is nore reset
  641. * here, because LZMA state may be reset without resetting the dictionary.
  642. */
  643. static void lzma_reset(struct xz_dec_lzma2 *s)
  644. {
  645. uint16_t *probs;
  646. size_t i;
  647. s->lzma.state = STATE_LIT_LIT;
  648. s->lzma.rep0 = 0;
  649. s->lzma.rep1 = 0;
  650. s->lzma.rep2 = 0;
  651. s->lzma.rep3 = 0;
  652. /*
  653. * All probabilities are initialized to the same value. This hack
  654. * makes the code smaller by avoiding a separate loop for each
  655. * probability array.
  656. *
  657. * This could be optimized so that only that part of literal
  658. * probabilities that are actually required. In the common case
  659. * we would write 12 KiB less.
  660. */
  661. probs = s->lzma.is_match[0];
  662. for (i = 0; i < PROBS_TOTAL; ++i)
  663. probs[i] = RC_BIT_MODEL_TOTAL / 2;
  664. rc_reset(&s->rc);
  665. }
  666. /*
  667. * Decode and validate LZMA properties (lc/lp/pb) and calculate the bit masks
  668. * from the decoded lp and pb values. On success, the LZMA decoder state is
  669. * reset and true is returned.
  670. */
  671. static bool lzma_props(struct xz_dec_lzma2 *s, uint8_t props)
  672. {
  673. if (props > (4 * 5 + 4) * 9 + 8)
  674. return false;
  675. s->lzma.pos_mask = 0;
  676. while (props >= 9 * 5) {
  677. props -= 9 * 5;
  678. ++s->lzma.pos_mask;
  679. }
  680. s->lzma.pos_mask = (1 << s->lzma.pos_mask) - 1;
  681. s->lzma.literal_pos_mask = 0;
  682. while (props >= 9) {
  683. props -= 9;
  684. ++s->lzma.literal_pos_mask;
  685. }
  686. s->lzma.lc = props;
  687. if (s->lzma.lc + s->lzma.literal_pos_mask > 4)
  688. return false;
  689. s->lzma.literal_pos_mask = (1 << s->lzma.literal_pos_mask) - 1;
  690. lzma_reset(s);
  691. return true;
  692. }
  693. /*********
  694. * LZMA2 *
  695. *********/
  696. /*
  697. * The LZMA decoder assumes that if the input limit (s->rc.in_limit) hasn't
  698. * been exceeded, it is safe to read up to LZMA_IN_REQUIRED bytes. This
  699. * wrapper function takes care of making the LZMA decoder's assumption safe.
  700. *
  701. * As long as there is plenty of input left to be decoded in the current LZMA
  702. * chunk, we decode directly from the caller-supplied input buffer until
  703. * there's LZMA_IN_REQUIRED bytes left. Those remaining bytes are copied into
  704. * s->temp.buf, which (hopefully) gets filled on the next call to this
  705. * function. We decode a few bytes from the temporary buffer so that we can
  706. * continue decoding from the caller-supplied input buffer again.
  707. */
  708. static bool lzma2_lzma(struct xz_dec_lzma2 *s, struct xz_buf *b)
  709. {
  710. size_t in_avail;
  711. uint32_t tmp;
  712. in_avail = b->in_size - b->in_pos;
  713. if (s->temp.size > 0 || s->lzma2.compressed == 0) {
  714. tmp = 2 * LZMA_IN_REQUIRED - s->temp.size;
  715. if (tmp > s->lzma2.compressed - s->temp.size)
  716. tmp = s->lzma2.compressed - s->temp.size;
  717. if (tmp > in_avail)
  718. tmp = in_avail;
  719. memcpy(s->temp.buf + s->temp.size, b->in + b->in_pos, tmp);
  720. if (s->temp.size + tmp == s->lzma2.compressed) {
  721. memzero(s->temp.buf + s->temp.size + tmp,
  722. sizeof(s->temp.buf)
  723. - s->temp.size - tmp);
  724. s->rc.in_limit = s->temp.size + tmp;
  725. } else if (s->temp.size + tmp < LZMA_IN_REQUIRED) {
  726. s->temp.size += tmp;
  727. b->in_pos += tmp;
  728. return true;
  729. } else {
  730. s->rc.in_limit = s->temp.size + tmp - LZMA_IN_REQUIRED;
  731. }
  732. s->rc.in = s->temp.buf;
  733. s->rc.in_pos = 0;
  734. if (!lzma_main(s) || s->rc.in_pos > s->temp.size + tmp)
  735. return false;
  736. s->lzma2.compressed -= s->rc.in_pos;
  737. if (s->rc.in_pos < s->temp.size) {
  738. s->temp.size -= s->rc.in_pos;
  739. memmove(s->temp.buf, s->temp.buf + s->rc.in_pos,
  740. s->temp.size);
  741. return true;
  742. }
  743. b->in_pos += s->rc.in_pos - s->temp.size;
  744. s->temp.size = 0;
  745. }
  746. in_avail = b->in_size - b->in_pos;
  747. if (in_avail >= LZMA_IN_REQUIRED) {
  748. s->rc.in = b->in;
  749. s->rc.in_pos = b->in_pos;
  750. if (in_avail >= s->lzma2.compressed + LZMA_IN_REQUIRED)
  751. s->rc.in_limit = b->in_pos + s->lzma2.compressed;
  752. else
  753. s->rc.in_limit = b->in_size - LZMA_IN_REQUIRED;
  754. if (!lzma_main(s))
  755. return false;
  756. in_avail = s->rc.in_pos - b->in_pos;
  757. if (in_avail > s->lzma2.compressed)
  758. return false;
  759. s->lzma2.compressed -= in_avail;
  760. b->in_pos = s->rc.in_pos;
  761. }
  762. in_avail = b->in_size - b->in_pos;
  763. if (in_avail < LZMA_IN_REQUIRED) {
  764. if (in_avail > s->lzma2.compressed)
  765. in_avail = s->lzma2.compressed;
  766. memcpy(s->temp.buf, b->in + b->in_pos, in_avail);
  767. s->temp.size = in_avail;
  768. b->in_pos += in_avail;
  769. }
  770. return true;
  771. }
  772. /*
  773. * Take care of the LZMA2 control layer, and forward the job of actual LZMA
  774. * decoding or copying of uncompressed chunks to other functions.
  775. */
  776. XZ_EXTERN enum xz_ret xz_dec_lzma2_run(struct xz_dec_lzma2 *s,
  777. struct xz_buf *b)
  778. {
  779. uint32_t tmp;
  780. while (b->in_pos < b->in_size || s->lzma2.sequence == SEQ_LZMA_RUN) {
  781. switch (s->lzma2.sequence) {
  782. case SEQ_CONTROL:
  783. /*
  784. * LZMA2 control byte
  785. *
  786. * Exact values:
  787. * 0x00 End marker
  788. * 0x01 Dictionary reset followed by
  789. * an uncompressed chunk
  790. * 0x02 Uncompressed chunk (no dictionary reset)
  791. *
  792. * Highest three bits (s->control & 0xE0):
  793. * 0xE0 Dictionary reset, new properties and state
  794. * reset, followed by LZMA compressed chunk
  795. * 0xC0 New properties and state reset, followed
  796. * by LZMA compressed chunk (no dictionary
  797. * reset)
  798. * 0xA0 State reset using old properties,
  799. * followed by LZMA compressed chunk (no
  800. * dictionary reset)
  801. * 0x80 LZMA chunk (no dictionary or state reset)
  802. *
  803. * For LZMA compressed chunks, the lowest five bits
  804. * (s->control & 1F) are the highest bits of the
  805. * uncompressed size (bits 16-20).
  806. *
  807. * A new LZMA2 stream must begin with a dictionary
  808. * reset. The first LZMA chunk must set new
  809. * properties and reset the LZMA state.
  810. *
  811. * Values that don't match anything described above
  812. * are invalid and we return XZ_DATA_ERROR.
  813. */
  814. tmp = b->in[b->in_pos++];
  815. if (tmp == 0x00)
  816. return XZ_STREAM_END;
  817. if (tmp >= 0xE0 || tmp == 0x01) {
  818. s->lzma2.need_props = true;
  819. s->lzma2.need_dict_reset = false;
  820. dict_reset(&s->dict, b);
  821. } else if (s->lzma2.need_dict_reset) {
  822. return XZ_DATA_ERROR;
  823. }
  824. if (tmp >= 0x80) {
  825. s->lzma2.uncompressed = (tmp & 0x1F) << 16;
  826. s->lzma2.sequence = SEQ_UNCOMPRESSED_1;
  827. if (tmp >= 0xC0) {
  828. /*
  829. * When there are new properties,
  830. * state reset is done at
  831. * SEQ_PROPERTIES.
  832. */
  833. s->lzma2.need_props = false;
  834. s->lzma2.next_sequence
  835. = SEQ_PROPERTIES;
  836. } else if (s->lzma2.need_props) {
  837. return XZ_DATA_ERROR;
  838. } else {
  839. s->lzma2.next_sequence
  840. = SEQ_LZMA_PREPARE;
  841. if (tmp >= 0xA0)
  842. lzma_reset(s);
  843. }
  844. } else {
  845. if (tmp > 0x02)
  846. return XZ_DATA_ERROR;
  847. s->lzma2.sequence = SEQ_COMPRESSED_0;
  848. s->lzma2.next_sequence = SEQ_COPY;
  849. }
  850. break;
  851. case SEQ_UNCOMPRESSED_1:
  852. s->lzma2.uncompressed
  853. += (uint32_t)b->in[b->in_pos++] << 8;
  854. s->lzma2.sequence = SEQ_UNCOMPRESSED_2;
  855. break;
  856. case SEQ_UNCOMPRESSED_2:
  857. s->lzma2.uncompressed
  858. += (uint32_t)b->in[b->in_pos++] + 1;
  859. s->lzma2.sequence = SEQ_COMPRESSED_0;
  860. break;
  861. case SEQ_COMPRESSED_0:
  862. s->lzma2.compressed
  863. = (uint32_t)b->in[b->in_pos++] << 8;
  864. s->lzma2.sequence = SEQ_COMPRESSED_1;
  865. break;
  866. case SEQ_COMPRESSED_1:
  867. s->lzma2.compressed
  868. += (uint32_t)b->in[b->in_pos++] + 1;
  869. s->lzma2.sequence = s->lzma2.next_sequence;
  870. break;
  871. case SEQ_PROPERTIES:
  872. if (!lzma_props(s, b->in[b->in_pos++]))
  873. return XZ_DATA_ERROR;
  874. s->lzma2.sequence = SEQ_LZMA_PREPARE;
  875. /* Fall through */
  876. case SEQ_LZMA_PREPARE:
  877. if (s->lzma2.compressed < RC_INIT_BYTES)
  878. return XZ_DATA_ERROR;
  879. if (!rc_read_init(&s->rc, b))
  880. return XZ_OK;
  881. s->lzma2.compressed -= RC_INIT_BYTES;
  882. s->lzma2.sequence = SEQ_LZMA_RUN;
  883. /* Fall through */
  884. case SEQ_LZMA_RUN:
  885. /*
  886. * Set dictionary limit to indicate how much we want
  887. * to be encoded at maximum. Decode new data into the
  888. * dictionary. Flush the new data from dictionary to
  889. * b->out. Check if we finished decoding this chunk.
  890. * In case the dictionary got full but we didn't fill
  891. * the output buffer yet, we may run this loop
  892. * multiple times without changing s->lzma2.sequence.
  893. */
  894. dict_limit(&s->dict, min_t(size_t,
  895. b->out_size - b->out_pos,
  896. s->lzma2.uncompressed));
  897. if (!lzma2_lzma(s, b))
  898. return XZ_DATA_ERROR;
  899. s->lzma2.uncompressed -= dict_flush(&s->dict, b);
  900. if (s->lzma2.uncompressed == 0) {
  901. if (s->lzma2.compressed > 0 || s->lzma.len > 0
  902. || !rc_is_finished(&s->rc))
  903. return XZ_DATA_ERROR;
  904. rc_reset(&s->rc);
  905. s->lzma2.sequence = SEQ_CONTROL;
  906. } else if (b->out_pos == b->out_size
  907. || (b->in_pos == b->in_size
  908. && s->temp.size
  909. < s->lzma2.compressed)) {
  910. return XZ_OK;
  911. }
  912. break;
  913. case SEQ_COPY:
  914. dict_uncompressed(&s->dict, b, &s->lzma2.compressed);
  915. if (s->lzma2.compressed > 0)
  916. return XZ_OK;
  917. s->lzma2.sequence = SEQ_CONTROL;
  918. break;
  919. }
  920. }
  921. return XZ_OK;
  922. }
  923. XZ_EXTERN struct xz_dec_lzma2 *xz_dec_lzma2_create(enum xz_mode mode,
  924. uint32_t dict_max)
  925. {
  926. struct xz_dec_lzma2 *s = kmalloc(sizeof(*s), GFP_KERNEL);
  927. if (s == NULL)
  928. return NULL;
  929. s->dict.mode = mode;
  930. s->dict.size_max = dict_max;
  931. if (DEC_IS_PREALLOC(mode)) {
  932. s->dict.buf = vmalloc(dict_max);
  933. if (s->dict.buf == NULL) {
  934. kfree(s);
  935. return NULL;
  936. }
  937. } else if (DEC_IS_DYNALLOC(mode)) {
  938. s->dict.buf = NULL;
  939. s->dict.allocated = 0;
  940. }
  941. return s;
  942. }
  943. XZ_EXTERN enum xz_ret xz_dec_lzma2_reset(struct xz_dec_lzma2 *s, uint8_t props)
  944. {
  945. /* This limits dictionary size to 3 GiB to keep parsing simpler. */
  946. if (props > 39)
  947. return XZ_OPTIONS_ERROR;
  948. s->dict.size = 2 + (props & 1);
  949. s->dict.size <<= (props >> 1) + 11;
  950. if (DEC_IS_MULTI(s->dict.mode)) {
  951. if (s->dict.size > s->dict.size_max)
  952. return XZ_MEMLIMIT_ERROR;
  953. s->dict.end = s->dict.size;
  954. if (DEC_IS_DYNALLOC(s->dict.mode)) {
  955. if (s->dict.allocated < s->dict.size) {
  956. vfree(s->dict.buf);
  957. s->dict.buf = vmalloc(s->dict.size);
  958. if (s->dict.buf == NULL) {
  959. s->dict.allocated = 0;
  960. return XZ_MEM_ERROR;
  961. }
  962. }
  963. }
  964. }
  965. s->lzma.len = 0;
  966. s->lzma2.sequence = SEQ_CONTROL;
  967. s->lzma2.need_dict_reset = true;
  968. s->temp.size = 0;
  969. return XZ_OK;
  970. }
  971. XZ_EXTERN void xz_dec_lzma2_end(struct xz_dec_lzma2 *s)
  972. {
  973. if (DEC_IS_MULTI(s->dict.mode))
  974. vfree(s->dict.buf);
  975. kfree(s);
  976. }