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-bcel.git

commit 86d5e56953fc5a39ab23b49759d0978caabb6416
Author: Gary Gregory <[email protected]>
AuthorDate: Fri Nov 20 12:02:19 2026 -0500

    Fix BCELifier invokedynamic round trips (BCEL-378)
    
    Preserve constant pools and BootstrapMethods attributes so regenerated
    classes retain valid invokedynamic references. Preserve interface method
    references and split large constant-pool, bootstrap-table, and argument
    initializers into smaller methods.
    
    Add documented regression tests for lambdas, method references, string
    concatenation, and large initializers. Verify constant-pool and
    bootstrap
    preservation and execute regenerated classes through two round trips.
    
    Re-enable Java 8 fixture checks on Java 25 and later.
---
 src/changes/changes.xml                            |   1 +
 .../java/org/apache/bcel/util/BCELFactory.java     |  30 +++-
 src/main/java/org/apache/bcel/util/BCELifier.java  | 173 ++++++++++++++++++-
 .../java/org/apache/bcel/util/BCELifierTest.java   | 189 ++++++++++++++++++++-
 4 files changed, 379 insertions(+), 14 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 8e7ba364..cd0f818e 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -66,6 +66,7 @@ The <action> type attribute can be add,update,fix,remove.
       <action                  type="fix" dev="ggregory" due-to="Gary 
Gregory">Fix Class2HTML ArrayIndexOutOfBoundsException for unknown Code 
sub-attributes and render their descriptions with HTML escaping.</action>
       <action                  type="fix" dev="ggregory" due-to="Gary 
Gregory">Reject class names containing '#' or '%' before generating Class2HTML 
reports, and encode report links for accepted names containing spaces, 
ampersands, and other special characters.</action>
       <action                  type="fix" dev="ggregory" due-to="Gary 
Gregory">Avoid ArrayIndexOutOfBoundsException in Attribute.toString() for 
custom attributes with unrecognized tags.</action>
+      <action issue="BCEL-378" type="fix" dev="ggregory" due-to="Gary 
Gregory">Fix BCELifier invokedynamic round trips by preserving the constant 
pool and bootstrap methods.</action>
       <!-- ADD -->
       <!-- UPDATE -->
       <action                  type="update" dev="ggregory" due-to="Gary 
Gregory">Bump org.apache.commons:commons-lang3 from 3.21.0 to 3.22.0.</action>
diff --git a/src/main/java/org/apache/bcel/util/BCELFactory.java 
b/src/main/java/org/apache/bcel/util/BCELFactory.java
index 59674b68..382f3f01 100644
--- a/src/main/java/org/apache/bcel/util/BCELFactory.java
+++ b/src/main/java/org/apache/bcel/util/BCELFactory.java
@@ -25,6 +25,7 @@ import java.util.List;
 import java.util.Map;
 
 import org.apache.bcel.Const;
+import org.apache.bcel.classfile.ConstantInterfaceMethodref;
 import org.apache.bcel.classfile.Utility;
 import org.apache.bcel.generic.AllocationInstruction;
 import org.apache.bcel.generic.ArrayInstruction;
