Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 //! This library implements the LZX compression format as described in
2 //! [LZX DELTA Compression and Decompression], revision 9.0.
3 //!
4 //! Lempel-Ziv Extended (LZX) is an LZ77-based compression engine, as described in [UASDC],
5 //! that is a universal lossless data compression algorithm. It performs no analysis on the
6 //! data.
7 //!
8 //! Lempel-Ziv Extended Delta (LZXD) is a derivative of the Lempel-Ziv Extended (LZX) format with
9 //! some modifications to facilitate efficient delta compression.
10 //!
11 //! In order to use this module, refer to the main [`Lzxd`] type and its methods.
12 //!
13 //! [LZX DELTA Compression and Decompression]: https://docs.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-patch/cc78752a-b4af-4eee-88cb-01f4d8a4c2bf
14 //! [UASDC]: https://ieeexplore.ieee.org/document/1055714
15 //! [`Lzxd`]: struct.Lzxd.html
16 use std::{fmt, mem};
17
18 pub(crate) use bitstream::Bitstream;
19 pub(crate) use block::{Block, Decoded, Kind as BlockKind};
20 pub(crate) use tree::{CanonicalTree, Tree};
21 use window::Window;
22 pub use window::WindowSize;
23
24 mod bitstream;
25 mod block;
26 mod tree;
27 mod window;
28
29 /// A chunk represents exactly 32 KB of uncompressed data until the last chunk in the stream,
30 /// which can represent less than 32 KB.
31 pub const MAX_CHUNK_SIZE: usize = 32 * 1024;
32
33 /// Decoder state needed for new blocks.
34 // TODO not sure how much we want to keep in DecoderState and Lzxd respectively
35 pub(crate) struct DecoderState {
36 /// The window size we're working with.
37 window_size: WindowSize,
38
39 /// This tree cannot be used directly, it exists only to apply the delta of upcoming trees
40 /// to its path lengths.
41 main_tree: CanonicalTree,
42
43 /// This tree cannot be used directly, it exists only to apply the delta of upcoming trees
44 /// to its path lengths.
45 length_tree: CanonicalTree,
46 }
47
48 struct PostProcessState {
49 /// The pointer in the file at which to stop performing E8 translation.
50 e8_translation_size: i32,
51
52 /// A buffer that can be used to hold postprocessed chunks.
53 data_chunk: Box<[u8]>,
54 }
55
56 /// The main interface to perform LZXD decompression.
57 ///
58 /// This structure stores the required state to process the compressed chunks of data in a
59 /// sequential order.
60 ///
61 /// ```no_run
62 /// # fn get_compressed_chunk() -> Option<(Vec<u8>, usize)> { unimplemented!() }
63 /// # fn write_data(a: &[u8]) { unimplemented!() }
64 /// use ::lzxd::{Lzxd, WindowSize};
65 ///
66 /// let mut lzxd = Lzxd::new(WindowSize::KB64);
67 ///
68 /// while let Some((chunk, output_size)) = get_compressed_chunk() {
69 /// let decompressed = lzxd.decompress_next(&chunk, output_size);
70 /// write_data(decompressed.unwrap());
71 /// }
72 /// ```
73 pub struct Lzxd {
74 /// Sliding window into which data is decompressed.
75 window: Window,
76
77 /// Current decoder state.
78 state: DecoderState,
79
80 /// > The three most recent real match offsets are kept in a list.
81 r: [u32; 3],
82
83 /// The current offset into the decompressed data.
84 chunk_offset: usize,
85
86 /// Has the very first chunk been read yet? Unlike the rest, it has additional data.
87 first_chunk_read: bool,
88
89 /// Current block.
90 current_block: Block,
91
92 /// Information and data related to E8 postprocessing. This is populated after
93 /// the first chunk is read.
94 postprocess: Option<PostProcessState>,
95 }
96
97 /// Specific cause for decompression failure.
98 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
99 pub enum DecodeFailed {
100 /// The chunk data caused a read of more items than the current block had in a single step.
101 OverreadBlock,
102
103 /// There was not enough data in the chunk to fully decode, and a premature end was found.
104 UnexpectedEof,
105
106 /// An invalid block type was found.
107 InvalidBlock(u8),
108
109 /// An invalid block size was found.
110 InvalidBlockSize(u32),
111
112 /// An invalid pretree element was found.
113 InvalidPretreeElement(u16),
114
115 /// Invalid pretree run-length encoding.
116 InvalidPretreeRle,
117
118 /// When attempting to construct a decode tree, we encountered an invalid path length tree.
119 InvalidPathLengths,
120
121 /// A required decode tree was empty (all path lengths were 0).
122 EmptyTree,
123
124 /// The given window size was too small.
125 WindowTooSmall,
126
127 /// Tried to read a chunk longer than [`MAX_CHUNK_SIZE`].
128 ///
129 /// [`MAX_CHUNK_SIZE`]: constant.MAX_CHUNK_SIZE.html
130 ChunkTooLong,
131 }
132
133 impl fmt::Display for DecodeFailed {
134 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135 use DecodeFailed::*;
136
137 match self {
138 OverreadBlock => write!(
139 f,
140 "read more items than available in the block in a single step"
141 ),
142 UnexpectedEof => write!(f, "reached end of chunk without fully decoding it"),
143 InvalidBlock(kind) => write!(f, "block type {} is invalid", kind),
144 InvalidBlockSize(size) => write!(f, "block size {} is invalid", size),
145 InvalidPretreeElement(elem) => write!(f, "found invalid pretree element {}", elem),
146 InvalidPretreeRle => write!(f, "found invalid pretree rle element"),
147 InvalidPathLengths => write!(f, "encountered invalid path lengths"),
148 EmptyTree => write!(f, "encountered empty decode tree"),
149 WindowTooSmall => write!(f, "decode window was too small"),
150 ChunkTooLong => write!(
151 f,
152 "tried reading a chunk longer than {} bytes",
153 MAX_CHUNK_SIZE
154 ),
155 }
156 }
157 }
158
159 impl std::error::Error for DecodeFailed {}
160
161 /// The error type used when decompression fails.
162 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
163 pub struct DecompressError(DecodeFailed);
164
165 impl fmt::Display for DecompressError {
166 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167 self.0.fmt(f)
168 }
169 }
170
171 impl std::error::Error for DecompressError {}
172
173 impl From<DecodeFailed> for DecompressError {
174 fn from(value: DecodeFailed) -> Self {
175 Self(value)
176 }
177 }
178
179 impl Lzxd {
180 /// Creates a new instance of the LZXD decoder state. The [`WindowSize`] must be obtained
181 /// from elsewhere (e.g. it may be predetermined to a certain value), and if it's wrong,
182 /// the decompressed values won't be those expected.
183 ///
184 /// [`WindowSize`]: enum.WindowSize.html
185 pub fn new(window_size: WindowSize) -> Self {
186 // > The main tree comprises 256 elements that correspond to all possible 8-bit
187 // > characters, plus 8 * NUM_POSITION_SLOTS elements that correspond to matches.
188 let main_tree = CanonicalTree::new(256 + 8 * window_size.position_slots());
189
190 // > The length tree comprises 249 elements.
191 let length_tree = CanonicalTree::new(249);
192
193 Self {
194 window: window_size.create_buffer(),
195 // > Because trees are output several times during compression of large amounts of
196 // > data (multiple blocks), LZXD optimizes compression by encoding only the delta
197 // > path lengths lengths between the current and previous trees.
198 //
199 // Because it uses deltas, we need to store the previous value across blocks.
200 state: DecoderState {
201 window_size,
202 main_tree,
203 length_tree,
204 },
205 // > The initial state of R0, R1, R2 is (1, 1, 1).
206 r: [1, 1, 1],
207 first_chunk_read: false,
208 chunk_offset: 0,
209 postprocess: None,
210 // Start with some dummy value.
211 current_block: Block {
212 remaining: 0,
213 size: 0,
214 kind: BlockKind::Uncompressed { r: [1, 1, 1] },
215 },
216 }
217 }
218
219 /// Try reading the header for the first chunk.
220 fn try_read_first_chunk(&mut self, bitstream: &mut Bitstream) -> Result<(), DecodeFailed> {
221 // > The first bit in the first chunk in the LZXD bitstream (following the 2-byte,
222 // > chunk-size prefix described in section 2.2.1) indicates the presence or absence of
223 // > two 16-bit fields immediately following the single bit. If the bit is set, E8
224 // > translation is enabled.
225 if !self.first_chunk_read {
226 self.first_chunk_read = true;
227
228 let e8_translation = bitstream.read_bit()? != 0;
229 self.postprocess = if e8_translation {
230 Some(PostProcessState {
231 data_chunk: vec![0; MAX_CHUNK_SIZE].into_boxed_slice(),
232 e8_translation_size: bitstream.read_bits(32)? as i32,
233 })
234 } else {
235 None
236 };
237 }
238
239 Ok(())
240 }
241
242 /// Attempts to perform post-decompression E8 fixups on an output data buffer.
243 fn postprocess(
244 translation_size: i32,
245 chunk_offset: usize,
246 idata: &mut [u8],
247 ) -> Result<&[u8], DecodeFailed> {
248 let mut processed = 0usize;
249
250 // Find the next E8 match, or finish once there are no more E8 matches.
251 while let Some(pos) = idata[processed..]
252 .iter()
253 .position(|&e| e == 0xE8)
254 .map(|pos| processed + pos)
255 {
256 // N.B: E8 fixups are only performed for up to 10 bytes before the end of a chunk.
257 if idata.len() - pos <= 10 {
258 break;
259 }
260
261 // This is the current file output pointer.
262 let current_pointer = chunk_offset + pos;
263
264 // Match. Fix up the following bytes.
265 let abs_val = i32::from_le_bytes([
266 idata[pos + 1],
267 idata[pos + 2],
268 idata[pos + 3],
269 idata[pos + 4],
270 ]);
271 if (abs_val >= -(current_pointer as i32)) && abs_val < translation_size {
272 let rel_val = if abs_val.is_positive() {
273 abs_val.wrapping_sub(current_pointer as i32)
274 } else {
275 abs_val.wrapping_add(translation_size)
276 };
277
278 idata[pos + 1..pos + 5].copy_from_slice(&rel_val.to_le_bytes());
279 }
280
281 processed = pos + 5;
282 }
283
284 Ok(idata)
285 }
286
287 /// Decompresses the next compressed `chunk` from the LZXD data stream.
288 pub fn decompress_next(
289 &mut self,
290 chunk: &[u8],
291 output_len: usize,
292 ) -> Result<&[u8], DecompressError> {
293 // > A chunk represents exactly 32 KB of uncompressed data until the last chunk in the
294 // > stream, which can represent less than 32 KB.
295 //
296 // > The LZXD engine encodes a compressed, chunk-size prefix field preceding each
297 // > compressed chunk in the compressed byte stream. The compressed, chunk-size prefix
298 // > field is a byte aligned, little-endian, 16-bit field.
299 //
300 // However, this doesn't seem to be part of LZXD itself? At least when testing with
301 // `.xnb` files, every chunk comes with a compressed chunk size unless it has the flag
302 // set to 0xff where it also includes the uncompressed chunk size.
303 //
304 // TODO maybe the docs could clarify whether this length is compressed or not
305
306 let mut bitstream = Bitstream::new(chunk);
307
308 self.try_read_first_chunk(&mut bitstream)?;
309
310 let mut decoded_len = 0;
311 while decoded_len != output_len {
312 if self.current_block.remaining == 0 {
313 // Re-align the bitstream to word
314 // Related: https://github.com/GNOME/gcab/blob/master/libgcab/decomp.c#L883.
315 // Related: https://github.com/kyz/libmspack/blob/master/libmspack/mspack/lzxd.c#L469
316 if matches!(self.current_block.kind, BlockKind::Uncompressed { .. })
317 && self.current_block.size % 2 != 0
318 {
319 bitstream.read_byte();
320 }
321 self.current_block = Block::read(&mut bitstream, &mut self.state)?;
322 assert_ne!(self.current_block.remaining, 0);
323 }
324
325 let decoded = self
326 .current_block
327 .decode_element(&mut bitstream, &mut self.r)?;
328
329 let advance = match decoded {
330 Decoded::Single(value) => {
331 self.window.push(value);
332 1
333 }
334 Decoded::Match { offset, length } => {
335 self.window.copy_from_self(offset, length);
336 length
337 }
338 Decoded::Read(length) => {
339 // Read up to end of chunk, to allow for larger blocks.
340 let length = usize::min(bitstream.remaining_bytes(), length);
341 // Will re-align if needed, just as decompressed reads mandate.
342 self.window.copy_from_bitstream(&mut bitstream, length)?;
343 length
344 }
345 };
346
347 if advance == 0 {
348 return Err(DecodeFailed::UnexpectedEof.into());
349 }
350
351 decoded_len += advance;
352 if let Some(value) = self.current_block.remaining.checked_sub(advance as u32) {
353 self.current_block.remaining = value;
354 } else {
355 return Err(DecodeFailed::OverreadBlock.into());
356 }
357 }
358
359 let chunk_offset = self.chunk_offset;
360 self.chunk_offset += decoded_len;
361
362 let view = self.window.past_view(decoded_len)?;
363 if let Some(postprocess) = self.postprocess.as_mut() {
364 // E8 fixups are disabled after 1GB of input data,
365 // or if the chunk size is too small.
366 if chunk_offset >= 0x4000_0000 || decoded_len <= 10 {
367 Ok(view)
368 } else {
369 let postprocess_buf = &mut postprocess.data_chunk[..decoded_len];
370 postprocess_buf.copy_from_slice(view);
371
372 // E8 fixups are enabled. Postprocess the output buffer.
373 let view = Self::postprocess(
374 postprocess.e8_translation_size,
375 chunk_offset,
376 postprocess_buf,
377 )?;
378 Ok(view)
379 }
380 } else {
381 Ok(view)
382 }
383 }
384
385 /// Resets the decoder state.
386 ///
387 /// This is equivalent to calling [`Self::new`] with the same [`WindowSize`].
388 /// [`WindowSize`]: enum.WindowSize.html
389 pub fn reset(&mut self) {
390 let this = Self::new(self.state.window_size);
391 let _ = mem::replace(self, this);
392 }
393 }
394
395 #[cfg(test)]
396 mod tests {
397 use super::*;
398
399 #[test]
400 fn check_uncompressed() {
401 let data = [
402 0x00, 0x30, 0x30, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00,
403 0x00, 0x00, b'a', b'b', b'c', 0x00,
404 ];
405
406 let mut lzxd = Lzxd::new(WindowSize::KB32); // size does not matter
407 let res = lzxd.decompress_next(&data, 3);
408 assert_eq!(res.unwrap(), [b'a', b'b', b'c']);
409 }
410
411 #[test]
412 fn reset() {
413 let data = [
414 0x00, 0x30, 0x30, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00,
415 0x00, 0x00, b'a', b'b', b'c', 0x00,
416 ];
417
418 let mut lzxd = Lzxd::new(WindowSize::KB32); // size does not matter
419 let res = lzxd.decompress_next(&data, 3);
420 assert_eq!(res.unwrap(), [b'a', b'b', b'c']);
421
422 lzxd.reset();
423 let res = lzxd.decompress_next(&data, 3);
424 assert_eq!(res.unwrap(), [b'a', b'b', b'c']);
425 }
426
427 #[test]
428 fn check_e8() {
429 let data = [
430 0x5B, 0x80, 0x80, 0x8D, 0x00, 0x30, 0x80, 0x0A, 0x18, 0x00, 0x00, 0x00, 0x01, 0x00,
431 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x54, 0x68, 0x69, 0x73, 0x20, 0x66, 0x69, 0x6C,
432 0x65, 0x20, 0x68, 0x61, 0x73, 0x20, 0x61, 0x6E, 0x20, 0x45, 0x38, 0x20, 0x62, 0x79,
433 0x74, 0x65, 0x20, 0x74, 0x6F, 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x45, 0x38, 0x20,
434 0x74, 0x72, 0x61, 0x6E, 0x73, 0x6C, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x2C, 0x20, 0x58,
435 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64,
436 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64,
437 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64,
438 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64,
439 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64,
440 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64,
441 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0xE8, 0x7B,
442 0x00, 0x00, 0x00, 0xE8, 0x7B, 0x00, 0x00, 0x00, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64,
443 0x64, 0x64, 0x64, 0x64, 0x64, 0x64,
444 ];
445
446 let mut lzxd = Lzxd::new(WindowSize::KB32);
447 let res = lzxd.decompress_next(&data, 168);
448 assert_eq!(
449 res.unwrap(),
450 b"This file has an E8 byte to test E8 translation, Xdddddddddddddddd\
451 dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd\
452 dddddddddddddd\xE8\xE9\xFF\xFF\xFF\xE8\xE4\xFF\xFF\xFFdddddddddddd"
453 );
454 }
455
456 #[test]
457 fn uncompressed_single_byte_data() {
458 let mut lzxd = Lzxd::new(WindowSize::KB32);
459 let res = lzxd.decompress_next(&[0x00], 32);
460 assert_eq!(res.unwrap_err().0, DecodeFailed::UnexpectedEof);
461 }
462
463 #[test]
464 fn uncompressed_advance_zero() {
465 // Regression test for "assertion `left != right` failed: left: 0, right: 0" panic
466 // This occurs when the decoder cannot advance (advance == 0)
467 // Data from fuzzer crash
468 let data = vec![
469 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
470 0x32, 0x32
471 ];
472
473 let mut lzxd = Lzxd::new(WindowSize::KB32);
474 let res = lzxd.decompress_next(&data, 32);
475 assert_eq!(res.unwrap_err().0, DecodeFailed::UnexpectedEof);
476 }
477
478 #[test]
479 fn peek_bits_oneword_bounds_check() {
480 // Regression test for peek_bits_oneword index out of bounds panic
481 // This exercises the buffer.len() < 2 check in peek_bits_oneword
482 // Data from fuzzer crash
483 let data = vec![
484 0x12, 0x12, 0x12, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12,
485 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x00, 0x00, 0x00, 0x12, 0x8a,
486 ];
487
488 let mut lzxd = Lzxd::new(WindowSize::KB32);
489 let res = lzxd.decompress_next(&data, 32);
490 assert_eq!(res.unwrap_err().0, DecodeFailed::UnexpectedEof);
491 }
492 }