* Not Supported:
@@ -316,10 +316,10 @@ private void readBlock() throws IOException {
}
}
- // Reads the data of a block of the given length, growing buf as the data arrives
- private byte[] readBlockData(byte[] buf, int len) throws IOException {
+ // Reads the data of a block of the given length into buf at off, growing buf as the data arrives
+ private byte[] readBlockData(byte[] buf, int off, int len, int maxLen) throws IOException {
try {
- return LZ4Utils.readFullyGrowing(in, buf == null ? EMPTY : buf, len, maxBlockSize);
+ return LZ4Utils.readFullyGrowing(in, buf == null ? EMPTY : buf, off, len, maxLen);
} catch (EOFException e) {
// report truncation like the other parts of the frame do, not as an EOFException that callers may take for a
// clean end of data
@@ -327,6 +327,11 @@ private byte[] readBlockData(byte[] buf, int len) throws IOException {
}
}
+ // The decompressed data, up to the end of the current block. Tests use it to see where blocks are decoded.
+ ByteBuffer decompressedBuffer() {
+ return buffer;
+ }
+
private void setRawBuffer(byte[] rawBuffer) {
if (rawBuffer != this.rawBuffer) {
this.rawBuffer = rawBuffer;
@@ -335,6 +340,19 @@ private void setRawBuffer(byte[] rawBuffer) {
}
}
+ // Linked blocks: if fewer than len bytes follow blockOff in rawBuffer, and at least MAX_DISTANCE bytes before the
+ // history are no longer needed, moves the prefixLen bytes of history before blockOff to the start of rawBuffer.
+ // Returns the offset of the block, right after the history. Otherwise the caller grows rawBuffer, up to
+ // 2 * MAX_DISTANCE + maxBlockSize: as in liblz4, the history is then moved at most once per MAX_DISTANCE bytes of
+ // decompressed data, however small the blocks are.
+ private int makeRoom(int blockOff, int prefixLen, int len) {
+ if (blockOff - prefixLen >= MAX_DISTANCE && notEnoughSpace(rawBuffer.length - blockOff, len)) {
+ System.arraycopy(rawBuffer, blockOff - prefixLen, rawBuffer, 0, prefixLen);
+ return prefixLen;
+ }
+ return blockOff;
+ }
+
private IOException fail(IOException e) {
failure = e;
return e;
@@ -351,12 +369,12 @@ private void readBlock0() throws IOException {
// the content checksum hash was released by close()
throw new IOException("Stream closed");
}
- int blockSize = readInt(in);
- final boolean compressed = (blockSize & LZ4FrameOutputStream.LZ4_FRAME_INCOMPRESSIBLE_MASK) == 0;
- blockSize &= ~LZ4FrameOutputStream.LZ4_FRAME_INCOMPRESSIBLE_MASK;
+ final int blockHeader = readInt(in);
+ final boolean compressed = (blockHeader & LZ4FrameOutputStream.LZ4_FRAME_INCOMPRESSIBLE_MASK) == 0;
+ final int blockSize = blockHeader & ~LZ4FrameOutputStream.LZ4_FRAME_INCOMPRESSIBLE_MASK;
- // Check for EndMark
- if (blockSize == 0) {
+ // Check for EndMark. Only 0 is an EndMark: 0x80000000 is an empty uncompressed block, which doesn't end the frame.
+ if (blockHeader == 0) {
if (frameInfo.isEnabled(LZ4FrameOutputStream.FLG.Bits.CONTENT_CHECKSUM)) {
final int contentChecksum = readInt(in);
if (contentChecksum != frameInfo.currentStreamHash()) {
@@ -374,21 +392,37 @@ private void readBlock0() throws IOException {
throw new IOException(String.format(Locale.ROOT, "Block size %s exceeded max: %s", blockSize, maxBlockSize));
}
+ // Independent blocks are decoded at the start of rawBuffer. Linked blocks may reference up to 64 KB of the data
+ // decoded before them in the frame, so they are decoded after it. This data ends at buffer.limit().
+ int blockOff = 0;
+ int prefixLen = 0;
+ int maxRawBufferSize = maxBlockSize;
+ if (!frameInfo.isEnabled(LZ4FrameOutputStream.FLG.Bits.BLOCK_INDEPENDENCE)) {
+ blockOff = buffer.limit();
+ prefixLen = Math.min(blockOff, MAX_DISTANCE);
+ // room for the history, for up to MAX_DISTANCE bytes before it that makeRoom does not move yet, and the block
+ maxRawBufferSize = 2 * MAX_DISTANCE + maxBlockSize;
+ }
+
// The block size comes from the untrusted input, so the buffers are only allocated as the block data actually
// arrives. They may be larger than maxBlockSize if a previous frame had a larger block size. Never shrink them.
final byte[] tmpBuffer;
+ final int tmpOff;
if (compressed) {
- compressedBuffer = readBlockData(compressedBuffer, blockSize);
+ compressedBuffer = readBlockData(compressedBuffer, 0, blockSize, maxBlockSize);
tmpBuffer = compressedBuffer;
+ tmpOff = 0;
} else {
- setRawBuffer(readBlockData(rawBuffer, blockSize));
+ blockOff = makeRoom(blockOff, prefixLen, blockSize);
+ setRawBuffer(readBlockData(rawBuffer, blockOff, blockSize, maxRawBufferSize));
tmpBuffer = rawBuffer;
+ tmpOff = blockOff;
}
// verify block checksum
if (frameInfo.isEnabled(LZ4FrameOutputStream.FLG.Bits.BLOCK_CHECKSUM)) {
final int hashCheck = readInt(in);
- if (hashCheck != checksum.hash(tmpBuffer, 0, blockSize, 0)) {
+ if (hashCheck != checksum.hash(tmpBuffer, tmpOff, blockSize, 0)) {
throw new IOException(BLOCK_HASH_MISMATCH);
}
}
@@ -397,12 +431,24 @@ private void readBlock0() throws IOException {
if (compressed) {
// the block cannot decompress to more than the maximum compression ratio allows
final int maxDecompressedSize = (int) Math.min(maxBlockSize, (long) blockSize * MAX_COMPRESSION_RATIO);
- if (rawBuffer == null || rawBuffer.length < maxDecompressedSize) {
+ blockOff = makeRoom(blockOff, prefixLen, maxDecompressedSize);
+ if (rawBuffer == null || notEnoughSpace(rawBuffer.length - blockOff, maxDecompressedSize)) {
+ // the history, if any, ends at blockOff
final int oldLength = rawBuffer == null ? 0 : rawBuffer.length;
- setRawBuffer(new byte[LZ4Utils.grownLength(oldLength, maxDecompressedSize, maxBlockSize)]);
+ final byte[] grown = new byte[LZ4Utils.grownLength(oldLength, blockOff + maxDecompressedSize, maxRawBufferSize)];
+ if (blockOff > 0) {
+ System.arraycopy(rawBuffer, 0, grown, 0, blockOff);
+ }
+ setRawBuffer(grown);
}
try {
- currentBufferSize = decompressor.decompress(tmpBuffer, 0, blockSize, rawBuffer, 0, maxDecompressedSize);
+ // Without history (independent blocks, first linked block), decompress as before. This also keeps working with
+ // an older native library loaded from java.library.path. With such a library, decompressing with history
+ // fails with an LZ4Exception, so linked blocks after the first fail with an IOException.
+ currentBufferSize = prefixLen == 0
+ ? decompressor.decompress(tmpBuffer, 0, blockSize, rawBuffer, blockOff, maxDecompressedSize)
+ : decompressor.decompressWithPrefix(tmpBuffer, 0, blockSize, rawBuffer, blockOff, maxDecompressedSize,
+ prefixLen);
} catch (LZ4Exception e) {
throw new IOException(e);
}
@@ -410,11 +456,11 @@ private void readBlock0() throws IOException {
currentBufferSize = blockSize;
}
if (frameInfo.isEnabled(LZ4FrameOutputStream.FLG.Bits.CONTENT_CHECKSUM)) {
- frameInfo.updateStreamHash(rawBuffer, 0, currentBufferSize);
+ frameInfo.updateStreamHash(rawBuffer, blockOff, currentBufferSize);
}
totalContentSize += currentBufferSize;
- buffer.limit(currentBufferSize);
- buffer.rewind();
+ buffer.limit(blockOff + currentBufferSize);
+ buffer.position(blockOff);
}
@Override
diff --git a/src/java/net/jpountz/lz4/LZ4FrameOutputStream.java b/src/java/net/jpountz/lz4/LZ4FrameOutputStream.java
index e5df5162..edd8cea7 100644
--- a/src/java/net/jpountz/lz4/LZ4FrameOutputStream.java
+++ b/src/java/net/jpountz/lz4/LZ4FrameOutputStream.java
@@ -340,6 +340,10 @@ public FLG(int version, Bits... bits) {
}
}
validate();
+ // LZ4FrameOutputStream only writes independent blocks. LZ4FrameInputStream reads both, through fromByte.
+ if (!bitSet.get(Bits.BLOCK_INDEPENDENCE.position)) {
+ throw new RuntimeException("Dependent block stream is unsupported (BLOCK_INDEPENDENCE must be set)");
+ }
}
private FLG(int version, byte b) {
@@ -349,12 +353,13 @@ private FLG(int version, byte b) {
}
public static FLG fromByte(byte flg) {
- final byte versionMask = (byte) (flg & (3 << 6));
- return new FLG(versionMask >>> 6, (byte) (flg ^ versionMask));
+ return new FLG((flg >> 6) & 3, (byte) (flg & 0x3F));
}
public byte toByte() {
- return (byte) (bitSet.toByteArray()[0] | ((version & 3) << 6));
+ // toByteArray() is empty if no bit is set, which fromByte allows for linked blocks
+ final byte[] bits = bitSet.toByteArray();
+ return (byte) ((bits.length == 0 ? 0 : bits[0]) | ((version & 3) << 6));
}
private void validate() {
@@ -364,9 +369,6 @@ private void validate() {
if (bitSet.get(Bits.RESERVED_1.position)) {
throw new RuntimeException("Reserved1 field must be 0");
}
- if (!bitSet.get(Bits.BLOCK_INDEPENDENCE.position)) {
- throw new RuntimeException("Dependent block stream is unsupported (BLOCK_INDEPENDENCE must be set)");
- }
if (version != DEFAULT_VERSION) {
throw new RuntimeException(String.format(Locale.ROOT, "Version %d is unsupported", version));
}
diff --git a/src/java/net/jpountz/lz4/LZ4JNI.java b/src/java/net/jpountz/lz4/LZ4JNI.java
index dfb99283..12075883 100644
--- a/src/java/net/jpountz/lz4/LZ4JNI.java
+++ b/src/java/net/jpountz/lz4/LZ4JNI.java
@@ -37,6 +37,11 @@ enum LZ4JNI {
static native int LZ4_compressHC(byte[] srcArray, ByteBuffer srcBuffer, int srcOff, int srcLen, byte[] destArray, ByteBuffer destBuffer, int destOff, int maxDestLen, int compressionLevel);
static native int LZ4_decompress_fast(byte[] srcArray, ByteBuffer srcBuffer, int srcOff, byte[] destArray, ByteBuffer destBuffer, int destOff, int destLen);
static native int LZ4_decompress_safe(byte[] srcArray, ByteBuffer srcBuffer, int srcOff, int srcLen, byte[] destArray, ByteBuffer destBuffer, int destOff, int maxDestLen);
+ /**
+ * Calls {@code LZ4_decompress_safe_usingDict()} with the {@code dictLen} bytes before {@code destOff} in the
+ * destination as the dictionary. liblz4 detects this prefix case and decompresses without copying it.
+ */
+ static native int LZ4_decompress_safe_usingDict(byte[] srcArray, ByteBuffer srcBuffer, int srcOff, int srcLen, byte[] destArray, ByteBuffer destBuffer, int destOff, int maxDestLen, int dictLen);
static native int LZ4_compressBound(int len);
/**
diff --git a/src/java/net/jpountz/lz4/LZ4JNISafeDecompressor.java b/src/java/net/jpountz/lz4/LZ4JNISafeDecompressor.java
index 7f75866e..84fc6d21 100644
--- a/src/java/net/jpountz/lz4/LZ4JNISafeDecompressor.java
+++ b/src/java/net/jpountz/lz4/LZ4JNISafeDecompressor.java
@@ -57,6 +57,25 @@ public final int decompress(byte[] src, int srcOff, int srcLen, byte[] dest, int
return result;
}
+ @Override
+ final int decompressWithPrefix(byte[] src, int srcOff, int srcLen, byte[] dest, int destOff, int maxDestLen, int prefixLen) {
+ SafeUtils.checkRange(src, srcOff, srcLen);
+ SafeUtils.checkRange(dest, destOff, maxDestLen);
+ SafeUtils.checkRange(dest, destOff - prefixLen, prefixLen);
+ final int result;
+ try {
+ result = LZ4JNI.LZ4_decompress_safe_usingDict(src, null, srcOff, srcLen, dest, null, destOff, maxDestLen, prefixLen);
+ } catch (UnsatisfiedLinkError e) {
+ // an older native library loaded from java.library.path lacks this function. Linked blocks were unsupported
+ // before it was added, so fail like other unsupported input rather than with an Error.
+ throw new LZ4Exception("The loaded native library does not support linked blocks", e);
+ }
+ if (result < 0) {
+ throw new LZ4Exception(errorMessage(result));
+ }
+ return result;
+ }
+
@Override
public int decompress(ByteBuffer src, int srcOff, int srcLen, ByteBuffer dest, int destOff, int maxDestLen) {
ByteBufferUtils.checkNotReadOnly(dest);
diff --git a/src/java/net/jpountz/lz4/LZ4SafeDecompressor.java b/src/java/net/jpountz/lz4/LZ4SafeDecompressor.java
index 92792c34..dd85e66b 100644
--- a/src/java/net/jpountz/lz4/LZ4SafeDecompressor.java
+++ b/src/java/net/jpountz/lz4/LZ4SafeDecompressor.java
@@ -61,6 +61,19 @@ public abstract class LZ4SafeDecompressor implements LZ4UnknownSizeDecompressor
*/
public abstract int decompress(ByteBuffer src, int srcOff, int srcLen, ByteBuffer dest, int destOff, int maxDestLen);
+ /**
+ * Same as {@link #decompress(byte[], int, int, byte[], int, int)}, but the compressed data may also reference the
+ * prefixLen bytes before destOff in dest, which hold the data decompressed
+ * before it. The linked blocks of the LZ4 frame format need this. Implementations outside of this package don't
+ * support a prefix.
+ */
+ int decompressWithPrefix(byte[] src, int srcOff, int srcLen, byte[] dest, int destOff, int maxDestLen, int prefixLen) {
+ if (prefixLen != 0) {
+ throw new LZ4Exception(getClass().getName() + " does not support linked blocks");
+ }
+ return decompress(src, srcOff, srcLen, dest, destOff, maxDestLen);
+ }
+
/**
* Convenience method, equivalent to calling
* {@link #decompress(byte[], int, int, byte[], int, int) decompress(src, srcOff, srcLen, dest, destOff, dest.length - destOff)}.
diff --git a/src/java/net/jpountz/lz4/LZ4Utils.java b/src/java/net/jpountz/lz4/LZ4Utils.java
index 8b8f3e56..6bacde92 100644
--- a/src/java/net/jpountz/lz4/LZ4Utils.java
+++ b/src/java/net/jpountz/lz4/LZ4Utils.java
@@ -56,16 +56,27 @@ static int maxCompressedLength(int length) {
* @throws EOFException if the stream ends before {@code len} bytes were read
*/
static byte[] readFullyGrowing(InputStream in, byte[] buf, int len, int maxLen) throws IOException {
- int read = 0;
- while (read < len) {
- if (read == buf.length) {
- buf = Arrays.copyOf(buf, grownLength(buf.length, Math.min(len, MIN_GROWN_BUFFER_SIZE), maxLen));
+ return readFullyGrowing(in, buf, 0, len, maxLen);
+ }
+
+ /**
+ * Same as {@link #readFullyGrowing(InputStream, byte[], int, int)}, but reads into {@code buf} at {@code off}. A
+ * grown buffer keeps the first {@code off} bytes of {@code buf}.
+ *
+ * @param maxLen the largest {@code off + len} of any read into this buffer
+ */
+ static byte[] readFullyGrowing(InputStream in, byte[] buf, int off, int len, int maxLen) throws IOException {
+ final int end = off + len;
+ int pos = off;
+ while (pos < end) {
+ if (pos == buf.length) {
+ buf = Arrays.copyOf(buf, grownLength(buf.length, off + Math.min(len, MIN_GROWN_BUFFER_SIZE), maxLen));
}
- final int r = in.read(buf, read, Math.min(len, buf.length) - read);
+ final int r = in.read(buf, pos, Math.min(end, buf.length) - pos);
if (r < 0) {
throw new EOFException("Stream ended prematurely");
}
- read += r;
+ pos += r;
}
return buf;
}
diff --git a/src/jni/net_jpountz_lz4_LZ4JNI.c b/src/jni/net_jpountz_lz4_LZ4JNI.c
index 8932e4a8..633d8154 100644
--- a/src/jni/net_jpountz_lz4_LZ4JNI.c
+++ b/src/jni/net_jpountz_lz4_LZ4JNI.c
@@ -293,6 +293,57 @@ JNIEXPORT jint JNICALL Java_net_jpountz_lz4_LZ4JNI_LZ4_1decompress_1safe
}
+/*
+ * Class: net_jpountz_lz4_LZ4JNI
+ * Method: LZ4_decompress_safe_usingDict
+ * Signature: ([BLjava/nio/ByteBuffer;II[BLjava/nio/ByteBuffer;III)I
+ */
+JNIEXPORT jint JNICALL Java_net_jpountz_lz4_LZ4JNI_LZ4_1decompress_1safe_1usingDict
+ (JNIEnv *env, jclass cls, jbyteArray srcArray, jobject srcBuffer, jint srcOff, jint srcLen, jbyteArray destArray, jobject destBuffer, jint destOff, jint maxDestLen, jint dictLen) {
+
+ char* in;
+ char* out;
+ jint decompressed;
+
+ if (srcArray != NULL) {
+ in = (char*) (*env)->GetPrimitiveArrayCritical(env, srcArray, 0);
+ } else {
+ in = (char*) (*env)->GetDirectBufferAddress(env, srcBuffer);
+ }
+
+ if (in == NULL) {
+ throw_OOM(env);
+ return 0;
+ }
+
+ if (destArray != NULL) {
+ out = (char*) (*env)->GetPrimitiveArrayCritical(env, destArray, 0);
+ } else {
+ out = (char*) (*env)->GetDirectBufferAddress(env, destBuffer);
+ }
+
+ if (out == NULL) {
+ if (srcArray != NULL) {
+ (*env)->ReleasePrimitiveArrayCritical(env, srcArray, in, 0);
+ }
+ throw_OOM(env);
+ return 0;
+ }
+
+ // The dictionary immediately precedes the output, so liblz4 uses it in place as a prefix
+ decompressed = LZ4_decompress_safe_usingDict(in + srcOff, out + destOff, srcLen, maxDestLen, out + destOff - dictLen, dictLen);
+
+ if (srcArray != NULL) {
+ (*env)->ReleasePrimitiveArrayCritical(env, srcArray, in, 0);
+ }
+ if (destArray != NULL) {
+ (*env)->ReleasePrimitiveArrayCritical(env, destArray, out, 0);
+ }
+
+ return decompressed;
+
+}
+
/*
* Class: net_jpountz_lz4_LZ4JNI
* Method: LZ4_compressBound
diff --git a/src/test-resources/net/jpountz/fuzz/LZ4InputStreamTestInputs/frame_multi/linked b/src/test-resources/net/jpountz/fuzz/LZ4InputStreamTestInputs/frame_multi/linked
new file mode 100644
index 00000000..d76807c7
Binary files /dev/null and b/src/test-resources/net/jpountz/fuzz/LZ4InputStreamTestInputs/frame_multi/linked differ
diff --git a/src/test-resources/net/jpountz/fuzz/LZ4InputStreamTestInputs/frame_single/linked b/src/test-resources/net/jpountz/fuzz/LZ4InputStreamTestInputs/frame_single/linked
new file mode 100644
index 00000000..d76807c7
Binary files /dev/null and b/src/test-resources/net/jpountz/fuzz/LZ4InputStreamTestInputs/frame_single/linked differ
diff --git a/src/test/net/jpountz/fuzz/LZ4DecompressorTest.java b/src/test/net/jpountz/fuzz/LZ4DecompressorTest.java
index 544f1b4f..a2d924d9 100644
--- a/src/test/net/jpountz/fuzz/LZ4DecompressorTest.java
+++ b/src/test/net/jpountz/fuzz/LZ4DecompressorTest.java
@@ -4,6 +4,8 @@
import com.code_intelligence.jazzer.junit.FuzzTest;
import net.jpountz.lz4.LZ4Exception;
import net.jpountz.lz4.LZ4Factory;
+import net.jpountz.lz4.LZ4SafeDecompressor;
+import net.jpountz.lz4.LZ4TestAccess;
import java.nio.ByteBuffer;
import java.util.Arrays;
@@ -59,6 +61,56 @@ private void test(FuzzedDataProvider data, LZ4Factory factory, boolean fast, boo
}
}
+ // Linked blocks: the input may also reference the prefixLen bytes before the output. Decompresses twice, with
+ // different data before the prefix and after the output, and compares: the decompressor must not read them.
+ private void testPrefix(FuzzedDataProvider data, LZ4Factory factory) {
+ // up to twice the 64 KB window, so that liblz4 takes both of its prefix paths
+ int prefixLen = data.consumeInt(0, 1 << 17);
+ int garbageLen = data.consumeInt(0, 16);
+ int destLen = data.consumeInt(0, MAX_LEN);
+ byte seed = data.consumeByte();
+ byte[] src = data.consumeRemainingAsBytes();
+ int destOff = garbageLen + prefixLen;
+ byte[] dest1 = new byte[destOff + destLen];
+ byte[] dest2 = new byte[destOff + destLen];
+ Arrays.fill(dest2, (byte) 'x');
+ for (int i = 0; i < prefixLen; i++) {
+ dest1[garbageLen + i] = dest2[garbageLen + i] = (byte) (seed + i * 31);
+ }
+ LZ4SafeDecompressor decompressor = factory.safeDecompressor();
+ int n1;
+ try {
+ n1 = LZ4TestAccess.decompressWithPrefix(decompressor, src, 0, src.length, dest1, destOff, destLen, prefixLen);
+ } catch (LZ4Exception e) {
+ n1 = -1;
+ }
+ int n2;
+ try {
+ n2 = LZ4TestAccess.decompressWithPrefix(decompressor, src, 0, src.length, dest2, destOff, destLen, prefixLen);
+ } catch (LZ4Exception e) {
+ n2 = -1;
+ }
+ assertEquals(n1, n2);
+ if (n1 >= 0) {
+ assertArrayEquals(Arrays.copyOfRange(dest1, destOff, destOff + n1), Arrays.copyOfRange(dest2, destOff, destOff + n2));
+ }
+ }
+
+ @FuzzTest
+ public void safe_prefix(FuzzedDataProvider provider) {
+ testPrefix(provider, LZ4Factory.safeInstance());
+ }
+
+ @FuzzTest
+ public void unsafe_prefix(FuzzedDataProvider provider) {
+ testPrefix(provider, LZ4Factory.unsafeInsecureInstance());
+ }
+
+ @FuzzTest
+ public void native_prefix(FuzzedDataProvider provider) {
+ testPrefix(provider, LZ4Factory.nativeInstance());
+ }
+
@FuzzTest
public void safe_safe_array(FuzzedDataProvider provider) {
test(provider, LZ4Factory.safeInstance(), false, false);
diff --git a/src/test/net/jpountz/lz4/LZ4FrameIOStreamTest.java b/src/test/net/jpountz/lz4/LZ4FrameIOStreamTest.java
index de2b242b..28ad3515 100644
--- a/src/test/net/jpountz/lz4/LZ4FrameIOStreamTest.java
+++ b/src/test/net/jpountz/lz4/LZ4FrameIOStreamTest.java
@@ -861,11 +861,13 @@ public void testUncompressableEnd() throws IOException {
}
final ByteBuffer buffer = ByteBuffer.wrap(bytes);
- // Make sure final "block" is a zero length block, then set it to an incompressible zero length block.
+ // Make sure final "block" is a zero length block, then set it to an incompressible zero length block. This is an
+ // empty block rather than an EndMark, so the frame is truncated.
Assert.assertEquals(0, buffer.getInt(bytes.length - (Integer.SIZE >> 3)));
buffer.putInt(bytes.length - (Integer.SIZE >> 3), LZ4FrameOutputStream.LZ4_FRAME_INCOMPRESSIBLE_MASK);
try (final InputStream is = new LZ4FrameInputStream(new ByteArrayInputStream(bytes))) {
Assert.assertEquals(data, (byte) is.read());
+ Assert.assertThrows(IOException.class, is::read);
}
}
}
@@ -1043,17 +1045,20 @@ public void testMalformedFirstHeaderThrowsIOException() throws IOException {
}
@Test
- public void testLinkedBlocksFirstHeaderThrowsIOException() throws IOException {
+ public void testLinkedBlocksFlagIsAccepted() throws IOException {
+ Assume.assumeTrue(testSize == 0); // does not depend on the test size
final byte[] frame = compressFrame("hello".getBytes("UTF-8"), LZ4FrameOutputStream.FLG.Bits.BLOCK_INDEPENDENCE);
// version 01, BLOCK_INDEPENDENCE cleared (linked blocks), with a valid descriptor checksum
frame[4] = 0x40;
frame[6] = (byte) ((XXHashFactory.fastestInstance().hash32().hash(frame, 4, 2, 0) >> 8) & 0xFF);
- // the header is read lazily, so construction must not fail
- final LZ4FrameInputStream is = new LZ4FrameInputStream(new ByteArrayInputStream(frame), true);
- assertInvalidDescriptor(Assert.assertThrows(IOException.class, is::isExpectedContentSizeDefined));
- Assert.assertThrows(IOException.class, is::getExpectedContentSize);
- assertFailedStream(is);
+ try (LZ4FrameInputStream is = new LZ4FrameInputStream(new ByteArrayInputStream(frame), true)) {
+ Assert.assertFalse(is.isExpectedContentSizeDefined());
+ final byte[] decoded = new byte[16];
+ Assert.assertEquals(5, is.read(decoded));
+ Assert.assertEquals("hello", new String(decoded, 0, 5, "UTF-8"));
+ Assert.assertEquals(-1, is.read());
+ }
}
@Test
@@ -1095,7 +1100,6 @@ private static void assertInvalidDescriptor(IOException e) {
public void testInvalidOrUnsupportedFrameDescriptor() throws IOException {
Assume.assumeTrue(testSize == 0); // does not depend on the test size
final int[][] descriptors = {
- {0x40, 0x70}, // dependent blocks
{0x61, 0x70}, // dictionary ID
{0x62, 0x70}, // reserved FLG bit
{0x20, 0x70}, // unsupported version
diff --git a/src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java b/src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java
new file mode 100644
index 00000000..17ba18e4
--- /dev/null
+++ b/src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java
@@ -0,0 +1,639 @@
+package net.jpountz.lz4;
+
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import net.jpountz.xxhash.XXHash32;
+import net.jpountz.xxhash.XXHashFactory;
+import org.junit.jupiter.api.Assumptions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.ByteBuffer;
+import java.nio.file.Files;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Random;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Linked blocks (FLG.B.Indep = 0): matches may reference up to 64 KB of the data decoded before the block, in the same
+ * frame. Frames are written by hand here, along with the data they decode to, or by the lz4 CLI.
+ */
+public class LZ4FrameLinkedBlocksTest {
+
+ private static final int FLG_VERSION = 0x40;
+ private static final int FLG_BLOCK_INDEPENDENCE = 0x20;
+ private static final int FLG_BLOCK_CHECKSUM = 0x10;
+ private static final int FLG_CONTENT_SIZE = 0x08;
+ private static final int FLG_CONTENT_CHECKSUM = 0x04;
+ private static final int BD_64KB = 0x40;
+ private static final int BD_256KB = 0x50;
+ private static final int BD_4MB = 0x70;
+ private static final int WINDOW = 65535; // largest match offset
+ private static final XXHash32 XXH32 = XXHashFactory.safeInstance().hash32();
+
+ static LZ4SafeDecompressor[] decompressors() {
+ return Instances.SAFE_DECOMPRESSORS;
+ }
+
+ /** Growable byte array. */
+ private static final class Bytes {
+ byte[] buf = new byte[256];
+ int size;
+
+ void write(byte[] b) {
+ ensure(b.length);
+ System.arraycopy(b, 0, buf, size, b.length);
+ size += b.length;
+ }
+
+ void write(int b) {
+ ensure(1);
+ buf[size++] = (byte) b;
+ }
+
+ void writeIntLE(int v) {
+ for (int i = 0; i < 4; i++) {
+ write(v >>> (8 * i));
+ }
+ }
+
+ // Byte by byte, since a match may overlap its own output
+ void copyMatch(int offset, int len) {
+ ensure(len);
+ for (int i = 0; i < len; i++, size++) {
+ buf[size] = size >= offset ? buf[size - offset] : 0; // 0 for invalid frames, which must not decode
+ }
+ }
+
+ private void ensure(int n) {
+ if (size + n > buf.length) {
+ buf = Arrays.copyOf(buf, Math.max(2 * buf.length, size + n));
+ }
+ }
+
+ byte[] toByteArray() {
+ return Arrays.copyOf(buf, size);
+ }
+ }
+
+ /** Writes a frame block by block, and keeps the data it decodes to. */
+ private static final class FrameWriter {
+ final int flg;
+ final int bd;
+ final Bytes content = new Bytes();
+ final List