From bd0e6d85ae6377203e02e5662521a9be6494809f Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 25 Nov 2026 15:32:45 -0800 Subject: [PATCH 1/8] Decode linked blocks in LZ4FrameInputStream LZ4FrameInputStream rejected frames with linked blocks (FLG.B.Indep = 0), although they are the default of liblz4's frame API (LZ4F_blockLinked = 0). In such frames, a block may reference up to 64 KB of the data decoded before it in the same frame. LZ4FrameOutputStream still writes independent blocks only. The templates generate a separate decompressWithPrefix copy of the safe decoder, for byte arrays, whose matches may also reach the prefixLen bytes before destOff in dest. The existing decompress methods keep the same bytecode: a variant sharing their code made the safe decoder 3 to 5% slower on independent blocks with JDK 21 and 25, a code generation effect. JNI gets a new native, LZ4_decompress_safe_usingDict, for which liblz4 detects the prefix in place. The existing natives are unchanged. decompressWithPrefix is package-private and not abstract on LZ4SafeDecompressor. Implementations outside this package keep working, and reject a non-empty prefix. LZ4FrameInputStream decodes a linked block right after the data decoded before it in the frame, and moves the last 64 KB of that data to the start of the buffer only when the block doesn't fit after it. The buffer grows to at most 64 KB + the maximum block size, still only as data arrives. Blocks without history (independent blocks, first block of a linked frame) still go through decompress(), which also keeps them working with an older native library from java.library.path. FLG.fromByte accepts linked blocks; the FLG constructor, used by LZ4FrameOutputStream, still rejects them. LZ4FrameLinkedBlocksTest writes linked frames by hand along with their content: matches up to offset 65535 across several blocks, matches before the frame start, no history across frames, random concatenated frames. It also decodes frames written by the lz4 CLI with -BD (each block size, -BX, --content-size, -9), checked to depend on the history, with the three decompressors. New fuzz targets decompress with a prefix twice, with different data before the prefix and after the output, and compare; LZ4TestAccess gives them access to the package-private method. The frame fuzz targets get a seed with linked frames. Decoding speed on silesia, lz4 CLI frames, JDK 25: unchanged for independent blocks. Linked vs independent blocks of the same size: JNI -0.4% with 256 KB and 4 MB blocks, +8% with 64 KB blocks (better ratio); safe decoder -3% with 256 KB and 4 MB blocks, +8% with 64 KB blocks. --- pom.xml | 21 + .../source_templates/decompress.template | 15 +- .../source_templates/decompressor.template | 8 +- .../net/jpountz/lz4/LZ4FrameInputStream.java | 62 ++- .../net/jpountz/lz4/LZ4FrameOutputStream.java | 7 +- src/java/net/jpountz/lz4/LZ4JNI.java | 5 + .../jpountz/lz4/LZ4JNISafeDecompressor.java | 12 + .../net/jpountz/lz4/LZ4SafeDecompressor.java | 13 + src/java/net/jpountz/lz4/LZ4Utils.java | 23 +- src/jni/net_jpountz_lz4_LZ4JNI.c | 51 ++ .../frame_multi/linked | Bin 0 -> 200 bytes .../frame_single/linked | Bin 0 -> 200 bytes .../net/jpountz/fuzz/LZ4DecompressorTest.java | 52 ++ .../net/jpountz/lz4/LZ4FrameIOStreamTest.java | 16 +- .../jpountz/lz4/LZ4FrameLinkedBlocksTest.java | 511 ++++++++++++++++++ src/test/net/jpountz/lz4/LZ4TestAccess.java | 28 + 16 files changed, 792 insertions(+), 32 deletions(-) create mode 100644 src/test-resources/net/jpountz/fuzz/LZ4InputStreamTestInputs/frame_multi/linked create mode 100644 src/test-resources/net/jpountz/fuzz/LZ4InputStreamTestInputs/frame_single/linked create mode 100644 src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java create mode 100644 src/test/net/jpountz/lz4/LZ4TestAccess.java diff --git a/pom.xml b/pom.xml index 16471a07..cc30713d 100644 --- a/pom.xml +++ b/pom.xml @@ -922,6 +922,27 @@ net.jpountz.fuzz.LZ4DecompressorTest#native_fast_bytebuffer + + fuzz-net.jpountz.fuzz.LZ4DecompressorTest#safe_prefix + test + + net.jpountz.fuzz.LZ4DecompressorTest#safe_prefix + + + + fuzz-net.jpountz.fuzz.LZ4DecompressorTest#unsafe_prefix + test + + net.jpountz.fuzz.LZ4DecompressorTest#unsafe_prefix + + + + fuzz-net.jpountz.fuzz.LZ4DecompressorTest#native_prefix + test + + net.jpountz.fuzz.LZ4DecompressorTest#native_prefix + + diff --git a/src/build/source_templates/decompress.template b/src/build/source_templates/decompress.template index 20faa596..178489af 100644 --- a/src/build/source_templates/decompress.template +++ b/src/build/source_templates/decompress.template @@ -13,6 +13,15 @@ See the License for the specific language governing permissions and limitations under the License. } +@if{ prefix } + // Same as decompress, but matches may also reference the prefixLen bytes before destOff in dest, which hold the + // previously decompressed data. A separate copy, so that the code generated for decompress stays the same. + @Override + int decompressWithPrefix(${storage} src, final int srcOff, final int srcLen, ${storage} dest, final int destOff, int destLen, final int prefixLen) { + ${utils}.checkRange(src, srcOff, srcLen); + ${utils}.checkRange(dest, destOff, destLen); + ${utils}.checkRange(dest, destOff - prefixLen, prefixLen); +@else{} @Override public @if{ size == "Fast" }int decompress(${storage} src, final int srcOff, ${storage} dest, final int destOff, int destLen) { @if{ storage == "ByteBuffer"} @@ -26,6 +35,7 @@ private @end{}int decompress(${storage} src, final int srcOff, final int srcLen, ${storage} dest, final int destOff, int destLen) { ${utils}.checkRange(src, srcOff, srcLen); ${utils}.checkRange(dest, destOff, destLen); +@end{} @if{ storage == "ByteBuffer"} if (src.hasArray() && dest.hasArray()) { return decompress(src.array(), srcOff + src.arrayOffset(), srcLen, dest.array(), destOff + dest.arrayOffset(), destLen); @@ -51,6 +61,9 @@ @end{} final int srcEnd = srcOff + srcLen; final int destEnd = destOff + destLen; +@if{ prefix } + final int prefixStart = destOff - prefixLen; +@end{} int sOff = srcOff; int dOff = destOff; @@ -112,7 +125,7 @@ sOff += 2; int matchOff = dOff - matchDec; - if (matchOff < destOff) { + if (matchOff < @if{ prefix }prefixStart@else{}destOff@end{}) { throw new LZ4Exception("Malformed input at " + sOff); } diff --git a/src/build/source_templates/decompressor.template b/src/build/source_templates/decompressor.template index 8e51c142..f78d41ea 100644 --- a/src/build/source_templates/decompressor.template +++ b/src/build/source_templates/decompressor.template @@ -17,9 +17,13 @@ final class LZ4Java@{type}${size}Decompressor extends LZ4${size}Decompressor { public static final LZ4${size}Decompressor INSTANCE = new LZ4Java${type}${size}Decompressor(); -@include{"decompress.template"; storage = "byte[]"; utils = "${type}Utils"} +@include{"decompress.template"; storage = "byte[]"; utils = "${type}Utils"; prefix = false} -@include{"decompress.template"; storage = "ByteBuffer"; utils = "ByteBufferUtils"} +@include{"decompress.template"; storage = "ByteBuffer"; utils = "ByteBufferUtils"; prefix = false} +@if{ size == "Safe" } + +@include{"decompress.template"; storage = "byte[]"; utils = "${type}Utils"; prefix = true} +@end{} } diff --git a/src/java/net/jpountz/lz4/LZ4FrameInputStream.java b/src/java/net/jpountz/lz4/LZ4FrameInputStream.java index fccfdb93..ded8f7c7 100644 --- a/src/java/net/jpountz/lz4/LZ4FrameInputStream.java +++ b/src/java/net/jpountz/lz4/LZ4FrameInputStream.java @@ -29,6 +29,7 @@ import java.util.Locale; import static net.jpountz.lz4.LZ4Constants.MAX_COMPRESSION_RATIO; +import static net.jpountz.lz4.LZ4Constants.MAX_DISTANCE; import static net.jpountz.lz4.LZ4Utils.notEnoughSpace; /** @@ -37,7 +38,6 @@ * this stream throws an {@link IOException} as well. *

