xz_dec_lzma2.c 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175
  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 XZ_FUNC 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 XZ_FUNC 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 __always_inline bool XZ_FUNC 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 __always_inline uint32_t XZ_FUNC dict_get(
  270. const struct dictionary *dict, uint32_t dist)
  271. {
  272. size_t offset = dict->pos - dist - 1;
  273. if (dist >= dict->pos)
  274. offset += dict->end;
  275. return dict->full > 0 ? dict->buf[offset] : 0;
  276. }
  277. /*
  278. * Put one byte into the dictionary. It is assumed that there is space for it.
  279. */
  280. static inline void XZ_FUNC dict_put(struct dictionary *dict, uint8_t byte)
  281. {
  282. dict->buf[dict->pos++] = byte;
  283. if (dict->full < dict->pos)
  284. dict->full = dict->pos;
  285. }
  286. /*
  287. * Repeat given number of bytes from the given distance. If the distance is
  288. * invalid, false is returned. On success, true is returned and *len is
  289. * updated to indicate how many bytes were left to be repeated.
  290. */
  291. static bool XZ_FUNC dict_repeat(
  292. struct dictionary *dict, uint32_t *len, uint32_t dist)
  293. {
  294. size_t back;
  295. uint32_t left;
  296. if (dist >= dict->full || dist >= dict->size)
  297. return false;
  298. left = min_t(size_t, dict->limit - dict->pos, *len);
  299. *len -= left;
  300. back = dict->pos - dist - 1;
  301. if (dist >= dict->pos)
  302. back += dict->end;
  303. do {
  304. dict->buf[dict->pos++] = dict->buf[back++];
  305. if (back == dict->end)
  306. back = 0;
  307. } while (--left > 0);
  308. if (dict->full < dict->pos)
  309. dict->full = dict->pos;
  310. return true;
  311. }
  312. /* Copy uncompressed data as is from input to dictionary and output buffers. */
  313. static void XZ_FUNC dict_uncompressed(
  314. struct dictionary *dict, struct xz_buf *b, uint32_t *left)
  315. {
  316. size_t copy_size;
  317. while (*left > 0 && b->in_pos < b->in_size
  318. && b->out_pos < b->out_size) {
  319. copy_size = min(b->in_size - b->in_pos,
  320. b->out_size - b->out_pos);
  321. if (copy_size > dict->end - dict->pos)
  322. copy_size = dict->end - dict->pos;
  323. if (copy_size > *left)
  324. copy_size = *left;
  325. *left -= copy_size;
  326. memcpy(dict->buf + dict->pos, b->in + b->in_pos, copy_size);
  327. dict->pos += copy_size;
  328. if (dict->full < dict->pos)
  329. dict->full = dict->pos;
  330. if (DEC_IS_MULTI(dict->mode)) {
  331. if (dict->pos == dict->end)
  332. dict->pos = 0;
  333. memcpy(b->out + b->out_pos, b->in + b->in_pos,
  334. copy_size);
  335. }
  336. dict->start = dict->pos;
  337. b->out_pos += copy_size;
  338. b->in_pos += copy_size;
  339. }
  340. }
  341. /*
  342. * Flush pending data from dictionary to b->out. It is assumed that there is
  343. * enough space in b->out. This is guaranteed because caller uses dict_limit()
  344. * before decoding data into the dictionary.
  345. */
  346. static uint32_t XZ_FUNC dict_flush(struct dictionary *dict, struct xz_buf *b)
  347. {
  348. size_t copy_size = dict->pos - dict->start;
  349. if (DEC_IS_MULTI(dict->mode)) {
  350. if (dict->pos == dict->end)
  351. dict->pos = 0;
  352. memcpy(b->out + b->out_pos, dict->buf + dict->start,
  353. copy_size);
  354. }
  355. dict->start = dict->pos;
  356. b->out_pos += copy_size;
  357. return copy_size;
  358. }
  359. /*****************
  360. * Range decoder *
  361. *****************/
  362. /* Reset the range decoder. */
  363. static void XZ_FUNC rc_reset(struct rc_dec *rc)
  364. {
  365. rc->range = (uint32_t)-1;
  366. rc->code = 0;
  367. rc->init_bytes_left = RC_INIT_BYTES;
  368. }
  369. /*
  370. * Read the first five initial bytes into rc->code if they haven't been
  371. * read already. (Yes, the first byte gets completely ignored.)
  372. */
  373. static bool XZ_FUNC rc_read_init(struct rc_dec *rc, struct xz_buf *b)
  374. {
  375. while (rc->init_bytes_left > 0) {
  376. if (b->in_pos == b->in_size)
  377. return false;
  378. rc->code = (rc->code << 8) + b->in[b->in_pos++];
  379. --rc->init_bytes_left;
  380. }
  381. return true;
  382. }
  383. /* Return true if there may not be enough input for the next decoding loop. */
  384. static inline bool XZ_FUNC rc_limit_exceeded(const struct rc_dec *rc)
  385. {
  386. return rc->in_pos > rc->in_limit;
  387. }
  388. /*
  389. * Return true if it is possible (from point of view of range decoder) that
  390. * we have reached the end of the LZMA chunk.
  391. */
  392. static inline bool XZ_FUNC rc_is_finished(const struct rc_dec *rc)
  393. {
  394. return rc->code == 0;
  395. }
  396. /* Read the next input byte if needed. */
  397. static __always_inline void XZ_FUNC rc_normalize(struct rc_dec *rc)
  398. {
  399. if (rc->range < RC_TOP_VALUE) {
  400. rc->range <<= RC_SHIFT_BITS;
  401. rc->code = (rc->code << RC_SHIFT_BITS) + rc->in[rc->in_pos++];
  402. }
  403. }
  404. /*
  405. * Decode one bit. In some versions, this function has been splitted in three
  406. * functions so that the compiler is supposed to be able to more easily avoid
  407. * an extra branch. In this particular version of the LZMA decoder, this
  408. * doesn't seem to be a good idea (tested with GCC 3.3.6, 3.4.6, and 4.3.3
  409. * on x86). Using a non-splitted version results in nicer looking code too.
  410. *
  411. * NOTE: This must return an int. Do not make it return a bool or the speed
  412. * of the code generated by GCC 3.x decreases 10-15 %. (GCC 4.3 doesn't care,
  413. * and it generates 10-20 % faster code than GCC 3.x from this file anyway.)
  414. */
  415. static __always_inline int XZ_FUNC rc_bit(struct rc_dec *rc, uint16_t *prob)
  416. {
  417. uint32_t bound;
  418. int bit;
  419. rc_normalize(rc);
  420. bound = (rc->range >> RC_BIT_MODEL_TOTAL_BITS) * *prob;
  421. if (rc->code < bound) {
  422. rc->range = bound;
  423. *prob += (RC_BIT_MODEL_TOTAL - *prob) >> RC_MOVE_BITS;
  424. bit = 0;
  425. } else {
  426. rc->range -= bound;
  427. rc->code -= bound;
  428. *prob -= *prob >> RC_MOVE_BITS;
  429. bit = 1;
  430. }
  431. return bit;
  432. }
  433. /* Decode a bittree starting from the most significant bit. */
  434. static __always_inline uint32_t XZ_FUNC rc_bittree(
  435. struct rc_dec *rc, uint16_t *probs, uint32_t limit)
  436. {
  437. uint32_t symbol = 1;
  438. do {
  439. if (rc_bit(rc, &probs[symbol]))
  440. symbol = (symbol << 1) + 1;
  441. else
  442. symbol <<= 1;
  443. } while (symbol < limit);
  444. return symbol;
  445. }
  446. /* Decode a bittree starting from the least significant bit. */
  447. static __always_inline void XZ_FUNC rc_bittree_reverse(struct rc_dec *rc,
  448. uint16_t *probs, uint32_t *dest, uint32_t limit)
  449. {
  450. uint32_t symbol = 1;
  451. uint32_t i = 0;
  452. do {
  453. if (rc_bit(rc, &probs[symbol])) {
  454. symbol = (symbol << 1) + 1;
  455. *dest += 1 << i;
  456. } else {
  457. symbol <<= 1;
  458. }
  459. } while (++i < limit);
  460. }
  461. /* Decode direct bits (fixed fifty-fifty probability) */
  462. static inline void XZ_FUNC rc_direct(
  463. struct rc_dec *rc, uint32_t *dest, uint32_t limit)
  464. {
  465. uint32_t mask;
  466. do {
  467. rc_normalize(rc);
  468. rc->range >>= 1;
  469. rc->code -= rc->range;
  470. mask = (uint32_t)0 - (rc->code >> 31);
  471. rc->code += rc->range & mask;
  472. *dest = (*dest << 1) + (mask + 1);
  473. } while (--limit > 0);
  474. }
  475. /********
  476. * LZMA *
  477. ********/
  478. /* Get pointer to literal coder probability array. */
  479. static uint16_t * XZ_FUNC lzma_literal_probs(struct xz_dec_lzma2 *s)
  480. {
  481. uint32_t prev_byte = dict_get(&s->dict, 0);
  482. uint32_t low = prev_byte >> (8 - s->lzma.lc);
  483. uint32_t high = (s->dict.pos & s->lzma.literal_pos_mask) << s->lzma.lc;
  484. return s->lzma.literal[low + high];
  485. }
  486. /* Decode a literal (one 8-bit byte) */
  487. static void XZ_FUNC lzma_literal(struct xz_dec_lzma2 *s)
  488. {
  489. uint16_t *probs;
  490. uint32_t symbol;
  491. uint32_t match_byte;
  492. uint32_t match_bit;
  493. uint32_t offset;
  494. uint32_t i;
  495. probs = lzma_literal_probs(s);
  496. if (lzma_state_is_literal(s->lzma.state)) {
  497. symbol = rc_bittree(&s->rc, probs, 0x100);
  498. } else {
  499. symbol = 1;
  500. match_byte = dict_get(&s->dict, s->lzma.rep0) << 1;
  501. offset = 0x100;
  502. do {
  503. match_bit = match_byte & offset;
  504. match_byte <<= 1;
  505. i = offset + match_bit + symbol;
  506. if (rc_bit(&s->rc, &probs[i])) {
  507. symbol = (symbol << 1) + 1;
  508. offset &= match_bit;
  509. } else {
  510. symbol <<= 1;
  511. offset &= ~match_bit;
  512. }
  513. } while (symbol < 0x100);
  514. }
  515. dict_put(&s->dict, (uint8_t)symbol);
  516. lzma_state_literal(&s->lzma.state);
  517. }
  518. /* Decode the length of the match into s->lzma.len. */
  519. static void XZ_FUNC lzma_len(struct xz_dec_lzma2 *s, struct lzma_len_dec *l,
  520. uint32_t pos_state)
  521. {
  522. uint16_t *probs;
  523. uint32_t limit;
  524. if (!rc_bit(&s->rc, &l->choice)) {
  525. probs = l->low[pos_state];
  526. limit = LEN_LOW_SYMBOLS;
  527. s->lzma.len = MATCH_LEN_MIN;
  528. } else {
  529. if (!rc_bit(&s->rc, &l->choice2)) {
  530. probs = l->mid[pos_state];
  531. limit = LEN_MID_SYMBOLS;
  532. s->lzma.len = MATCH_LEN_MIN + LEN_LOW_SYMBOLS;
  533. } else {
  534. probs = l->high;
  535. limit = LEN_HIGH_SYMBOLS;
  536. s->lzma.len = MATCH_LEN_MIN + LEN_LOW_SYMBOLS
  537. + LEN_MID_SYMBOLS;
  538. }
  539. }
  540. s->lzma.len += rc_bittree(&s->rc, probs, limit) - limit;
  541. }
  542. /* Decode a match. The distance will be stored in s->lzma.rep0. */
  543. static void XZ_FUNC lzma_match(struct xz_dec_lzma2 *s, uint32_t pos_state)
  544. {
  545. uint16_t *probs;
  546. uint32_t dist_slot;
  547. uint32_t limit;
  548. lzma_state_match(&s->lzma.state);
  549. s->lzma.rep3 = s->lzma.rep2;
  550. s->lzma.rep2 = s->lzma.rep1;
  551. s->lzma.rep1 = s->lzma.rep0;
  552. lzma_len(s, &s->lzma.match_len_dec, pos_state);
  553. probs = s->lzma.dist_slot[lzma_get_dist_state(s->lzma.len)];
  554. dist_slot = rc_bittree(&s->rc, probs, DIST_SLOTS) - DIST_SLOTS;
  555. if (dist_slot < DIST_MODEL_START) {
  556. s->lzma.rep0 = dist_slot;
  557. } else {
  558. limit = (dist_slot >> 1) - 1;
  559. s->lzma.rep0 = 2 + (dist_slot & 1);
  560. if (dist_slot < DIST_MODEL_END) {
  561. s->lzma.rep0 <<= limit;
  562. probs = s->lzma.dist_special + s->lzma.rep0
  563. - dist_slot - 1;
  564. rc_bittree_reverse(&s->rc, probs,
  565. &s->lzma.rep0, limit);
  566. } else {
  567. rc_direct(&s->rc, &s->lzma.rep0, limit - ALIGN_BITS);
  568. s->lzma.rep0 <<= ALIGN_BITS;
  569. rc_bittree_reverse(&s->rc, s->lzma.dist_align,
  570. &s->lzma.rep0, ALIGN_BITS);
  571. }
  572. }
  573. }
  574. /*
  575. * Decode a repeated match. The distance is one of the four most recently
  576. * seen matches. The distance will be stored in s->lzma.rep0.
  577. */
  578. static void XZ_FUNC lzma_rep_match(struct xz_dec_lzma2 *s, uint32_t pos_state)
  579. {
  580. uint32_t tmp;
  581. if (!rc_bit(&s->rc, &s->lzma.is_rep0[s->lzma.state])) {
  582. if (!rc_bit(&s->rc, &s->lzma.is_rep0_long[
  583. s->lzma.state][pos_state])) {
  584. lzma_state_short_rep(&s->lzma.state);
  585. s->lzma.len = 1;
  586. return;
  587. }
  588. } else {
  589. if (!rc_bit(&s->rc, &s->lzma.is_rep1[s->lzma.state])) {
  590. tmp = s->lzma.rep1;
  591. } else {
  592. if (!rc_bit(&s->rc, &s->lzma.is_rep2[s->lzma.state])) {
  593. tmp = s->lzma.rep2;
  594. } else {
  595. tmp = s->lzma.rep3;
  596. s->lzma.rep3 = s->lzma.rep2;
  597. }
  598. s->lzma.rep2 = s->lzma.rep1;
  599. }
  600. s->lzma.rep1 = s->lzma.rep0;
  601. s->lzma.rep0 = tmp;
  602. }
  603. lzma_state_long_rep(&s->lzma.state);
  604. lzma_len(s, &s->lzma.rep_len_dec, pos_state);
  605. }
  606. /* LZMA decoder core */
  607. static bool XZ_FUNC lzma_main(struct xz_dec_lzma2 *s)
  608. {
  609. uint32_t pos_state;
  610. /*
  611. * If the dictionary was reached during the previous call, try to
  612. * finish the possibly pending repeat in the dictionary.
  613. */
  614. if (dict_has_space(&s->dict) && s->lzma.len > 0)
  615. dict_repeat(&s->dict, &s->lzma.len, s->lzma.rep0);
  616. /*
  617. * Decode more LZMA symbols. One iteration may consume up to
  618. * LZMA_IN_REQUIRED - 1 bytes.
  619. */
  620. while (dict_has_space(&s->dict) && !rc_limit_exceeded(&s->rc)) {
  621. pos_state = s->dict.pos & s->lzma.pos_mask;
  622. if (!rc_bit(&s->rc, &s->lzma.is_match[
  623. s->lzma.state][pos_state])) {
  624. lzma_literal(s);
  625. } else {
  626. if (rc_bit(&s->rc, &s->lzma.is_rep[s->lzma.state]))
  627. lzma_rep_match(s, pos_state);
  628. else
  629. lzma_match(s, pos_state);
  630. if (!dict_repeat(&s->dict, &s->lzma.len, s->lzma.rep0))
  631. return false;
  632. }
  633. }
  634. /*
  635. * Having the range decoder always normalized when we are outside
  636. * this function makes it easier to correctly handle end of the chunk.
  637. */
  638. rc_normalize(&s->rc);
  639. return true;
  640. }
  641. /*
  642. * Reset the LZMA decoder and range decoder state. Dictionary is nore reset
  643. * here, because LZMA state may be reset without resetting the dictionary.
  644. */
  645. static void XZ_FUNC lzma_reset(struct xz_dec_lzma2 *s)
  646. {
  647. uint16_t *probs;
  648. size_t i;
  649. s->lzma.state = STATE_LIT_LIT;
  650. s->lzma.rep0 = 0;
  651. s->lzma.rep1 = 0;
  652. s->lzma.rep2 = 0;
  653. s->lzma.rep3 = 0;
  654. /*
  655. * All probabilities are initialized to the same value. This hack
  656. * makes the code smaller by avoiding a separate loop for each
  657. * probability array.
  658. *
  659. * This could be optimized so that only that part of literal
  660. * probabilities that are actually required. In the common case
  661. * we would write 12 KiB less.
  662. */
  663. probs = s->lzma.is_match[0];
  664. for (i = 0; i < PROBS_TOTAL; ++i)
  665. probs[i] = RC_BIT_MODEL_TOTAL / 2;
  666. rc_reset(&s->rc);
  667. }
  668. /*
  669. * Decode and validate LZMA properties (lc/lp/pb) and calculate the bit masks
  670. * from the decoded lp and pb values. On success, the LZMA decoder state is
  671. * reset and true is returned.
  672. */
  673. static bool XZ_FUNC lzma_props(struct xz_dec_lzma2 *s, uint8_t props)
  674. {
  675. if (props > (4 * 5 + 4) * 9 + 8)
  676. return false;
  677. s->lzma.pos_mask = 0;
  678. while (props >= 9 * 5) {
  679. props -= 9 * 5;
  680. ++s->lzma.pos_mask;
  681. }
  682. s->lzma.pos_mask = (1 << s->lzma.pos_mask) - 1;
  683. s->lzma.literal_pos_mask = 0;
  684. while (props >= 9) {
  685. props -= 9;
  686. ++s->lzma.literal_pos_mask;
  687. }
  688. s->lzma.lc = props;
  689. if (s->lzma.lc + s->lzma.literal_pos_mask > 4)
  690. return false;
  691. s->lzma.literal_pos_mask = (1 << s->lzma.literal_pos_mask) - 1;
  692. lzma_reset(s);
  693. return true;
  694. }
  695. /*********
  696. * LZMA2 *
  697. *********/
  698. /*
  699. * The LZMA decoder assumes that if the input limit (s->rc.in_limit) hasn't
  700. * been exceeded, it is safe to read up to LZMA_IN_REQUIRED bytes. This
  701. * wrapper function takes care of making the LZMA decoder's assumption safe.
  702. *
  703. * As long as there is plenty of input left to be decoded in the current LZMA
  704. * chunk, we decode directly from the caller-supplied input buffer until
  705. * there's LZMA_IN_REQUIRED bytes left. Those remaining bytes are copied into
  706. * s->temp.buf, which (hopefully) gets filled on the next call to this
  707. * function. We decode a few bytes from the temporary buffer so that we can
  708. * continue decoding from the caller-supplied input buffer again.
  709. */
  710. static bool XZ_FUNC lzma2_lzma(struct xz_dec_lzma2 *s, struct xz_buf *b)
  711. {
  712. size_t in_avail;
  713. uint32_t tmp;
  714. in_avail = b->in_size - b->in_pos;
  715. if (s->temp.size > 0 || s->lzma2.compressed == 0) {
  716. tmp = 2 * LZMA_IN_REQUIRED - s->temp.size;
  717. if (tmp > s->lzma2.compressed - s->temp.size)
  718. tmp = s->lzma2.compressed - s->temp.size;
  719. if (tmp > in_avail)
  720. tmp = in_avail;
  721. memcpy(s->temp.buf + s->temp.size, b->in + b->in_pos, tmp);
  722. if (s->temp.size + tmp == s->lzma2.compressed) {
  723. memzero(s->temp.buf + s->temp.size + tmp,
  724. sizeof(s->temp.buf)
  725. - s->temp.size - tmp);
  726. s->rc.in_limit = s->temp.size + tmp;
  727. } else if (s->temp.size + tmp < LZMA_IN_REQUIRED) {
  728. s->temp.size += tmp;
  729. b->in_pos += tmp;
  730. return true;
  731. } else {
  732. s->rc.in_limit = s->temp.size + tmp - LZMA_IN_REQUIRED;
  733. }
  734. s->rc.in = s->temp.buf;
  735. s->rc.in_pos = 0;
  736. if (!lzma_main(s) || s->rc.in_pos > s->temp.size + tmp)
  737. return false;
  738. s->lzma2.compressed -= s->rc.in_pos;
  739. if (s->rc.in_pos < s->temp.size) {
  740. s->temp.size -= s->rc.in_pos;
  741. memmove(s->temp.buf, s->temp.buf + s->rc.in_pos,
  742. s->temp.size);
  743. return true;
  744. }
  745. b->in_pos += s->rc.in_pos - s->temp.size;
  746. s->temp.size = 0;
  747. }
  748. in_avail = b->in_size - b->in_pos;
  749. if (in_avail >= LZMA_IN_REQUIRED) {
  750. s->rc.in = b->in;
  751. s->rc.in_pos = b->in_pos;
  752. if (in_avail >= s->lzma2.compressed + LZMA_IN_REQUIRED)
  753. s->rc.in_limit = b->in_pos + s->lzma2.compressed;
  754. else
  755. s->rc.in_limit = b->in_size - LZMA_IN_REQUIRED;
  756. if (!lzma_main(s))
  757. return false;
  758. in_avail = s->rc.in_pos - b->in_pos;
  759. if (in_avail > s->lzma2.compressed)
  760. return false;
  761. s->lzma2.compressed -= in_avail;
  762. b->in_pos = s->rc.in_pos;
  763. }
  764. in_avail = b->in_size - b->in_pos;
  765. if (in_avail < LZMA_IN_REQUIRED) {
  766. if (in_avail > s->lzma2.compressed)
  767. in_avail = s->lzma2.compressed;
  768. memcpy(s->temp.buf, b->in + b->in_pos, in_avail);
  769. s->temp.size = in_avail;
  770. b->in_pos += in_avail;
  771. }
  772. return true;
  773. }
  774. /*
  775. * Take care of the LZMA2 control layer, and forward the job of actual LZMA
  776. * decoding or copying of uncompressed chunks to other functions.
  777. */
  778. XZ_EXTERN NOINLINE enum xz_ret XZ_FUNC xz_dec_lzma2_run(
  779. struct xz_dec_lzma2 *s, struct xz_buf *b)
  780. {
  781. uint32_t tmp;
  782. while (b->in_pos < b->in_size || s->lzma2.sequence == SEQ_LZMA_RUN) {
  783. switch (s->lzma2.sequence) {
  784. case SEQ_CONTROL:
  785. /*
  786. * LZMA2 control byte
  787. *
  788. * Exact values:
  789. * 0x00 End marker
  790. * 0x01 Dictionary reset followed by
  791. * an uncompressed chunk
  792. * 0x02 Uncompressed chunk (no dictionary reset)
  793. *
  794. * Highest three bits (s->control & 0xE0):
  795. * 0xE0 Dictionary reset, new properties and state
  796. * reset, followed by LZMA compressed chunk
  797. * 0xC0 New properties and state reset, followed
  798. * by LZMA compressed chunk (no dictionary
  799. * reset)
  800. * 0xA0 State reset using old properties,
  801. * followed by LZMA compressed chunk (no
  802. * dictionary reset)
  803. * 0x80 LZMA chunk (no dictionary or state reset)
  804. *
  805. * For LZMA compressed chunks, the lowest five bits
  806. * (s->control & 1F) are the highest bits of the
  807. * uncompressed size (bits 16-20).
  808. *
  809. * A new LZMA2 stream must begin with a dictionary
  810. * reset. The first LZMA chunk must set new
  811. * properties and reset the LZMA state.
  812. *
  813. * Values that don't match anything described above
  814. * are invalid and we return XZ_DATA_ERROR.
  815. */
  816. tmp = b->in[b->in_pos++];
  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 == 0x00)
  846. return XZ_STREAM_END;
  847. if (tmp > 0x02)
  848. return XZ_DATA_ERROR;
  849. s->lzma2.sequence = SEQ_COMPRESSED_0;
  850. s->lzma2.next_sequence = SEQ_COPY;
  851. }
  852. break;
  853. case SEQ_UNCOMPRESSED_1:
  854. s->lzma2.uncompressed
  855. += (uint32_t)b->in[b->in_pos++] << 8;
  856. s->lzma2.sequence = SEQ_UNCOMPRESSED_2;
  857. break;
  858. case SEQ_UNCOMPRESSED_2:
  859. s->lzma2.uncompressed
  860. += (uint32_t)b->in[b->in_pos++] + 1;
  861. s->lzma2.sequence = SEQ_COMPRESSED_0;
  862. break;
  863. case SEQ_COMPRESSED_0:
  864. s->lzma2.compressed
  865. = (uint32_t)b->in[b->in_pos++] << 8;
  866. s->lzma2.sequence = SEQ_COMPRESSED_1;
  867. break;
  868. case SEQ_COMPRESSED_1:
  869. s->lzma2.compressed
  870. += (uint32_t)b->in[b->in_pos++] + 1;
  871. s->lzma2.sequence = s->lzma2.next_sequence;
  872. break;
  873. case SEQ_PROPERTIES:
  874. if (!lzma_props(s, b->in[b->in_pos++]))
  875. return XZ_DATA_ERROR;
  876. s->lzma2.sequence = SEQ_LZMA_PREPARE;
  877. case SEQ_LZMA_PREPARE:
  878. if (s->lzma2.compressed < RC_INIT_BYTES)
  879. return XZ_DATA_ERROR;
  880. if (!rc_read_init(&s->rc, b))
  881. return XZ_OK;
  882. s->lzma2.compressed -= RC_INIT_BYTES;
  883. s->lzma2.sequence = SEQ_LZMA_RUN;
  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_FUNC xz_dec_lzma2_create(
  924. enum xz_mode mode, 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_FUNC xz_dec_lzma2_reset(
  944. struct xz_dec_lzma2 *s, uint8_t props)
  945. {
  946. /* This limits dictionary size to 3 GiB to keep parsing simpler. */
  947. if (props > 39)
  948. return XZ_OPTIONS_ERROR;
  949. s->dict.size = 2 + (props & 1);
  950. s->dict.size <<= (props >> 1) + 11;
  951. if (DEC_IS_MULTI(s->dict.mode)) {
  952. if (s->dict.size > s->dict.size_max)
  953. return XZ_MEMLIMIT_ERROR;
  954. s->dict.end = s->dict.size;
  955. if (DEC_IS_DYNALLOC(s->dict.mode)) {
  956. if (s->dict.allocated < s->dict.size) {
  957. vfree(s->dict.buf);
  958. s->dict.buf = vmalloc(s->dict.size);
  959. if (s->dict.buf == NULL) {
  960. s->dict.allocated = 0;
  961. return XZ_MEM_ERROR;
  962. }
  963. }
  964. }
  965. }
  966. s->lzma.len = 0;
  967. s->lzma2.sequence = SEQ_CONTROL;
  968. s->lzma2.need_dict_reset = true;
  969. s->temp.size = 0;
  970. return XZ_OK;
  971. }
  972. XZ_EXTERN void XZ_FUNC xz_dec_lzma2_end(struct xz_dec_lzma2 *s)
  973. {
  974. if (DEC_IS_MULTI(s->dict.mode))
  975. vfree(s->dict.buf);
  976. kfree(s);
  977. }