Lzma.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  1. /*
  2. * Copyright (c) 2023, Tim Schumacher <timschumi@gmx.de>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibCompress/Lzma.h>
  7. namespace Compress {
  8. u32 LzmaHeader::dictionary_size() const
  9. {
  10. // "If the value of dictionary size in properties is smaller than (1 << 12),
  11. // the LZMA decoder must set the dictionary size variable to (1 << 12)."
  12. constexpr u32 minimum_dictionary_size = (1 << 12);
  13. if (m_dictionary_size < minimum_dictionary_size)
  14. return minimum_dictionary_size;
  15. return m_dictionary_size;
  16. }
  17. Optional<u64> LzmaHeader::uncompressed_size() const
  18. {
  19. // We are making a copy of the packed field here because we would otherwise
  20. // pass an unaligned reference to the constructor of Optional, which is
  21. // undefined behavior.
  22. auto uncompressed_size = m_uncompressed_size;
  23. // "If "Uncompressed size" field contains ones in all 64 bits, it means that
  24. // uncompressed size is unknown and there is the "end marker" in stream,
  25. // that indicates the end of decoding point."
  26. if (uncompressed_size == UINT64_MAX)
  27. return {};
  28. // "In opposite case, if the value from "Uncompressed size" field is not
  29. // equal to ((2^64) - 1), the LZMA stream decoding must be finished after
  30. // specified number of bytes (Uncompressed size) is decoded. And if there
  31. // is the "end marker", the LZMA decoder must read that marker also."
  32. return uncompressed_size;
  33. }
  34. ErrorOr<LzmaModelProperties> LzmaHeader::decode_model_properties(u8 input_bits)
  35. {
  36. // "Decodes the following values from the encoded model properties field:
  37. //
  38. // name Range Description
  39. // lc [0, 8] the number of "literal context" bits
  40. // lp [0, 4] the number of "literal pos" bits
  41. // pb [0, 4] the number of "pos" bits
  42. //
  43. // Encoded using `((pb * 5 + lp) * 9 + lc)`."
  44. if (input_bits >= (9 * 5 * 5))
  45. return Error::from_string_literal("Encoded model properties value is larger than the highest possible value");
  46. u8 literal_context_bits = input_bits % 9;
  47. input_bits /= 9;
  48. VERIFY(literal_context_bits >= 0 && literal_context_bits <= 8);
  49. u8 literal_position_bits = input_bits % 5;
  50. input_bits /= 5;
  51. VERIFY(literal_position_bits >= 0 && literal_position_bits <= 4);
  52. u8 position_bits = input_bits;
  53. VERIFY(position_bits >= 0 && position_bits <= 4);
  54. return LzmaModelProperties {
  55. .literal_context_bits = literal_context_bits,
  56. .literal_position_bits = literal_position_bits,
  57. .position_bits = position_bits,
  58. };
  59. }
  60. ErrorOr<LzmaDecompressorOptions> LzmaHeader::as_decompressor_options() const
  61. {
  62. auto model_properties = TRY(decode_model_properties(m_encoded_model_properties));
  63. return Compress::LzmaDecompressorOptions {
  64. .literal_context_bits = model_properties.literal_context_bits,
  65. .literal_position_bits = model_properties.literal_position_bits,
  66. .position_bits = model_properties.position_bits,
  67. .dictionary_size = dictionary_size(),
  68. .uncompressed_size = uncompressed_size(),
  69. .reject_end_of_stream_marker = false,
  70. };
  71. }
  72. void LzmaDecompressor::initialize_to_default_probability(Span<Probability> span)
  73. {
  74. for (auto& entry : span)
  75. entry = default_probability;
  76. }
  77. ErrorOr<NonnullOwnPtr<LzmaDecompressor>> LzmaDecompressor::create_from_container(MaybeOwned<Stream> stream, Optional<MaybeOwned<CircularBuffer>> dictionary)
  78. {
  79. auto header = TRY(stream->read_value<LzmaHeader>());
  80. return TRY(LzmaDecompressor::create_from_raw_stream(move(stream), TRY(header.as_decompressor_options()), move(dictionary)));
  81. }
  82. ErrorOr<NonnullOwnPtr<LzmaDecompressor>> LzmaDecompressor::create_from_raw_stream(MaybeOwned<Stream> stream, LzmaDecompressorOptions const& options, Optional<MaybeOwned<CircularBuffer>> dictionary)
  83. {
  84. if (!dictionary.has_value()) {
  85. auto new_dictionary = TRY(CircularBuffer::create_empty(options.dictionary_size));
  86. dictionary = TRY(try_make<CircularBuffer>(move(new_dictionary)));
  87. }
  88. VERIFY((*dictionary)->capacity() >= options.dictionary_size);
  89. // "The LZMA Decoder uses (1 << (lc + lp)) tables with CProb values, where each table contains 0x300 CProb values."
  90. auto literal_probabilities = TRY(FixedArray<Probability>::create(literal_probability_table_size * (1 << (options.literal_context_bits + options.literal_position_bits))));
  91. auto decompressor = TRY(adopt_nonnull_own_or_enomem(new (nothrow) LzmaDecompressor(move(stream), options, dictionary.release_value(), move(literal_probabilities))));
  92. TRY(decompressor->initialize_range_decoder());
  93. return decompressor;
  94. }
  95. LzmaDecompressor::LzmaDecompressor(MaybeOwned<Stream> stream, LzmaDecompressorOptions options, MaybeOwned<CircularBuffer> dictionary, FixedArray<Probability> literal_probabilities)
  96. : m_stream(move(stream))
  97. , m_options(move(options))
  98. , m_dictionary(move(dictionary))
  99. , m_literal_probabilities(move(literal_probabilities))
  100. {
  101. initialize_to_default_probability(m_literal_probabilities.span());
  102. for (auto& array : m_length_to_position_states)
  103. initialize_to_default_probability(array);
  104. for (auto& array : m_binary_tree_distance_probabilities)
  105. initialize_to_default_probability(array);
  106. initialize_to_default_probability(m_alignment_bit_probabilities);
  107. initialize_to_default_probability(m_is_match_probabilities);
  108. initialize_to_default_probability(m_is_rep_probabilities);
  109. initialize_to_default_probability(m_is_rep_g0_probabilities);
  110. initialize_to_default_probability(m_is_rep_g1_probabilities);
  111. initialize_to_default_probability(m_is_rep_g2_probabilities);
  112. initialize_to_default_probability(m_is_rep0_long_probabilities);
  113. }
  114. bool LzmaDecompressor::is_range_decoder_in_clean_state() const
  115. {
  116. return m_range_decoder_code == 0;
  117. }
  118. bool LzmaDecompressor::has_reached_expected_data_size() const
  119. {
  120. if (!m_options.uncompressed_size.has_value())
  121. return false;
  122. return m_total_decoded_bytes >= m_options.uncompressed_size.value();
  123. }
  124. ErrorOr<void> LzmaDecompressor::initialize_range_decoder()
  125. {
  126. // "The LZMA Encoder always writes ZERO in initial byte of compressed stream.
  127. // That scheme allows to simplify the code of the Range Encoder in the
  128. // LZMA Encoder. If initial byte is not equal to ZERO, the LZMA Decoder must
  129. // stop decoding and report error."
  130. {
  131. auto byte = TRY(m_stream->read_value<u8>());
  132. if (byte != 0)
  133. return Error::from_string_literal("Initial byte of data stream is not zero");
  134. }
  135. // Read the initial bytes into the range decoder.
  136. m_range_decoder_code = 0;
  137. for (size_t i = 0; i < 4; i++) {
  138. auto byte = TRY(m_stream->read_value<u8>());
  139. m_range_decoder_code = m_range_decoder_code << 8 | byte;
  140. }
  141. m_range_decoder_range = 0xFFFFFFFF;
  142. return {};
  143. }
  144. ErrorOr<void> LzmaDecompressor::append_input_stream(MaybeOwned<Stream> stream, Optional<u64> uncompressed_size)
  145. {
  146. m_stream = move(stream);
  147. TRY(initialize_range_decoder());
  148. if (m_options.uncompressed_size.has_value() != uncompressed_size.has_value())
  149. return Error::from_string_literal("Appending LZMA streams with mismatching uncompressed size status");
  150. if (uncompressed_size.has_value())
  151. *m_options.uncompressed_size += *uncompressed_size;
  152. return {};
  153. }
  154. ErrorOr<void> LzmaDecompressor::normalize_range_decoder()
  155. {
  156. // "The value of the "Range" variable before each bit decoding can not be smaller
  157. // than ((UInt32)1 << 24). The Normalize() function keeps the "Range" value in
  158. // described range."
  159. constexpr u32 minimum_range_value = 1 << 24;
  160. if (m_range_decoder_range >= minimum_range_value)
  161. return {};
  162. m_range_decoder_range <<= 8;
  163. m_range_decoder_code <<= 8;
  164. m_range_decoder_code |= TRY(m_stream->read_value<u8>());
  165. VERIFY(m_range_decoder_range >= minimum_range_value);
  166. return {};
  167. }
  168. ErrorOr<u8> LzmaDecompressor::decode_direct_bit()
  169. {
  170. m_range_decoder_range >>= 1;
  171. m_range_decoder_code -= m_range_decoder_range;
  172. u32 temp = 0 - (m_range_decoder_code >> 31);
  173. m_range_decoder_code += m_range_decoder_range & temp;
  174. if (m_range_decoder_code == m_range_decoder_range)
  175. return Error::from_string_literal("Reached an invalid state while decoding LZMA stream");
  176. TRY(normalize_range_decoder());
  177. return temp + 1;
  178. }
  179. ErrorOr<u8> LzmaDecompressor::decode_bit_with_probability(Probability& probability)
  180. {
  181. // "The LZMA decoder provides the pointer to CProb variable that contains
  182. // information about estimated probability for symbol 0 and the Range Decoder
  183. // updates that CProb variable after decoding."
  184. // The significance of the shift width is not explained and appears to be a magic constant.
  185. constexpr size_t probability_shift_width = 5;
  186. u32 bound = (m_range_decoder_range >> probability_bit_count) * probability;
  187. if (m_range_decoder_code < bound) {
  188. probability += ((1 << probability_bit_count) - probability) >> probability_shift_width;
  189. m_range_decoder_range = bound;
  190. TRY(normalize_range_decoder());
  191. return 0;
  192. } else {
  193. probability -= probability >> probability_shift_width;
  194. m_range_decoder_code -= bound;
  195. m_range_decoder_range -= bound;
  196. TRY(normalize_range_decoder());
  197. return 1;
  198. }
  199. }
  200. ErrorOr<u16> LzmaDecompressor::decode_symbol_using_bit_tree(size_t bit_count, Span<Probability> probability_tree)
  201. {
  202. VERIFY(bit_count <= sizeof(u16) * 8);
  203. VERIFY(probability_tree.size() >= 1ul << bit_count);
  204. // This has been modified from the reference implementation to unlink the result and the tree index,
  205. // which should allow for better readability.
  206. u16 result = 0;
  207. size_t tree_index = 1;
  208. for (size_t i = 0; i < bit_count; i++) {
  209. u16 next_bit = TRY(decode_bit_with_probability(probability_tree[tree_index]));
  210. result = (result << 1) | next_bit;
  211. tree_index = (tree_index << 1) | next_bit;
  212. }
  213. return result;
  214. }
  215. ErrorOr<u16> LzmaDecompressor::decode_symbol_using_reverse_bit_tree(size_t bit_count, Span<Probability> probability_tree)
  216. {
  217. VERIFY(bit_count <= sizeof(u16) * 8);
  218. VERIFY(probability_tree.size() >= 1ul << bit_count);
  219. u16 result = 0;
  220. size_t tree_index = 1;
  221. for (size_t i = 0; i < bit_count; i++) {
  222. u16 next_bit = TRY(decode_bit_with_probability(probability_tree[tree_index]));
  223. result |= next_bit << i;
  224. tree_index = (tree_index << 1) | next_bit;
  225. }
  226. return result;
  227. }
  228. ErrorOr<void> LzmaDecompressor::decode_literal_to_output_buffer()
  229. {
  230. u8 previous_byte = 0;
  231. if (m_dictionary->seekback_limit() > 0) {
  232. auto read_bytes = MUST(m_dictionary->read_with_seekback({ &previous_byte, sizeof(previous_byte) }, 1));
  233. VERIFY(read_bytes.size() == sizeof(previous_byte));
  234. }
  235. // "To select the table for decoding it uses the context that consists of
  236. // (lc) high bits from previous literal and (lp) low bits from value that
  237. // represents current position in outputStream."
  238. u16 literal_state_bits_from_position = m_total_decoded_bytes & ((1 << m_options.literal_position_bits) - 1);
  239. u16 literal_state_bits_from_output = previous_byte >> (8 - m_options.literal_context_bits);
  240. u16 literal_state = literal_state_bits_from_position << m_options.literal_context_bits | literal_state_bits_from_output;
  241. Span<Probability> selected_probability_table = m_literal_probabilities.span().slice(literal_probability_table_size * literal_state, literal_probability_table_size);
  242. // The result is defined as u16 here and initialized to 1, but we will cut off the top bits before queueing them into the output buffer.
  243. // The top bit is only used to track how much we have decoded already, and to select the correct probability table.
  244. u16 result = 1;
  245. // "If (State > 7), the Literal Decoder also uses "matchByte" that represents
  246. // the byte in OutputStream at position the is the DISTANCE bytes before
  247. // current position, where the DISTANCE is the distance in DISTANCE-LENGTH pair
  248. // of latest decoded match."
  249. // Note: The specification says `(State > 7)`, but the reference implementation does `(State >= 7)`, which is a mismatch.
  250. // Testing `(State > 7)` with actual test files yields errors, so the reference implementation appears to be the correct one.
  251. if (m_state >= 7) {
  252. u8 matched_byte = 0;
  253. auto read_bytes = TRY(m_dictionary->read_with_seekback({ &matched_byte, sizeof(matched_byte) }, current_repetition_offset()));
  254. VERIFY(read_bytes.size() == sizeof(matched_byte));
  255. do {
  256. u8 match_bit = (matched_byte >> 7) & 1;
  257. matched_byte <<= 1;
  258. u8 decoded_bit = TRY(decode_bit_with_probability(selected_probability_table[((1 + match_bit) << 8) + result]));
  259. result = result << 1 | decoded_bit;
  260. if (match_bit != decoded_bit)
  261. break;
  262. } while (result < 0x100);
  263. }
  264. while (result < 0x100)
  265. result = (result << 1) | TRY(decode_bit_with_probability(selected_probability_table[result]));
  266. u8 actual_result = result - 0x100;
  267. size_t written_bytes = m_dictionary->write({ &actual_result, sizeof(actual_result) });
  268. VERIFY(written_bytes == sizeof(actual_result));
  269. m_total_decoded_bytes += sizeof(actual_result);
  270. return {};
  271. }
  272. LzmaDecompressor::LzmaLengthDecoderState::LzmaLengthDecoderState()
  273. {
  274. for (auto& array : m_low_length_probabilities)
  275. initialize_to_default_probability(array);
  276. for (auto& array : m_medium_length_probabilities)
  277. initialize_to_default_probability(array);
  278. initialize_to_default_probability(m_high_length_probabilities);
  279. }
  280. ErrorOr<u16> LzmaDecompressor::decode_normalized_match_length(LzmaLengthDecoderState& length_decoder_state)
  281. {
  282. // "LZMA uses "posState" value as context to select the binary tree
  283. // from LowCoder and MidCoder binary tree arrays:"
  284. u16 position_state = m_total_decoded_bytes & ((1 << m_options.position_bits) - 1);
  285. // "The following scheme is used for the match length encoding:
  286. //
  287. // Binary encoding Binary Tree structure Zero-based match length
  288. // sequence (binary + decimal):
  289. //
  290. // 0 xxx LowCoder[posState] xxx
  291. if (TRY(decode_bit_with_probability(length_decoder_state.m_first_choice_probability)) == 0)
  292. return TRY(decode_symbol_using_bit_tree(3, length_decoder_state.m_low_length_probabilities[position_state].span()));
  293. // 1 0 yyy MidCoder[posState] yyy + 8
  294. if (TRY(decode_bit_with_probability(length_decoder_state.m_second_choice_probability)) == 0)
  295. return TRY(decode_symbol_using_bit_tree(3, length_decoder_state.m_medium_length_probabilities[position_state].span())) + 8;
  296. // 1 1 zzzzzzzz HighCoder zzzzzzzz + 16"
  297. return TRY(decode_symbol_using_bit_tree(8, length_decoder_state.m_high_length_probabilities.span())) + 16;
  298. }
  299. ErrorOr<u32> LzmaDecompressor::decode_normalized_match_distance(u16 normalized_match_length)
  300. {
  301. // "LZMA uses normalized match length (zero-based length)
  302. // to calculate the context state "lenState" do decode the distance value."
  303. u16 length_state = min(normalized_match_length, number_of_length_to_position_states - 1);
  304. // "At first stage the distance decoder decodes 6-bit "posSlot" value with bit
  305. // tree decoder from PosSlotDecoder array."
  306. u16 position_slot = TRY(decode_symbol_using_bit_tree(6, m_length_to_position_states[length_state].span()));
  307. // "The encoding scheme for distance value is shown in the following table:
  308. //
  309. // posSlot (decimal) /
  310. // zero-based distance (binary)
  311. // 0 0
  312. // 1 1
  313. // 2 10
  314. // 3 11
  315. //
  316. // 4 10 x
  317. // 5 11 x
  318. // 6 10 xx
  319. // 7 11 xx
  320. // 8 10 xxx
  321. // 9 11 xxx
  322. // 10 10 xxxx
  323. // 11 11 xxxx
  324. // 12 10 xxxxx
  325. // 13 11 xxxxx
  326. //
  327. // 14 10 yy zzzz
  328. // 15 11 yy zzzz
  329. // 16 10 yyy zzzz
  330. // 17 11 yyy zzzz
  331. // ...
  332. // 62 10 yyyyyyyyyyyyyyyyyyyyyyyyyy zzzz
  333. // 63 11 yyyyyyyyyyyyyyyyyyyyyyyyyy zzzz
  334. //
  335. // where
  336. // "x ... x" means the sequence of binary symbols encoded with binary tree and
  337. // "Reverse" scheme. It uses separated binary tree for each posSlot from 4 to 13.
  338. // "y" means direct bit encoded with range coder.
  339. // "zzzz" means the sequence of four binary symbols encoded with binary
  340. // tree with "Reverse" scheme, where one common binary tree "AlignDecoder"
  341. // is used for all posSlot values."
  342. // "If (posSlot < 4), the "dist" value is equal to posSlot value."
  343. if (position_slot < first_position_slot_with_binary_tree_bits)
  344. return position_slot;
  345. // From here on, the first bit of the distance is always set and the second bit is set if the last bit of the position slot is set.
  346. u32 distance_prefix = ((1 << 1) | ((position_slot & 1) << 0));
  347. // "If (posSlot >= 4), the decoder uses "posSlot" value to calculate the value of
  348. // the high bits of "dist" value and the number of the low bits.
  349. // If (4 <= posSlot < kEndPosModelIndex), the decoder uses bit tree decoders.
  350. // (one separated bit tree decoder per one posSlot value) and "Reverse" scheme."
  351. if (position_slot < first_position_slot_with_direct_encoded_bits) {
  352. size_t number_of_bits_to_decode = (position_slot / 2) - 1;
  353. auto& selected_probability_tree = m_binary_tree_distance_probabilities[position_slot - first_position_slot_with_binary_tree_bits];
  354. return (distance_prefix << number_of_bits_to_decode) | TRY(decode_symbol_using_reverse_bit_tree(number_of_bits_to_decode, selected_probability_tree));
  355. }
  356. // " if (posSlot >= kEndPosModelIndex), the middle bits are decoded as direct
  357. // bits from RangeDecoder and the low 4 bits are decoded with a bit tree
  358. // decoder "AlignDecoder" with "Reverse" scheme."
  359. size_t number_of_direct_bits_to_decode = ((position_slot - first_position_slot_with_direct_encoded_bits) / 2) + 2;
  360. for (size_t i = 0; i < number_of_direct_bits_to_decode; i++) {
  361. distance_prefix = (distance_prefix << 1) | TRY(decode_direct_bit());
  362. }
  363. return (distance_prefix << number_of_alignment_bits) | TRY(decode_symbol_using_reverse_bit_tree(number_of_alignment_bits, m_alignment_bit_probabilities));
  364. }
  365. u32 LzmaDecompressor::current_repetition_offset() const
  366. {
  367. // LZMA never needs to read at offset 0 (i.e. the actual read head of the buffer).
  368. // Instead, the values are remapped so that the rep-value n starts reading n + 1 bytes back.
  369. // The special rep-value 0xFFFFFFFF is reserved for marking the end of the stream,
  370. // so this should never overflow.
  371. VERIFY(m_rep0 < NumericLimits<u32>::max());
  372. return m_rep0 + 1;
  373. }
  374. ErrorOr<Bytes> LzmaDecompressor::read_some(Bytes bytes)
  375. {
  376. while (m_dictionary->used_space() < bytes.size() && m_dictionary->empty_space() != 0) {
  377. if (m_found_end_of_stream_marker)
  378. break;
  379. if (has_reached_expected_data_size()) {
  380. // If the decoder is in a clean state, we assume that this is fine.
  381. if (is_range_decoder_in_clean_state())
  382. break;
  383. // Otherwise, we give it one last try to find the end marker in the remaining data.
  384. }
  385. // "The decoder calculates "state2" variable value to select exact variable from
  386. // "IsMatch" and "IsRep0Long" arrays."
  387. u16 position_state = m_total_decoded_bytes & ((1 << m_options.position_bits) - 1);
  388. u16 state2 = (m_state << maximum_number_of_position_bits) + position_state;
  389. auto update_state_after_literal = [&] {
  390. if (m_state < 4)
  391. m_state = 0;
  392. else if (m_state < 10)
  393. m_state -= 3;
  394. else
  395. m_state -= 6;
  396. };
  397. auto update_state_after_match = [&] {
  398. if (m_state < 7)
  399. m_state = 7;
  400. else
  401. m_state = 10;
  402. };
  403. auto update_state_after_rep = [&] {
  404. if (m_state < 7)
  405. m_state = 8;
  406. else
  407. m_state = 11;
  408. };
  409. auto update_state_after_short_rep = [&] {
  410. if (m_state < 7)
  411. m_state = 9;
  412. else
  413. m_state = 11;
  414. };
  415. auto copy_match_to_buffer = [&](u16 real_length) -> ErrorOr<void> {
  416. VERIFY(!m_leftover_match_length.has_value());
  417. if (m_options.uncompressed_size.has_value() && m_options.uncompressed_size.value() < m_total_decoded_bytes + real_length)
  418. return Error::from_string_literal("Tried to copy match beyond expected uncompressed file size");
  419. auto copied_length = TRY(m_dictionary->copy_from_seekback(current_repetition_offset(), real_length));
  420. m_total_decoded_bytes += copied_length;
  421. real_length -= copied_length;
  422. if (real_length > 0)
  423. m_leftover_match_length = real_length;
  424. return {};
  425. };
  426. // If we have a leftover part of a repeating match, we should finish that first.
  427. if (m_leftover_match_length.has_value()) {
  428. TRY(copy_match_to_buffer(m_leftover_match_length.release_value()));
  429. continue;
  430. }
  431. // "The decoder uses the following code flow scheme to select exact
  432. // type of LITERAL or MATCH:
  433. //
  434. // IsMatch[state2] decode
  435. // 0 - the Literal"
  436. if (TRY(decode_bit_with_probability(m_is_match_probabilities[state2])) == 0) {
  437. // If we are already past the expected uncompressed size, we are already in "look for EOS only" mode.
  438. if (has_reached_expected_data_size())
  439. return Error::from_string_literal("Found literal after reaching expected uncompressed size");
  440. // "At first the LZMA decoder must check that it doesn't exceed
  441. // specified uncompressed size."
  442. // This is already checked for at the beginning of the loop.
  443. // "Then it decodes literal value and puts it to sliding window."
  444. TRY(decode_literal_to_output_buffer());
  445. // "Then the decoder must update the "state" value."
  446. update_state_after_literal();
  447. continue;
  448. }
  449. // " 1 - the Match
  450. // IsRep[state] decode
  451. // 0 - Simple Match"
  452. if (TRY(decode_bit_with_probability(m_is_rep_probabilities[m_state])) == 0) {
  453. // "The distance history table is updated with the following scheme:"
  454. m_rep3 = m_rep2;
  455. m_rep2 = m_rep1;
  456. m_rep1 = m_rep0;
  457. // "The zero-based length is decoded with "LenDecoder"."
  458. u16 normalized_length = TRY(decode_normalized_match_length(m_length_decoder));
  459. // "The state is update with UpdateState_Match function."
  460. update_state_after_match();
  461. // "and the new "rep0" value is decoded with DecodeDistance."
  462. m_rep0 = TRY(decode_normalized_match_distance(normalized_length));
  463. // "If the value of "rep0" is equal to 0xFFFFFFFF, it means that we have
  464. // "End of stream" marker, so we can stop decoding and check finishing
  465. // condition in Range Decoder"
  466. if (m_rep0 == 0xFFFFFFFF) {
  467. // If we should reject end-of-stream markers, do so now.
  468. // Note that this is not part of LZMA, as LZMA allows end-of-stream markers in all contexts, so pure LZMA should never set this option.
  469. if (m_options.reject_end_of_stream_marker)
  470. return Error::from_string_literal("An end-of-stream marker was found, but the LZMA stream is configured to reject them");
  471. // The range decoder condition is checked after breaking out of the loop.
  472. m_found_end_of_stream_marker = true;
  473. continue;
  474. }
  475. // If we are looking for EOS, but haven't found it here, the stream is corrupted.
  476. if (has_reached_expected_data_size())
  477. return Error::from_string_literal("First simple match after the expected uncompressed size is not the EOS marker");
  478. // "If uncompressed size is defined, LZMA decoder must check that it doesn't
  479. // exceed that specified uncompressed size."
  480. // This is being checked for in the common "copy to buffer" implementation.
  481. // "Also the decoder must check that "rep0" value is not larger than dictionary size
  482. // and is not larger than the number of already decoded bytes."
  483. if (current_repetition_offset() > m_dictionary->seekback_limit())
  484. return Error::from_string_literal("rep0 value is larger than the possible lookback size");
  485. // "Then the decoder must copy match bytes as described in
  486. // "The match symbols copying" section."
  487. TRY(copy_match_to_buffer(normalized_length + normalized_to_real_match_length_offset));
  488. continue;
  489. }
  490. // If we are looking for EOS, but find another match type, the stream is also corrupted.
  491. if (has_reached_expected_data_size())
  492. return Error::from_string_literal("First match type after the expected uncompressed size is not a simple match");
  493. // " 1 - Rep Match
  494. // IsRepG0[state] decode
  495. // 0 - the distance is rep0"
  496. if (TRY(decode_bit_with_probability(m_is_rep_g0_probabilities[m_state])) == 0) {
  497. // "LZMA doesn't update the distance history."
  498. // " IsRep0Long[state2] decode
  499. // 0 - Short Rep Match"
  500. if (TRY(decode_bit_with_probability(m_is_rep0_long_probabilities[state2])) == 0) {
  501. // "If the subtype is "Short Rep Match", the decoder updates the state, puts
  502. // the one byte from window to current position in window and goes to next
  503. // MATCH/LITERAL symbol."
  504. update_state_after_short_rep();
  505. TRY(copy_match_to_buffer(1));
  506. continue;
  507. }
  508. // " 1 - Rep Match 0"
  509. // Intentional fallthrough, we just need to make sure to not run the detection for other match types and to not switch around the distance history.
  510. } else {
  511. // " 1 -
  512. // IsRepG1[state] decode
  513. // 0 - Rep Match 1"
  514. if (TRY(decode_bit_with_probability(m_is_rep_g1_probabilities[m_state])) == 0) {
  515. u32 distance = m_rep1;
  516. m_rep1 = m_rep0;
  517. m_rep0 = distance;
  518. }
  519. // " 1 -
  520. // IsRepG2[state] decode
  521. // 0 - Rep Match 2"
  522. else if (TRY(decode_bit_with_probability(m_is_rep_g2_probabilities[m_state])) == 0) {
  523. u32 distance = m_rep2;
  524. m_rep2 = m_rep1;
  525. m_rep1 = m_rep0;
  526. m_rep0 = distance;
  527. }
  528. // " 1 - Rep Match 3"
  529. else {
  530. u32 distance = m_rep3;
  531. m_rep3 = m_rep2;
  532. m_rep2 = m_rep1;
  533. m_rep1 = m_rep0;
  534. m_rep0 = distance;
  535. }
  536. }
  537. // "In other cases (Rep Match 0/1/2/3), it decodes the zero-based
  538. // length of match with "RepLenDecoder" decoder."
  539. u16 normalized_length = TRY(decode_normalized_match_length(m_rep_length_decoder));
  540. // "Then it updates the state."
  541. update_state_after_rep();
  542. // "Then the decoder must copy match bytes as described in
  543. // "The Match symbols copying" section."
  544. TRY(copy_match_to_buffer(normalized_length + normalized_to_real_match_length_offset));
  545. }
  546. if (m_found_end_of_stream_marker || has_reached_expected_data_size()) {
  547. if (m_options.uncompressed_size.has_value() && m_total_decoded_bytes < m_options.uncompressed_size.value())
  548. return Error::from_string_literal("Found end-of-stream marker earlier than expected");
  549. if (!is_range_decoder_in_clean_state())
  550. return Error::from_string_literal("LZMA stream ends in an unclean state");
  551. }
  552. return m_dictionary->read(bytes);
  553. }
  554. ErrorOr<size_t> LzmaDecompressor::write_some(ReadonlyBytes)
  555. {
  556. return Error::from_errno(EBADF);
  557. }
  558. bool LzmaDecompressor::is_eof() const
  559. {
  560. if (m_dictionary->used_space() > 0)
  561. return false;
  562. if (has_reached_expected_data_size())
  563. return true;
  564. return m_found_end_of_stream_marker;
  565. }
  566. bool LzmaDecompressor::is_open() const
  567. {
  568. return true;
  569. }
  570. void LzmaDecompressor::close()
  571. {
  572. }
  573. }