* 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 @@ -335,6 +335,16 @@ private void setRawBuffer(byte[] rawBuffer) { } } + // Linked blocks: if fewer than len bytes follow blockOff in rawBuffer, moves the prefixLen bytes of history before + // blockOff to the start of rawBuffer. Returns the offset of the block, right after the history. + private int makeRoom(int blockOff, int prefixLen, int len) { + if (blockOff > prefixLen && 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; @@ -374,21 +384,36 @@ 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); + maxRawBufferSize = 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 +422,23 @@ 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, is now at the start of rawBuffer 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. + 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 +446,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..eae6b717 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) { @@ -364,9 +368,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..f549c7e9 100644 --- a/src/java/net/jpountz/lz4/LZ4JNISafeDecompressor.java +++ b/src/java/net/jpountz/lz4/LZ4JNISafeDecompressor.java @@ -57,6 +57,18 @@ 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 = LZ4JNI.LZ4_decompress_safe_usingDict(src, null, srcOff, srcLen, dest, null, destOff, maxDestLen, prefixLen); + 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 0000000000000000000000000000000000000000..d76807c7220027a04bbd6693fe2938430e7002b1 GIT binary patch literal 200 zcmZS30u;1QOiH$4kUx-0u;1QOiH$4kUx-= 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..48cfa9ac 100644 --- a/src/test/net/jpountz/lz4/LZ4FrameIOStreamTest.java +++ b/src/test/net/jpountz/lz4/LZ4FrameIOStreamTest.java @@ -1043,17 +1043,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 +1098,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..5cbbbdd7 --- /dev/null +++ b/src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java @@ -0,0 +1,511 @@ +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 blocks = new ArrayList<>(); + final List compressed = new ArrayList<>(); + // the block being written by sequence() and lastLiterals() + private Bytes block; + + FrameWriter(int flg, int bd) { + this.flg = flg; + this.bd = bd; + } + + int maxBlockSize() { + return 1 << (2 * ((bd >>> 4) & 7) + 8); + } + + FrameWriter uncompressedBlock(byte[] data) { + blocks.add(data); + compressed.add(false); + content.write(data); + return this; + } + + FrameWriter sequence(byte[] literals, int offset, int matchLen) { + if (block == null) { + block = new Bytes(); + } + final int litLen = literals.length; + final int ml = matchLen - LZ4Constants.MIN_MATCH; + block.write((Math.min(litLen, 15) << 4) | Math.min(ml, 15)); + writeLength(litLen); + block.write(literals); + block.write(offset); + block.write(offset >>> 8); + writeLength(ml); + content.write(literals); + content.copyMatch(offset, matchLen); + return this; + } + + // Ends the compressed block. The last 5 bytes of a block are literals, and its last match starts at least 12 bytes + // before its end: callers pass at least 12 literals after a match. + FrameWriter lastLiterals(byte[] literals) { + if (block == null) { + block = new Bytes(); + } + block.write(Math.min(literals.length, 15) << 4); + writeLength(literals.length); + block.write(literals); + content.write(literals); + blocks.add(block.toByteArray()); + compressed.add(true); + block = null; + return this; + } + + private void writeLength(int len) { + if (len >= 15) { + len -= 15; + for (; len >= 255; len -= 255) { + block.write(255); + } + block.write(len); + } + } + + byte[] toByteArray() { + final Bytes out = new Bytes(); + out.writeIntLE(LZ4FrameOutputStream.MAGIC); + final int descriptorStart = out.size; + out.write(flg); + out.write(bd); + if ((flg & FLG_CONTENT_SIZE) != 0) { + out.writeIntLE(content.size); + out.writeIntLE(0); + } + out.write((XXH32.hash(out.buf, descriptorStart, out.size - descriptorStart, 0) >> 8) & 0xFF); + for (int i = 0; i < blocks.size(); i++) { + final byte[] b = blocks.get(i); + out.writeIntLE(b.length | (compressed.get(i) ? 0 : LZ4FrameOutputStream.LZ4_FRAME_INCOMPRESSIBLE_MASK)); + out.write(b); + if ((flg & FLG_BLOCK_CHECKSUM) != 0) { + out.writeIntLE(XXH32.hash(b, 0, b.length, 0)); + } + } + out.writeIntLE(0); // EndMark + if ((flg & FLG_CONTENT_CHECKSUM) != 0) { + out.writeIntLE(XXH32.hash(content.buf, 0, content.size, 0)); + } + return out.toByteArray(); + } + } + + private static byte[] randomBytes(Random rnd, int len) { + final byte[] b = new byte[len]; + rnd.nextBytes(b); + return b; + } + + private static byte[] decode(byte[] frames, LZ4SafeDecompressor decompressor) throws IOException { + try (InputStream is = new LZ4FrameInputStream(new ByteArrayInputStream(frames), decompressor, XXH32)) { + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + final byte[] buf = new byte[8192]; + for (int n; (n = is.read(buf)) != -1; ) { + out.write(buf, 0, n); + } + return out.toByteArray(); + } + } + + // Decodes with a mix of read(), read(byte[], int, int) and skip() of various sizes, and checks the result + private static void assertDecodes(byte[] expected, byte[] frames, LZ4SafeDecompressor decompressor, Random rnd) + throws IOException { + try (InputStream is = new LZ4FrameInputStream(new ByteArrayInputStream(frames), decompressor, XXH32)) { + final byte[] buf = new byte[1 << 17]; + int pos = 0; + while (true) { + final int op = rnd.nextInt(8); + final int len = 1 + rnd.nextInt(1 << rnd.nextInt(18)); + if (op == 0) { + final int b = is.read(); + if (b == -1) { + break; + } + assertEquals(expected[pos++], (byte) b, "at " + pos); + } else if (op == 1) { + final long n = is.skip(len); + assertTrue(n >= 0 && n <= len); + if (n == 0) { // end of stream + break; + } + pos += (int) n; + } else { + final int n = is.read(buf, 0, len); + if (n == -1) { + break; + } + assertArrayEquals(Arrays.copyOfRange(expected, pos, pos + n), Arrays.copyOf(buf, n), "at " + pos); + pos += n; + } + } + assertEquals(expected.length, pos); + } + } + + @ParameterizedTest + @MethodSource("decompressors") + public void matchesReachBackAcrossBlocks(LZ4SafeDecompressor decompressor) throws IOException { + final Random rnd = new Random(1); + final FrameWriter w = new FrameWriter(FLG_VERSION | FLG_CONTENT_CHECKSUM, BD_64KB) + .uncompressedBlock(randomBytes(rnd, 40000)) + .uncompressedBlock(randomBytes(rnd, 30000)) + // the farthest match, into the first block; a match across the boundary of the first two blocks + .sequence(new byte[0], WINDOW, 100) + .sequence(randomBytes(rnd, 3), 30000 + 100 + 3 + 50, 100) + .lastLiterals(randomBytes(rnd, 20)) + // a match that starts in the previous block and continues into this one, overlapping its own output + .sequence(new byte[0], 10, 1000) + .lastLiterals(randomBytes(rnd, 12)); + final byte[] frame = w.toByteArray(); + assertArrayEquals(w.content.toByteArray(), decode(frame, decompressor)); + + // the same blocks must not decode as independent blocks + final FrameWriter independent = new FrameWriter(w.flg | FLG_BLOCK_INDEPENDENCE, w.bd); + independent.blocks.addAll(w.blocks); + independent.compressed.addAll(w.compressed); + independent.content.write(w.content.toByteArray()); + assertThrows(IOException.class, () -> decode(independent.toByteArray(), decompressor)); + } + + @ParameterizedTest + @MethodSource("decompressors") + public void matchBeforeFrameStartIsRejected(LZ4SafeDecompressor decompressor) throws IOException { + final Random rnd = new Random(2); + final byte[] frame = new FrameWriter(FLG_VERSION, BD_64KB) + .uncompressedBlock(randomBytes(rnd, 1000)) + .sequence(new byte[0], 1001, 4) + .lastLiterals(randomBytes(rnd, 12)) + .toByteArray(); + assertThrows(IOException.class, () -> decode(frame, decompressor)); + + // the history doesn't carry over to the next frame + final byte[] first = new FrameWriter(FLG_VERSION, BD_64KB).uncompressedBlock(randomBytes(rnd, 1000)).toByteArray(); + final byte[] second = new FrameWriter(FLG_VERSION, BD_64KB) + .sequence(randomBytes(rnd, 1), 2, 4) + .lastLiterals(randomBytes(rnd, 12)) + .toByteArray(); + final byte[] frames = new byte[first.length + second.length]; + System.arraycopy(first, 0, frames, 0, first.length); + System.arraycopy(second, 0, frames, first.length, second.length); + assertThrows(IOException.class, () -> decode(frames, decompressor)); + } + + // Writes a frame of blockCount blocks of random sizes. Compressed blocks have random matches over the whole window + private static FrameWriter randomFrame(Random rnd, int flg, int bd, int blockCount) { + final FrameWriter w = new FrameWriter(flg, bd); + final boolean linked = (flg & FLG_BLOCK_INDEPENDENCE) == 0; + for (int i = 0; i < blockCount; i++) { + final int size; + switch (rnd.nextInt(4)) { + case 0: + size = 1 + rnd.nextInt(100); + break; + case 1: + size = 1 + rnd.nextInt(w.maxBlockSize()); + break; + default: + size = w.maxBlockSize() - rnd.nextInt(100); + } + if (rnd.nextInt(5) == 0) { + w.uncompressedBlock(randomBytes(rnd, size)); + continue; + } + final int blockStart = w.content.size; + final int historyStart = linked ? Math.max(0, blockStart - WINDOW) : blockStart; + int remaining = size; + // up to 19 literals and a match, followed by at least 12 last literals + while (remaining >= 19 + LZ4Constants.MIN_MATCH + 12) { + byte[] literals = randomBytes(rnd, rnd.nextInt(20)); + int available = Math.min(WINDOW, w.content.size + literals.length - historyStart); + if (available == 0) { // nothing to reference yet + literals = randomBytes(rnd, 1); + available = 1; + } + final int maxMatchLen = remaining - 19 - 12; + final int matchLen = LZ4Constants.MIN_MATCH + + rnd.nextInt(Math.min(maxMatchLen - LZ4Constants.MIN_MATCH + 1, 1 << rnd.nextInt(16))); + // either anywhere in the window, or near its start + final int offset = rnd.nextBoolean() ? 1 + rnd.nextInt(available) : available - rnd.nextInt(Math.min(available, 64)); + w.sequence(literals, offset, matchLen); + remaining -= literals.length + matchLen; + } + w.lastLiterals(randomBytes(rnd, remaining)); + } + return w; + } + + @ParameterizedTest + @MethodSource("decompressors") + public void randomFrames(LZ4SafeDecompressor decompressor) throws IOException { + final Random rnd = new Random(3); + final int[] blockSizes = {BD_64KB, BD_256KB, BD_4MB}; + final int[] options = {0, FLG_BLOCK_CHECKSUM, FLG_CONTENT_SIZE | FLG_CONTENT_CHECKSUM}; + for (int iter = 0; iter < 20; iter++) { + // concatenated frames, mostly linked, with different block sizes, so that buffers are reused across frames + final Bytes frames = new Bytes(); + final Bytes expected = new Bytes(); + final int frameCount = 1 + rnd.nextInt(3); + for (int f = 0; f < frameCount; f++) { + // 4 MB blocks are slow to write here, so only some iterations use them + final int bd = blockSizes[rnd.nextInt(iter % 5 == 0 ? 3 : 2)]; + final int flg = FLG_VERSION | options[rnd.nextInt(options.length)] + | (rnd.nextInt(4) == 0 ? FLG_BLOCK_INDEPENDENCE : 0); + final FrameWriter w = randomFrame(rnd, flg, bd, bd == BD_4MB ? 2 : 1 + rnd.nextInt(12)); + frames.write(w.toByteArray()); + expected.write(w.content.toByteArray()); + } + assertDecodes(expected.toByteArray(), frames.toByteArray(), decompressor, rnd); + } + } + + @Test + public void decompressorsOutsideThisPackageRejectAPrefix() throws IOException { + final LZ4SafeDecompressor safe = LZ4Factory.safeInstance().safeDecompressor(); + // does not override decompressWithPrefix, like a subclass outside of this package + final LZ4SafeDecompressor custom = new LZ4SafeDecompressor() { + @Override + public int decompress(byte[] src, int srcOff, int srcLen, byte[] dest, int destOff, int maxDestLen) { + return safe.decompress(src, srcOff, srcLen, dest, destOff, maxDestLen); + } + + @Override + public int decompress(ByteBuffer src, int srcOff, int srcLen, ByteBuffer dest, int destOff, int maxDestLen) { + return safe.decompress(src, srcOff, srcLen, dest, destOff, maxDestLen); + } + }; + final Random rnd = new Random(4); + // the first block of a frame has no prefix + final FrameWriter first = new FrameWriter(FLG_VERSION, BD_64KB) + .sequence(randomBytes(rnd, 10), 10, 100) + .lastLiterals(randomBytes(rnd, 12)); + assertArrayEquals(first.content.toByteArray(), decode(first.toByteArray(), custom)); + + final byte[] frame = new FrameWriter(FLG_VERSION, BD_64KB) + .uncompressedBlock(randomBytes(rnd, 1000)) + .sequence(new byte[0], 1000, 4) + .lastLiterals(randomBytes(rnd, 12)) + .toByteArray(); + final IOException e = assertThrows(IOException.class, () -> decode(frame, custom)); + assertTrue(e.getCause().getMessage().contains("does not support linked blocks"), e.getCause().getMessage()); + } + + // A block whose first match has the given offset + private static byte[] blockWithMatch(int offset) { + final FrameWriter w = new FrameWriter(FLG_VERSION, BD_64KB) + .sequence(new byte[0], offset, 20) + .lastLiterals(new byte[12]); + return w.blocks.get(0); + } + + @ParameterizedTest + @MethodSource("decompressors") + public void decompressWithPrefixBounds(LZ4SafeDecompressor decompressor) { + final int destOff = 100; + final byte[] dest = new byte[destOff + 64]; + for (int i = 0; i < destOff; i++) { + dest[i] = (byte) i; + } + final byte[] block = blockWithMatch(30); + assertEquals(32, decompressor.decompressWithPrefix(block, 0, block.length, dest, destOff, 64, 30)); + for (int i = 0; i < 20; i++) { + assertEquals((byte) (destOff - 30 + i % 30), dest[destOff + i]); + } + + // the match starts one byte before the prefix + assertThrows(LZ4Exception.class, () -> decompressor.decompressWithPrefix(block, 0, block.length, dest, destOff, 64, 29)); + assertThrows(LZ4Exception.class, () -> decompressor.decompressWithPrefix(block, 0, block.length, dest, destOff, 64, 0)); + assertThrows(LZ4Exception.class, () -> decompressor.decompress(block, 0, block.length, dest, destOff, 64)); + assertThrows(IllegalArgumentException.class, + () -> decompressor.decompressWithPrefix(block, 0, block.length, dest, destOff, 64, -1)); + assertThrows(ArrayIndexOutOfBoundsException.class, + () -> decompressor.decompressWithPrefix(block, 0, block.length, dest, destOff, 64, destOff + 1)); + + // a prefix of 64 KB or more + final byte[] large = new byte[2 * WINDOW + 64]; + final byte[] farthest = blockWithMatch(WINDOW); + assertEquals(32, decompressor.decompressWithPrefix(farthest, 0, farthest.length, large, 2 * WINDOW, 64, 2 * WINDOW)); + } + + private static boolean hasLz4Cli() { + try { + return new ProcessBuilder("lz4", "-V").redirectErrorStream(true).redirectOutput(ProcessBuilder.Redirect.DISCARD) + .start().waitFor() == 0; + } catch (IOException | InterruptedException e) { + return false; + } + } + + // Compressible data, whose repetitions are less than 64 KB apart, with incompressible parts in between + private static byte[] cliTestData() throws IOException { + final byte[] text; + try (InputStream is = LZ4FrameLinkedBlocksTest.class.getResourceAsStream("/calgary/book1")) { + text = new byte[40000]; + int n = 0; + for (int r; n < text.length && (r = is.read(text, n, text.length - n)) != -1; ) { + n += r; + } + assertEquals(text.length, n); + } + final Random rnd = new Random(5); + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + while (out.size() < 6 << 20) { + if (rnd.nextInt(10) == 0) { + out.write(randomBytes(rnd, 200000), 0, 200000); + } else { + final int start = rnd.nextInt(text.length / 2); + final byte[] chunk = Arrays.copyOfRange(text, start, start + 1000 + rnd.nextInt(text.length / 2 - 1000)); + chunk[rnd.nextInt(chunk.length)] ^= 1; + out.write(chunk, 0, chunk.length); + } + } + return out.toByteArray(); + } + + @Test + public void decodesLz4CliLinkedFrames() throws IOException, InterruptedException { + final boolean cli = hasLz4Cli(); + // CI must run this test, like LZ4FrameIOStreamTest + assertFalse(!cli && "true".equals(System.getenv("CI")), "lz4 CLI not available"); + Assumptions.assumeTrue(cli); + final byte[] data = cliTestData(); + final File in = Files.createTempFile("lz4linked", ".dat").toFile(); + final File out = Files.createTempFile("lz4linked", ".lz4").toFile(); + try { + Files.write(in.toPath(), data); + final String[][] optionSets = { + {"-B4"}, {"-B5"}, {"-B6"}, {"-B7"}, {"-B4", "-BX"}, {"-B5", "--content-size", "--no-frame-crc"}, {"-B4", "-9"}}; + for (String[] options : optionSets) { + final List cmd = new ArrayList<>(Arrays.asList("lz4", "-q", "-f", "-BD")); + cmd.addAll(Arrays.asList(options)); + cmd.add(in.getAbsolutePath()); + cmd.add(out.getAbsolutePath()); + assertEquals(0, new ProcessBuilder(cmd).inheritIO().start().waitFor(), cmd.toString()); + final byte[] frame = Files.readAllBytes(out.toPath()); + assertEquals(0, frame[4] & FLG_BLOCK_INDEPENDENCE, "linked blocks expected"); + for (LZ4SafeDecompressor decompressor : decompressors()) { + assertArrayEquals(data, decode(frame, decompressor), cmd + " " + decompressor); + } + + // the frame depends on the history: it doesn't decode as independent blocks + final int descriptorEnd = (frame[4] & FLG_CONTENT_SIZE) != 0 ? 14 : 6; + frame[4] |= FLG_BLOCK_INDEPENDENCE; + frame[descriptorEnd] = (byte) ((XXH32.hash(frame, 4, descriptorEnd - 4, 0) >> 8) & 0xFF); + try { + assertFalse(Arrays.equals(data, decode(frame, LZ4Factory.safeInstance().safeDecompressor())), cmd.toString()); + } catch (IOException expected) { + // matches before the block start + } + } + } finally { + in.delete(); + out.delete(); + } + } +} diff --git a/src/test/net/jpountz/lz4/LZ4TestAccess.java b/src/test/net/jpountz/lz4/LZ4TestAccess.java new file mode 100644 index 00000000..86a5846e --- /dev/null +++ b/src/test/net/jpountz/lz4/LZ4TestAccess.java @@ -0,0 +1,28 @@ +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. + */ + +/** + * Gives tests in other packages, such as the fuzz tests, access to package-private members. + */ +public final class LZ4TestAccess { + private LZ4TestAccess() { + } + + public static int decompressWithPrefix(LZ4SafeDecompressor decompressor, byte[] src, int srcOff, int srcLen, + byte[] dest, int destOff, int maxDestLen, int prefixLen) { + return decompressor.decompressWithPrefix(src, srcOff, srcLen, dest, destOff, maxDestLen, prefixLen); + } +} From 811e95baa928777c9caf1c6f02eba6ceb016b839 Mon Sep 17 00:00:00 2001 From: Jonas Konrad Date: Thu, 26 Nov 2026 10:59:25 +0100 Subject: [PATCH 2/8] Fail linked blocks with an IOException on an older native library An older liblz4-java loaded from java.library.path lacks LZ4_decompress_safe_usingDict, so decoding a linked block with history threw UnsatisfiedLinkError out of LZ4FrameInputStream. Wrap it in an LZ4Exception, which the stream reports as an IOException, as it did for these frames before linked blocks were supported. Co-Authored-By: Claude Opus 5.5 --- src/java/net/jpountz/lz4/LZ4FrameInputStream.java | 3 ++- src/java/net/jpountz/lz4/LZ4JNISafeDecompressor.java | 9 ++++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/java/net/jpountz/lz4/LZ4FrameInputStream.java b/src/java/net/jpountz/lz4/LZ4FrameInputStream.java index ded8f7c7..281aea97 100644 --- a/src/java/net/jpountz/lz4/LZ4FrameInputStream.java +++ b/src/java/net/jpountz/lz4/LZ4FrameInputStream.java @@ -434,7 +434,8 @@ private void readBlock0() throws IOException { } try { // Without history (independent blocks, first linked block), decompress as before. This also keeps working with - // an older native library loaded from java.library.path. + // 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, diff --git a/src/java/net/jpountz/lz4/LZ4JNISafeDecompressor.java b/src/java/net/jpountz/lz4/LZ4JNISafeDecompressor.java index f549c7e9..84fc6d21 100644 --- a/src/java/net/jpountz/lz4/LZ4JNISafeDecompressor.java +++ b/src/java/net/jpountz/lz4/LZ4JNISafeDecompressor.java @@ -62,7 +62,14 @@ final int decompressWithPrefix(byte[] src, int srcOff, int srcLen, byte[] dest, SafeUtils.checkRange(src, srcOff, srcLen); SafeUtils.checkRange(dest, destOff, maxDestLen); SafeUtils.checkRange(dest, destOff - prefixLen, prefixLen); - final int result = LZ4JNI.LZ4_decompress_safe_usingDict(src, null, srcOff, srcLen, dest, null, destOff, maxDestLen, 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)); } From c67eca7985c290763087e796e4f4c65dce5d964b Mon Sep 17 00:00:00 2001 From: Jonas Konrad Date: Thu, 26 Nov 2026 11:35:05 +0100 Subject: [PATCH 3/8] Move the history of linked blocks at most once per 64 KB LZ4FrameInputStream capped the buffer of a linked frame at 64 KB + the maximum block size, and moved the 64 KB history to its start whenever a block didn't fit after it. With small blocks, this moved the history for almost every block: about 64 KB copied per block, whatever its size. A crafted 10 MB frame of 1-byte stored blocks copied 131 GB, and ordinary streams with frequent flushes decoded several times slower, as each compressed block of 258 bytes or more reserves room for a full block. Like liblz4's frame decoder, which keeps 128 KB before its output buffer, the buffer now grows to 2 * 64 KB + the maximum block size, and the history is only moved once at least 64 KB before it is no longer needed. Copying the history then costs at most one byte per decompressed byte. Co-Authored-By: Claude Opus 5.5 --- .../net/jpountz/lz4/LZ4FrameInputStream.java | 14 ++++-- .../jpountz/lz4/LZ4FrameLinkedBlocksTest.java | 50 +++++++++++++++++++ 2 files changed, 59 insertions(+), 5 deletions(-) diff --git a/src/java/net/jpountz/lz4/LZ4FrameInputStream.java b/src/java/net/jpountz/lz4/LZ4FrameInputStream.java index 281aea97..2251e91a 100644 --- a/src/java/net/jpountz/lz4/LZ4FrameInputStream.java +++ b/src/java/net/jpountz/lz4/LZ4FrameInputStream.java @@ -335,10 +335,13 @@ private void setRawBuffer(byte[] rawBuffer) { } } - // Linked blocks: if fewer than len bytes follow blockOff in rawBuffer, moves the prefixLen bytes of history before - // blockOff to the start of rawBuffer. Returns the offset of the block, right after the history. + // 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 && notEnoughSpace(rawBuffer.length - blockOff, len)) { + if (blockOff - prefixLen >= MAX_DISTANCE && notEnoughSpace(rawBuffer.length - blockOff, len)) { System.arraycopy(rawBuffer, blockOff - prefixLen, rawBuffer, 0, prefixLen); return prefixLen; } @@ -392,7 +395,8 @@ private void readBlock0() throws IOException { if (!frameInfo.isEnabled(LZ4FrameOutputStream.FLG.Bits.BLOCK_INDEPENDENCE)) { blockOff = buffer.limit(); prefixLen = Math.min(blockOff, MAX_DISTANCE); - maxRawBufferSize = MAX_DISTANCE + maxBlockSize; + // 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 @@ -424,7 +428,7 @@ private void readBlock0() throws IOException { final int maxDecompressedSize = (int) Math.min(maxBlockSize, (long) blockSize * MAX_COMPRESSION_RATIO); blockOff = makeRoom(blockOff, prefixLen, maxDecompressedSize); if (rawBuffer == null || notEnoughSpace(rawBuffer.length - blockOff, maxDecompressedSize)) { - // the history, if any, is now at the start of rawBuffer + // the history, if any, ends at blockOff final int oldLength = rawBuffer == null ? 0 : rawBuffer.length; final byte[] grown = new byte[LZ4Utils.grownLength(oldLength, blockOff + maxDecompressedSize, maxRawBufferSize)]; if (blockOff > 0) { diff --git a/src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java b/src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java index 5cbbbdd7..23f9ea4e 100644 --- a/src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java +++ b/src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java @@ -365,6 +365,56 @@ public void randomFrames(LZ4SafeDecompressor decompressor) throws IOException { } } + @ParameterizedTest + @MethodSource("decompressors") + public void historyIsMovedOncePer64KB(LZ4SafeDecompressor decompressor) throws IOException { + // records where blocks with history are decoded, and where they end: the history was moved when a block is not + // decoded right after the previous one + final List destOffs = new ArrayList<>(); + final List destEnds = new ArrayList<>(); + final LZ4SafeDecompressor recording = new LZ4SafeDecompressor() { + @Override + public int decompress(byte[] src, int srcOff, int srcLen, byte[] dest, int destOff, int maxDestLen) { + return decompressor.decompress(src, srcOff, srcLen, dest, destOff, maxDestLen); + } + + @Override + public int decompress(ByteBuffer src, int srcOff, int srcLen, ByteBuffer dest, int destOff, int maxDestLen) { + return decompressor.decompress(src, srcOff, srcLen, dest, destOff, maxDestLen); + } + + @Override + int decompressWithPrefix(byte[] src, int srcOff, int srcLen, byte[] dest, int destOff, int maxDestLen, + int prefixLen) { + final int n = decompressor.decompressWithPrefix(src, srcOff, srcLen, dest, destOff, maxDestLen, prefixLen); + destOffs.add(destOff); + destEnds.add(destOff + n); + return n; + } + }; + + // Small compressed blocks: each one may decompress to the maximum block size, so the stream needs room for 64 KB + // after the history for each of them. Each block references the farthest byte of the history. + final Random rnd = new Random(5); + final FrameWriter w = new FrameWriter(FLG_VERSION | FLG_CONTENT_CHECKSUM, BD_64KB) + .uncompressedBlock(randomBytes(rnd, 1 << 16)); + final int blockCount = 2000; + for (int i = 0; i < blockCount; i++) { + w.sequence(randomBytes(rnd, 300), WINDOW, 4).lastLiterals(randomBytes(rnd, 12)); + } + assertArrayEquals(w.content.toByteArray(), decode(w.toByteArray(), recording)); + + assertEquals(blockCount, destOffs.size()); + int moves = 0; + for (int i = 1; i < destOffs.size(); i++) { + if (!destOffs.get(i).equals(destEnds.get(i - 1))) { + moves++; + } + } + final int decodedAfterFirstBlock = w.content.size - (1 << 16); + assertTrue(moves > 0 && moves <= decodedAfterFirstBlock / (1 << 16) + 1, "moves: " + moves); + } + @Test public void decompressorsOutsideThisPackageRejectAPrefix() throws IOException { final LZ4SafeDecompressor safe = LZ4Factory.safeInstance().safeDecompressor(); From 1c7992ea79a7e22997848f33da06d84ee536bf56 Mon Sep 17 00:00:00 2001 From: Jonas Konrad Date: Thu, 26 Nov 2026 11:36:23 +0100 Subject: [PATCH 4/8] Fix FLG.toByte for linked blocks without other flags Now that FLG.fromByte accepts linked blocks, FLG 0x40 (version 01, no flags, as written by lz4 -BD --no-frame-crc) has an empty BitSet, and toByte threw ArrayIndexOutOfBoundsException on bitSet.toByteArray()[0]. Before, B.Indep was always set, so the BitSet was never empty. Co-Authored-By: Claude Opus 5.5 --- .../net/jpountz/lz4/LZ4FrameOutputStream.java | 4 +++- .../jpountz/lz4/LZ4FrameLinkedBlocksTest.java | 17 +++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/java/net/jpountz/lz4/LZ4FrameOutputStream.java b/src/java/net/jpountz/lz4/LZ4FrameOutputStream.java index eae6b717..5ca12706 100644 --- a/src/java/net/jpountz/lz4/LZ4FrameOutputStream.java +++ b/src/java/net/jpountz/lz4/LZ4FrameOutputStream.java @@ -358,7 +358,9 @@ public static FLG fromByte(byte flg) { } 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() { diff --git a/src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java b/src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java index 23f9ea4e..02eaf1a1 100644 --- a/src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java +++ b/src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java @@ -415,6 +415,23 @@ int decompressWithPrefix(byte[] src, int srcOff, int srcLen, byte[] dest, int de assertTrue(moves > 0 && moves <= decodedAfterFirstBlock / (1 << 16) + 1, "moves: " + moves); } + @Test + public void flgRoundTrips() { + int accepted = 0; + for (int b = 0; b < 256; b++) { + final LZ4FrameOutputStream.FLG flg; + try { + flg = LZ4FrameOutputStream.FLG.fromByte((byte) b); + } catch (RuntimeException e) { + continue; + } + accepted++; + assertEquals((byte) b, flg.toByte(), "FLG " + Integer.toHexString(b)); + } + // version 01, no dictionary ID, reserved bit unset: the other 4 bits are free, including B.Indep + assertEquals(16, accepted); + } + @Test public void decompressorsOutsideThisPackageRejectAPrefix() throws IOException { final LZ4SafeDecompressor safe = LZ4Factory.safeInstance().safeDecompressor(); From f5ea8e1dccf494143f23ffaed35f55e2fa829632 Mon Sep 17 00:00:00 2001 From: Jonas Konrad Date: Thu, 26 Nov 2026 13:37:46 +0100 Subject: [PATCH 5/8] Test how often linked frames move the history, and their buffer size The move test only used small compressed blocks of one size, which reach the buffer cap within two blocks, and observed the history through the decompressor, so stored blocks were not covered. Moving the history for each stored block, a lower move threshold, or no buffer cap all went unnoticed. The tests now look at where LZ4FrameInputStream decodes each block in its buffer: a frame of 1-byte stored blocks, frames of compressed blocks of 316, 2000 and 40000 bytes, and a 4 MB frame for the buffer cap. Each compressed block starts with a match at the largest offset. Co-Authored-By: Claude Opus 5.5 --- .../jpountz/lz4/LZ4FrameLinkedBlocksTest.java | 112 ++++++++++++------ 1 file changed, 74 insertions(+), 38 deletions(-) diff --git a/src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java b/src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java index 02eaf1a1..fcdae74f 100644 --- a/src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java +++ b/src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java @@ -26,6 +26,7 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.nio.file.Files; import java.util.ArrayList; @@ -365,54 +366,89 @@ public void randomFrames(LZ4SafeDecompressor decompressor) throws IOException { } } - @ParameterizedTest - @MethodSource("decompressors") - public void historyIsMovedOncePer64KB(LZ4SafeDecompressor decompressor) throws IOException { - // records where blocks with history are decoded, and where they end: the history was moved when a block is not - // decoded right after the previous one - final List destOffs = new ArrayList<>(); - final List destEnds = new ArrayList<>(); - final LZ4SafeDecompressor recording = new LZ4SafeDecompressor() { - @Override - public int decompress(byte[] src, int srcOff, int srcLen, byte[] dest, int destOff, int maxDestLen) { - return decompressor.decompress(src, srcOff, srcLen, dest, destOff, maxDestLen); - } + /** What decoding a frame did with the buffer of LZ4FrameInputStream. */ + private static final class BufferStats { + final ByteArrayOutputStream content = new ByteArrayOutputStream(); + // linked blocks not decoded right after the previous block: the history was moved before them + int moves; + int maxBufferLength; + } - @Override - public int decompress(ByteBuffer src, int srcOff, int srcLen, ByteBuffer dest, int destOff, int maxDestLen) { - return decompressor.decompress(src, srcOff, srcLen, dest, destOff, maxDestLen); + // Decodes one block per read, and looks at where the stream decoded it in its buffer + private static BufferStats decodeTracking(byte[] frame, LZ4SafeDecompressor decompressor) throws Exception { + final Field bufferField = LZ4FrameInputStream.class.getDeclaredField("buffer"); + bufferField.setAccessible(true); + final BufferStats stats = new BufferStats(); + try (LZ4FrameInputStream is = new LZ4FrameInputStream(new ByteArrayInputStream(frame), decompressor, XXH32)) { + final byte[] buf = new byte[1 << 22]; // a whole block of any size + int previousEnd = -1; + for (int n; (n = is.read(buf)) != -1; ) { + final ByteBuffer buffer = (ByteBuffer) bufferField.get(is); + assertEquals(0, buffer.remaining(), "the block was not read at once"); + final int blockOff = buffer.limit() - n; + if (previousEnd >= 0 && blockOff != previousEnd) { + stats.moves++; + } + previousEnd = buffer.limit(); + stats.maxBufferLength = Math.max(stats.maxBufferLength, buffer.capacity()); + stats.content.write(buf, 0, n); } + } + return stats; + } - @Override - int decompressWithPrefix(byte[] src, int srcOff, int srcLen, byte[] dest, int destOff, int maxDestLen, - int prefixLen) { - final int n = decompressor.decompressWithPrefix(src, srcOff, srcLen, dest, destOff, maxDestLen, prefixLen); - destOffs.add(destOff); - destEnds.add(destOff + n); - return n; - } - }; + // Checks that the history was moved, but at most once per 64 KB decoded, and that the buffer stayed within + // 2 * 64 KB + the maximum block size + private static void assertHistoryMovesBounded(FrameWriter w, LZ4SafeDecompressor decompressor) throws Exception { + final BufferStats stats = decodeTracking(w.toByteArray(), decompressor); + assertArrayEquals(w.content.toByteArray(), stats.content.toByteArray()); + assertTrue(stats.moves > 0 && stats.moves <= w.content.size / (1 << 16), "moves: " + stats.moves); + assertTrue(stats.maxBufferLength <= 2 * (1 << 16) + w.maxBlockSize(), "buffer: " + stats.maxBufferLength); + } - // Small compressed blocks: each one may decompress to the maximum block size, so the stream needs room for 64 KB - // after the history for each of them. Each block references the farthest byte of the history. + @ParameterizedTest + @MethodSource("decompressors") + public void historyIsMovedOncePer64KBWithStoredBlocks(LZ4SafeDecompressor decompressor) throws Exception { + // The small compressed block makes the buffer just large enough for the history and a 1-byte block. Moving the + // history whenever a block doesn't fit after it would then move it for each of the 1-byte blocks. final Random rnd = new Random(5); final FrameWriter w = new FrameWriter(FLG_VERSION | FLG_CONTENT_CHECKSUM, BD_64KB) - .uncompressedBlock(randomBytes(rnd, 1 << 16)); - final int blockCount = 2000; - for (int i = 0; i < blockCount; i++) { - w.sequence(randomBytes(rnd, 300), WINDOW, 4).lastLiterals(randomBytes(rnd, 12)); + .uncompressedBlock(randomBytes(rnd, 1)) + .lastLiterals(randomBytes(rnd, 262)); + for (int i = 0; i < 300_000; i++) { + w.uncompressedBlock(randomBytes(rnd, 1)); } - assertArrayEquals(w.content.toByteArray(), decode(w.toByteArray(), recording)); + assertHistoryMovesBounded(w, decompressor); + } - assertEquals(blockCount, destOffs.size()); - int moves = 0; - for (int i = 1; i < destOffs.size(); i++) { - if (!destOffs.get(i).equals(destEnds.get(i - 1))) { - moves++; + @ParameterizedTest + @MethodSource("decompressors") + public void historyIsMovedOncePer64KBWithCompressedBlocks(LZ4SafeDecompressor decompressor) throws Exception { + // Compressed blocks of 258 bytes or more may decompress to the maximum block size, so the stream needs room for + // 64 KB after the history for each of them. Each block starts with a match at the largest offset. + final Random rnd = new Random(6); + for (int blockSize : new int[] {316, 2000, 40000}) { + final FrameWriter w = new FrameWriter(FLG_VERSION | FLG_CONTENT_CHECKSUM, BD_64KB) + .uncompressedBlock(randomBytes(rnd, 1 << 16)); + for (int decoded = 0; decoded < (1 << 20); decoded += blockSize) { + w.sequence(new byte[0], WINDOW, 4).lastLiterals(randomBytes(rnd, blockSize - 4)); } + assertHistoryMovesBounded(w, decompressor); + } + } + + @ParameterizedTest + @MethodSource("decompressors") + public void linkedBufferIsBounded(LZ4SafeDecompressor decompressor) throws Exception { + final Random rnd = new Random(7); + final FrameWriter w = new FrameWriter(FLG_VERSION, BD_4MB).uncompressedBlock(randomBytes(rnd, 1 << 16)); + for (int i = 0; i < 300; i++) { + w.sequence(new byte[0], WINDOW, 4).lastLiterals(randomBytes(rnd, 20000)); } - final int decodedAfterFirstBlock = w.content.size - (1 << 16); - assertTrue(moves > 0 && moves <= decodedAfterFirstBlock / (1 << 16) + 1, "moves: " + moves); + final BufferStats stats = decodeTracking(w.toByteArray(), decompressor); + assertArrayEquals(w.content.toByteArray(), stats.content.toByteArray()); + assertTrue(stats.moves > 0, "moves: " + stats.moves); + assertTrue(stats.maxBufferLength <= 2 * (1 << 16) + w.maxBlockSize(), "buffer: " + stats.maxBufferLength); } @Test From a3233f05df98b50f3f1749c6e2accf20c2c2739d Mon Sep 17 00:00:00 2001 From: Jonas Konrad Date: Thu, 26 Nov 2026 13:41:06 +0100 Subject: [PATCH 6/8] Report the right version for unsupported FLG bytes FLG.fromByte shifted the sign-extended version bits, so FLG bytes 0x80 to 0xFF reported version 67108862 or 67108863 instead of 2 or 3. These frames were still rejected. Co-Authored-By: Claude Opus 5.5 --- src/java/net/jpountz/lz4/LZ4FrameOutputStream.java | 3 +-- src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java | 3 +++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/java/net/jpountz/lz4/LZ4FrameOutputStream.java b/src/java/net/jpountz/lz4/LZ4FrameOutputStream.java index 5ca12706..edd8cea7 100644 --- a/src/java/net/jpountz/lz4/LZ4FrameOutputStream.java +++ b/src/java/net/jpountz/lz4/LZ4FrameOutputStream.java @@ -353,8 +353,7 @@ 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() { diff --git a/src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java b/src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java index fcdae74f..a385242b 100644 --- a/src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java +++ b/src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java @@ -459,6 +459,9 @@ public void flgRoundTrips() { try { flg = LZ4FrameOutputStream.FLG.fromByte((byte) b); } catch (RuntimeException e) { + if ((b & 3) == 0) { // only the version is wrong + assertEquals("Version " + (b >>> 6) + " is unsupported", e.getMessage()); + } continue; } accepted++; From 4a0867843c84b6f84023c35b05e8384d73844ce5 Mon Sep 17 00:00:00 2001 From: Jonas Konrad Date: Thu, 26 Nov 2026 13:52:38 +0100 Subject: [PATCH 7/8] Don't end a frame at an empty uncompressed block LZ4FrameInputStream cleared the uncompressed bit of a block header before checking for the EndMark, so 0x80000000, an empty uncompressed block, ended the frame. The rest of the frame was then read as the next frame and failed. The frame format specifies that only 0x00000000 is an EndMark and that an empty uncompressed block doesn't end the frame, for example to be used as a keep-alive. liblz4 had the same bug, and fixed it in v1.9.3. lz4-java accepted 0x80000000 as an EndMark since 2017. No encoder is known to write it: liblz4, pierrec/lz4, lz4_flex and LZ4FrameOutputStream write 0. A frame ending with 0x80000000 now fails as truncated, as with liblz4. Co-Authored-By: Claude Opus 5.5 --- .../net/jpountz/lz4/LZ4FrameInputStream.java | 10 ++++---- .../net/jpountz/lz4/LZ4FrameIOStreamTest.java | 4 ++- .../jpountz/lz4/LZ4FrameLinkedBlocksTest.java | 25 +++++++++++++++++++ 3 files changed, 33 insertions(+), 6 deletions(-) diff --git a/src/java/net/jpountz/lz4/LZ4FrameInputStream.java b/src/java/net/jpountz/lz4/LZ4FrameInputStream.java index 2251e91a..b11c96ee 100644 --- a/src/java/net/jpountz/lz4/LZ4FrameInputStream.java +++ b/src/java/net/jpountz/lz4/LZ4FrameInputStream.java @@ -364,12 +364,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()) { diff --git a/src/test/net/jpountz/lz4/LZ4FrameIOStreamTest.java b/src/test/net/jpountz/lz4/LZ4FrameIOStreamTest.java index 48cfa9ac..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); } } } diff --git a/src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java b/src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java index a385242b..51e0b073 100644 --- a/src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java +++ b/src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java @@ -451,6 +451,31 @@ public void linkedBufferIsBounded(LZ4SafeDecompressor decompressor) throws Excep assertTrue(stats.maxBufferLength <= 2 * (1 << 16) + w.maxBlockSize(), "buffer: " + stats.maxBufferLength); } + @ParameterizedTest + @MethodSource("decompressors") + public void emptyUncompressedBlocksDontEndTheFrame(LZ4SafeDecompressor decompressor) throws IOException { + // A block header of 0x80000000 is an empty uncompressed block, such as a keep-alive. Only 0 is an EndMark. + final Random rnd = new Random(8); + for (int flg : new int[] {FLG_VERSION, FLG_VERSION | FLG_BLOCK_INDEPENDENCE}) { + for (int options : new int[] {0, FLG_BLOCK_CHECKSUM | FLG_CONTENT_CHECKSUM}) { + final FrameWriter w = new FrameWriter(flg | options, BD_64KB) + .uncompressedBlock(new byte[0]) + .uncompressedBlock(randomBytes(rnd, 100)) + .uncompressedBlock(new byte[0]) + .uncompressedBlock(new byte[0]); + if ((flg & FLG_BLOCK_INDEPENDENCE) == 0) { + // the history continues across empty blocks + w.sequence(new byte[0], 100, 50).lastLiterals(randomBytes(rnd, 12)); + } else { + w.sequence(randomBytes(rnd, 10), 10, 50).lastLiterals(randomBytes(rnd, 12)); + } + w.uncompressedBlock(new byte[0]); + assertArrayEquals(w.content.toByteArray(), decode(w.toByteArray(), decompressor), + "FLG " + Integer.toHexString(flg | options)); + } + } + } + @Test public void flgRoundTrips() { int accepted = 0; From 0c007d2fc74422d0c64ceb02ded14dbf54af7e25 Mon Sep 17 00:00:00 2001 From: Jonas Konrad Date: Fri, 27 Nov 2026 09:59:04 +0100 Subject: [PATCH 8/8] Look at the frame stream's buffer without reflection in tests The history move tests read the private buffer field of LZ4FrameInputStream by reflection. A package-private accessor now gives them the buffer instead. Co-Authored-By: Claude Opus 5.5 --- src/java/net/jpountz/lz4/LZ4FrameInputStream.java | 5 +++++ .../net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java | 15 ++++++--------- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/src/java/net/jpountz/lz4/LZ4FrameInputStream.java b/src/java/net/jpountz/lz4/LZ4FrameInputStream.java index b11c96ee..a0d9e406 100644 --- a/src/java/net/jpountz/lz4/LZ4FrameInputStream.java +++ b/src/java/net/jpountz/lz4/LZ4FrameInputStream.java @@ -327,6 +327,11 @@ private byte[] readBlockData(byte[] buf, int off, int len, int maxLen) throws IO } } + // 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; diff --git a/src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java b/src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java index 51e0b073..17ba18e4 100644 --- a/src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java +++ b/src/test/net/jpountz/lz4/LZ4FrameLinkedBlocksTest.java @@ -26,7 +26,6 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.nio.file.Files; import java.util.ArrayList; @@ -375,15 +374,13 @@ private static final class BufferStats { } // Decodes one block per read, and looks at where the stream decoded it in its buffer - private static BufferStats decodeTracking(byte[] frame, LZ4SafeDecompressor decompressor) throws Exception { - final Field bufferField = LZ4FrameInputStream.class.getDeclaredField("buffer"); - bufferField.setAccessible(true); + private static BufferStats decodeTracking(byte[] frame, LZ4SafeDecompressor decompressor) throws IOException { final BufferStats stats = new BufferStats(); try (LZ4FrameInputStream is = new LZ4FrameInputStream(new ByteArrayInputStream(frame), decompressor, XXH32)) { final byte[] buf = new byte[1 << 22]; // a whole block of any size int previousEnd = -1; for (int n; (n = is.read(buf)) != -1; ) { - final ByteBuffer buffer = (ByteBuffer) bufferField.get(is); + final ByteBuffer buffer = is.decompressedBuffer(); assertEquals(0, buffer.remaining(), "the block was not read at once"); final int blockOff = buffer.limit() - n; if (previousEnd >= 0 && blockOff != previousEnd) { @@ -399,7 +396,7 @@ private static BufferStats decodeTracking(byte[] frame, LZ4SafeDecompressor deco // Checks that the history was moved, but at most once per 64 KB decoded, and that the buffer stayed within // 2 * 64 KB + the maximum block size - private static void assertHistoryMovesBounded(FrameWriter w, LZ4SafeDecompressor decompressor) throws Exception { + private static void assertHistoryMovesBounded(FrameWriter w, LZ4SafeDecompressor decompressor) throws IOException { final BufferStats stats = decodeTracking(w.toByteArray(), decompressor); assertArrayEquals(w.content.toByteArray(), stats.content.toByteArray()); assertTrue(stats.moves > 0 && stats.moves <= w.content.size / (1 << 16), "moves: " + stats.moves); @@ -408,7 +405,7 @@ private static void assertHistoryMovesBounded(FrameWriter w, LZ4SafeDecompressor @ParameterizedTest @MethodSource("decompressors") - public void historyIsMovedOncePer64KBWithStoredBlocks(LZ4SafeDecompressor decompressor) throws Exception { + public void historyIsMovedOncePer64KBWithStoredBlocks(LZ4SafeDecompressor decompressor) throws IOException { // The small compressed block makes the buffer just large enough for the history and a 1-byte block. Moving the // history whenever a block doesn't fit after it would then move it for each of the 1-byte blocks. final Random rnd = new Random(5); @@ -423,7 +420,7 @@ public void historyIsMovedOncePer64KBWithStoredBlocks(LZ4SafeDecompressor decomp @ParameterizedTest @MethodSource("decompressors") - public void historyIsMovedOncePer64KBWithCompressedBlocks(LZ4SafeDecompressor decompressor) throws Exception { + public void historyIsMovedOncePer64KBWithCompressedBlocks(LZ4SafeDecompressor decompressor) throws IOException { // Compressed blocks of 258 bytes or more may decompress to the maximum block size, so the stream needs room for // 64 KB after the history for each of them. Each block starts with a match at the largest offset. final Random rnd = new Random(6); @@ -439,7 +436,7 @@ public void historyIsMovedOncePer64KBWithCompressedBlocks(LZ4SafeDecompressor de @ParameterizedTest @MethodSource("decompressors") - public void linkedBufferIsBounded(LZ4SafeDecompressor decompressor) throws Exception { + public void linkedBufferIsBounded(LZ4SafeDecompressor decompressor) throws IOException { final Random rnd = new Random(7); final FrameWriter w = new FrameWriter(FLG_VERSION, BD_4MB).uncompressedBlock(randomBytes(rnd, 1 << 16)); for (int i = 0; i < 300; i++) {