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 eb3cfd558 Avoid quadratic scanning when rewriting Pack200 switch 
targets (f005) (#861)
eb3cfd558 is described below

commit eb3cfd5586f6f083d43c7660effda6d4ee9ec810
Author: Gary Gregory <[email protected]>
AuthorDate: Wed Dec 2 09:39:03 2026 -0500

    Avoid quadratic scanning when rewriting Pack200 switch targets (f005) (#861)
    
    Resume placeholder searches after each rewritten operand, sharing the
    search logic with the existing writer. Preserve output and exception
    behavior.
    
    Add regression tests for both switch forms, alignment, signed offsets,
    missing placeholders, and large switches.
---
 src/changes/changes.xml                            |   1 +
 .../unpack200/bytecode/forms/SwitchForm.java       |   6 +-
 .../bytecode/forms/VariableInstructionForm.java    |  32 ++--
 .../unpack200/bytecode/forms/SwitchFormTest.java   | 161 +++++++++++++++++++++
 .../forms/VariableInstructionFormTest.java         |  66 +++++++++
 5 files changed, 254 insertions(+), 12 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 9ff74606f..2ebbc7e2c 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -134,6 +134,7 @@ The <action> type attribute can be add,update,fix,remove.
       <action type="fix" dev="ggregory" due-to="KALI 834X, Gary 
Gregory">[Unpack200] Reject out-of-range cpUTF8Prefix in CpBands.parseCpUtf8 
(#800).</action>
       <action type="fix" dev="ggregory" due-to="KALI 834X, Gary 
Gregory">[Unpack200] Remove Error rethrow in pack200 ReferenceForm and 
NewClassRefForm (unpack200 package) (#805).</action>
       <action type="fix" dev="ggregory" due-to="Gary Gregory">[Unpack200] 
Preserve known input bounds when unpacking files and buffering streams.</action>
+      <action type="fix" dev="ggregory" due-to="Claude Security, Gary 
Gregory">[Unpack200] Avoid quadratic scanning when rewriting switch bytecode 
targets.</action>
       <!-- FIX pack200 -->
       <action type="fix" dev="ggregory" due-to="Gary Gregory, Igor 
Morgenstern">[Pack200] org.apache.commons.compress.harmony.pack200 now throws 
Pack200Exception, IllegalArgumentException, IllegalStateException, instead of 
other runtime exceptions and Error.</action>
       <action type="fix" dev="ppkarwasz" due-to="Raeps">[Pack200] Extract 
duplicate code in org.apache.commons.compress.harmony.pack200.IntList.</action>
diff --git 
a/src/main/java/org/apache/commons/compress/harmony/unpack200/bytecode/forms/SwitchForm.java
 
b/src/main/java/org/apache/commons/compress/harmony/unpack200/bytecode/forms/SwitchForm.java
index ada6e15a7..132d2ce43 100644
--- 
a/src/main/java/org/apache/commons/compress/harmony/unpack200/bytecode/forms/SwitchForm.java
+++ 
b/src/main/java/org/apache/commons/compress/harmony/unpack200/bytecode/forms/SwitchForm.java
@@ -58,8 +58,10 @@ public void fixUpByteCodeTargets(final ByteCode byteCode, 
final CodeAttribute co
             replacementTargets[index] = targetValue - sourceValue;
         }
         final int[] rewriteArray = byteCode.getRewrite();
-        for (int index = 0; index < numberOfLabels; index++) {
-            setRewrite4Bytes(replacementTargets[index], rewriteArray);
+        // Resume after each operand so that all labels are filled in a single 
forward scan.
+        int nextPosition = 0;
+        for (final int replacementTarget : replacementTargets) {
+            nextPosition = setNextRewrite4Bytes(replacementTarget, 
rewriteArray, nextPosition);
         }
     }
 
diff --git 
a/src/main/java/org/apache/commons/compress/harmony/unpack200/bytecode/forms/VariableInstructionForm.java
 
b/src/main/java/org/apache/commons/compress/harmony/unpack200/bytecode/forms/VariableInstructionForm.java
index df93aca25..003d2e7fb 100644
--- 
a/src/main/java/org/apache/commons/compress/harmony/unpack200/bytecode/forms/VariableInstructionForm.java
+++ 
b/src/main/java/org/apache/commons/compress/harmony/unpack200/bytecode/forms/VariableInstructionForm.java
@@ -36,6 +36,27 @@ public VariableInstructionForm(final int opcode, final 
String name) {
         super(opcode, name);
     }
 
+    /**
+     * Writes a four-byte operand into the next available placeholder at or 
after the given position.
+     *
+     * @param operand value to write.
+     * @param rewrite array to write into.
+     * @param startPosition non-negative position at which to start searching 
for four consecutive {@code -1} values.
+     * @return the position immediately after the written operand.
+     * @throws IllegalArgumentException if no four-byte placeholder is 
available at or after {@code startPosition}.
+     */
+    int setNextRewrite4Bytes(final int operand, final int[] rewrite, final int 
startPosition) {
+        int firstOperandPosition = -1;
+        for (int index = startPosition; index < rewrite.length - 3; index++) {
+            if (rewrite[index] == -1 && rewrite[index + 1] == -1 && 
rewrite[index + 2] == -1 && rewrite[index + 3] == -1) {
+                firstOperandPosition = index;
+                break;
+            }
+        }
+        setRewrite4Bytes(operand, firstOperandPosition, rewrite);
+        return firstOperandPosition + 4;
+    }
+
     /**
      * This method writes operand directly into the rewrite array at index 
position specified.
      *
@@ -91,15 +112,6 @@ public void setRewrite4Bytes(final int operand, final int 
absPosition, final int
      * @param rewrite int[] bytes to rewrite
      */
     public void setRewrite4Bytes(final int operand, final int[] rewrite) {
-        int firstOperandPosition = -1;
-
-        // Find the first -1 in the rewrite array
-        for (int index = 0; index < rewrite.length - 3; index++) {
-            if (rewrite[index] == -1 && rewrite[index + 1] == -1 && 
rewrite[index + 2] == -1 && rewrite[index + 3] == -1) {
-                firstOperandPosition = index;
-                break;
-            }
-        }
-        setRewrite4Bytes(operand, firstOperandPosition, rewrite);
+        setNextRewrite4Bytes(operand, rewrite, 0);
     }
 }
diff --git 
a/src/test/java/org/apache/commons/compress/harmony/unpack200/bytecode/forms/SwitchFormTest.java
 
b/src/test/java/org/apache/commons/compress/harmony/unpack200/bytecode/forms/SwitchFormTest.java
new file mode 100644
index 000000000..915e1151e
--- /dev/null
+++ 
b/src/test/java/org/apache/commons/compress/harmony/unpack200/bytecode/forms/SwitchFormTest.java
@@ -0,0 +1,161 @@
+/*
+ * 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.harmony.unpack200.bytecode.forms;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+import org.apache.commons.compress.harmony.pack200.Pack200Exception;
+import org.apache.commons.compress.harmony.unpack200.bytecode.ByteCode;
+import org.apache.commons.compress.harmony.unpack200.bytecode.CodeAttribute;
+import org.apache.commons.compress.harmony.unpack200.bytecode.OperandManager;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/**
+ * Tests {@link SwitchForm}.
+ */
+class SwitchFormTest {
+
+    private static void assertRewrite(final int opcode, final int padding, 
final int[] body, final int[] actual) {
+        final int[] expected = new int[1 + padding + body.length];
+        expected[0] = opcode;
+        System.arraycopy(body, 0, expected, 1 + padding, body.length);
+        assertArrayEquals(expected, actual);
+    }
+
+    private static OperandManager newOperandManager(final int caseCount, final 
int[] caseValues, final int[] labels) {
+        final int[] empty = {};
+        return new OperandManager(new int[] { caseCount }, caseValues, empty, 
empty, empty, labels, empty, empty, empty, empty, empty, empty, empty, empty,
+                empty, empty, empty, empty, empty, empty, empty);
+    }
+
+    private static int[] rewrite(final int opcode, final int prefixLength, 
final int caseCount, final int[] caseValues, final int[] labels)
+            throws Pack200Exception {
+        // All four alignments, with a one-byte instruction immediately before 
the switch and a return after it.
+        final byte[] packed = new byte[prefixLength + 3];
+        packed[prefixLength] = 3; // iconst_0
+        packed[prefixLength + 1] = (byte) opcode;
+        packed[prefixLength + 2] = (byte) 177; // return
+        final CodeAttribute attribute = new CodeAttribute(1, 0, packed, null, 
newOperandManager(caseCount, caseValues, labels), Collections.emptyList());
+        return attribute.byteCodes.get(prefixLength + 1).getRewrite();
+    }
+
+    @Test
+    void testInvalidTargetDoesNotModifyRewrite() throws Pack200Exception {
+        final LookupSwitchForm form = new LookupSwitchForm(171, 
"lookupswitch");
+        final ByteCode byteCode = ByteCode.getByteCode(171);
+        byteCode.setByteCodeIndex(0);
+        form.setByteCodeOperands(byteCode, newOperandManager(1, new int[] { 0 
}, new int[] { 0, 1 }), 0);
+        final int[] original = byteCode.getRewrite().clone();
+        final CodeAttribute attribute = new CodeAttribute(0, 0, new byte[0], 
null, null, Collections.emptyList());
+        assertThrows(IndexOutOfBoundsException.class, () -> 
form.fixUpByteCodeTargets(byteCode, attribute));
+        assertArrayEquals(original, byteCode.getRewrite());
+    }
+
+    @ParameterizedTest
+    @ValueSource(ints = { 170, 171 })
+    @Timeout(10)
+    void testLargeSwitch(final int opcode) throws Pack200Exception {
+        // An oversized switch exercises the linear scan with ample time for 
slow CI machines.
+        final int caseCount = 200_000;
+        final int[] caseValues = new int[opcode == 170 ? 1 : caseCount];
+        for (int index = 0; index < caseValues.length; index++) {
+            caseValues[index] = index;
+        }
+        final int[] actual = rewrite(opcode, 0, caseCount, caseValues, new 
int[caseCount + 1]);
+        // Every target points back to the switch itself, so all rewritten 
offsets are zero.
+        assertArrayEquals(new int[4], Arrays.copyOfRange(actual, 3, 7));
+        final int stride = opcode == 170 ? 4 : 8;
+        for (int position = 15; position < actual.length; position += stride) {
+            assertEquals(0, actual[position]);
+            assertEquals(0, actual[position + 1]);
+            assertEquals(0, actual[position + 2]);
+            assertEquals(0, actual[position + 3]);
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(ints = { 0, 1, 2, 3 })
+    void testLookupSwitch(final int prefixLength) throws Pack200Exception {
+        final int padding = 3 - (prefixLength + 1) % 4;
+        final int forwardOffset = 33 + padding;
+        final int[] body = {
+                -1, 255, 255, 255, // default: previous instruction
+                0, 0, 0, 3, // npairs
+                -128, 0, 0, 0, 0, 0, 0, forwardOffset, // minimum int: next 
instruction
+                -1, 255, 255, 255, -1, 255, 255, 255, // -1: previous 
instruction
+                127, 255, 255, 255, 0, 0, 0, 0 // maximum int: switch itself
+        };
+        assertRewrite(171, padding, body,
+                rewrite(171, prefixLength, 3, new int[] { Integer.MIN_VALUE, 
-1, Integer.MAX_VALUE }, new int[] { -1, 1, -1, 0 }));
+    }
+
+    @ParameterizedTest
+    @ValueSource(ints = { 0, 1, 2, 3 })
+    void testLookupSwitchWithoutCases(final int prefixLength) throws 
Pack200Exception {
+        final int padding = 3 - (prefixLength + 1) % 4;
+        final int[] body = { 0, 0, 0, 9 + padding, 0, 0, 0, 0 };
+        assertRewrite(171, padding, body, rewrite(171, prefixLength, 0, new 
int[0], new int[] { 1 }));
+    }
+
+    @Test
+    void testMissingPlaceholder() throws Pack200Exception {
+        final ByteCode byteCode = ByteCode.getByteCode(171);
+        byteCode.setByteCodeIndex(0);
+        byteCode.setByteCodeTargets(new int[] { 0, 0 });
+        byteCode.setRewrite(new int[] { 171, -1, -1, -1, -1, 0, -1, -1, -1 });
+        final CodeAttribute attribute = new CodeAttribute(0, 0, new byte[0], 
null, null, Collections.emptyList());
+        final LookupSwitchForm form = new LookupSwitchForm(171, 
"lookupswitch");
+        final IllegalArgumentException exception = 
assertThrows(IllegalArgumentException.class, () -> 
form.fixUpByteCodeTargets(byteCode, attribute));
+        assertEquals("Trying to rewrite " + form + " but there is no room for 
4 bytes", exception.getMessage());
+        assertArrayEquals(new int[] { 171, 0, 0, 0, 0, 0, -1, -1, -1 }, 
byteCode.getRewrite());
+    }
+
+    @ParameterizedTest
+    @ValueSource(ints = { 170, 171 })
+    void testSingleCase(final int opcode) throws Pack200Exception {
+        final int[] body = opcode == 170
+                ? new int[] { 0, 0, 0, 19, -1, 255, 255, 255, -1, 255, 255, 
255, -1, 255, 255, 255 }
+                : new int[] { 0, 0, 0, 19, 0, 0, 0, 1, -1, 255, 255, 255, -1, 
255, 255, 255 };
+        assertRewrite(opcode, 2, body, rewrite(opcode, 0, 1, new int[] { -1 }, 
new int[] { 1, -1 }));
+    }
+
+    @ParameterizedTest
+    @ValueSource(ints = { 0, 1, 2, 3 })
+    void testTableSwitch(final int prefixLength) throws Pack200Exception {
+        final int padding = 3 - (prefixLength + 1) % 4;
+        final int forwardOffset = 25 + padding;
+        final int[] body = {
+                -1, 255, 255, 255, // default: previous instruction
+                -1, 255, 255, 255, // low: -1
+                0, 0, 0, 1, // high: 1
+                0, 0, 0, forwardOffset, // next instruction
+                -1, 255, 255, 255, // previous instruction
+                0, 0, 0, 0 // switch itself
+        };
+        assertRewrite(170, padding, body, rewrite(170, prefixLength, 3, new 
int[] { -1 }, new int[] { -1, 1, -1, 0 }));
+    }
+}
diff --git 
a/src/test/java/org/apache/commons/compress/harmony/unpack200/bytecode/forms/VariableInstructionFormTest.java
 
b/src/test/java/org/apache/commons/compress/harmony/unpack200/bytecode/forms/VariableInstructionFormTest.java
new file mode 100644
index 000000000..8f261ddea
--- /dev/null
+++ 
b/src/test/java/org/apache/commons/compress/harmony/unpack200/bytecode/forms/VariableInstructionFormTest.java
@@ -0,0 +1,66 @@
+/*
+ * 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.harmony.unpack200.bytecode.forms;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/**
+ * Tests {@link VariableInstructionForm}.
+ */
+class VariableInstructionFormTest {
+
+    @Test
+    void testNextRewrite4Bytes() {
+        final VariableInstructionForm form = new LookupSwitchForm(171, 
"lookupswitch");
+        final int[] rewrite = { 171, -1, -1, -1, -1, 42, -1, -1, -1, -1, -1, 
-1, -1, -1 };
+        final int nextPosition = form.setNextRewrite4Bytes(-1, rewrite, 5);
+        assertEquals(10, nextPosition);
+        assertArrayEquals(new int[] { 171, -1, -1, -1, -1, 42, -1, 255, 255, 
255, -1, -1, -1, -1 }, rewrite);
+        assertEquals(14, form.setNextRewrite4Bytes(0x12345678, rewrite, 
nextPosition));
+        assertArrayEquals(new int[] { 171, -1, -1, -1, -1, 42, -1, 255, 255, 
255, 0x12, 0x34, 0x56, 0x78 }, rewrite);
+    }
+
+    @ParameterizedTest
+    @ValueSource(ints = { 0, 1, 3, 4, 5 })
+    void testNextRewrite4BytesWithoutPlaceholder(final int startPosition) {
+        final VariableInstructionForm form = new LookupSwitchForm(171, 
"lookupswitch");
+        final int[] rewrite = { 171, -1, -1, -1, 0 };
+        final int[] original = rewrite.clone();
+        final IllegalArgumentException exception = 
assertThrows(IllegalArgumentException.class, () -> form.setNextRewrite4Bytes(0, 
rewrite, startPosition));
+        assertEquals("Trying to rewrite " + form + " but there is no room for 
4 bytes", exception.getMessage());
+        assertArrayEquals(original, rewrite);
+    }
+
+    @Test
+    void testRewrite4BytesFromStart() {
+        final VariableInstructionForm form = new LookupSwitchForm(171, 
"lookupswitch");
+        final int[] rewrite = { 171, -1, -1, -1, -1, -1, -1, -1, -1 };
+        form.setRewrite4Bytes(-1, rewrite);
+        assertArrayEquals(new int[] { 171, -1, 255, 255, 255, -1, -1, -1, -1 
}, rewrite);
+        form.setRewrite4Bytes(0, rewrite);
+        assertArrayEquals(new int[] { 171, -1, 255, 255, 255, 0, 0, 0, 0 }, 
rewrite);
+        assertThrows(IllegalArgumentException.class, () -> 
form.setRewrite4Bytes(0, rewrite));
+    }
+}

Reply via email to