From 6d989083629946550d64fd4df18982f6664c0130 Mon Sep 17 00:00:00 2001 From: Dominik Opwis Date: Sun, 29 Nov 2026 20:17:00 +0100 Subject: [PATCH 1/2] Don't clear the compressed buffer before every frame block LZ4FrameOutputStream cleared its whole compressed buffer before every block, over 4 MB with the default block size, however little data was in the block. Only the bytes that the compressor returned are written and checksummed, so this has no effect on the output. Co-Authored-By: Claude Opus 5.5 --- src/java/net/jpountz/lz4/LZ4FrameOutputStream.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/java/net/jpountz/lz4/LZ4FrameOutputStream.java b/src/java/net/jpountz/lz4/LZ4FrameOutputStream.java index edd8cea7..262ad364 100644 --- a/src/java/net/jpountz/lz4/LZ4FrameOutputStream.java +++ b/src/java/net/jpountz/lz4/LZ4FrameOutputStream.java @@ -205,9 +205,6 @@ private void writeBlock() throws IOException { if (buffer.position() == 0) { return; } - // Make sure there's no stale data - Arrays.fill(compressedBuffer, (byte) 0); - if (frameInfo.isEnabled(FLG.Bits.CONTENT_CHECKSUM)) { frameInfo.updateStreamHash(buffer.array(), 0, buffer.position()); } From 2a2f4761008825fd343f523bcaec7f0dd61789b2 Mon Sep 17 00:00:00 2001 From: Dominik Opwis Date: Sun, 29 Nov 2026 20:17:00 +0100 Subject: [PATCH 2/2] Close the underlying stream if close() fails, and check knownSize If close() could not write the remaining data, LZ4FrameOutputStream and LZ4BlockOutputStream left the underlying stream open, and another close() wrote the data again. Now the underlying stream is always closed, once. LZ4FrameOutputStream also wrote knownSize to the header without checking it. The resulting frame could not be decoded. close() now throws instead. Co-Authored-By: Claude Opus 5.5 --- .../net/jpountz/lz4/LZ4BlockOutputStream.java | 16 +- .../net/jpountz/lz4/LZ4FrameOutputStream.java | 30 ++- src/java/net/jpountz/lz4/LZ4Utils.java | 13 ++ .../net/jpountz/lz4/LZ4OutputStreamTest.java | 210 ++++++++++++++++++ 4 files changed, 263 insertions(+), 6 deletions(-) create mode 100644 src/test/net/jpountz/lz4/LZ4OutputStreamTest.java diff --git a/src/java/net/jpountz/lz4/LZ4BlockOutputStream.java b/src/java/net/jpountz/lz4/LZ4BlockOutputStream.java index 322e4b23..ff034753 100644 --- a/src/java/net/jpountz/lz4/LZ4BlockOutputStream.java +++ b/src/java/net/jpountz/lz4/LZ4BlockOutputStream.java @@ -201,10 +201,22 @@ public void write(byte[] b) throws IOException { write(b, 0, b.length); } + /** + * Same as {@link #finish()}, but also closes the underlying stream. The underlying stream is closed even if finishing + * fails. + */ @Override public void close() throws IOException { - if (!finished) { - finish(); + try { + if (!finished) { + finish(); + } + } catch (Throwable t) { + final OutputStream failedOut = out; + finished = true; + out = null; + LZ4Utils.closeAfterFailure(failedOut, t); + throw t; } if (out != null) { out.close(); diff --git a/src/java/net/jpountz/lz4/LZ4FrameOutputStream.java b/src/java/net/jpountz/lz4/LZ4FrameOutputStream.java index 262ad364..d69af65d 100644 --- a/src/java/net/jpountz/lz4/LZ4FrameOutputStream.java +++ b/src/java/net/jpountz/lz4/LZ4FrameOutputStream.java @@ -90,6 +90,7 @@ public static BLOCKSIZE valueOf(int indicator) { private final byte[] compressedBuffer; // Only allocated once so it can be reused private final int maxBlockSize; private final long knownSize; + private long totalContentSize = 0L; private final ByteBuffer intLEBuffer = ByteBuffer.allocate(INTEGER_BYTES).order(ByteOrder.LITTLE_ENDIAN); private FrameInfo frameInfo = null; @@ -114,7 +115,9 @@ public LZ4FrameOutputStream(OutputStream out, BLOCKSIZE blockSize, FLG.Bits... b * * @param out the output stream to compress * @param blockSize the BLOCKSIZE to use - * @param knownSize the size of the uncompressed data. A value less than zero means unknown. + * @param knownSize the size of the uncompressed data. A value less than zero means unknown. If + * {@link FLG.Bits#CONTENT_SIZE} is set and the value is greater than zero, {@link #close()} fails if + * a different number of bytes was written. * @param bits a set of features to use * @throws IOException if an I/O error occurs */ @@ -128,7 +131,9 @@ public LZ4FrameOutputStream(OutputStream out, BLOCKSIZE blockSize, long knownSiz * * @param out the output stream to compress * @param blockSize the BLOCKSIZE to use - * @param knownSize the size of the uncompressed data. A value less than zero means unknown. + * @param knownSize the size of the uncompressed data. A value less than zero means unknown. If + * {@link FLG.Bits#CONTENT_SIZE} is set and the value is greater than zero, {@link #close()} fails if + * a different number of bytes was written. * @param compressor the {@link LZ4Compressor} instance to use to compress data * @param checksum the {@link XXHash32} instance to use to check data for integrity * @param bits a set of features to use @@ -205,6 +210,7 @@ private void writeBlock() throws IOException { if (buffer.position() == 0) { return; } + if (frameInfo.isEnabled(FLG.Bits.CONTENT_CHECKSUM)) { frameInfo.updateStreamHash(buffer.array(), 0, buffer.position()); } @@ -233,6 +239,7 @@ private void writeBlock() throws IOException { intLEBuffer.putInt(0, checksum.hash(bufferToWrite, 0, compressedLength, 0)); out.write(intLEBuffer.array()); } + totalContentSize += buffer.position(); buffer.rewind(); } @@ -298,13 +305,28 @@ private void ensureNotFinished() { } } + /** + * Ends the frame and closes the underlying stream. The underlying stream is closed even if ending the frame fails. + */ @Override public void close() throws IOException { - if (!frameInfo.isFinished()) { + if (frameInfo.isFinished()) { + return; + } + try { flush(); + // as in liblz4, 0 is not checked: the lz4 CLI decodes such frames whatever their size + if (frameInfo.isEnabled(FLG.Bits.CONTENT_SIZE) && knownSize > 0 && totalContentSize != knownSize) { + throw new IOException("Expected " + knownSize + " bytes of content, but " + totalContentSize + " were written"); + } writeEndMark(); + out.flush(); + } catch (Throwable t) { + frameInfo.finish(); + LZ4Utils.closeAfterFailure(out, t); + throw t; } - super.close(); + out.close(); } public static class FLG { diff --git a/src/java/net/jpountz/lz4/LZ4Utils.java b/src/java/net/jpountz/lz4/LZ4Utils.java index 6bacde92..94242841 100644 --- a/src/java/net/jpountz/lz4/LZ4Utils.java +++ b/src/java/net/jpountz/lz4/LZ4Utils.java @@ -16,6 +16,7 @@ * limitations under the License. */ +import java.io.Closeable; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; @@ -89,6 +90,18 @@ static int grownLength(int length, int minLength, int maxLength) { return (int) Math.min(maxLength, Math.max(minLength, 2L * length)); } + /** Closes {@code closeable} after {@code failure}, which the caller rethrows. Never throws. */ + static void closeAfterFailure(Closeable closeable, Throwable failure) { + try { + closeable.close(); + } catch (Throwable t) { + // streams may rethrow an earlier exception, and an exception cannot suppress itself + if (t != failure) { + failure.addSuppressed(t); + } + } + } + /** * Returns {@code true} if {@code available < required}. *

diff --git a/src/test/net/jpountz/lz4/LZ4OutputStreamTest.java b/src/test/net/jpountz/lz4/LZ4OutputStreamTest.java new file mode 100644 index 00000000..ae94b71a --- /dev/null +++ b/src/test/net/jpountz/lz4/LZ4OutputStreamTest.java @@ -0,0 +1,210 @@ +package net.jpountz.lz4; + +/* + * Copyright 2026 Dominik Opwis and the lz4-java contributors. + * + * 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.lz4.LZ4FrameOutputStream.BLOCKSIZE; +import net.jpountz.lz4.LZ4FrameOutputStream.FLG; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class LZ4OutputStreamTest { + + enum Format { + FRAME { + @Override + OutputStream open(OutputStream out) throws IOException { + return new LZ4FrameOutputStream(out, BLOCKSIZE.SIZE_64KB); + } + }, + BLOCK { + @Override + OutputStream open(OutputStream out) { + return new LZ4BlockOutputStream(out); + } + }; + + abstract OutputStream open(OutputStream out) throws IOException; + } + + /** Records what was written, throws the given exceptions, if any, and counts calls. */ + private static final class FailingOutputStream extends OutputStream { + final ByteArrayOutputStream written = new ByteArrayOutputStream(); + Throwable writeFailure; + Throwable flushFailure; + IOException closeFailure; + int failedWrites; + int closes; + int flushedSize; + + @Override + public void write(int b) throws IOException { + if (writeFailure != null) { + failedWrites++; + } + throwIfNotNull(writeFailure); + written.write(b); + } + + @Override + public void flush() throws IOException { + throwIfNotNull(flushFailure); + flushedSize = written.size(); + } + + @Override + public void close() throws IOException { + closes++; + throwIfNotNull(closeFailure); + } + + private static void throwIfNotNull(Throwable t) throws IOException { + if (t instanceof IOException) { + throw (IOException) t; + } else if (t != null) { + throw (Error) t; + } + } + } + + @ParameterizedTest + @EnumSource(Format.class) + public void testFailedCloseClosesUnderlyingStream(Format format) throws IOException { + for (Throwable failure : new Throwable[] {new IOException("write"), new Error("write")}) { + final FailingOutputStream out = new FailingOutputStream(); + final OutputStream os = format.open(out); + os.write(1); + out.writeFailure = failure; + out.closeFailure = new IOException("close"); + + assertSame(failure, assertThrows(Throwable.class, os::close)); + assertArrayEquals(new Throwable[] {out.closeFailure}, failure.getSuppressed()); + assertEquals(1, out.closes); + } + } + + @ParameterizedTest + @EnumSource(Format.class) + public void testFailedFlushClosesUnderlyingStream(Format format) throws IOException { + final FailingOutputStream out = new FailingOutputStream(); + final OutputStream os = format.open(out); + out.flushFailure = new Error("flush"); + + assertSame(out.flushFailure, assertThrows(Error.class, os::close)); + assertEquals(1, out.closes); + } + + @ParameterizedTest + @EnumSource(Format.class) + public void testFailedCloseIsNotRetried(Format format) throws IOException { + final FailingOutputStream out = new FailingOutputStream(); + final OutputStream os = format.open(out); + os.write(1); + out.writeFailure = new IOException("write"); + assertThrows(IOException.class, os::close); + final int failedWrites = out.failedWrites; + + os.close(); + assertEquals(failedWrites, out.failedWrites); + assertEquals(1, out.closes); + assertThrows(IllegalStateException.class, () -> os.write(1)); + } + + /** Streams may rethrow the exception of an earlier failure, and an exception must not suppress itself. */ + @ParameterizedTest + @EnumSource(Format.class) + public void testSameExceptionOnWriteAndClose(Format format) throws IOException { + final FailingOutputStream out = new FailingOutputStream(); + final OutputStream os = format.open(out); + os.write(1); + out.closeFailure = new IOException("failed"); + out.writeFailure = out.closeFailure; + + assertSame(out.closeFailure, assertThrows(IOException.class, os::close)); + assertEquals(1, out.closes); + } + + @ParameterizedTest + @EnumSource(Format.class) + public void testDoubleCloseClosesUnderlyingStreamOnce(Format format) throws IOException { + final FailingOutputStream out = new FailingOutputStream(); + final OutputStream os = format.open(out); + os.close(); + assertEquals(out.written.size(), out.flushedSize); + out.flushFailure = new IOException("flush"); + os.close(); + assertEquals(1, out.closes); + } + + private static OutputStream frameWithKnownSize(OutputStream out, long knownSize) throws IOException { + return new LZ4FrameOutputStream(out, BLOCKSIZE.SIZE_64KB, knownSize, FLG.Bits.BLOCK_INDEPENDENCE, + FLG.Bits.CONTENT_SIZE); + } + + @ParameterizedTest + @ValueSource(ints = {0, 9, 11, (1 << 16) + 10}) + public void testCloseRejectsKnownSizeMismatch(int size) throws IOException { + final FailingOutputStream out = new FailingOutputStream(); + final OutputStream os = frameWithKnownSize(out, 10); + os.write(new byte[size]); + os.flush(); + final int writtenBeforeClose = out.written.size(); + + assertThrows(IOException.class, os::close); + assertEquals(writtenBeforeClose, out.written.size(), "the frame must not be ended"); + assertEquals(1, out.closes); + } + + /** The lz4 CLI decodes such frames, so writing them must keep working. */ + @Test + public void testKnownSizeZeroIsNotChecked() throws IOException { + final OutputStream os = frameWithKnownSize(new ByteArrayOutputStream(), 0); + os.write(new byte[5]); + os.close(); + } + + @Test + public void testKnownSizeIsNotCheckedWithoutContentSize() throws IOException { + final OutputStream os = new LZ4FrameOutputStream(new ByteArrayOutputStream(), BLOCKSIZE.SIZE_64KB, 10, + FLG.Bits.BLOCK_INDEPENDENCE); + os.write(new byte[5]); + os.close(); + } + + @Test + public void testKnownSizeAcrossBlocksAndFlushes() throws IOException { + final byte[] data = new byte[(1 << 16) + 10]; + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + try (OutputStream os = frameWithKnownSize(out, data.length)) { + os.write(data, 0, 5); + os.flush(); + os.write(data, 5, data.length - 5); + } + assertArrayEquals(data, new LZ4FrameInputStream(new ByteArrayInputStream(out.toByteArray())).readAllBytes()); + } +}