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..a0d9e406 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 @@ -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 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); + } + } + + /** 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; + } + + // 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 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 = is.decompressedBuffer(); + 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; + } + + // 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 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); + assertTrue(stats.maxBufferLength <= 2 * (1 << 16) + w.maxBlockSize(), "buffer: " + stats.maxBufferLength); + } + + @ParameterizedTest + @MethodSource("decompressors") + 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); + final FrameWriter w = new FrameWriter(FLG_VERSION | FLG_CONTENT_CHECKSUM, BD_64KB) + .uncompressedBlock(randomBytes(rnd, 1)) + .lastLiterals(randomBytes(rnd, 262)); + for (int i = 0; i < 300_000; i++) { + w.uncompressedBlock(randomBytes(rnd, 1)); + } + assertHistoryMovesBounded(w, decompressor); + } + + @ParameterizedTest + @MethodSource("decompressors") + 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); + 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 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++) { + w.sequence(new byte[0], WINDOW, 4).lastLiterals(randomBytes(rnd, 20000)); + } + 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); + } + + @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; + for (int b = 0; b < 256; b++) { + final LZ4FrameOutputStream.FLG flg; + 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++; + 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(); + // 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); + } +}