Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -922,6 +922,27 @@
<test>net.jpountz.fuzz.LZ4DecompressorTest#native_fast_bytebuffer</test>
</configuration>
</execution>
<execution>
<id>fuzz-net.jpountz.fuzz.LZ4DecompressorTest#safe_prefix</id>
<goals><goal>test</goal></goals>
<configuration>
<test>net.jpountz.fuzz.LZ4DecompressorTest#safe_prefix</test>
</configuration>
</execution>
<execution>
<id>fuzz-net.jpountz.fuzz.LZ4DecompressorTest#unsafe_prefix</id>
<goals><goal>test</goal></goals>
<configuration>
<test>net.jpountz.fuzz.LZ4DecompressorTest#unsafe_prefix</test>
</configuration>
</execution>
<execution>
<id>fuzz-net.jpountz.fuzz.LZ4DecompressorTest#native_prefix</id>
<goals><goal>test</goal></goals>
<configuration>
<test>net.jpountz.fuzz.LZ4DecompressorTest#native_prefix</test>
</configuration>
</execution>

<!-- LZ4CompressorTest fast compressor (array) -->
<execution>
Expand Down
15 changes: 14 additions & 1 deletion src/build/source_templates/decompress.template
Original file line number Diff line number Diff line change
Expand Up @@ -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"}
Expand All @@ -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);
Expand All @@ -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;
Expand Down Expand Up @@ -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);
}

Expand Down
8 changes: 6 additions & 2 deletions src/build/source_templates/decompressor.template
Original file line number Diff line number Diff line change
Expand Up @@ -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{}


}
Expand Down
82 changes: 64 additions & 18 deletions src/java/net/jpountz/lz4/LZ4FrameInputStream.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand All @@ -37,7 +38,6 @@
* this stream throws an {@link IOException} as well.
* <p>
* Not Supported:<ul>
* <li>Dependent blocks</li>
* <li>Legacy streams</li>
* </ul>
* <p>
Expand Down Expand Up @@ -316,17 +316,22 @@ 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
throw new IOException(PREMATURE_EOS);
}
}

// 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;
Expand All @@ -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;
Expand All @@ -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()) {
Expand All @@ -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);
}
}
Expand All @@ -397,24 +431,36 @@ 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);
}
} else {
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
Expand Down
14 changes: 8 additions & 6 deletions src/java/net/jpountz/lz4/LZ4FrameOutputStream.java
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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() {
Expand All @@ -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));
}
Expand Down
5 changes: 5 additions & 0 deletions src/java/net/jpountz/lz4/LZ4JNI.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);

/**
Expand Down
19 changes: 19 additions & 0 deletions src/java/net/jpountz/lz4/LZ4JNISafeDecompressor.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
13 changes: 13 additions & 0 deletions src/java/net/jpountz/lz4/LZ4SafeDecompressor.java
Original file line number Diff line number Diff line change
Expand Up @@ -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
* <code>prefixLen</code> bytes before <code>destOff</code> in <code>dest</code>, 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)}.
Expand Down
23 changes: 17 additions & 6 deletions src/java/net/jpountz/lz4/LZ4Utils.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
Loading
Loading