This is an automated email from the ASF dual-hosted git repository.

garydgregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-compress.git


The following commit(s) were added to refs/heads/master by this push:
     new 6bc21c07c Fix 7z substream memory accounting and validation (#862)
6bc21c07c is described below

commit 6bc21c07cf58932358513a29054288fb3397b3fb
Author: Gary Gregory <[email protected]>
AuthorDate: Wed Dec 2 10:46:29 2026 -0500

    Fix 7z substream memory accounting and validation (#862)
    
    Calculate storage with long arithmetic and count the BitSet backing
    array once, removing false overflow failures for large valid archives.
    
    Enforce configured limits before allocation, include substream storage
    in aggregate metadata estimates, and round KiB requirements up.
    Reject missing or truncated size records and overflowing substream
    counts during header validation.
    
    Add regression tests for allocation boundaries, mixed folder counts,
    encoded headers, and large valid archives. Update Javadoc.
---
 src/changes/changes.xml                            |   1 +
 .../compress/archivers/sevenz/SevenZFile.java      |  23 +-
 .../compress/archivers/sevenz/SubStreamsInfo.java  |  37 ++-
 .../archivers/sevenz/SevenZSubStreamsInfoTest.java | 347 +++++++++++++++++++++
 .../archivers/sevenz/SubStreamsInfoTest.java       |  75 +++++
 5 files changed, 463 insertions(+), 20 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 2ebbc7e2c..37c2c3090 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -67,6 +67,7 @@ The <action> type attribute can be add,update,fix,remove.
       <action type="fix" dev="ggregory" due-to="Gary Gregory">[7-Zip] 
AES256SHA256Decoder now throws ArchiveException instead of 
IllegalArgumetException/IllegalStateException.</action>
       <action type="fix" dev="ggregory" due-to="Gary Gregory">[7-Zip] 
SevenZMethodConfiguration now throws ArchiveException instead of 
IllegalArgumetException/IllegalStateException.</action>
       <action type="fix" dev="ggregory" due-to="Gary Gregory">[7-Zip] 
SevenZOutputFile now throws ArchiveException instead of 
IllegalArgumetException/IllegalStateException.</action>
+      <action type="fix" dev="ggregory" due-to="Claude Security, Gary 
Gregory">[7-Zip] Correct substream memory accounting, enforce the configured 
memory limit, and reject missing substream sizes.</action>
       <!-- FIX bzip2 -->
       <action type="fix" dev="ggregory" due-to="Tyler Nighswander, Gary 
Gregory">[BZip2] BZip2CompressorInputStream now throws CompressorException 
instead of IllegalArgumetException/IllegalStateException.</action>
       <action type="fix" dev="pkarwasz" due-to="Tyler Nighswander, Piotr P. 
Karwasz">[BZip2] BZip2 input streams treat Huffman codes longer than 20 bits as 
corrupted data, matching the behavior of the reference implementation.</action>
diff --git 
a/src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZFile.java 
b/src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZFile.java
index ab4a9c747..38a667abb 100644
--- a/src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZFile.java
+++ b/src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZFile.java
@@ -82,7 +82,7 @@ private static final class ArchiveStatistics {
         private long numberOfCoders;
         private long numberOfOutStreams;
         private long numberOfInStreams;
-        private long numberOfUnpackSubStreams;
+        private int numberOfUnpackSubStreams;
         private int numberOfFolders;
         private BitSet folderHasCrc;
         private int numberOfEntries;
@@ -101,7 +101,7 @@ void assertValidity(final int maxMemoryLimitKiB) throws 
CompressException {
             if (numberOfEntriesWithStream > numberOfUnpackSubStreams) {
                 throw new ArchiveException("7z archive doesn't contain enough 
substreams for entries");
             }
-            MemoryLimitException.checkKiB(bytesToKiB(estimateSizeBytes()), 
maxMemoryLimitKiB);
+            MemoryLimitException.checkKiB((estimateSizeBytes() + 1023) / 1024, 
maxMemoryLimitKiB);
         }
 
         private long bindPairSize() {
@@ -141,6 +141,7 @@ long estimateSizeBytes() {
                     + (numberOfOutStreams - numberOfFolders) * bindPairSize() 
/* bindPairs in Folder */
                     + 8L * (numberOfInStreams - numberOfOutStreams + 
numberOfFolders) /* packedStreams in Folder */
                     + 8L * numberOfOutStreams /* unpackSizes in Folder */
+                    + 
SubStreamsInfo.estimateSizeBytes(numberOfUnpackSubStreams)
                     + numberOfEntries * entrySize() /* files in Archive */
                     + streamMapSize();
             return 2 * lowerBound /* conservative guess */;
@@ -172,6 +173,11 @@ public String toString() {
      * {@link Integer#MAX_VALUE} kibibytes (KiB). Negative values do not mean 
no configured limit for this builder.
      * </p>
      *
+     * <p>
+     * Archive metadata usage is estimated, including the arrays holding 
substream sizes, CRCs, and CRC flags. The limit is not an exact bound on total 
JVM heap
+     * usage.
+     * </p>
+     *
      * @since 1.26.0
      */
     public static class Builder extends AbstractArchiveBuilder<SevenZFile, 
Builder> {
@@ -2177,17 +2183,24 @@ private void sanityCheckStreamsInfo(final ByteBuffer 
header, final ArchiveStatis
     private void sanityCheckSubStreamsInfo(final ByteBuffer header, final 
ArchiveStatistics stats) throws IOException {
         int nid = getUnsignedByte(header);
         final List<Integer> numUnpackSubStreamsPerFolder = new LinkedList<>();
+        long numUnpackSizes = 0;
         if (nid == NID.kNumUnpackStream) {
+            stats.numberOfUnpackSubStreams = 0;
             for (int i = 0; i < stats.numberOfFolders; i++) {
-                numUnpackSubStreamsPerFolder.add(readUint64ToIntExact(header, 
"numStreams"));
+                final int numStreams = readUint64ToIntExact(header, 
"numStreams");
+                numUnpackSubStreamsPerFolder.add(numStreams);
+                stats.numberOfUnpackSubStreams = 
accumulate(stats.numberOfUnpackSubStreams, numStreams, "totalUnpackStreams");
+                numUnpackSizes += Math.max(0, numStreams - 1);
             }
-            stats.numberOfUnpackSubStreams = 
numUnpackSubStreamsPerFolder.stream().mapToLong(Integer::longValue).sum();
             nid = getUnsignedByte(header);
         } else {
             stats.numberOfUnpackSubStreams = stats.numberOfFolders;
         }
-        toNonNegativeInt("totalUnpackStreams", stats.numberOfUnpackSubStreams);
+        if (numUnpackSizes > 0 && nid != NID.kSize) {
+            throw new ArchiveException("7z archive: Missing substream sizes");
+        }
         if (nid == NID.kSize) {
+            ensureRemaining(header, MIN_UINT64_BYTES * numUnpackSizes);
             for (final int numUnpackSubStreams : numUnpackSubStreamsPerFolder) 
{
                 if (numUnpackSubStreams == 0) {
                     continue;
diff --git 
a/src/main/java/org/apache/commons/compress/archivers/sevenz/SubStreamsInfo.java
 
b/src/main/java/org/apache/commons/compress/archivers/sevenz/SubStreamsInfo.java
index fe404de04..c25aef429 100644
--- 
a/src/main/java/org/apache/commons/compress/archivers/sevenz/SubStreamsInfo.java
+++ 
b/src/main/java/org/apache/commons/compress/archivers/sevenz/SubStreamsInfo.java
@@ -21,13 +21,23 @@
 
 import java.util.BitSet;
 
-import org.apache.commons.compress.archivers.ArchiveException;
+import org.apache.commons.compress.MemoryLimitException;
 
 /**
  * Properties for non-empty files.
  */
 final class SubStreamsInfo {
 
+    /**
+     * Estimates the array storage for the substream sizes, CRCs, and CRC 
flags, excluding object headers and alignment.
+     *
+     * @param totalUnpackStreams the non-negative number of substreams.
+     * @return the estimated storage in bytes.
+     */
+    static long estimateSizeBytes(final int totalUnpackStreams) {
+        return 2L * Long.BYTES * totalUnpackStreams + Long.BYTES * 
((totalUnpackStreams + 63L) / 64);
+    }
+
     /**
      * Unpacked size of each unpacked stream.
      */
@@ -43,21 +53,18 @@ final class SubStreamsInfo {
      */
     final long[] crcs;
 
-    SubStreamsInfo(final int totalUnpackStreams, final int maxMemoryLimitKiB) 
throws ArchiveException {
-        long alloc;
-        try {
-            // 2 long arrays, just count the longs
-            alloc = Math.multiplyExact(totalUnpackStreams, Long.BYTES * 2);
-            // one BitSet [boolean, long[], int]. just count the long array
-            final int sizeOfBitSet = Math.multiplyExact(Long.BYTES, 
(totalUnpackStreams - 1 >> 6) + 1);
-            alloc = Math.addExact(alloc, 
Math.multiplyExact(totalUnpackStreams, sizeOfBitSet));
-        } catch (final ArithmeticException e) {
-            throw new ArchiveException("Cannot create allocation request for a 
SubStreamsInfo of totalUnpackStreams %,d, maxMemoryLimitKiB %,d: %s",
-                    totalUnpackStreams, maxMemoryLimitKiB, e);
+    /**
+     * Allocates substream metadata after checking its estimated array storage 
against the configured memory limit.
+     *
+     * @param totalUnpackStreams the non-negative number of substreams.
+     * @param maxMemoryLimitKiB  the maximum estimated storage in kibibytes.
+     * @throws MemoryLimitException if the estimated storage exceeds the 
configured limit.
+     */
+    SubStreamsInfo(final int totalUnpackStreams, final int maxMemoryLimitKiB) 
throws MemoryLimitException {
+        final long memoryNeededKiB = (estimateSizeBytes(totalUnpackStreams) + 
1023) / 1024;
+        if (memoryNeededKiB > maxMemoryLimitKiB) {
+            throw new MemoryLimitException(memoryNeededKiB, maxMemoryLimitKiB);
         }
-        // Avoid false positives.
-        // Not a reliable check in old VMs or in low memory VMs.
-        // MemoryLimitException.checkKiB(SevenZFile.bytesToKiB(alloc), 
maxMemoryLimitKiB);
         this.hasCrc = new BitSet(totalUnpackStreams);
         this.crcs = new long[totalUnpackStreams];
         this.unpackSizes = new long[totalUnpackStreams];
diff --git 
a/src/test/java/org/apache/commons/compress/archivers/sevenz/SevenZSubStreamsInfoTest.java
 
b/src/test/java/org/apache/commons/compress/archivers/sevenz/SevenZSubStreamsInfoTest.java
new file mode 100644
index 000000000..90c10ff3b
--- /dev/null
+++ 
b/src/test/java/org/apache/commons/compress/archivers/sevenz/SevenZSubStreamsInfoTest.java
@@ -0,0 +1,347 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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
+ *
+ *   https://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.
+ */
+
+package org.apache.commons.compress.archivers.sevenz;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.util.Arrays;
+import java.util.zip.CRC32;
+
+import org.apache.commons.compress.MemoryLimitException;
+import org.apache.commons.compress.archivers.ArchiveException;
+import org.apache.commons.io.channels.ByteArraySeekableByteChannel;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/**
+ * Tests substream metadata parsing through the public archive builder.
+ */
+class SevenZSubStreamsInfoTest {
+
+    /**
+     * Builds a COPY folder containing {@code count} zero bytes and optionally 
one named entry for each byte.
+     *
+     * @param count      the number of bytes in the folder.
+     * @param subStreams the complete substream information section.
+     * @param folderCrc  whether the folder has a CRC.
+     * @param files      whether to include file entries.
+     * @return the archive bytes.
+     */
+    private static byte[] archive(final int count, final byte[] subStreams, 
final boolean folderCrc, final boolean files) {
+        return archive(new int[] {count}, subStreams, folderCrc, files);
+    }
+
+    private static byte[] archive(final int[] counts, final byte[] subStreams, 
final boolean folderCrc, final boolean files) {
+        final int count = Arrays.stream(counts).sum();
+        final byte[] data = new byte[count];
+        final UnsynchronizedByteArrayOutputStream header = 
UnsynchronizedByteArrayOutputStream.builder().get();
+        header.write(NID.kHeader);
+        header.write(NID.kMainStreamsInfo);
+        header.write(NID.kPackInfo);
+        header.write(0); // packPos
+        header.write(counts.length);
+        header.write(NID.kSize);
+        for (final int size : counts) {
+            writeUint64(header, size);
+        }
+        header.write(NID.kEnd);
+        header.write(NID.kUnpackInfo);
+        header.write(NID.kFolder);
+        header.write(counts.length);
+        header.write(0); // not external
+        for (int i = 0; i < counts.length; i++) {
+            header.write(1); // one coder
+            header.write(1); // one byte coder id, one input and one output
+            header.write(0); // COPY
+        }
+        header.write(NID.kCodersUnpackSize);
+        for (final int size : counts) {
+            writeUint64(header, size);
+        }
+        if (folderCrc) {
+            header.write(NID.kCRC);
+            header.write(1); // all CRCs defined
+            for (final int size : counts) {
+                writeCrc(header, new byte[size]);
+            }
+        }
+        header.write(NID.kEnd);
+        header.write(subStreams, 0, subStreams.length);
+        header.write(NID.kEnd);
+        if (files) {
+            header.write(NID.kFilesInfo);
+            writeUint64(header, count);
+            header.write(NID.kName);
+            writeUint64(header, 1L + 4L * count);
+            header.write(0); // not external
+            for (int i = 0; i < count; i++) {
+                header.write('a');
+                header.write(0);
+                header.write(0);
+                header.write(0);
+            }
+            header.write(NID.kEnd);
+        }
+        header.write(NID.kEnd);
+        return archive(data, header.toByteArray());
+    }
+
+    private static byte[] archive(final byte[] data, final byte[] headerBytes) 
{
+        final CRC32 crc = new CRC32();
+        crc.update(headerBytes);
+        final ByteBuffer start = 
ByteBuffer.allocate(20).order(ByteOrder.LITTLE_ENDIAN);
+        start.putLong(data.length);
+        start.putLong(headerBytes.length);
+        start.putInt((int) crc.getValue());
+        crc.reset();
+        crc.update(start.array());
+        final ByteBuffer result = ByteBuffer.allocate(32 + data.length + 
headerBytes.length).order(ByteOrder.LITTLE_ENDIAN);
+        result.put(SevenZFile.SIGNATURE).put((byte) 0).put((byte) 
4).putInt((int) crc.getValue());
+        result.put(start.array()).put(data).put(headerBytes);
+        return result.array();
+    }
+
+    private static SevenZFile open(final byte[] archive, final int limitKiB) 
throws IOException {
+        return 
SevenZFile.builder().setChannel(ByteArraySeekableByteChannel.builder().setByteArray(archive).get()).setMaxMemoryLimitKiB(limitKiB).get();
+    }
+
+    /**
+     * Builds substream information with explicit counts and optional sizes 
and CRCs.
+     *
+     * @param count    the declared count, or {@code -1} to use the default of 
one substream.
+     * @param numSizes the number of one byte sizes to write, or {@code -1} to 
omit the size section.
+     * @param crc      whether to write CRCs for all substreams.
+     * @return the substream information bytes.
+     */
+    private static byte[] subStreams(final int count, final int numSizes, 
final boolean crc) {
+        final UnsynchronizedByteArrayOutputStream info = 
UnsynchronizedByteArrayOutputStream.builder().get();
+        info.write(NID.kSubStreamsInfo);
+        if (count >= 0) {
+            info.write(NID.kNumUnpackStream);
+            writeUint64(info, count);
+        }
+        if (numSizes >= 0) {
+            info.write(NID.kSize);
+            for (int i = 0; i < numSizes; i++) {
+                info.write(1);
+            }
+        }
+        if (crc) {
+            info.write(NID.kCRC);
+            info.write(1); // all CRCs defined
+            for (int i = 0; i < count; i++) {
+                writeCrc(info, new byte[1]);
+            }
+        }
+        info.write(NID.kEnd);
+        return info.toByteArray();
+    }
+
+    private static byte[] subStreams(final int[] counts, final boolean sizes) {
+        final UnsynchronizedByteArrayOutputStream info = 
UnsynchronizedByteArrayOutputStream.builder().get();
+        info.write(NID.kSubStreamsInfo);
+        info.write(NID.kNumUnpackStream);
+        for (final int count : counts) {
+            writeUint64(info, count);
+        }
+        if (sizes) {
+            info.write(NID.kSize);
+            for (final int count : counts) {
+                for (int i = 1; i < count; i++) {
+                    info.write(1);
+                }
+            }
+        }
+        info.write(NID.kEnd);
+        return info.toByteArray();
+    }
+
+    private static void writeCrc(final UnsynchronizedByteArrayOutputStream 
out, final byte[] data) {
+        final CRC32 crc = new CRC32();
+        crc.update(data);
+        for (int i = 0; i < Integer.BYTES; i++) {
+            out.write((int) (crc.getValue() >>> (i * Byte.SIZE)) & 0xff);
+        }
+    }
+
+    private static void writeUint64(final UnsynchronizedByteArrayOutputStream 
out, final long value) {
+        out.write(0xff);
+        for (int i = 0; i < Long.BYTES; i++) {
+            out.write((int) (value >>> (i * Byte.SIZE)) & 0xff);
+        }
+    }
+
+    @Test
+    void testAggregateEncodedHeaderMemoryLimit() {
+        final byte[] plain = archive(1000, subStreams(1000, 999, false), 
false, false);
+        // Reuse the same stream declarations as an encoded header. Its 
contents must not be decoded before the budget check.
+        final byte[] encodedHeader = Arrays.copyOfRange(plain, 32 + 1000 + 1, 
plain.length - 1);
+        encodedHeader[0] = NID.kEncodedHeader;
+        final byte[] encoded = archive(new byte[1000], encodedHeader);
+        final MemoryLimitException exception = 
assertThrows(MemoryLimitException.class, () -> open(encoded, 20).close());
+        assertEquals(32, exception.getMemoryNeededInKb());
+        assertEquals(20, exception.getMemoryLimitInKiBLong());
+    }
+
+    @Test
+    void testAggregateMemoryLimit() throws IOException {
+        final byte[] bytes = archive(1000, subStreams(1000, 999, false), 
false, false);
+        // The header and substream arrays each fit in 20 KiB, but the 
conservative aggregate estimate does not.
+        final MemoryLimitException exception = 
assertThrows(MemoryLimitException.class, () -> open(bytes, 20).close());
+        assertEquals(32, exception.getMemoryNeededInKb());
+        assertEquals(20, exception.getMemoryLimitInKiBLong());
+        try (SevenZFile file = open(bytes, 64)) {
+            assertEquals(0, file.stream().count());
+        }
+    }
+
+    @Test
+    void testCombinedCountOverflow() {
+        final UnsynchronizedByteArrayOutputStream info = 
UnsynchronizedByteArrayOutputStream.builder().get();
+        info.write(NID.kSubStreamsInfo);
+        info.write(NID.kNumUnpackStream);
+        writeUint64(info, Integer.MAX_VALUE);
+        writeUint64(info, 1);
+        info.write(NID.kEnd);
+        final byte[] bytes = archive(new int[] {0, 0}, info.toByteArray(), 
false, false);
+        final ArchiveException exception = 
assertThrows(ArchiveException.class, () -> open(bytes, 
Integer.MAX_VALUE).close());
+        assertTrue(exception.getMessage().contains("totalUnpackStreams"));
+    }
+
+    @ParameterizedTest
+    @ValueSource(ints = {-1, 1})
+    void testDefaultAndExplicitSingleSubstream(final int count) throws 
IOException {
+        try (SevenZFile file = open(archive(1, subStreams(count, -1, false), 
true, true), 64)) {
+            final SevenZArchiveEntry entry = file.getNextEntry();
+            assertNotNull(entry);
+            assertEquals(1, entry.getSize());
+            assertFalse(entry.getHasCrc());
+            assertEquals(0, file.read());
+            assertEquals(-1, file.read());
+            assertNull(file.getNextEntry());
+        }
+    }
+
+    @Test
+    void testInheritedFolderCrc() throws IOException {
+        final byte[] info = {(byte) NID.kSubStreamsInfo, (byte) NID.kCRC, 1, 
(byte) NID.kEnd};
+        try (SevenZFile file = open(archive(1, info, true, true), 64)) {
+            final SevenZArchiveEntry entry = file.getNextEntry();
+            assertNotNull(entry);
+            assertTrue(entry.getHasCrc());
+            assertEquals(0, file.read());
+            assertEquals(-1, file.read());
+        }
+    }
+
+    @Test
+    void testLargeValidArchive() throws IOException {
+        final int count = 131_072;
+        try (SevenZFile file = open(archive(count, subStreams(count, count - 
1, false), false, true), 65_536)) {
+            assertEquals(count, file.stream().count());
+            assertEquals(1, file.getNextEntry().getSize());
+            assertEquals(0, file.read());
+        }
+    }
+
+    @Test
+    void testMetadataMemoryLimitRoundsUp() throws IOException {
+        final byte[] bytes = archive(20, subStreams(20, 19, false), false, 
true);
+        final MemoryLimitException exception = 
assertThrows(MemoryLimitException.class, () -> open(bytes, 4).close());
+        assertEquals(5, exception.getMemoryNeededInKb());
+        assertEquals(4, exception.getMemoryLimitInKiBLong());
+        try (SevenZFile file = open(bytes, 5)) {
+            assertEquals(20, file.stream().count());
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(ints = {2, 100_000, Integer.MAX_VALUE - 1})
+    void testMissingSizes(final int count) {
+        final byte[] bytes = archive(0, subStreams(count, -1, false), false, 
false);
+        final ArchiveException exception = 
assertThrows(ArchiveException.class, () -> open(bytes, 
Integer.MAX_VALUE).close());
+        assertEquals("7z archive: Missing substream sizes", 
exception.getMessage());
+    }
+
+    @Test
+    void testMissingSizesWithEmptyFolder() {
+        // The total stream count equals the folder count, but the second 
folder still needs an explicit size.
+        final int[] counts = {0, 2};
+        final byte[] bytes = archive(counts, subStreams(counts, false), false, 
true);
+        final ArchiveException exception = 
assertThrows(ArchiveException.class, () -> open(bytes, 64).close());
+        assertEquals("7z archive: Missing substream sizes", 
exception.getMessage());
+    }
+
+    @Test
+    void testMixedFolderCounts() throws IOException {
+        final int[] counts = {0, 1, 0, 2};
+        try (SevenZFile file = open(archive(counts, subStreams(counts, true), 
false, true), 64)) {
+            for (int i = 0; i < 3; i++) {
+                final SevenZArchiveEntry entry = file.getNextEntry();
+                assertNotNull(entry);
+                assertEquals(1, entry.getSize());
+                assertEquals(0, file.read());
+                assertEquals(-1, file.read());
+            }
+            assertNull(file.getNextEntry());
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void testMultipleSubstreams(final boolean crc) throws IOException {
+        try (SevenZFile file = open(archive(2, subStreams(2, 1, crc), false, 
true), 64)) {
+            for (int i = 0; i < 2; i++) {
+                final SevenZArchiveEntry entry = file.getNextEntry();
+                assertNotNull(entry);
+                assertEquals(1, entry.getSize());
+                assertEquals(crc, entry.getHasCrc());
+                assertEquals(0, file.read());
+                assertEquals(-1, file.read());
+            }
+            assertNull(file.getNextEntry());
+        }
+    }
+
+    @Test
+    void testTruncatedSizes() {
+        final byte[] bytes = archive(0, subStreams(100_000, 1, false), false, 
false);
+        final ArchiveException exception = 
assertThrows(ArchiveException.class, () -> open(bytes, 
Integer.MAX_VALUE).close());
+        assertTrue(exception.getMessage().contains(String.format("expecting 
%,d bytes", 99_999)));
+    }
+
+    @ParameterizedTest
+    @ValueSource(ints = {-1, 0})
+    void testZeroSubstreams(final int numSizes) throws IOException {
+        try (SevenZFile file = open(archive(0, subStreams(0, numSizes, false), 
false, true), 64)) {
+            assertNull(file.getNextEntry());
+        }
+    }
+}
diff --git 
a/src/test/java/org/apache/commons/compress/archivers/sevenz/SubStreamsInfoTest.java
 
b/src/test/java/org/apache/commons/compress/archivers/sevenz/SubStreamsInfoTest.java
new file mode 100644
index 000000000..62610d691
--- /dev/null
+++ 
b/src/test/java/org/apache/commons/compress/archivers/sevenz/SubStreamsInfoTest.java
@@ -0,0 +1,75 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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
+ *
+ *   https://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.
+ */
+
+package org.apache.commons.compress.archivers.sevenz;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import org.apache.commons.compress.MemoryLimitException;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/**
+ * Tests substream allocation estimates and configured memory limits.
+ */
+class SubStreamsInfoTest {
+
+    @ParameterizedTest
+    @CsvSource({"0, 0", "1, 24", "63, 1016", "64, 1032", "65, 1056", "127, 
2048", "128, 2064", "131072, 2113536",
+            "2147483647, 34628173808"})
+    void testEstimateSizeBytes(final int count, final long bytes) {
+        assertEquals(bytes, SubStreamsInfo.estimateSizeBytes(count));
+    }
+
+    @ParameterizedTest
+    @ValueSource(ints = {Integer.MAX_VALUE - 1, Integer.MAX_VALUE})
+    void testHugeCount(final int count) {
+        final MemoryLimitException exception = 
assertThrows(MemoryLimitException.class, () -> new SubStreamsInfo(count, 1));
+        assertEquals(33_816_576, exception.getMemoryNeededInKb());
+        assertEquals(1, exception.getMemoryLimitInKiBLong());
+    }
+
+    @ParameterizedTest
+    @CsvSource({"1, 1", "63, 1", "64, 2", "65, 2", "127, 2", "128, 3", 
"131072, 2064", "131073, 2065"})
+    void testMemoryLimit(final int count, final int memoryKiB) throws 
MemoryLimitException {
+        final SubStreamsInfo info = new SubStreamsInfo(count, memoryKiB);
+        assertEquals(count, info.crcs.length);
+        assertEquals(count, info.unpackSizes.length);
+        assertEquals(0, info.hasCrc.cardinality());
+        final MemoryLimitException exception = 
assertThrows(MemoryLimitException.class, () -> new SubStreamsInfo(count, 
memoryKiB - 1));
+        assertEquals(memoryKiB, exception.getMemoryNeededInKb());
+        assertEquals(memoryKiB - 1, exception.getMemoryLimitInKiBLong());
+    }
+
+    @Test
+    void testNegativeLimit() {
+        assertThrows(MemoryLimitException.class, () -> new SubStreamsInfo(0, 
-1));
+    }
+
+    @Test
+    void testZeroLimit() throws MemoryLimitException {
+        final SubStreamsInfo info = new SubStreamsInfo(0, 0);
+        assertEquals(0, info.crcs.length);
+        assertEquals(0, info.unpackSizes.length);
+        assertEquals(0, info.hasCrc.size());
+    }
+}

Reply via email to