Debian Codegraph @

src/org/tukaani/xz/LZMA2InputStream.java

raw symbols SCIP
1 // SPDX-License-Identifier: 0BSD
2 // SPDX-FileCopyrightText: The XZ for Java authors and contributors
3 // SPDX-FileContributor: Lasse Collin <[email protected]>
4 // SPDX-FileContributor: Igor Pavlov <https://7-zip.org/>
5
6 package org.tukaani.xz;
7
8 import java.io.InputStream;
9 import java.io.DataInputStream;
10 import java.io.IOException;
11 import java.io.EOFException;
12 import org.tukaani.xz.lz.LZDecoder;
13 import org.tukaani.xz.rangecoder.RangeDecoderFromBuffer;
14 import org.tukaani.xz.lzma.LZMADecoder;
15
16 /**
17 * Decompresses a raw LZMA2 stream (no XZ headers).
18 */
19 public class LZMA2InputStream extends InputStream {
20 /**
21 * Smallest valid LZMA2 dictionary size.
22 * <p>
23 * Very tiny dictionaries would be a performance problem, so
24 * the minimum is 4 KiB.
25 */
26 public static final int DICT_SIZE_MIN = 4096;
27
28 /**
29 * Largest dictionary size supported by this implementation.
30 * <p>
31 * The LZMA2 algorithm allows dictionaries up to one byte less than 4 GiB.
32 * This implementation supports only 16 bytes less than 2 GiB for raw
33 * LZMA2 streams, and for .xz files the maximum is 1.5 GiB. This
34 * limitation is due to Java using signed 32-bit integers for array
35 * indexing. The limitation shouldn't matter much in practice since so
36 * huge dictionaries are not normally used.
37 */
38 public static final int DICT_SIZE_MAX = Integer.MAX_VALUE & ~15;
39
40 private static final int COMPRESSED_SIZE_MAX = 1 << 16;
41
42 private final ArrayCache arrayCache;
43 private DataInputStream in;
44
45 private LZDecoder lz;
46 private RangeDecoderFromBuffer rc;
47 private LZMADecoder lzma;
48
49 private int uncompressedSize = 0;
50 private boolean isLZMAChunk = false;
51
52 private boolean needDictReset = true;
53 private boolean needProps = true;
54 private boolean endReached = false;
55
56 private IOException exception = null;
57
58 private final byte[] tempBuf = new byte[1];
59
60 /**
61 * Gets approximate decompressor memory requirements as kibibytes for
62 * the given dictionary size.
63 *
64 * @param dictSize LZMA2 dictionary size as bytes, must be
65 * in the range [{@code DICT_SIZE_MIN},
66 * {@code DICT_SIZE_MAX}]
67 *
68 * @return approximate memory requirements as kibibytes (KiB)
69 */
70 public static int getMemoryUsage(int dictSize) {
71 // The base state is around 30-40 KiB (probabilities etc.),
72 // range decoder needs COMPRESSED_SIZE_MAX bytes for buffering,
73 // and LZ decoder needs a dictionary buffer.
74 return 40 + COMPRESSED_SIZE_MAX / 1024 + getDictSize(dictSize) / 1024;
75 }
76
77 private static int getDictSize(int dictSize) {
78 if (dictSize < DICT_SIZE_MIN || dictSize > DICT_SIZE_MAX)
79 throw new IllegalArgumentException(
80 "Unsupported dictionary size " + dictSize);
81
82 // Round dictionary size upward to a multiple of 16. This way LZMA
83 // can use LZDecoder.getPos() for calculating LZMA's posMask.
84 // Note that this check is needed only for raw LZMA2 streams; it is
85 // redundant with .xz.
86 return (dictSize + 15) & ~15;
87 }
88
89 /**
90 * Creates a new input stream that decompresses raw LZMA2 data
91 * from {@code in}.
92 * <p>
93 * The caller needs to know the dictionary size used when compressing;
94 * the dictionary size isn't stored as part of a raw LZMA2 stream.
95 * <p>
96 * Specifying a too small dictionary size will prevent decompressing
97 * the stream. Specifying a too big dictionary is waste of memory but
98 * decompression will work.
99 * <p>
100 * There is no need to specify a dictionary bigger than
101 * the uncompressed size of the data even if a bigger dictionary
102 * was used when compressing. If you know the uncompressed size
103 * of the data, this might allow saving some memory.
104 *
105 * @param in input stream from which LZMA2-compressed
106 * data is read
107 *
108 * @param dictSize LZMA2 dictionary size as bytes, must be
109 * in the range [{@code DICT_SIZE_MIN},
110 * {@code DICT_SIZE_MAX}]
111 */
112 public LZMA2InputStream(InputStream in, int dictSize) {
113 this(in, dictSize, null);
114 }
115
116 /**
117 * Creates a new LZMA2 decompressor using a preset dictionary.
118 * <p>
119 * This is like {@code LZMA2InputStream(InputStream, int)} except
120 * that the dictionary may be initialized using a preset dictionary.
121 * If a preset dictionary was used when compressing the data, the
122 * same preset dictionary must be provided when decompressing.
123 *
124 * @param in input stream from which LZMA2-compressed
125 * data is read
126 *
127 * @param dictSize LZMA2 dictionary size as bytes, must be
128 * in the range [{@code DICT_SIZE_MIN},
129 * {@code DICT_SIZE_MAX}]
130 *
131 * @param presetDict preset dictionary or {@code null}
132 * to use no preset dictionary
133 */
134 public LZMA2InputStream(InputStream in, int dictSize, byte[] presetDict) {
135 this(in, dictSize, presetDict, ArrayCache.getDefaultCache());
136 }
137
138 /**
139 * Creates a new LZMA2 decompressor using a preset dictionary
140 * and array cache.
141 * <p>
142 * This is like {@code LZMA2InputStream(InputStream, int, byte[])}
143 * except that this also takes the {@code arrayCache} argument.
144 *
145 * @param in input stream from which LZMA2-compressed
146 * data is read
147 *
148 * @param dictSize LZMA2 dictionary size as bytes, must be
149 * in the range [{@code DICT_SIZE_MIN},
150 * {@code DICT_SIZE_MAX}]
151 *
152 * @param presetDict preset dictionary or {@code null}
153 * to use no preset dictionary
154 *
155 * @param arrayCache cache to be used for allocating large arrays
156 *
157 * @since 1.7
158 */
159 LZMA2InputStream(InputStream in, int dictSize, byte[] presetDict,
160 ArrayCache arrayCache) {
161 // Check for null because otherwise null isn't detect
162 // in this constructor.
163 if (in == null)
164 throw new NullPointerException();
165
166 this.arrayCache = arrayCache;
167 this.in = new DataInputStream(in);
168 this.rc = new RangeDecoderFromBuffer(COMPRESSED_SIZE_MAX, arrayCache);
169 this.lz = new LZDecoder(getDictSize(dictSize), presetDict, arrayCache);
170
171 if (presetDict != null && presetDict.length > 0)
172 needDictReset = false;
173 }
174
175 /**
176 * Decompresses the next byte from this input stream.
177 * <p>
178 * Reading lots of data with {@code read()} from this input stream
179 * may be inefficient. Wrap it in {@code java.io.BufferedInputStream}
180 * if you need to read lots of data one byte at a time.
181 *
182 * @return the next decompressed byte, or {@code -1}
183 * to indicate the end of the compressed stream
184 *
185 * @throws CorruptedInputException
186 *
187 * @throws XZIOException if the stream has been closed
188 *
189 * @throws EOFException
190 * compressed input is truncated or corrupt
191 *
192 * @throws IOException may be thrown by {@code in}
193 */
194 @Override
195 public int read() throws IOException {
196 return read(tempBuf, 0, 1) == -1 ? -1 : (tempBuf[0] & 0xFF);
197 }
198
199 /**
200 * Decompresses into an array of bytes.
201 * <p>
202 * If {@code len} is zero, no bytes are read and {@code 0}
203 * is returned. Otherwise this will block until {@code len}
204 * bytes have been decompressed, the end of the LZMA2 stream is reached,
205 * or an exception is thrown.
206 *
207 * @param buf target buffer for uncompressed data
208 * @param off start offset in {@code buf}
209 * @param len maximum number of uncompressed bytes to read
210 *
211 * @return number of bytes read, or {@code -1} to indicate
212 * the end of the compressed stream
213 *
214 * @throws CorruptedInputException
215 *
216 * @throws XZIOException if the stream has been closed
217 *
218 * @throws EOFException
219 * compressed input is truncated or corrupt
220 *
221 * @throws IOException may be thrown by {@code in}
222 */
223 @Override
224 public int read(byte[] buf, int off, int len) throws IOException {
225 if (off < 0 || len < 0 || off + len < 0 || off + len > buf.length)
226 throw new IndexOutOfBoundsException();
227
228 if (len == 0)
229 return 0;
230
231 if (in == null)
232 throw new XZIOException("Stream closed");
233
234 if (exception != null)
235 throw exception;
236
237 if (endReached)
238 return -1;
239
240 try {
241 int size = 0;
242
243 while (len > 0) {
244 if (uncompressedSize == 0) {
245 decodeChunkHeader();
246 if (endReached)
247 return size == 0 ? -1 : size;
248 }
249
250 int copySizeMax = Math.min(uncompressedSize, len);
251
252 if (!isLZMAChunk) {
253 lz.copyUncompressed(in, copySizeMax);
254 } else {
255 lz.setLimit(copySizeMax);
256 lzma.decode();
257 }
258
259 int copiedSize = lz.flush(buf, off);
260 off += copiedSize;
261 len -= copiedSize;
262 size += copiedSize;
263 uncompressedSize -= copiedSize;
264
265 if (uncompressedSize == 0)
266 if (!rc.isFinished() || lz.hasPending())
267 throw new CorruptedInputException();
268 }
269
270 return size;
271
272 } catch (IOException e) {
273 exception = e;
274 throw e;
275 }
276 }
277
278 private void decodeChunkHeader() throws IOException {
279 int control = in.readUnsignedByte();
280
281 if (control == 0x00) {
282 endReached = true;
283 putArraysToCache();
284 return;
285 }
286
287 if (control >= 0xE0 || control == 0x01) {
288 needProps = true;
289 needDictReset = false;
290 lz.reset();
291 } else if (needDictReset) {
292 throw new CorruptedInputException();
293 }
294
295 if (control >= 0x80) {
296 isLZMAChunk = true;
297
298 uncompressedSize = (control & 0x1F) << 16;
299 uncompressedSize += in.readUnsignedShort() + 1;
300
301 int compressedSize = in.readUnsignedShort() + 1;
302
303 if (control >= 0xC0) {
304 needProps = false;
305 decodeProps();
306
307 } else if (needProps) {
308 throw new CorruptedInputException();
309
310 } else if (control >= 0xA0) {
311 lzma.reset();
312 }
313
314 rc.prepareInputBuffer(in, compressedSize);
315
316 } else if (control > 0x02) {
317 throw new CorruptedInputException();
318
319 } else {
320 isLZMAChunk = false;
321 uncompressedSize = in.readUnsignedShort() + 1;
322 }
323 }
324
325 private void decodeProps() throws IOException {
326 int props = in.readUnsignedByte();
327
328 if (props > (4 * 5 + 4) * 9 + 8)
329 throw new CorruptedInputException();
330
331 int pb = props / (9 * 5);
332 props -= pb * 9 * 5;
333 int lp = props / 9;
334 int lc = props - lp * 9;
335
336 if (lc + lp > 4)
337 throw new CorruptedInputException();
338
339 lzma = new LZMADecoder(lz, rc, lc, lp, pb);
340 }
341
342 /**
343 * Returns the number of uncompressed bytes that can be read
344 * without blocking. The value is returned with an assumption
345 * that the compressed input data will be valid. If the compressed
346 * data is corrupt, {@code CorruptedInputException} may get
347 * thrown before the number of bytes claimed to be available have
348 * been read from this input stream.
349 * <p>
350 * In LZMA2InputStream, the return value will be non-zero when the
351 * decompressor is in the middle of an LZMA2 chunk. The return value
352 * will then be the number of uncompressed bytes remaining from that
353 * chunk. The return value can also be non-zero in the middle of
354 * an uncompressed chunk, but then the return value depends also on
355 * the {@code available()} method of the underlying InputStream.
356 *
357 * @return the number of uncompressed bytes that can be read
358 * without blocking
359 */
360 @Override
361 public int available() throws IOException {
362 if (in == null)
363 throw new XZIOException("Stream closed");
364
365 if (exception != null)
366 throw exception;
367
368 return isLZMAChunk ? uncompressedSize
369 : Math.min(uncompressedSize, in.available());
370 }
371
372 private void putArraysToCache() {
373 if (lz != null) {
374 lz.putArraysToCache(arrayCache);
375 lz = null;
376
377 rc.putArraysToCache(arrayCache);
378 rc = null;
379 }
380 }
381
382 /**
383 * Closes the stream and calls {@code in.close()}.
384 * If the stream was already closed, this does nothing.
385 *
386 * @throws IOException if thrown by {@code in.close()}
387 */
388 @Override
389 public void close() throws IOException {
390 if (in != null) {
391 putArraysToCache();
392
393 try {
394 in.close();
395 } finally {
396 in = null;
397 }
398 }
399 }
400 }