< prev index next >

src/java.base/share/classes/jdk/internal/classfile/impl/StackMapGenerator.java

Print this page

  13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  15  * version 2 for more details (a copy is included in the LICENSE file that
  16  * accompanied this code).
  17  *
  18  * You should have received a copy of the GNU General Public License version
  19  * 2 along with this work; if not, write to the Free Software Foundation,
  20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  21  *
  22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  23  * or visit www.oracle.com if you need additional information or have any
  24  * questions.
  25  *
  26  */
  27 package jdk.internal.classfile.impl;
  28 
  29 import java.lang.classfile.Attribute;
  30 import java.lang.classfile.Attributes;
  31 import java.lang.classfile.Label;
  32 import java.lang.classfile.attribute.StackMapTableAttribute;
  33 import java.lang.classfile.constantpool.ClassEntry;
  34 import java.lang.classfile.constantpool.ConstantDynamicEntry;
  35 import java.lang.classfile.constantpool.ConstantPoolBuilder;
  36 import java.lang.classfile.constantpool.InvokeDynamicEntry;
  37 import java.lang.classfile.constantpool.MemberRefEntry;
  38 import java.lang.classfile.constantpool.Utf8Entry;
  39 import java.lang.constant.ClassDesc;
  40 import java.lang.constant.MethodTypeDesc;
  41 import java.util.ArrayList;
  42 import java.util.Arrays;
  43 import java.util.List;
  44 import java.util.Objects;
  45 import java.util.stream.Collectors;
  46 

  47 import jdk.internal.constant.ClassOrInterfaceDescImpl;
  48 import jdk.internal.util.Preconditions;
  49 
  50 import static java.lang.classfile.ClassFile.*;
  51 import static java.lang.classfile.constantpool.PoolEntry.*;
  52 import static java.lang.constant.ConstantDescs.*;
  53 import static jdk.internal.classfile.impl.RawBytecodeHelper.*;
  54 
  55 /**
  56  * StackMapGenerator is responsible for stack map frames generation.
  57  * <p>
  58  * Stack map frames are computed from serialized bytecode similar way they are verified during class loading process.
  59  * <p>
  60  * The {@linkplain #generate() frames computation} consists of following steps:
  61  * <ol>
  62  * <li>{@linkplain #detectFrames() Detection} of mandatory stack map frames:<ul>
  63  *      <li>Mandatory stack map frame include all jump and switch instructions targets,
  64  *          offsets immediately following {@linkplain #noControlFlow(int) "no control flow"}
  65  *          and all exception table handlers.
  66  *      <li>Detection is performed in a single fast pass through the bytecode,

 140  * Focus of the whole algorithm is on high performance and low memory footprint:<ul>
 141  *      <li>It does not produce, collect nor visit any complex intermediate structures
 142  *          <i>(beside {@linkplain RawBytecodeHelper traversing} the {@linkplain #bytecode bytecode in binary form}).</i>
 143  *      <li>It works with only minimal mandatory stack map frames.
 144  *      <li>It does not spend time on any non-essential verifications.
 145  * </ul>
 146  */
 147 
 148 public final class StackMapGenerator {
 149 
 150     static StackMapGenerator of(DirectCodeBuilder dcb, BufWriterImpl buf) {
 151         return new StackMapGenerator(
 152                 dcb,
 153                 buf.thisClass().asSymbol(),
 154                 dcb.methodInfo.methodName().stringValue(),
 155                 dcb.methodInfo.methodTypeSymbol(),
 156                 (dcb.methodInfo.methodFlags() & ACC_STATIC) != 0,
 157                 dcb.bytecodesBufWriter.bytecodeView(),
 158                 dcb.constantPool,
 159                 dcb.context,

 160                 dcb.handlers);
 161     }
 162 
 163     private static final String OBJECT_INITIALIZER_NAME = "<init>";
 164     private static final int FLAG_THIS_UNINIT = 0x01;
 165     private static final int FRAME_DEFAULT_CAPACITY = 10;
 166     private static final int T_BOOLEAN = 4, T_LONG = 11;
 167     private static final Frame[] EMPTY_FRAME_ARRAY = {};
 168 
 169     public static final int
 170             ITEM_TOP = 0,
 171             ITEM_INTEGER = 1,
 172             ITEM_FLOAT = 2,
 173             ITEM_DOUBLE = 3,
 174             ITEM_LONG = 4,
 175             ITEM_NULL = 5,
 176             ITEM_UNINITIALIZED_THIS = 6,
 177             ITEM_OBJECT = 7,
 178             ITEM_UNINITIALIZED = 8,
 179             ITEM_BOOLEAN = 9,
 180             ITEM_BYTE = 10,
 181             ITEM_SHORT = 11,
 182             ITEM_CHAR = 12,
 183             ITEM_LONG_2ND = 13,
 184             ITEM_DOUBLE_2ND = 14,
 185             ITEM_BOGUS = -1;
 186 
 187     // Ranges represented by these constants are inclusive on both ends
 188     public static final int
 189             SAME_FRAME_END = 63,
 190             SAME_LOCALS_1_STACK_ITEM_FRAME_START = 64,
 191             SAME_LOCALS_1_STACK_ITEM_FRAME_END = 127,
 192             RESERVED_END = 246,

 193             SAME_LOCALS_1_STACK_ITEM_EXTENDED = 247,
 194             CHOP_FRAME_START = 248,
 195             CHOP_FRAME_END = 250,
 196             SAME_FRAME_EXTENDED = 251,
 197             APPEND_FRAME_START = 252,
 198             APPEND_FRAME_END = 254,
 199             FULL_FRAME = 255;
 200 
 201     private static final Type[] ARRAY_FROM_BASIC_TYPE = {null, null, null, null,
 202         Type.BOOLEAN_ARRAY_TYPE, Type.CHAR_ARRAY_TYPE, Type.FLOAT_ARRAY_TYPE, Type.DOUBLE_ARRAY_TYPE,
 203         Type.BYTE_ARRAY_TYPE, Type.SHORT_ARRAY_TYPE, Type.INT_ARRAY_TYPE, Type.LONG_ARRAY_TYPE};
 204 
 205     static record RawExceptionCatch(int start, int end, int handler, Type catchType) {}
 206 
 207     private final Type thisType;
 208     private final String methodName;
 209     private final MethodTypeDesc methodDesc;
 210     private final RawBytecodeHelper.CodeRange bytecode;
 211     private final SplitConstantPool cp;
 212     private final boolean isStatic;
 213     private final LabelContext labelContext;
 214     private final List<AbstractPseudoInstruction.ExceptionCatchImpl> handlers;
 215     private final List<RawExceptionCatch> rawHandlers;
 216     private final ClassHierarchyImpl classHierarchy;

 217     private final boolean patchDeadCode;
 218     private final boolean filterDeadLabels;
 219     private Frame[] frames = EMPTY_FRAME_ARRAY;
 220     private int framesCount = 0;
 221     private final Frame currentFrame;
 222     private int maxStack, maxLocals;
 223 
 224     /**
 225      * Primary constructor of the <code>Generator</code> class.
 226      * New <code>Generator</code> instance must be created for each individual class/method.
 227      * Instance contains only immutable results, all the calculations are processed during instance construction.
 228      *
 229      * @param labelContext <code>LabelContext</code> instance used to resolve or patch <code>ExceptionHandler</code>
 230      * labels to bytecode offsets (or vice versa)
 231      * @param thisClass class to generate stack maps for
 232      * @param methodName method name to generate stack maps for
 233      * @param methodDesc method descriptor to generate stack maps for
 234      * @param isStatic information whether the method is static
 235      * @param bytecode R/W <code>ByteBuffer</code> wrapping method bytecode, the content is altered in case <code>Generator</code> detects  and patches dead code
 236      * @param cp R/W <code>ConstantPoolBuilder</code> instance used to resolve all involved CP entries and also generate new entries referenced from the generated stack maps
 237      * @param handlers R/W <code>ExceptionHandler</code> list used to detect mandatory frame offsets as well as to determine stack maps in exception handlers
 238      * and also to be altered when dead code is detected and must be excluded from exception handlers
 239      */
 240     public StackMapGenerator(LabelContext labelContext,
 241                      ClassDesc thisClass,
 242                      String methodName,
 243                      MethodTypeDesc methodDesc,
 244                      boolean isStatic,
 245                      RawBytecodeHelper.CodeRange bytecode,
 246                      SplitConstantPool cp,
 247                      ClassFileImpl context,

 248                      List<AbstractPseudoInstruction.ExceptionCatchImpl> handlers) {
 249         this.thisType = Type.referenceType(thisClass);
 250         this.methodName = methodName;
 251         this.methodDesc = methodDesc;
 252         this.isStatic = isStatic;
 253         this.bytecode = bytecode;
 254         this.cp = cp;
 255         this.labelContext = labelContext;
 256         this.handlers = handlers;
 257         this.rawHandlers = new ArrayList<>(handlers.size());
 258         this.classHierarchy = new ClassHierarchyImpl(context.classHierarchyResolver());
 259         this.patchDeadCode = context.patchDeadCode();
 260         this.filterDeadLabels = context.dropDeadLabels();
 261         this.currentFrame = new Frame(classHierarchy);





 262         generate();
 263     }
 264 
 265     /**
 266      * Calculated maximum number of the locals required
 267      * @return maximum number of the locals required
 268      */
 269     public int maxLocals() {
 270         return maxLocals;
 271     }
 272 
 273     /**
 274      * Calculated maximum stack size required
 275      * @return maximum stack size required
 276      */
 277     public int maxStack() {
 278         return maxStack;
 279     }
 280 
 281     private Frame getFrame(int offset) {

 390             } else {
 391                 //split
 392                 Label newStart = labelContext.newLabel();
 393                 labelContext.setLabelTarget(newStart, rangeEnd);
 394                 Label newEnd = labelContext.newLabel();
 395                 labelContext.setLabelTarget(newEnd, rangeStart);
 396                 it.set(new AbstractPseudoInstruction.ExceptionCatchImpl(e.handler(), e.tryStart(), newEnd, e.catchType()));
 397                 it.add(new AbstractPseudoInstruction.ExceptionCatchImpl(e.handler(), newStart, e.tryEnd(), e.catchType()));
 398             }
 399         }
 400     }
 401 
 402     /**
 403      * Getter of the generated <code>StackMapTableAttribute</code> or null if stack map is empty
 404      * @return <code>StackMapTableAttribute</code> or null if stack map is empty
 405      */
 406     public Attribute<? extends StackMapTableAttribute> stackMapTableAttribute() {
 407         return framesCount == 0 ? null : new UnboundAttribute.AdHocAttribute<>(Attributes.stackMapTable()) {
 408             @Override
 409             public void writeBody(BufWriterImpl b) {




 410                 b.writeU2(framesCount);
 411                 Frame prevFrame =  new Frame(classHierarchy);
 412                 prevFrame.setLocalsFromArg(methodName, methodDesc, isStatic, thisType);
 413                 prevFrame.trimAndCompress();
 414                 for (int i = 0; i < framesCount; i++) {
 415                     var fr = frames[i];
 416                     fr.trimAndCompress();
 417                     fr.writeTo(b, prevFrame, cp);
 418                     prevFrame = fr;
 419                 }
 420             }
 421 
 422             @Override
 423             public Utf8Entry attributeName() {
 424                 return cp.utf8Entry(Attributes.NAME_STACK_MAP_TABLE);
 425             }
 426         };
 427     }
 428 
 429     private static Type cpIndexToType(int index, ConstantPoolBuilder cp) {
 430         return Type.referenceType(cp.entryByIndex(index, ClassEntry.class).asSymbol());
 431     }
 432 
 433     private void processMethod() {
 434         var frames = this.frames;
 435         var currentFrame = this.currentFrame;
 436         currentFrame.setLocalsFromArg(methodName, methodDesc, isStatic, thisType);
 437         currentFrame.stackSize = 0;
 438         currentFrame.flags = 0;
 439         currentFrame.offset = -1;
 440         int stackmapIndex = 0;
 441         var bcs = bytecode.start();
 442         boolean ncf = false;
 443         while (bcs.next()) {
 444             currentFrame.offset = bcs.bci();
 445             if (stackmapIndex < framesCount) {
 446                 int thisOffset = frames[stackmapIndex].offset;
 447                 if (ncf && thisOffset > bcs.bci()) {
 448                     throw generatorError("Expecting a stack map frame");
 449                 }
 450                 if (thisOffset == bcs.bci()) {
 451                     Frame nextFrame = frames[stackmapIndex++];
 452                     if (!ncf) {
 453                         currentFrame.checkAssignableTo(nextFrame);
 454                     }
 455                     while (!nextFrame.dirty) { //skip unmatched frames
 456                         if (stackmapIndex == framesCount) return; //skip the rest of this round
 457                         nextFrame = frames[stackmapIndex++];
 458                     }

 761                 throw generatorError("number of keys in lookupswitch less than 0");
 762             }
 763             delta = 2;
 764             for (int i = 0; i < (keys - 1); i++) {
 765                 int this_key = bcs.getIntUnchecked(alignedBci + (2 + 2 * i) * 4);
 766                 int next_key = bcs.getIntUnchecked(alignedBci + (2 + 2 * i + 2) * 4);
 767                 if (this_key >= next_key) {
 768                     throw generatorError("Bad lookupswitch instruction");
 769                 }
 770             }
 771         }
 772         int target = bci + defaultOffset;
 773         checkJumpTarget(currentFrame, target);
 774         for (int i = 0; i < keys; i++) {
 775             target = bci + bcs.getIntUnchecked(alignedBci + (3 + i * delta) * 4);
 776             checkJumpTarget(currentFrame, target);
 777         }
 778     }
 779 
 780     private void processFieldInstructions(RawBytecodeHelper bcs) {
 781         var desc = Util.fieldTypeSymbol(cp.entryByIndex(bcs.getIndexU2(), MemberRefEntry.class).type());

 782         var currentFrame = this.currentFrame;
 783         switch (bcs.opcode()) {
 784             case GETSTATIC ->
 785                 currentFrame.pushStack(desc);
 786             case PUTSTATIC -> {
 787                 currentFrame.decStack(Util.isDoubleSlot(desc) ? 2 : 1);
 788             }
 789             case GETFIELD -> {
 790                 currentFrame.decStack(1);
 791                 currentFrame.pushStack(desc);
 792             }
 793             case PUTFIELD -> {



 794                 currentFrame.decStack(Util.isDoubleSlot(desc) ? 3 : 2);
 795             }
 796             default -> throw new AssertionError("Should not reach here");
 797         }
 798     }
 799 
 800     private boolean processInvokeInstructions(RawBytecodeHelper bcs, boolean inTryBlock, boolean thisUninit) {
 801         int index = bcs.getIndexU2();
 802         int opcode = bcs.opcode();
 803         var nameAndType = opcode == INVOKEDYNAMIC
 804                 ? cp.entryByIndex(index, InvokeDynamicEntry.class).nameAndType()
 805                 : cp.entryByIndex(index, MemberRefEntry.class).nameAndType();
 806         var mDesc = Util.methodTypeSymbol(nameAndType.type());
 807         int bci = bcs.bci();
 808         var currentFrame = this.currentFrame;
 809         currentFrame.decStack(Util.parameterSlots(mDesc));
 810         if (opcode != INVOKESTATIC && opcode != INVOKEDYNAMIC) {
 811             if (nameAndType.name().equalsString(OBJECT_INITIALIZER_NAME)) {
 812                 Type type = currentFrame.popStack();
 813                 if (type == Type.UNITIALIZED_THIS_TYPE) {
 814                     if (inTryBlock) {
 815                         processExceptionHandlerTargets(bci, true);
 816                     }





 817                     currentFrame.initializeObject(type, thisType);


 818                     thisUninit = true;
 819                 } else if (type.tag == ITEM_UNINITIALIZED) {
 820                     Type new_class_type = cpIndexToType(bcs.getU2(type.bci + 1), cp);
 821                     if (inTryBlock) {
 822                         processExceptionHandlerTargets(bci, thisUninit);
 823                     }
 824                     currentFrame.initializeObject(type, new_class_type);
 825                 } else {
 826                     throw generatorError("Bad operand type when invoking <init>");
 827                 }
 828             } else {
 829                 currentFrame.decStack(1);
 830             }
 831         }
 832         currentFrame.pushStack(mDesc.returnType());
 833         return thisUninit;
 834     }
 835 
 836     private Type getNewarrayType(int index) {
 837         if (index < T_BOOLEAN || index > T_LONG) throw generatorError("Illegal newarray instruction type %d".formatted(index));

 940                 return;
 941             }
 942             if (frameOffset > offset) {
 943                 break;
 944             }
 945         }
 946         if (framesCount >= frames.length) {
 947             int newCapacity = framesCount + 8;
 948             this.frames = frames = framesCount == 0 ? new Frame[newCapacity] : Arrays.copyOf(frames, newCapacity);
 949         }
 950         if (i != framesCount) {
 951             System.arraycopy(frames, i, frames, i + 1, framesCount - i);
 952         }
 953         frames[i] = new Frame(offset, classHierarchy);
 954         this.framesCount = framesCount + 1;
 955     }
 956 
 957     private final class Frame {
 958 
 959         int offset;
 960         int localsSize, stackSize;
 961         int flags;
 962         int frameMaxStack = 0, frameMaxLocals = 0;
 963         boolean dirty = false;
 964         boolean localsChanged = false;
 965 
 966         private final ClassHierarchyImpl classHierarchy;
 967 
 968         private Type[] locals, stack;

 969 
 970         Frame(ClassHierarchyImpl classHierarchy) {
 971             this(-1, 0, 0, 0, null, null, classHierarchy);
 972         }
 973 
 974         Frame(int offset, ClassHierarchyImpl classHierarchy) {
 975             this(offset, -1, 0, 0, null, null, classHierarchy);
 976         }
 977 
 978         Frame(int offset, int flags, int locals_size, int stack_size, Type[] locals, Type[] stack, ClassHierarchyImpl classHierarchy) {
 979             this.offset = offset;
 980             this.localsSize = locals_size;
 981             this.stackSize = stack_size;
 982             this.flags = flags;
 983             this.locals = locals;
 984             this.stack = stack;
 985             this.classHierarchy = classHierarchy;
 986         }
 987 
 988         @Override
 989         public String toString() {
 990             return (dirty ? "frame* @" : "frame @") + offset + " with locals " + (locals == null ? "[]" : Arrays.asList(locals).subList(0, localsSize)) + " and stack " + (stack == null ? "[]" : Arrays.asList(stack).subList(0, stackSize));



 991         }
 992 
 993         Frame pushStack(ClassDesc desc) {
 994             if (desc == CD_long)   return pushStack(Type.LONG_TYPE, Type.LONG2_TYPE);
 995             if (desc == CD_double) return pushStack(Type.DOUBLE_TYPE, Type.DOUBLE2_TYPE);
 996             return desc == CD_void ? this
 997                     : pushStack(
 998                     desc.isPrimitive()
 999                             ? (desc == CD_float ? Type.FLOAT_TYPE : Type.INTEGER_TYPE)
1000                             : Type.referenceType(desc));
1001         }
1002 
1003         Frame pushStack(Type type) {
1004             checkStack(stackSize);
1005             stack[stackSize++] = type;
1006             return this;
1007         }
1008 
1009         Frame pushStack(Type type1, Type type2) {
1010             checkStack(stackSize + 1);

1025         }
1026 
1027         Frame frameInExceptionHandler(int flags, Type excType) {
1028             return new Frame(offset, flags, localsSize, 1, locals, new Type[] {excType}, classHierarchy);
1029         }
1030 
1031         void initializeObject(Type old_object, Type new_object) {
1032             int i;
1033             for (i = 0; i < localsSize; i++) {
1034                 if (locals[i].equals(old_object)) {
1035                     locals[i] = new_object;
1036                     localsChanged = true;
1037                 }
1038             }
1039             for (i = 0; i < stackSize; i++) {
1040                 if (stack[i].equals(old_object)) {
1041                     stack[i] = new_object;
1042                 }
1043             }
1044             if (old_object == Type.UNITIALIZED_THIS_TYPE) {
1045                 flags = 0;

1046             }
1047         }
1048 
1049         Frame checkLocal(int index) {
1050             if (index >= frameMaxLocals) frameMaxLocals = index + 1;
1051             if (locals == null) {
1052                 locals = new Type[index + FRAME_DEFAULT_CAPACITY];
1053                 Arrays.fill(locals, Type.TOP_TYPE);
1054             } else if (index >= locals.length) {
1055                 int current = locals.length;
1056                 locals = Arrays.copyOf(locals, index + FRAME_DEFAULT_CAPACITY);
1057                 Arrays.fill(locals, current, locals.length, Type.TOP_TYPE);
1058             }
1059             return this;
1060         }
1061 


















1062         private void checkStack(int index) {
1063             if (index >= frameMaxStack) frameMaxStack = index + 1;
1064             if (stack == null) {
1065                 stack = new Type[index + FRAME_DEFAULT_CAPACITY];
1066                 Arrays.fill(stack, Type.TOP_TYPE);
1067             } else if (index >= stack.length) {
1068                 int current = stack.length;
1069                 stack = Arrays.copyOf(stack, index + FRAME_DEFAULT_CAPACITY);
1070                 Arrays.fill(stack, current, stack.length, Type.TOP_TYPE);
1071             }
1072         }
1073 
1074         private void setLocalRawInternal(int index, Type type) {
1075             checkLocal(index);
1076             localsChanged |= !type.equals(locals[index]);
1077             locals[index] = type;
1078         }
1079 
1080         void setLocalsFromArg(String name, MethodTypeDesc methodDesc, boolean isStatic, Type thisKlass) {
1081             int localsSize = 0;
1082             // Pre-emptively create a locals array that encompass all parameter slots
1083             checkLocal(Util.parameterSlots(methodDesc) + (isStatic ? -1 : 0));
1084             Type type;
1085             Type[] locals = this.locals;
1086             if (!isStatic) {
1087                 if (OBJECT_INITIALIZER_NAME.equals(name) && !CD_Object.equals(thisKlass.sym)) {



1088                     type = Type.UNITIALIZED_THIS_TYPE;
1089                     flags |= FLAG_THIS_UNINIT;
1090                 } else {


1091                     type = thisKlass;

1092                 }
1093                 locals[localsSize++] = type;
1094             }
1095             for (int i = 0; i < methodDesc.parameterCount(); i++) {
1096                 var desc = methodDesc.parameterType(i);
1097                 if (desc == CD_long) {
1098                     locals[localsSize    ] = Type.LONG_TYPE;
1099                     locals[localsSize + 1] = Type.LONG2_TYPE;
1100                     localsSize += 2;
1101                 } else if (desc == CD_double) {
1102                     locals[localsSize    ] = Type.DOUBLE_TYPE;
1103                     locals[localsSize + 1] = Type.DOUBLE2_TYPE;
1104                     localsSize += 2;
1105                 } else {
1106                     if (!desc.isPrimitive()) {
1107                         type = Type.referenceType(desc);
1108                     } else if (desc == CD_float) {
1109                         type = Type.FLOAT_TYPE;
1110                     } else {
1111                         type = Type.INTEGER_TYPE;
1112                     }
1113                     locals[localsSize++] = type;
1114                 }
1115             }
1116             this.localsSize = localsSize;
1117         }
1118 
1119         void copyFrom(Frame src) {
1120             if (locals != null && src.localsSize < locals.length) Arrays.fill(locals, src.localsSize, locals.length, Type.TOP_TYPE);
1121             localsSize = src.localsSize;
1122             checkLocal(src.localsSize - 1);
1123             if (src.localsSize > 0) System.arraycopy(src.locals, 0, locals, 0, src.localsSize);
1124             if (stack != null && src.stackSize < stack.length) Arrays.fill(stack, src.stackSize, stack.length, Type.TOP_TYPE);
1125             stackSize = src.stackSize;
1126             checkStack(src.stackSize - 1);
1127             if (src.stackSize > 0) System.arraycopy(src.stack, 0, stack, 0, src.stackSize);


1128             flags = src.flags;
1129             localsChanged = true;
1130         }
1131 
1132         void checkAssignableTo(Frame target) {
1133             int localsSize = this.localsSize;
1134             int stackSize = this.stackSize;

1135             if (target.flags == -1) {
1136                 target.locals = locals == null ? null : locals.clone();
1137                 target.localsSize = localsSize;
1138                 if (stackSize > 0) {
1139                     target.stack = stack.clone();
1140                     target.stackSize = stackSize;
1141                 }


1142                 target.flags = flags;
1143                 target.dirty = true;
1144             } else {
1145                 if (target.localsSize > localsSize) {
1146                     target.localsSize = localsSize;
1147                     target.dirty = true;
1148                 }
1149                 for (int i = 0; i < target.localsSize; i++) {
1150                     merge(locals[i], target.locals, i, target);
1151                 }
1152                 if (stackSize != target.stackSize) {
1153                     throw generatorError("Stack size mismatch");
1154                 }
1155                 for (int i = 0; i < target.stackSize; i++) {
1156                     if (merge(stack[i], target.stack, i, target) == Type.TOP_TYPE) {
1157                         throw generatorError("Stack content mismatch");
1158                     }
1159                 }



1160             }
1161         }
1162 
1163         private Type getLocalRawInternal(int index) {
1164             checkLocal(index);
1165             return locals[index];
1166         }
1167 
1168         Type getLocal(int index) {
1169             Type ret = getLocalRawInternal(index);
1170             if (index >= localsSize) {
1171                 localsSize = index + 1;
1172             }
1173             return ret;
1174         }
1175 
1176         void setLocal(int index, Type type) {
1177             Type old = getLocalRawInternal(index);
1178             if (old == Type.DOUBLE_TYPE || old == Type.LONG_TYPE) {
1179                 setLocalRawInternal(index + 1, Type.TOP_TYPE);

1196             if (old == Type.DOUBLE2_TYPE || old == Type.LONG2_TYPE) {
1197                 setLocalRawInternal(index - 1, Type.TOP_TYPE);
1198             }
1199             setLocalRawInternal(index, type1);
1200             setLocalRawInternal(index + 1, type2);
1201             if (index >= localsSize - 1) {
1202                 localsSize = index + 2;
1203             }
1204         }
1205 
1206         private Type merge(Type me, Type[] toTypes, int i, Frame target) {
1207             var to = toTypes[i];
1208             var newTo = to.mergeFrom(me, classHierarchy);
1209             if (to != newTo && !to.equals(newTo)) {
1210                 toTypes[i] = newTo;
1211                 target.dirty = true;
1212             }
1213             return newTo;
1214         }
1215 













































1216         private static int trimAndCompress(Type[] types, int count) {
1217             while (count > 0 && types[count - 1] == Type.TOP_TYPE) count--;
1218             int compressed = 0;
1219             for (int i = 0; i < count; i++) {
1220                 if (!types[i].isCategory2_2nd()) {
1221                     if (compressed != i) {
1222                         types[compressed] = types[i];
1223                     }
1224                     compressed++;
1225                 }
1226             }
1227             return compressed;
1228         }
1229 
1230         void trimAndCompress() {
1231             localsSize = trimAndCompress(locals, localsSize);
1232             stackSize = trimAndCompress(stack, stackSize);
1233         }
1234 










1235         private static boolean equals(Type[] l1, Type[] l2, int commonSize) {
1236             if (l1 == null || l2 == null) return commonSize == 0;
1237             return Arrays.equals(l1, 0, commonSize, l2, 0, commonSize);
1238         }
1239 











1240         void writeTo(BufWriterImpl out, Frame prevFrame, ConstantPoolBuilder cp) {









1241             int localsSize = this.localsSize;
1242             int stackSize = this.stackSize;
1243             int offsetDelta = offset - prevFrame.offset - 1;
1244             if (stackSize == 0) {
1245                 int commonLocalsSize = localsSize > prevFrame.localsSize ? prevFrame.localsSize : localsSize;
1246                 int diffLocalsSize = localsSize - prevFrame.localsSize;
1247                 if (-3 <= diffLocalsSize && diffLocalsSize <= 3 && equals(locals, prevFrame.locals, commonLocalsSize)) {
1248                     if (diffLocalsSize == 0 && offsetDelta <= SAME_FRAME_END) { //same frame
1249                         out.writeU1(offsetDelta);
1250                     } else {   //chop, same extended or append frame
1251                         out.writeU1U2(SAME_FRAME_EXTENDED + diffLocalsSize, offsetDelta);
1252                         for (int i=commonLocalsSize; i<localsSize; i++) locals[i].writeTo(out, cp);
1253                     }
1254                     return;
1255                 }
1256             } else if (stackSize == 1 && localsSize == prevFrame.localsSize && equals(locals, prevFrame.locals, localsSize)) {
1257                 if (offsetDelta <= SAME_LOCALS_1_STACK_ITEM_FRAME_END  - SAME_LOCALS_1_STACK_ITEM_FRAME_START) {  //same locals 1 stack item frame
1258                     out.writeU1(SAME_LOCALS_1_STACK_ITEM_FRAME_START + offsetDelta);
1259                 } else {  //same locals 1 stack item extended frame
1260                     out.writeU1U2(SAME_LOCALS_1_STACK_ITEM_EXTENDED, offsetDelta);

  13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  15  * version 2 for more details (a copy is included in the LICENSE file that
  16  * accompanied this code).
  17  *
  18  * You should have received a copy of the GNU General Public License version
  19  * 2 along with this work; if not, write to the Free Software Foundation,
  20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  21  *
  22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  23  * or visit www.oracle.com if you need additional information or have any
  24  * questions.
  25  *
  26  */
  27 package jdk.internal.classfile.impl;
  28 
  29 import java.lang.classfile.Attribute;
  30 import java.lang.classfile.Attributes;
  31 import java.lang.classfile.Label;
  32 import java.lang.classfile.attribute.StackMapTableAttribute;
  33 import java.lang.classfile.constantpool.*;





  34 import java.lang.constant.ClassDesc;
  35 import java.lang.constant.MethodTypeDesc;
  36 import java.util.ArrayList;
  37 import java.util.Arrays;
  38 import java.util.List;
  39 import java.util.Objects;
  40 import java.util.stream.Collectors;
  41 
  42 import jdk.internal.classfile.impl.WritableField.UnsetField;
  43 import jdk.internal.constant.ClassOrInterfaceDescImpl;
  44 import jdk.internal.util.Preconditions;
  45 
  46 import static java.lang.classfile.ClassFile.*;
  47 import static java.lang.classfile.constantpool.PoolEntry.*;
  48 import static java.lang.constant.ConstantDescs.*;
  49 import static jdk.internal.classfile.impl.RawBytecodeHelper.*;
  50 
  51 /**
  52  * StackMapGenerator is responsible for stack map frames generation.
  53  * <p>
  54  * Stack map frames are computed from serialized bytecode similar way they are verified during class loading process.
  55  * <p>
  56  * The {@linkplain #generate() frames computation} consists of following steps:
  57  * <ol>
  58  * <li>{@linkplain #detectFrames() Detection} of mandatory stack map frames:<ul>
  59  *      <li>Mandatory stack map frame include all jump and switch instructions targets,
  60  *          offsets immediately following {@linkplain #noControlFlow(int) "no control flow"}
  61  *          and all exception table handlers.
  62  *      <li>Detection is performed in a single fast pass through the bytecode,

 136  * Focus of the whole algorithm is on high performance and low memory footprint:<ul>
 137  *      <li>It does not produce, collect nor visit any complex intermediate structures
 138  *          <i>(beside {@linkplain RawBytecodeHelper traversing} the {@linkplain #bytecode bytecode in binary form}).</i>
 139  *      <li>It works with only minimal mandatory stack map frames.
 140  *      <li>It does not spend time on any non-essential verifications.
 141  * </ul>
 142  */
 143 
 144 public final class StackMapGenerator {
 145 
 146     static StackMapGenerator of(DirectCodeBuilder dcb, BufWriterImpl buf) {
 147         return new StackMapGenerator(
 148                 dcb,
 149                 buf.thisClass().asSymbol(),
 150                 dcb.methodInfo.methodName().stringValue(),
 151                 dcb.methodInfo.methodTypeSymbol(),
 152                 (dcb.methodInfo.methodFlags() & ACC_STATIC) != 0,
 153                 dcb.bytecodesBufWriter.bytecodeView(),
 154                 dcb.constantPool,
 155                 dcb.context,
 156                 buf.getStrictInstanceFields(),
 157                 dcb.handlers);
 158     }
 159 
 160     private static final String OBJECT_INITIALIZER_NAME = "<init>";
 161     private static final int FLAG_THIS_UNINIT = 0x01;
 162     private static final int FRAME_DEFAULT_CAPACITY = 10;
 163     private static final int T_BOOLEAN = 4, T_LONG = 11;
 164     private static final Frame[] EMPTY_FRAME_ARRAY = {};
 165 
 166     public static final int
 167             ITEM_TOP = 0,
 168             ITEM_INTEGER = 1,
 169             ITEM_FLOAT = 2,
 170             ITEM_DOUBLE = 3,
 171             ITEM_LONG = 4,
 172             ITEM_NULL = 5,
 173             ITEM_UNINITIALIZED_THIS = 6,
 174             ITEM_OBJECT = 7,
 175             ITEM_UNINITIALIZED = 8,
 176             ITEM_BOOLEAN = 9,
 177             ITEM_BYTE = 10,
 178             ITEM_SHORT = 11,
 179             ITEM_CHAR = 12,
 180             ITEM_LONG_2ND = 13,
 181             ITEM_DOUBLE_2ND = 14,
 182             ITEM_BOGUS = -1;
 183 
 184     // Ranges represented by these constants are inclusive on both ends
 185     public static final int
 186             SAME_FRAME_END = 63,
 187             SAME_LOCALS_1_STACK_ITEM_FRAME_START = 64,
 188             SAME_LOCALS_1_STACK_ITEM_FRAME_END = 127,
 189             RESERVED_END = 245,
 190             EARLY_LARVAL = 246,
 191             SAME_LOCALS_1_STACK_ITEM_EXTENDED = 247,
 192             CHOP_FRAME_START = 248,
 193             CHOP_FRAME_END = 250,
 194             SAME_FRAME_EXTENDED = 251,
 195             APPEND_FRAME_START = 252,
 196             APPEND_FRAME_END = 254,
 197             FULL_FRAME = 255;
 198 
 199     private static final Type[] ARRAY_FROM_BASIC_TYPE = {null, null, null, null,
 200         Type.BOOLEAN_ARRAY_TYPE, Type.CHAR_ARRAY_TYPE, Type.FLOAT_ARRAY_TYPE, Type.DOUBLE_ARRAY_TYPE,
 201         Type.BYTE_ARRAY_TYPE, Type.SHORT_ARRAY_TYPE, Type.INT_ARRAY_TYPE, Type.LONG_ARRAY_TYPE};
 202 
 203     static record RawExceptionCatch(int start, int end, int handler, Type catchType) {}
 204 
 205     private final Type thisType;
 206     private final String methodName;
 207     private final MethodTypeDesc methodDesc;
 208     private final RawBytecodeHelper.CodeRange bytecode;
 209     private final SplitConstantPool cp;
 210     private final boolean isStatic;
 211     private final LabelContext labelContext;
 212     private final List<AbstractPseudoInstruction.ExceptionCatchImpl> handlers;
 213     private final List<RawExceptionCatch> rawHandlers;
 214     private final ClassHierarchyImpl classHierarchy;
 215     private final UnsetField[] strictFieldsToPut; // exact-sized, do not modify this copy!
 216     private final boolean patchDeadCode;
 217     private final boolean filterDeadLabels;
 218     private Frame[] frames = EMPTY_FRAME_ARRAY;
 219     private int framesCount = 0;
 220     private final Frame currentFrame;
 221     private int maxStack, maxLocals;
 222 
 223     /**
 224      * Primary constructor of the <code>Generator</code> class.
 225      * New <code>Generator</code> instance must be created for each individual class/method.
 226      * Instance contains only immutable results, all the calculations are processed during instance construction.
 227      *
 228      * @param labelContext <code>LabelContext</code> instance used to resolve or patch <code>ExceptionHandler</code>
 229      * labels to bytecode offsets (or vice versa)
 230      * @param thisClass class to generate stack maps for
 231      * @param methodName method name to generate stack maps for
 232      * @param methodDesc method descriptor to generate stack maps for
 233      * @param isStatic information whether the method is static
 234      * @param bytecode R/W <code>ByteBuffer</code> wrapping method bytecode, the content is altered in case <code>Generator</code> detects  and patches dead code
 235      * @param cp R/W <code>ConstantPoolBuilder</code> instance used to resolve all involved CP entries and also generate new entries referenced from the generated stack maps
 236      * @param handlers R/W <code>ExceptionHandler</code> list used to detect mandatory frame offsets as well as to determine stack maps in exception handlers
 237      * and also to be altered when dead code is detected and must be excluded from exception handlers
 238      */
 239     public StackMapGenerator(LabelContext labelContext,
 240                      ClassDesc thisClass,
 241                      String methodName,
 242                      MethodTypeDesc methodDesc,
 243                      boolean isStatic,
 244                      RawBytecodeHelper.CodeRange bytecode,
 245                      SplitConstantPool cp,
 246                      ClassFileImpl context,
 247                      UnsetField[] strictFields,
 248                      List<AbstractPseudoInstruction.ExceptionCatchImpl> handlers) {
 249         this.thisType = Type.referenceType(thisClass);
 250         this.methodName = methodName;
 251         this.methodDesc = methodDesc;
 252         this.isStatic = isStatic;
 253         this.bytecode = bytecode;
 254         this.cp = cp;
 255         this.labelContext = labelContext;
 256         this.handlers = handlers;
 257         this.rawHandlers = new ArrayList<>(handlers.size());
 258         this.classHierarchy = new ClassHierarchyImpl(context.classHierarchyResolver());
 259         this.patchDeadCode = context.patchDeadCode();
 260         this.filterDeadLabels = context.dropDeadLabels();
 261         this.currentFrame = new Frame(classHierarchy);
 262         if (OBJECT_INITIALIZER_NAME.equals(methodName)) {
 263             this.strictFieldsToPut = strictFields;
 264         } else {
 265             this.strictFieldsToPut = UnsetField.EMPTY_ARRAY;
 266         }
 267         generate();
 268     }
 269 
 270     /**
 271      * Calculated maximum number of the locals required
 272      * @return maximum number of the locals required
 273      */
 274     public int maxLocals() {
 275         return maxLocals;
 276     }
 277 
 278     /**
 279      * Calculated maximum stack size required
 280      * @return maximum stack size required
 281      */
 282     public int maxStack() {
 283         return maxStack;
 284     }
 285 
 286     private Frame getFrame(int offset) {

 395             } else {
 396                 //split
 397                 Label newStart = labelContext.newLabel();
 398                 labelContext.setLabelTarget(newStart, rangeEnd);
 399                 Label newEnd = labelContext.newLabel();
 400                 labelContext.setLabelTarget(newEnd, rangeStart);
 401                 it.set(new AbstractPseudoInstruction.ExceptionCatchImpl(e.handler(), e.tryStart(), newEnd, e.catchType()));
 402                 it.add(new AbstractPseudoInstruction.ExceptionCatchImpl(e.handler(), newStart, e.tryEnd(), e.catchType()));
 403             }
 404         }
 405     }
 406 
 407     /**
 408      * Getter of the generated <code>StackMapTableAttribute</code> or null if stack map is empty
 409      * @return <code>StackMapTableAttribute</code> or null if stack map is empty
 410      */
 411     public Attribute<? extends StackMapTableAttribute> stackMapTableAttribute() {
 412         return framesCount == 0 ? null : new UnboundAttribute.AdHocAttribute<>(Attributes.stackMapTable()) {
 413             @Override
 414             public void writeBody(BufWriterImpl b) {
 415                 int countPos = b.size();
 416                 if (framesCount != (char) framesCount) {
 417                     throw generatorError("Too many frames: " + framesCount);
 418                 }
 419                 b.writeU2(framesCount);
 420                 Frame prevFrame =  new Frame(classHierarchy);
 421                 prevFrame.setLocalsFromArg(methodName, methodDesc, isStatic, thisType, strictFieldsToPut);
 422                 prevFrame.trimAndCompress();
 423                 for (int i = 0; i < framesCount; i++) {
 424                     var fr = frames[i];
 425                     fr.trimAndCompress();
 426                     fr.writeTo(b, prevFrame, cp);
 427                     prevFrame = fr;
 428                 }
 429             }
 430 
 431             @Override
 432             public Utf8Entry attributeName() {
 433                 return cp.utf8Entry(Attributes.NAME_STACK_MAP_TABLE);
 434             }
 435         };
 436     }
 437 
 438     private static Type cpIndexToType(int index, ConstantPoolBuilder cp) {
 439         return Type.referenceType(cp.entryByIndex(index, ClassEntry.class).asSymbol());
 440     }
 441 
 442     private void processMethod() {
 443         var frames = this.frames;
 444         var currentFrame = this.currentFrame;
 445         currentFrame.setLocalsFromArg(methodName, methodDesc, isStatic, thisType, strictFieldsToPut);
 446         currentFrame.stackSize = 0;

 447         currentFrame.offset = -1;
 448         int stackmapIndex = 0;
 449         var bcs = bytecode.start();
 450         boolean ncf = false;
 451         while (bcs.next()) {
 452             currentFrame.offset = bcs.bci();
 453             if (stackmapIndex < framesCount) {
 454                 int thisOffset = frames[stackmapIndex].offset;
 455                 if (ncf && thisOffset > bcs.bci()) {
 456                     throw generatorError("Expecting a stack map frame");
 457                 }
 458                 if (thisOffset == bcs.bci()) {
 459                     Frame nextFrame = frames[stackmapIndex++];
 460                     if (!ncf) {
 461                         currentFrame.checkAssignableTo(nextFrame);
 462                     }
 463                     while (!nextFrame.dirty) { //skip unmatched frames
 464                         if (stackmapIndex == framesCount) return; //skip the rest of this round
 465                         nextFrame = frames[stackmapIndex++];
 466                     }

 769                 throw generatorError("number of keys in lookupswitch less than 0");
 770             }
 771             delta = 2;
 772             for (int i = 0; i < (keys - 1); i++) {
 773                 int this_key = bcs.getIntUnchecked(alignedBci + (2 + 2 * i) * 4);
 774                 int next_key = bcs.getIntUnchecked(alignedBci + (2 + 2 * i + 2) * 4);
 775                 if (this_key >= next_key) {
 776                     throw generatorError("Bad lookupswitch instruction");
 777                 }
 778             }
 779         }
 780         int target = bci + defaultOffset;
 781         checkJumpTarget(currentFrame, target);
 782         for (int i = 0; i < keys; i++) {
 783             target = bci + bcs.getIntUnchecked(alignedBci + (3 + i * delta) * 4);
 784             checkJumpTarget(currentFrame, target);
 785         }
 786     }
 787 
 788     private void processFieldInstructions(RawBytecodeHelper bcs) {
 789         var nameAndType = cp.entryByIndex(bcs.getIndexU2(), MemberRefEntry.class).nameAndType();
 790         var desc = Util.fieldTypeSymbol(nameAndType.type());
 791         var currentFrame = this.currentFrame;
 792         switch (bcs.opcode()) {
 793             case GETSTATIC ->
 794                 currentFrame.pushStack(desc);
 795             case PUTSTATIC -> {
 796                 currentFrame.decStack(Util.isDoubleSlot(desc) ? 2 : 1);
 797             }
 798             case GETFIELD -> {
 799                 currentFrame.decStack(1);
 800                 currentFrame.pushStack(desc);
 801             }
 802             case PUTFIELD -> {
 803                 if (strictFieldsToPut.length > 0) {
 804                     currentFrame.putStrictField(nameAndType);
 805                 }
 806                 currentFrame.decStack(Util.isDoubleSlot(desc) ? 3 : 2);
 807             }
 808             default -> throw new AssertionError("Should not reach here");
 809         }
 810     }
 811 
 812     private boolean processInvokeInstructions(RawBytecodeHelper bcs, boolean inTryBlock, boolean thisUninit) {
 813         int index = bcs.getIndexU2();
 814         int opcode = bcs.opcode();
 815         var nameAndType = opcode == INVOKEDYNAMIC
 816                 ? cp.entryByIndex(index, InvokeDynamicEntry.class).nameAndType()
 817                 : cp.entryByIndex(index, MemberRefEntry.class).nameAndType();
 818         var mDesc = Util.methodTypeSymbol(nameAndType.type());
 819         int bci = bcs.bci();
 820         var currentFrame = this.currentFrame;
 821         currentFrame.decStack(Util.parameterSlots(mDesc));
 822         if (opcode != INVOKESTATIC && opcode != INVOKEDYNAMIC) {
 823             if (nameAndType.name().equalsString(OBJECT_INITIALIZER_NAME)) {
 824                 Type type = currentFrame.popStack();
 825                 if (type == Type.UNITIALIZED_THIS_TYPE) {
 826                     if (inTryBlock) {
 827                         processExceptionHandlerTargets(bci, true);
 828                     }
 829                     var owner = cp.entryByIndex(index, MemberRefEntry.class).owner();
 830                     if (!owner.name().equalsString(((ClassOrInterfaceDescImpl) thisType.sym).internalName())
 831                             && currentFrame.unsetFieldsSize != 0) {
 832                         throw generatorError("Unset fields mismatch");
 833                     }
 834                     currentFrame.initializeObject(type, thisType);
 835                     currentFrame.unsetFieldsSize = 0;
 836                     currentFrame.unsetFields = UnsetField.EMPTY_ARRAY;
 837                     thisUninit = true;
 838                 } else if (type.tag == ITEM_UNINITIALIZED) {
 839                     Type new_class_type = cpIndexToType(bcs.getU2(type.bci + 1), cp);
 840                     if (inTryBlock) {
 841                         processExceptionHandlerTargets(bci, thisUninit);
 842                     }
 843                     currentFrame.initializeObject(type, new_class_type);
 844                 } else {
 845                     throw generatorError("Bad operand type when invoking <init>");
 846                 }
 847             } else {
 848                 currentFrame.decStack(1);
 849             }
 850         }
 851         currentFrame.pushStack(mDesc.returnType());
 852         return thisUninit;
 853     }
 854 
 855     private Type getNewarrayType(int index) {
 856         if (index < T_BOOLEAN || index > T_LONG) throw generatorError("Illegal newarray instruction type %d".formatted(index));

 959                 return;
 960             }
 961             if (frameOffset > offset) {
 962                 break;
 963             }
 964         }
 965         if (framesCount >= frames.length) {
 966             int newCapacity = framesCount + 8;
 967             this.frames = frames = framesCount == 0 ? new Frame[newCapacity] : Arrays.copyOf(frames, newCapacity);
 968         }
 969         if (i != framesCount) {
 970             System.arraycopy(frames, i, frames, i + 1, framesCount - i);
 971         }
 972         frames[i] = new Frame(offset, classHierarchy);
 973         this.framesCount = framesCount + 1;
 974     }
 975 
 976     private final class Frame {
 977 
 978         int offset;
 979         int localsSize, stackSize, unsetFieldsSize;
 980         int flags;
 981         int frameMaxStack = 0, frameMaxLocals = 0;
 982         boolean dirty = false;
 983         boolean localsChanged = false;
 984 
 985         private final ClassHierarchyImpl classHierarchy;
 986 
 987         private Type[] locals, stack;
 988         private UnsetField[] unsetFields = UnsetField.EMPTY_ARRAY; // sorted, modifiable oversized array
 989 
 990         Frame(ClassHierarchyImpl classHierarchy) {
 991             this(-1, 0, 0, 0, null, null, classHierarchy);
 992         }
 993 
 994         Frame(int offset, ClassHierarchyImpl classHierarchy) {
 995             this(offset, -1, 0, 0, null, null, classHierarchy);
 996         }
 997 
 998         Frame(int offset, int flags, int locals_size, int stack_size, Type[] locals, Type[] stack, ClassHierarchyImpl classHierarchy) {
 999             this.offset = offset;
1000             this.localsSize = locals_size;
1001             this.stackSize = stack_size;
1002             this.flags = flags;
1003             this.locals = locals;
1004             this.stack = stack;
1005             this.classHierarchy = classHierarchy;
1006         }
1007 
1008         @Override
1009         public String toString() {
1010             return (dirty ? "frame* @" : "frame @") + offset +
1011                     " with locals " + (locals == null ? "[]" : Arrays.asList(locals).subList(0, localsSize)) +
1012                     " and stack " + (stack == null ? "[]" : Arrays.asList(stack).subList(0, stackSize)) +
1013                     " and unset fields " + (unsetFields == null ? "[]" : Arrays.asList(unsetFields).subList(0, unsetFieldsSize));
1014         }
1015 
1016         Frame pushStack(ClassDesc desc) {
1017             if (desc == CD_long)   return pushStack(Type.LONG_TYPE, Type.LONG2_TYPE);
1018             if (desc == CD_double) return pushStack(Type.DOUBLE_TYPE, Type.DOUBLE2_TYPE);
1019             return desc == CD_void ? this
1020                     : pushStack(
1021                     desc.isPrimitive()
1022                             ? (desc == CD_float ? Type.FLOAT_TYPE : Type.INTEGER_TYPE)
1023                             : Type.referenceType(desc));
1024         }
1025 
1026         Frame pushStack(Type type) {
1027             checkStack(stackSize);
1028             stack[stackSize++] = type;
1029             return this;
1030         }
1031 
1032         Frame pushStack(Type type1, Type type2) {
1033             checkStack(stackSize + 1);

1048         }
1049 
1050         Frame frameInExceptionHandler(int flags, Type excType) {
1051             return new Frame(offset, flags, localsSize, 1, locals, new Type[] {excType}, classHierarchy);
1052         }
1053 
1054         void initializeObject(Type old_object, Type new_object) {
1055             int i;
1056             for (i = 0; i < localsSize; i++) {
1057                 if (locals[i].equals(old_object)) {
1058                     locals[i] = new_object;
1059                     localsChanged = true;
1060                 }
1061             }
1062             for (i = 0; i < stackSize; i++) {
1063                 if (stack[i].equals(old_object)) {
1064                     stack[i] = new_object;
1065                 }
1066             }
1067             if (old_object == Type.UNITIALIZED_THIS_TYPE) {
1068                 flags &= ~FLAG_THIS_UNINIT;
1069                 assert flags == 0 : flags;
1070             }
1071         }
1072 
1073         Frame checkLocal(int index) {
1074             if (index >= frameMaxLocals) frameMaxLocals = index + 1;
1075             if (locals == null) {
1076                 locals = new Type[index + FRAME_DEFAULT_CAPACITY];
1077                 Arrays.fill(locals, Type.TOP_TYPE);
1078             } else if (index >= locals.length) {
1079                 int current = locals.length;
1080                 locals = Arrays.copyOf(locals, index + FRAME_DEFAULT_CAPACITY);
1081                 Arrays.fill(locals, current, locals.length, Type.TOP_TYPE);
1082             }
1083             return this;
1084         }
1085 
1086         void putStrictField(NameAndTypeEntry nat) {
1087             int shift = 0;
1088             var array = unsetFields;
1089             for (int i = 0; i < unsetFieldsSize; i++) {
1090                 var f = array[i];
1091                 if (f.name().equals(nat.name()) && f.type().equals(nat.type())) {
1092                     shift++;
1093                 } else if (shift != 0) {
1094                     array[i - shift] = array[i];
1095                     array[i] = null;
1096                 }
1097             }
1098             if (shift > 1) {
1099                 throw generatorError(nat + "; discovered " + shift);
1100             }
1101             unsetFieldsSize -= shift;
1102         }
1103 
1104         private void checkStack(int index) {
1105             if (index >= frameMaxStack) frameMaxStack = index + 1;
1106             if (stack == null) {
1107                 stack = new Type[index + FRAME_DEFAULT_CAPACITY];
1108                 Arrays.fill(stack, Type.TOP_TYPE);
1109             } else if (index >= stack.length) {
1110                 int current = stack.length;
1111                 stack = Arrays.copyOf(stack, index + FRAME_DEFAULT_CAPACITY);
1112                 Arrays.fill(stack, current, stack.length, Type.TOP_TYPE);
1113             }
1114         }
1115 
1116         private void setLocalRawInternal(int index, Type type) {
1117             checkLocal(index);
1118             localsChanged |= !type.equals(locals[index]);
1119             locals[index] = type;
1120         }
1121 
1122         void setLocalsFromArg(String name, MethodTypeDesc methodDesc, boolean isStatic, Type thisKlass, UnsetField[] strictFieldsToPut) {
1123             int localsSize = 0;
1124             // Pre-emptively create a locals array that encompass all parameter slots
1125             checkLocal(Util.parameterSlots(methodDesc) + (isStatic ? -1 : 0));
1126             Type type;
1127             Type[] locals = this.locals;
1128             if (!isStatic) {
1129                 if (OBJECT_INITIALIZER_NAME.equals(name) && !CD_Object.equals(thisKlass.sym)) {
1130                     int strictFieldCount = strictFieldsToPut.length;
1131                     this.unsetFields = UnsetField.copyArray(strictFieldsToPut, strictFieldCount);
1132                     this.unsetFieldsSize = strictFieldCount;
1133                     type = Type.UNITIALIZED_THIS_TYPE;
1134                     this.flags = FLAG_THIS_UNINIT;
1135                 } else {
1136                     this.unsetFields = UnsetField.EMPTY_ARRAY;
1137                     this.unsetFieldsSize = 0;
1138                     type = thisKlass;
1139                     this.flags = 0;
1140                 }
1141                 locals[localsSize++] = type;
1142             }
1143             for (int i = 0; i < methodDesc.parameterCount(); i++) {
1144                 var desc = methodDesc.parameterType(i);
1145                 if (desc == CD_long) {
1146                     locals[localsSize    ] = Type.LONG_TYPE;
1147                     locals[localsSize + 1] = Type.LONG2_TYPE;
1148                     localsSize += 2;
1149                 } else if (desc == CD_double) {
1150                     locals[localsSize    ] = Type.DOUBLE_TYPE;
1151                     locals[localsSize + 1] = Type.DOUBLE2_TYPE;
1152                     localsSize += 2;
1153                 } else {
1154                     if (!desc.isPrimitive()) {
1155                         type = Type.referenceType(desc);
1156                     } else if (desc == CD_float) {
1157                         type = Type.FLOAT_TYPE;
1158                     } else {
1159                         type = Type.INTEGER_TYPE;
1160                     }
1161                     locals[localsSize++] = type;
1162                 }
1163             }
1164             this.localsSize = localsSize;
1165         }
1166 
1167         void copyFrom(Frame src) {
1168             if (locals != null && src.localsSize < locals.length) Arrays.fill(locals, src.localsSize, locals.length, Type.TOP_TYPE);
1169             localsSize = src.localsSize;
1170             checkLocal(src.localsSize - 1);
1171             if (src.localsSize > 0) System.arraycopy(src.locals, 0, locals, 0, src.localsSize);
1172             if (stack != null && src.stackSize < stack.length) Arrays.fill(stack, src.stackSize, stack.length, Type.TOP_TYPE);
1173             stackSize = src.stackSize;
1174             checkStack(src.stackSize - 1);
1175             if (src.stackSize > 0) System.arraycopy(src.stack, 0, stack, 0, src.stackSize);
1176             unsetFieldsSize = src.unsetFieldsSize;
1177             unsetFields = UnsetField.copyArray(src.unsetFields, src.unsetFieldsSize);
1178             flags = src.flags;
1179             localsChanged = true;
1180         }
1181 
1182         void checkAssignableTo(Frame target) {
1183             int localsSize = this.localsSize;
1184             int stackSize = this.stackSize;
1185             int myUnsetFieldsSize = this.unsetFieldsSize;
1186             if (target.flags == -1) {
1187                 target.locals = locals == null ? null : locals.clone();
1188                 target.localsSize = localsSize;
1189                 if (stackSize > 0) {
1190                     target.stack = stack.clone();
1191                     target.stackSize = stackSize;
1192                 }
1193                 target.unsetFields = UnsetField.copyArray(this.unsetFields, myUnsetFieldsSize);
1194                 target.unsetFieldsSize = myUnsetFieldsSize;
1195                 target.flags = flags;
1196                 target.dirty = true;
1197             } else {
1198                 if (target.localsSize > localsSize) {
1199                     target.localsSize = localsSize;
1200                     target.dirty = true;
1201                 }
1202                 for (int i = 0; i < target.localsSize; i++) {
1203                     merge(locals[i], target.locals, i, target);
1204                 }
1205                 if (stackSize != target.stackSize) {
1206                     throw generatorError("Stack size mismatch");
1207                 }
1208                 for (int i = 0; i < target.stackSize; i++) {
1209                     if (merge(stack[i], target.stack, i, target) == Type.TOP_TYPE) {
1210                         throw generatorError("Stack content mismatch");
1211                     }
1212                 }
1213                 if (myUnsetFieldsSize != 0) {
1214                     mergeUnsetFields(target);
1215                 }
1216             }
1217         }
1218 
1219         private Type getLocalRawInternal(int index) {
1220             checkLocal(index);
1221             return locals[index];
1222         }
1223 
1224         Type getLocal(int index) {
1225             Type ret = getLocalRawInternal(index);
1226             if (index >= localsSize) {
1227                 localsSize = index + 1;
1228             }
1229             return ret;
1230         }
1231 
1232         void setLocal(int index, Type type) {
1233             Type old = getLocalRawInternal(index);
1234             if (old == Type.DOUBLE_TYPE || old == Type.LONG_TYPE) {
1235                 setLocalRawInternal(index + 1, Type.TOP_TYPE);

1252             if (old == Type.DOUBLE2_TYPE || old == Type.LONG2_TYPE) {
1253                 setLocalRawInternal(index - 1, Type.TOP_TYPE);
1254             }
1255             setLocalRawInternal(index, type1);
1256             setLocalRawInternal(index + 1, type2);
1257             if (index >= localsSize - 1) {
1258                 localsSize = index + 2;
1259             }
1260         }
1261 
1262         private Type merge(Type me, Type[] toTypes, int i, Frame target) {
1263             var to = toTypes[i];
1264             var newTo = to.mergeFrom(me, classHierarchy);
1265             if (to != newTo && !to.equals(newTo)) {
1266                 toTypes[i] = newTo;
1267                 target.dirty = true;
1268             }
1269             return newTo;
1270         }
1271 
1272         // Merge this frame's unset fields into the target frame
1273         private void mergeUnsetFields(Frame target) {
1274             int myUnsetSize = unsetFieldsSize;
1275             int targetUnsetSize = target.unsetFieldsSize;
1276             var myUnsets = unsetFields;
1277             var targetUnsets = target.unsetFields;
1278             if (UnsetField.matches(myUnsets, myUnsetSize, targetUnsets, targetUnsetSize)) {
1279                 return; // no merge
1280             }
1281             // merge sort
1282             var merged = new UnsetField[StackMapGenerator.this.strictFieldsToPut.length];
1283             int mergedSize = 0;
1284             int i = 0;
1285             int j = 0;
1286             while (i < myUnsetSize && j < targetUnsetSize) {
1287                 var myCandidate = myUnsets[i];
1288                 var targetCandidate = targetUnsets[j];
1289                 var cmp = myCandidate.compareTo(targetCandidate);
1290                 if (cmp == 0) {
1291                     merged[mergedSize++] = myCandidate;
1292                     i++;
1293                     j++;
1294                 } else if (cmp < 0) {
1295                     merged[mergedSize++] = myCandidate;
1296                     i++;
1297                 } else {
1298                     merged[mergedSize++] = targetCandidate;
1299                     j++;
1300                 }
1301             }
1302             if (i < myUnsetSize) {
1303                 int len = myUnsetSize - i;
1304                 System.arraycopy(myUnsets, i, merged, mergedSize, len);
1305                 mergedSize += len;
1306             } else if (j < targetUnsetSize) {
1307                 int len = targetUnsetSize - j;
1308                 System.arraycopy(targetUnsets, j, merged, mergedSize, len);
1309                 mergedSize += len;
1310             }
1311 
1312             target.unsetFieldsSize = mergedSize;
1313             target.unsetFields = merged;
1314             target.dirty = true;
1315         }
1316 
1317         private static int trimAndCompress(Type[] types, int count) {
1318             while (count > 0 && types[count - 1] == Type.TOP_TYPE) count--;
1319             int compressed = 0;
1320             for (int i = 0; i < count; i++) {
1321                 if (!types[i].isCategory2_2nd()) {
1322                     if (compressed != i) {
1323                         types[compressed] = types[i];
1324                     }
1325                     compressed++;
1326                 }
1327             }
1328             return compressed;
1329         }
1330 
1331         void trimAndCompress() {
1332             localsSize = trimAndCompress(locals, localsSize);
1333             stackSize = trimAndCompress(stack, stackSize);
1334         }
1335 
1336         boolean hasUninitializedThis() {
1337             int size = this.localsSize;
1338             var localVars = this.locals;
1339             for (int i = 0; i < size; i++) {
1340                 if (localVars[i] == Type.UNITIALIZED_THIS_TYPE)
1341                     return true;
1342             }
1343             return false;
1344         }
1345 
1346         private static boolean equals(Type[] l1, Type[] l2, int commonSize) {
1347             if (l1 == null || l2 == null) return commonSize == 0;
1348             return Arrays.equals(l1, 0, commonSize, l2, 0, commonSize);
1349         }
1350 
1351         // In sync with StackMapDecoder::needsLarvalFrameForTransition
1352         private boolean needsLarvalFrame(Frame prevFrame) {
1353             if (UnsetField.matches(unsetFields, unsetFieldsSize, prevFrame.unsetFields, prevFrame.unsetFieldsSize))
1354                 return false;
1355             if (!hasUninitializedThis()) {
1356                 assert unsetFieldsSize == 0 : this; // Should have been handled by processInvokeInstructions
1357                 return false;
1358             }
1359             return true;
1360         }
1361 
1362         void writeTo(BufWriterImpl out, Frame prevFrame, ConstantPoolBuilder cp) {
1363             // enclosing frames
1364             if (needsLarvalFrame(prevFrame)) {
1365                 out.writeU1U2(EARLY_LARVAL, unsetFieldsSize);
1366                 for (int i = 0; i < unsetFieldsSize; i++) {
1367                     var f = unsetFields[i];
1368                     out.writeIndex(cp.nameAndTypeEntry(f.name(), f.type()));
1369                 }
1370             }
1371             // base frame
1372             int localsSize = this.localsSize;
1373             int stackSize = this.stackSize;
1374             int offsetDelta = offset - prevFrame.offset - 1;
1375             if (stackSize == 0) {
1376                 int commonLocalsSize = localsSize > prevFrame.localsSize ? prevFrame.localsSize : localsSize;
1377                 int diffLocalsSize = localsSize - prevFrame.localsSize;
1378                 if (-3 <= diffLocalsSize && diffLocalsSize <= 3 && equals(locals, prevFrame.locals, commonLocalsSize)) {
1379                     if (diffLocalsSize == 0 && offsetDelta <= SAME_FRAME_END) { //same frame
1380                         out.writeU1(offsetDelta);
1381                     } else {   //chop, same extended or append frame
1382                         out.writeU1U2(SAME_FRAME_EXTENDED + diffLocalsSize, offsetDelta);
1383                         for (int i=commonLocalsSize; i<localsSize; i++) locals[i].writeTo(out, cp);
1384                     }
1385                     return;
1386                 }
1387             } else if (stackSize == 1 && localsSize == prevFrame.localsSize && equals(locals, prevFrame.locals, localsSize)) {
1388                 if (offsetDelta <= SAME_LOCALS_1_STACK_ITEM_FRAME_END  - SAME_LOCALS_1_STACK_ITEM_FRAME_START) {  //same locals 1 stack item frame
1389                     out.writeU1(SAME_LOCALS_1_STACK_ITEM_FRAME_START + offsetDelta);
1390                 } else {  //same locals 1 stack item extended frame
1391                     out.writeU1U2(SAME_LOCALS_1_STACK_ITEM_EXTENDED, offsetDelta);
< prev index next >