@@ -68,16 +69,18 @@ final class BCELFactory extends EmptyVisitor {
     private final MethodGen methodGen;
     private final PrintWriter printWriter;
     private final ConstantPoolGen constantPoolGen;
+    private final boolean preserveConstantPool;
 
     private final Map<Instruction, InstructionHandle> branchMap = new 
HashMap<>();
 
     // Memorize BranchInstructions that need an update
     private final List<BranchInstruction> branches = new ArrayList<>();
 
-    BCELFactory(final MethodGen mg, final PrintWriter out) {
-        methodGen = mg;
-        constantPoolGen = mg.getConstantPool();
-        printWriter = out;
+    BCELFactory(final MethodGen methodGen, final PrintWriter printWriter, 
final boolean preserveConstantPool) {
+        this.methodGen = methodGen;
+        this.constantPoolGen = methodGen.getConstantPool();
+        this.printWriter = printWriter;
+        this.preserveConstantPool = preserveConstantPool;
     }
 
     private void createConstant(final Object value) {
@@ -294,23 +297,36 @@ final class BCELFactory extends EmptyVisitor {
     @Override
     public void visitInvokeInstruction(final InvokeInstruction i) {
         final short opcode = i.getOpcode();
+        if (opcode == Const.INVOKEDYNAMIC) {
+            printWriter.println("il.append(new INVOKEDYNAMIC(" + i.getIndex() 
+ "));");
+            return;
+        }
         final String className = i.getClassName(constantPoolGen);
         final String methodName = i.getMethodName(constantPoolGen);
         final Type type = i.getReturnType(constantPoolGen);
         final Type[] argTypes = i.getArgumentTypes(constantPoolGen);
         printWriter.println("il.append(_factory.createInvoke(\"" + 
Utility.convertString(className) + "\", \"" + Utility.convertString(methodName) 
+ "\", "
             + BCELifier.printType(type) + ", " + 
BCELifier.printArgumentTypes(argTypes) + ", " + CONSTANT_PREFIX
-            + StringUtils.toRootUpperCase(Const.getOpcodeName(opcode)) + 
"));");
+            + StringUtils.toRootUpperCase(Const.getOpcodeName(opcode))
+            + (opcode != Const.INVOKEINTERFACE && 
constantPoolGen.getConstant(i.getIndex()) instanceof ConstantInterfaceMethodref 
? ", true" : "") + "));");
     }
 
     @Override
     public void visitLDC(final LDC i) {
-        createConstant(i.getValue(constantPoolGen));
+        if (preserveConstantPool) {
+            printWriter.println("il.append(new " + 
StringUtils.toRootUpperCase(i.getName()) + "(" + i.getIndex() + "));");
+        } else {
+            createConstant(i.getValue(constantPoolGen));
+        }
     }
 
     @Override
     public void visitLDC2_W(final LDC2_W i) {
-        createConstant(i.getValue(constantPoolGen));
+        if (preserveConstantPool) {
+            printWriter.println("il.append(new " + 
StringUtils.toRootUpperCase(i.getName()) + "(" + i.getIndex() + "));");
+        } else {
+            createConstant(i.getValue(constantPoolGen));
+        }
     }
 
     @Override
diff --git a/src/main/java/org/apache/bcel/util/BCELifier.java 
b/src/main/java/org/apache/bcel/util/BCELifier.java
index 34f759e5..30e59ef6 100644
--- a/src/main/java/org/apache/bcel/util/BCELifier.java
+++ b/src/main/java/org/apache/bcel/util/BCELifier.java
@@ -23,11 +23,30 @@ import java.io.OutputStream;
 import java.io.OutputStreamWriter;
 import java.io.PrintWriter;
 import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.function.IntFunction;
 
 import org.apache.bcel.Const;
 import org.apache.bcel.Repository;
+import org.apache.bcel.classfile.Attribute;
+import org.apache.bcel.classfile.BootstrapMethod;
+import org.apache.bcel.classfile.BootstrapMethods;
 import org.apache.bcel.classfile.ClassParser;
 import org.apache.bcel.classfile.Code;
+import org.apache.bcel.classfile.Constant;
+import org.apache.bcel.classfile.ConstantCP;
+import org.apache.bcel.classfile.ConstantClass;
+import org.apache.bcel.classfile.ConstantDouble;
+import org.apache.bcel.classfile.ConstantFloat;
+import org.apache.bcel.classfile.ConstantInteger;
+import org.apache.bcel.classfile.ConstantLong;
+import org.apache.bcel.classfile.ConstantMethodHandle;
+import org.apache.bcel.classfile.ConstantMethodType;
+import org.apache.bcel.classfile.ConstantModule;
+import org.apache.bcel.classfile.ConstantNameAndType;
+import org.apache.bcel.classfile.ConstantPackage;
+import org.apache.bcel.classfile.ConstantString;
+import org.apache.bcel.classfile.ConstantUtf8;
 import org.apache.bcel.classfile.ConstantValue;
 import org.apache.bcel.classfile.ExceptionTable;
 import org.apache.bcel.classfile.Field;
@@ -71,6 +90,9 @@ public class BCELifier extends 
org.apache.bcel.classfile.EmptyVisitor {
     private static final String BASE_PACKAGE = 
Const.class.getPackage().getName();
     private static final String CONSTANT_PREFIX = Const.class.getSimpleName() 
+ ".";
 
+    // Bound each bootstrap expression so a batch of array assignments stays 
below the JVM's method-size limit.
+    private static final int MAX_INLINE_BOOTSTRAP_ARGUMENTS = 32;
+
     /**
      * Checks that a name from the parsed class file is a dotted sequence of 
valid Java identifiers before it is
      * emitted in identifier position of the generated source. The class file 
format allows characters in names (for
@@ -221,6 +243,8 @@ public class BCELifier extends 
org.apache.bcel.classfile.EmptyVisitor {
 
     private final ConstantPoolGen constantPoolGen;
 
+    private final boolean preserveConstantPool;
+
     /**
      * Constructs a new instance.
      *
@@ -231,6 +255,131 @@ public class BCELifier extends 
org.apache.bcel.classfile.EmptyVisitor {
         this.clazz = clazz;
         this.printWriter = new PrintWriter(new OutputStreamWriter(out, 
StandardCharsets.UTF_8), false);
         this.constantPoolGen = new 
ConstantPoolGen(this.clazz.getConstantPool());
+        this.preserveConstantPool = 
Arrays.stream(clazz.getAttributes()).anyMatch(BootstrapMethods.class::isInstance);
+    }
+
+    /**
+     * Prints an array factory with initialization split across bounded 
methods.
+     *
+     * @param name the generated factory method name.
+     * @param type the Java array element type.
+     * @param length the array length.
+     * @param initializer the expression for an element, or null to leave it 
uninitialized.
+     */
+    private void printArray(final String name, final String type, final int 
length, final IntFunction<String> initializer) {
+        final int batchSize = 100;
+        printWriter.println("  private static " + type + "[] " + name + "() 
{");
+        printWriter.println("    " + type + "[] values = new " + type + "[" + 
length + "];");
+        for (int start = 0; start < length; start += batchSize) {
+            printWriter.println("    " + name + "_" + start + "(values);");
+        }
+        printWriter.println("    return values;");
+        printWriter.println("  }");
+        printWriter.println();
+        for (int start = 0; start < length; start += batchSize) {
+            printWriter.println("  private static void " + name + "_" + start 
+ "(" + type + "[] values) {");
+            for (int i = start; i < Math.min(start + batchSize, length); i++) {
+                final String expression = initializer.apply(i);
+                if (expression != null) {
+                    printWriter.println("    values[" + i + "] = " + 
expression + ";");
+                }
+            }
+            printWriter.println("  }");
+            printWriter.println();
+        }
+    }
+
+    /**
+     * Prints bootstrap-table initialization, splitting large tables and 
argument lists into bounded methods.
+     *
+     * @param attribute the bootstrap-methods attribute to recreate.
+     */
+    private void printBootstrapMethods(final BootstrapMethods attribute) {
+        final BootstrapMethod[] methods = attribute.getBootstrapMethods();
+        printArray("createBootstrapMethods", "BootstrapMethod", 
methods.length, index -> {
+            final BootstrapMethod method = methods[index];
+            final int[] arguments = method.getBootstrapArguments();
+            final StringBuilder expression = new StringBuilder("new 
BootstrapMethod(").append(method.getBootstrapMethodRef()).append(", ");
+            if (arguments.length > MAX_INLINE_BOOTSTRAP_ARGUMENTS) {
+                
expression.append("createBootstrapArguments_").append(index).append("()");
+            } else {
+                expression.append("new int[] {");
+                for (int i = 0; i < arguments.length; i++) {
+                    if (i > 0) {
+                        expression.append(", ");
+                    }
+                    expression.append(arguments[i]);
+                }
+                expression.append('}');
+            }
+            return expression.append(')').toString();
+        });
+        for (int i = 0; i < methods.length; i++) {
+            final int[] arguments = methods[i].getBootstrapArguments();
+            if (arguments.length > MAX_INLINE_BOOTSTRAP_ARGUMENTS) {
+                printArray("createBootstrapArguments_" + i, "int", 
arguments.length, index -> Integer.toString(arguments[index]));
+            }
+        }
+    }
+
+    /**
+     * Prints a constant constructor using the original indices.
+     *
+     * <p>
+     * Bootstrap arguments can refer to any loadable constant, including 
another dynamic constant.
+     * </p>
+     *
+     * @param constant the constant to recreate.
+     * @return the Java constructor expression.
+     */
+    private String printConstant(final Constant constant) {
+        final String arguments;
+        if (constant instanceof ConstantCP) {
+            final ConstantCP reference = (ConstantCP) constant;
+            // For dynamic constants, classIndex holds the bootstrap-method 
index.
+            arguments = reference.getClassIndex() + ", " + 
reference.getNameAndTypeIndex();
+        } else if (constant instanceof ConstantClass) {
+            arguments = Integer.toString(((ConstantClass) 
constant).getNameIndex());
+        } else if (constant instanceof ConstantDouble) {
+            arguments = "Double.longBitsToDouble(" + 
Double.doubleToLongBits(((ConstantDouble) constant).getBytes()) + "L)";
+        } else if (constant instanceof ConstantFloat) {
+            arguments = "Float.intBitsToFloat(" + 
Float.floatToIntBits(((ConstantFloat) constant).getBytes()) + ")";
+        } else if (constant instanceof ConstantInteger) {
+            arguments = Integer.toString(((ConstantInteger) 
constant).getBytes());
+        } else if (constant instanceof ConstantLong) {
+            arguments = ((ConstantLong) constant).getBytes() + "L";
+        } else if (constant instanceof ConstantMethodHandle) {
+            final ConstantMethodHandle handle = (ConstantMethodHandle) 
constant;
+            arguments = handle.getReferenceKind() + ", " + 
handle.getReferenceIndex();
+        } else if (constant instanceof ConstantMethodType) {
+            arguments = Integer.toString(((ConstantMethodType) 
constant).getDescriptorIndex());
+        } else if (constant instanceof ConstantModule) {
+            arguments = Integer.toString(((ConstantModule) 
constant).getNameIndex());
+        } else if (constant instanceof ConstantNameAndType) {
+            final ConstantNameAndType nameAndType = (ConstantNameAndType) 
constant;
+            arguments = nameAndType.getNameIndex() + ", " + 
nameAndType.getSignatureIndex();
+        } else if (constant instanceof ConstantPackage) {
+            arguments = Integer.toString(((ConstantPackage) 
constant).getNameIndex());
+        } else if (constant instanceof ConstantString) {
+            arguments = Integer.toString(((ConstantString) 
constant).getStringIndex());
+        } else if (constant instanceof ConstantUtf8) {
+            arguments = "\"" + Utility.convertString(((ConstantUtf8) 
constant).getBytes()) + "\"";
+        } else {
+            throw new IllegalArgumentException("Unsupported constant: " + 
constant);
+        }
+        return "new " + constant.getClass().getSimpleName() + "(" + arguments 
+ ")";
+    }
+
+    /**
+     * Preserves the constant pool for bootstrap methods so all instruction, 
method-handle, and bootstrap-argument indices remain valid.
+     */
+    private void printConstantPool() {
+        final Constant[] constants = clazz.getConstantPool().getConstantPool();
+        printWriter.println("  private static ConstantPoolGen 
createConstantPool() {");
+        printWriter.println("    return new 
ConstantPoolGen(createConstants());");
+        printWriter.println("  }");
+        printWriter.println();
+        printArray("createConstants", "Constant", constants.length, index -> 
constants[index] == null ? null : printConstant(constants[index]));
     }
 
     private void printCreate() {
@@ -264,6 +413,12 @@ public class BCELifier extends 
org.apache.bcel.classfile.EmptyVisitor {
         printWriter.flush();
     }
 
+    @Override
+    public void visitBootstrapMethods(final BootstrapMethods bootstrapMethods) 
{
+        printWriter.println("    _cg.addAttribute(new BootstrapMethods(" + 
bootstrapMethods.getNameIndex() + ", " + bootstrapMethods.getLength()
+            + ", createBootstrapMethods(), _cp.getConstantPool()));");
+    }
+
     @Override
     public void visitField(final Field field) {
         printWriter.println();
@@ -326,14 +481,28 @@ public class BCELifier extends 
org.apache.bcel.classfile.EmptyVisitor {
         printWriter.println("  public " + className + "Creator() {");
         printWriter.println("    _cg = new ClassGen(\"" + 
Utility.convertString(packageName.isEmpty() ? className : packageName + "." + 
className) + "\", \""
             + Utility.convertString(superName) + "\", \"" + 
Utility.convertString(clazz.getSourceFileName()) + "\", "
-            + printFlags(clazz.getAccessFlags(), FLAGS.CLASS) + ", " + "new 
String[] { " + inter + " });");
+            + printFlags(clazz.getAccessFlags(), FLAGS.CLASS) + ", " + "new 
String[] { " + inter + " }"
+            + (preserveConstantPool ? ", createConstantPool()" : "") + ");");
         printWriter.println("    _cg.setMajor(" + clazz.getMajor() + ");");
         printWriter.println("    _cg.setMinor(" + clazz.getMinor() + ");");
         printWriter.println();
         printWriter.println("    _cp = _cg.getConstantPool();");
         printWriter.println("    _factory = new InstructionFactory(_cg, 
_cp);");
+        for (final Attribute attribute : clazz.getAttributes()) {
+            if (attribute instanceof BootstrapMethods) {
+                attribute.accept(this);
+            }
+        }
         printWriter.println("  }");
         printWriter.println();
+        if (preserveConstantPool) {
+            printConstantPool();
+            for (final Attribute attribute : clazz.getAttributes()) {
+                if (attribute instanceof BootstrapMethods) {
+                    printBootstrapMethods((BootstrapMethods) attribute);
+                }
+            }
+        }
         printCreate();
         final Field[] fields = clazz.getFields();
         if (fields.length > 0) {
@@ -384,7 +553,7 @@ public class BCELifier extends 
org.apache.bcel.classfile.EmptyVisitor {
             }
         }
         printWriter.println();
-        final BCELFactory factory = new BCELFactory(mg, printWriter);
+        final BCELFactory factory = new BCELFactory(mg, printWriter, 
preserveConstantPool);
         factory.start();
         printWriter.println("    method.setMaxStack();");
         printWriter.println("    method.setMaxLocals();");
diff --git a/src/test/java/org/apache/bcel/util/BCELifierTest.java 
b/src/test/java/org/apache/bcel/util/BCELifierTest.java
index 2c9ee809..cb4319e6 100644
--- a/src/test/java/org/apache/bcel/util/BCELifierTest.java
+++ b/src/test/java/org/apache/bcel/util/BCELifierTest.java
@@ -18,6 +18,7 @@
  */
 package org.apache.bcel.util;
 
+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.assertNotNull;
@@ -26,6 +27,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import java.io.BufferedInputStream;
 import java.io.ByteArrayOutputStream;
+import java.io.DataOutputStream;
 import java.io.File;
 import java.io.InputStream;
 import java.io.OutputStream;
@@ -33,13 +35,18 @@ import java.io.PrintStream;
 import java.nio.charset.StandardCharsets;
 import java.nio.file.Files;
 import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.function.Consumer;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
 import org.apache.bcel.AbstractTest;
 import org.apache.bcel.Const;
 import org.apache.bcel.HelloWorldCreator;
+import org.apache.bcel.classfile.BootstrapMethod;
+import org.apache.bcel.classfile.BootstrapMethods;
 import org.apache.bcel.classfile.ClassParser;
+import org.apache.bcel.classfile.Constant;
 import org.apache.bcel.classfile.ConstantValue;
 import org.apache.bcel.classfile.Field;
 import org.apache.bcel.classfile.JavaClass;
@@ -57,7 +64,7 @@ import org.apache.bcel.generic.Type;
 import org.apache.commons.lang3.SystemProperties;
 import org.apache.commons.lang3.SystemUtils;
 import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.condition.DisabledForJreRange;
+import org.junit.jupiter.api.condition.EnabledForJreRange;
 import org.junit.jupiter.api.condition.JRE;
 import org.junit.jupiter.api.io.TempDir;
 import org.junit.jupiter.params.ParameterizedTest;
@@ -73,6 +80,96 @@ class BCELifierTest extends AbstractTest {
     private static final String EOL = System.lineSeparator();
     public static final String CLASSPATH = "." + File.pathSeparator + 
SystemProperties.getJavaClassPath();
 
+    /**
+     * Checks two executable round trips without changing the fixture's 
bootstrap table.
+     *
+     * @param mainBody the Java statements to compile in {@code main}.
+     * @param java8 whether to target Java 8 bytecode.
+     * @param padding the number of additional UTF-8 constants.
+     * @param directory the temporary work directory.
+     * @throws Exception if compilation, generation, or execution fails.
+     */
+    private void assertInvokeDynamicRoundTrip(final String mainBody, final 
boolean java8, final int padding, final Path directory) throws Exception {
+        assertInvokeDynamicRoundTrip(mainBody, java8, padding, directory, 
bootstrapMethods -> {
+            // Keep the compiler's bootstrap table unchanged.
+        });
+    }
+
+    /**
+     * Compiles a fixture in an isolated directory, then regenerates and 
executes it twice with only the regenerated class on the runtime classpath.
+     *
+     * <p>
+     * Both generations must preserve the bootstrap table and every original 
constant at its original index. The optional padding exercises constant-pool
+     * initialization large enough to exceed a single generated method's 
code-size limit. Special floating-point values and two-slot constants check that
+     * seeding the pool preserves their values and indices as well.
+     * </p>
+     *
+     * @param mainBody the Java statements to compile in {@code main}.
+     * @param java8 whether to target Java 8 bytecode.
+     * @param padding the number of additional UTF-8 constants.
+     * @param directory the temporary work directory.
+     * @param bootstrapModifier the bootstrap-table customization to apply 
before verification and generation.
+     * @throws Exception if compilation, generation, or execution fails.
+     */
+    private void assertInvokeDynamicRoundTrip(final String mainBody, final 
boolean java8, final int padding, final Path directory,
+        final Consumer<BootstrapMethods> bootstrapModifier) throws Exception {
+        final String className = "InvokeDynamicExample";
+        final Path inputDirectory = 
Files.createDirectory(directory.resolve("input"));
+        final Path source = inputDirectory.resolve(className + ".java");
+        Files.write(source, ("public class " + className + " { public static 
void main(String[] args) { " + mainBody + " } }")
+            .getBytes(StandardCharsets.UTF_8));
+        if (java8) {
+            exec(inputDirectory.toFile(), getAppJavaC(), "-g", "-source", "8", 
"-target", "8", source.toString());
+        } else {
+            exec(inputDirectory.toFile(), getAppJavaC(), "-g", 
source.toString());
+        }
+        final Path inputFile = inputDirectory.resolve(className + 
JavaClass.EXTENSION);
+        JavaClass original = new ClassParser(inputFile.toString()).parse();
+        final ConstantPoolGen pool = new 
ConstantPoolGen(original.getConstantPool());
+        pool.addInteger(Integer.MIN_VALUE);
+        pool.addLong(Long.MIN_VALUE);
+        pool.addDouble(Double.NaN);
+        pool.addDouble(Double.NEGATIVE_INFINITY);
+        pool.addDouble(-0.0);
+        pool.addFloat(Float.NaN);
+        pool.addFloat(Float.POSITIVE_INFINITY);
+        pool.addFloat(-0.0f);
+        pool.addString("quote\" slash\\ newline\n");
+        for (int i = 0; i < padding; i++) {
+            pool.addUtf8("padding" + i);
+        }
+        original.setConstantPool(pool.getFinalConstantPool());
+        
bootstrapModifier.accept(Arrays.stream(original.getAttributes()).filter(BootstrapMethods.class::isInstance)
+            .map(BootstrapMethods.class::cast).findFirst().get());
+        original.dump(inputFile.toString());
+        assertEquals("lambda works" + EOL, exec(inputDirectory.toFile(), 
getAppJava(), "-cp", ".", className, "lambda"));
+        for (int pass = 1; pass <= 2; pass++) {
+            final Path outputDirectory = 
Files.createDirectory(directory.resolve("pass" + pass));
+            final ByteArrayOutputStream creator = new ByteArrayOutputStream();
+            new BCELifier(original, creator).start();
+            Files.write(outputDirectory.resolve(className + "Creator.java"), 
creator.toByteArray());
+            final File workDir = outputDirectory.toFile();
+            assertEquals("", exec(workDir, getAppJavaC(), 
"-Xlint:deprecation", "-cp", CLASSPATH, className + "Creator.java"));
+            assertEquals("", exec(workDir, getAppJava(), "-cp", CLASSPATH, 
className + "Creator"));
+            assertEquals("lambda works" + EOL, exec(workDir, getAppJava(), 
"-Xverify:all", "-cp", ".", className, "lambda"));
+            final JavaClass regenerated = new 
ClassParser(outputDirectory.resolve(className + 
JavaClass.EXTENSION).toString()).parse();
+            final Constant[] constants = 
original.getConstantPool().getConstantPool();
+            for (int i = 1; i < constants.length; i++) {
+                assertEquals(String.valueOf(constants[i]), 
String.valueOf(regenerated.getConstantPool().getConstantPool()[i]), "Constant " 
+ i);
+            }
+            final BootstrapMethods bootstrapMethods = 
Arrays.stream(original.getAttributes()).filter(BootstrapMethods.class::isInstance)
+                .map(BootstrapMethods.class::cast).findFirst().get();
+            final BootstrapMethods regeneratedBootstrapMethods = 
Arrays.stream(regenerated.getAttributes())
+                
.filter(BootstrapMethods.class::isInstance).map(BootstrapMethods.class::cast).findFirst().get();
+            final ByteArrayOutputStream expectedBootstrap = new 
ByteArrayOutputStream();
+            bootstrapMethods.dump(new DataOutputStream(expectedBootstrap));
+            final ByteArrayOutputStream actualBootstrap = new 
ByteArrayOutputStream();
+            regeneratedBootstrapMethods.dump(new 
DataOutputStream(actualBootstrap));
+            assertArrayEquals(expectedBootstrap.toByteArray(), 
actualBootstrap.toByteArray());
+            original = regenerated;
+        }
+    }
+
     // Canonicalise the javap output so it compares better
     private String canonHashRef(String input) {
         input = CANON1.matcher(input).replaceAll("#n");
@@ -384,6 +481,85 @@ class BCELifierTest extends AbstractTest {
         }
     }
 
+    /**
+     * Verifies that large bootstrap tables and argument lists compile and 
survive two executable round trips.
+     *
+     * <p>
+     * The active lambda keeps its original bootstrap entry. Additional unused 
entries and arguments contain valid constant-pool references and exercise
+     * initialization beyond the JVM's per-method code-size limit. The 
original class is executed before regeneration to check that the expanded table 
is valid.
+     * </p>
+     *
+     * @param methodCount the number of bootstrap entries.
+     * @param argumentCount the number of arguments in the final, unused entry.
+     * @param directory the temporary work directory.
+     * @throws Exception if compilation, generation, or execution fails.
+     */
+    @ParameterizedTest
+    @CsvSource({"4000, 3", "2, 12000"})
+    void testInvokeDynamicLargeBootstrapMethods(final int methodCount, final 
int argumentCount, @TempDir final Path directory) throws Exception {
+        assertInvokeDynamicRoundTrip("Runnable task = () -> 
System.out.println(\"lambda works\"); task.run();", true, 0, directory, 
bootstrapMethods -> {
+            final BootstrapMethod template = 
bootstrapMethods.getBootstrapMethods()[0];
+            final BootstrapMethod[] methods = new BootstrapMethod[methodCount];
+            for (int i = 0; i < methods.length; i++) {
+                methods[i] = template.copy();
+            }
+            final int[] arguments = new int[argumentCount];
+            Arrays.fill(arguments, template.getBootstrapArguments()[0]);
+            methods[methods.length - 1].setBootstrapArguments(arguments);
+            bootstrapMethods.setBootstrapMethods(methods);
+            bootstrapMethods.setLength(2 + 
Arrays.stream(methods).mapToInt(method -> 4 + 2 * 
method.getNumBootstrapArguments()).sum());
+        });
+    }
+
+    /**
+     * Verifies that preserving a large constant pool splits generated 
initialization into methods that javac can compile.
+     *
+     * @param directory the temporary work directory.
+     * @throws Exception if compilation, generation, or execution fails.
+     */
+    @Test
+    void testInvokeDynamicLargeConstantPool(@TempDir final Path directory) 
throws Exception {
+        assertInvokeDynamicRoundTrip("Runnable task = () -> 
System.out.println(\"lambda works\"); task.run();", true, 6000, directory);
+    }
+
+    /**
+     * Verifies BCEL-378 with ordinary and captured lambdas, a method 
reference, a serializable lambda, and a static interface method call.
+     *
+     * <p>
+     * The smallest case is {@code Runnable task = () -> 
System.out.println("lambda works"); task.run();}. Captured values require a 
nonempty invokedynamic
+     * descriptor; method references require preserving their target handle; 
serializable lambdas use {@code altMetafactory} with integer bootstrap arguments
+     * and generate branching deserialization code with stack maps. Each 
fixture is compiled for Java 8, regenerated twice, and executed after each pass.
+     * </p>
+     *
+     * @param mainBody the Java statements to compile in {@code main}.
+     * @param directory the temporary work directory.
+     * @throws Exception if compilation, generation, or execution fails.
+     */
+    @ParameterizedTest
+    @ValueSource(strings = {
+        "Runnable task = () -> System.out.println(\"lambda works\"); 
task.run();",
+        "String prefix = args[0]; java.util.function.Supplier<String> task = 
() -> prefix + \" works\"; System.out.println(task.get());",
+        "java.util.function.Function<String, String> task = String::trim; 
System.out.println(task.apply(\" lambda works \"));",
+        "Runnable task = (Runnable & java.io.Serializable) () -> 
System.out.println(\"lambda works\"); task.run();",
+        "java.util.function.Function<String, String> task = 
java.util.function.Function.<String>identity().andThen(value -> value + \" 
works\"); "
+            + "System.out.println(task.apply(args[0]));"
+    })
+    void testInvokeDynamicRoundTrip(final String mainBody, @TempDir final Path 
directory) throws Exception {
+        assertInvokeDynamicRoundTrip(mainBody, true, 0, directory);
+    }
+
+    /**
+     * Verifies the StringConcatFactory bootstrap emitted by javac on Java 9 
and later, including its string bootstrap argument.
+     *
+     * @param directory the temporary work directory.
+     * @throws Exception if compilation, generation, or execution fails.
+     */
+    @Test
+    @EnabledForJreRange(min = JRE.JAVA_9)
+    void testInvokeDynamicStringConcatenation(@TempDir final Path directory) 
throws Exception {
+        assertInvokeDynamicRoundTrip("System.out.println(args[0] + \" 
works\");", false, 0, directory);
+    }
+
     /*
      * Dumps a class using "javap" and compare with the same class recreated 
using BCELifier, "javac", "java" and dumped with "javap".
      *
@@ -406,8 +582,12 @@ class BCELifierTest extends AbstractTest {
         testClassOnPath(className, directory);
     }
 
-    /*
-     * See https://issues.apache.org/jira/browse/BCEL-378
+    /**
+     * Round-trips the existing Java 8 fixtures, including their invokedynamic 
instructions, on all supported JDKs.
+     *
+     * @param className the fixture class name.
+     * @param directory the temporary work directory.
+     * @throws Exception if generation, compilation, or bytecode comparison 
fails.
      */
     @ParameterizedTest
     @ValueSource(strings = {
@@ -416,8 +596,7 @@ class BCELifierTest extends AbstractTest {
         "Java8Example2",
     // @formatter:on
     })
-    @DisabledForJreRange(min = JRE.JAVA_25)
-    void testJavapCompareJava25KnownBroken(final String className, @TempDir 
final Path directory) throws Exception {
+    void testJavapCompareJava8(final String className, @TempDir final Path 
directory) throws Exception {
         testClassOnPath(className, directory);
     }
 

Reply via email to