1 /*
   2  * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 #include "cds/cdsConfig.hpp"
  25 #include "classfile/classFileParser.hpp"
  26 #include "classfile/classFileStream.hpp"
  27 #include "classfile/classLoader.hpp"
  28 #include "classfile/classLoaderData.inline.hpp"
  29 #include "classfile/classLoadInfo.hpp"
  30 #include "classfile/defaultMethods.hpp"
  31 #include "classfile/fieldLayoutBuilder.hpp"
  32 #include "classfile/javaClasses.inline.hpp"
  33 #include "classfile/moduleEntry.hpp"
  34 #include "classfile/packageEntry.hpp"
  35 #include "classfile/symbolTable.hpp"
  36 #include "classfile/systemDictionary.hpp"
  37 #include "classfile/systemDictionaryShared.hpp"
  38 #include "classfile/verificationType.hpp"
  39 #include "classfile/verifier.hpp"
  40 #include "classfile/vmClasses.hpp"
  41 #include "classfile/vmSymbols.hpp"
  42 #include "jvm.h"
  43 #include "logging/log.hpp"
  44 #include "logging/logStream.hpp"
  45 #include "memory/allocation.hpp"
  46 #include "memory/metadataFactory.hpp"
  47 #include "memory/oopFactory.hpp"
  48 #include "memory/resourceArea.hpp"
  49 #include "memory/universe.hpp"
  50 #include "oops/annotations.hpp"
  51 #include "oops/bsmAttribute.inline.hpp"
  52 #include "oops/constantPool.inline.hpp"
  53 #include "oops/fieldInfo.hpp"
  54 #include "oops/fieldStreams.inline.hpp"
  55 #include "oops/instanceKlass.inline.hpp"
  56 #include "oops/instanceMirrorKlass.hpp"
  57 #include "oops/klass.inline.hpp"
  58 #include "oops/klassVtable.hpp"
  59 #include "oops/metadata.hpp"
  60 #include "oops/method.inline.hpp"
  61 #include "oops/oop.inline.hpp"
  62 #include "oops/recordComponent.hpp"
  63 #include "oops/symbol.hpp"
  64 #include "prims/jvmtiExport.hpp"
  65 #include "prims/jvmtiThreadState.hpp"
  66 #include "runtime/arguments.hpp"
  67 #include "runtime/fieldDescriptor.inline.hpp"
  68 #include "runtime/handles.inline.hpp"
  69 #include "runtime/javaCalls.hpp"
  70 #include "runtime/os.hpp"
  71 #include "runtime/perfData.hpp"
  72 #include "runtime/reflection.hpp"
  73 #include "runtime/safepointVerifiers.hpp"
  74 #include "runtime/signature.hpp"
  75 #include "runtime/timer.hpp"
  76 #include "services/classLoadingService.hpp"
  77 #include "services/threadService.hpp"
  78 #include "utilities/align.hpp"
  79 #include "utilities/bitMap.inline.hpp"
  80 #include "utilities/checkedCast.hpp"
  81 #include "utilities/copy.hpp"
  82 #include "utilities/exceptions.hpp"
  83 #include "utilities/formatBuffer.hpp"
  84 #include "utilities/globalDefinitions.hpp"
  85 #include "utilities/growableArray.hpp"
  86 #include "utilities/hashTable.hpp"
  87 #include "utilities/macros.hpp"
  88 #include "utilities/ostream.hpp"
  89 #include "utilities/utf8.hpp"
  90 
  91 // We generally try to create the oops directly when parsing, rather than
  92 // allocating temporary data structures and copying the bytes twice. A
  93 // temporary area is only needed when parsing utf8 entries in the constant
  94 // pool and when parsing line number tables.
  95 
  96 // We add assert in debug mode when class format is not checked.
  97 
  98 #define JAVA_CLASSFILE_MAGIC              0xCAFEBABE
  99 #define JAVA_MIN_SUPPORTED_VERSION        45
 100 #define JAVA_PREVIEW_MINOR_VERSION        65535
 101 
 102 // Used for two backward compatibility reasons:
 103 // - to check for new additions to the class file format in JDK1.5
 104 // - to check for bug fixes in the format checker in JDK1.5
 105 #define JAVA_1_5_VERSION                  49
 106 
 107 // Used for backward compatibility reasons:
 108 // - to check for javac bug fixes that happened after 1.5
 109 // - also used as the max version when running in jdk6
 110 #define JAVA_6_VERSION                    50
 111 
 112 // Used for backward compatibility reasons:
 113 // - to disallow argument and require ACC_STATIC for <clinit> methods
 114 #define JAVA_7_VERSION                    51
 115 
 116 // Extension method support.
 117 #define JAVA_8_VERSION                    52
 118 
 119 #define JAVA_9_VERSION                    53
 120 
 121 #define JAVA_10_VERSION                   54
 122 
 123 #define JAVA_11_VERSION                   55
 124 
 125 #define JAVA_12_VERSION                   56
 126 
 127 #define JAVA_13_VERSION                   57
 128 
 129 #define JAVA_14_VERSION                   58
 130 
 131 #define JAVA_15_VERSION                   59
 132 
 133 #define JAVA_16_VERSION                   60
 134 
 135 #define JAVA_17_VERSION                   61
 136 
 137 #define JAVA_18_VERSION                   62
 138 
 139 #define JAVA_19_VERSION                   63
 140 
 141 #define JAVA_20_VERSION                   64
 142 
 143 #define JAVA_21_VERSION                   65
 144 
 145 #define JAVA_22_VERSION                   66
 146 
 147 #define JAVA_23_VERSION                   67
 148 
 149 #define JAVA_24_VERSION                   68
 150 
 151 #define JAVA_25_VERSION                   69
 152 
 153 #define JAVA_26_VERSION                   70
 154 
 155 #define JAVA_27_VERSION                   71
 156 
 157 void ClassFileParser::set_class_bad_constant_seen(short bad_constant) {
 158   assert((bad_constant == JVM_CONSTANT_Module ||
 159           bad_constant == JVM_CONSTANT_Package) && _major_version >= JAVA_9_VERSION,
 160          "Unexpected bad constant pool entry");
 161   if (_bad_constant_seen == 0) _bad_constant_seen = bad_constant;
 162 }
 163 
 164 void ClassFileParser::parse_constant_pool_entries(const ClassFileStream* const stream,
 165                                                   ConstantPool* cp,
 166                                                   const int length,
 167                                                   TRAPS) {
 168   assert(stream != nullptr, "invariant");
 169   assert(cp != nullptr, "invariant");
 170 
 171   // Use a local copy of ClassFileStream. It helps the C++ compiler to optimize
 172   // this function (_current can be allocated in a register, with scalar
 173   // replacement of aggregates). The _current pointer is copied back to
 174   // stream() when this function returns. DON'T call another method within
 175   // this method that uses stream().
 176   const ClassFileStream cfs1 = *stream;
 177   const ClassFileStream* const cfs = &cfs1;
 178 
 179   DEBUG_ONLY(const u1* const old_current = stream->current();)
 180 
 181   // Used for batching symbol allocations.
 182   const char* names[SymbolTable::symbol_alloc_batch_size];
 183   int lengths[SymbolTable::symbol_alloc_batch_size];
 184   int indices[SymbolTable::symbol_alloc_batch_size];
 185   unsigned int hashValues[SymbolTable::symbol_alloc_batch_size];
 186   int names_count = 0;
 187 
 188   // parsing  Index 0 is unused
 189   for (int index = 1; index < length; index++) {
 190     // Each of the following case guarantees one more byte in the stream
 191     // for the following tag or the access_flags following constant pool,
 192     // so we don't need bounds-check for reading tag.
 193     const u1 tag = cfs->get_u1_fast();
 194     switch (tag) {
 195       case JVM_CONSTANT_Class: {
 196         cfs->guarantee_more(3, CHECK);  // name_index, tag/access_flags
 197         const u2 name_index = cfs->get_u2_fast();
 198         cp->klass_index_at_put(index, name_index);
 199         break;
 200       }
 201       case JVM_CONSTANT_Fieldref: {
 202         cfs->guarantee_more(5, CHECK);  // class_index, name_and_type_index, tag/access_flags
 203         const u2 class_index = cfs->get_u2_fast();
 204         const u2 name_and_type_index = cfs->get_u2_fast();
 205         cp->field_at_put(index, class_index, name_and_type_index);
 206         break;
 207       }
 208       case JVM_CONSTANT_Methodref: {
 209         cfs->guarantee_more(5, CHECK);  // class_index, name_and_type_index, tag/access_flags
 210         const u2 class_index = cfs->get_u2_fast();
 211         const u2 name_and_type_index = cfs->get_u2_fast();
 212         cp->method_at_put(index, class_index, name_and_type_index);
 213         break;
 214       }
 215       case JVM_CONSTANT_InterfaceMethodref: {
 216         cfs->guarantee_more(5, CHECK);  // class_index, name_and_type_index, tag/access_flags
 217         const u2 class_index = cfs->get_u2_fast();
 218         const u2 name_and_type_index = cfs->get_u2_fast();
 219         cp->interface_method_at_put(index, class_index, name_and_type_index);
 220         break;
 221       }
 222       case JVM_CONSTANT_String : {
 223         cfs->guarantee_more(3, CHECK);  // string_index, tag/access_flags
 224         const u2 string_index = cfs->get_u2_fast();
 225         cp->string_index_at_put(index, string_index);
 226         break;
 227       }
 228       case JVM_CONSTANT_MethodHandle :
 229       case JVM_CONSTANT_MethodType: {
 230         if (_major_version < Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {
 231           classfile_parse_error(
 232             "Class file version does not support constant tag %u in class file %s",
 233             tag, THREAD);
 234           return;
 235         }
 236         if (tag == JVM_CONSTANT_MethodHandle) {
 237           cfs->guarantee_more(4, CHECK);  // ref_kind, method_index, tag/access_flags
 238           const u1 ref_kind = cfs->get_u1_fast();
 239           const u2 method_index = cfs->get_u2_fast();
 240           cp->method_handle_index_at_put(index, ref_kind, method_index);
 241         }
 242         else if (tag == JVM_CONSTANT_MethodType) {
 243           cfs->guarantee_more(3, CHECK);  // signature_index, tag/access_flags
 244           const u2 signature_index = cfs->get_u2_fast();
 245           cp->method_type_index_at_put(index, signature_index);
 246         }
 247         else {
 248           ShouldNotReachHere();
 249         }
 250         break;
 251       }
 252       case JVM_CONSTANT_Dynamic : {
 253         if (_major_version < Verifier::DYNAMICCONSTANT_MAJOR_VERSION) {
 254           classfile_parse_error(
 255               "Class file version does not support constant tag %u in class file %s",
 256               tag, THREAD);
 257           return;
 258         }
 259         cfs->guarantee_more(5, CHECK);  // bsm_index, nt, tag/access_flags
 260         const u2 bootstrap_specifier_index = cfs->get_u2_fast();
 261         const u2 name_and_type_index = cfs->get_u2_fast();
 262         if (_max_bootstrap_specifier_index < (int) bootstrap_specifier_index) {
 263           _max_bootstrap_specifier_index = (int) bootstrap_specifier_index;  // collect for later
 264         }
 265         cp->dynamic_constant_at_put(index, bootstrap_specifier_index, name_and_type_index);
 266         break;
 267       }
 268       case JVM_CONSTANT_InvokeDynamic : {
 269         if (_major_version < Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {
 270           classfile_parse_error(
 271               "Class file version does not support constant tag %u in class file %s",
 272               tag, THREAD);
 273           return;
 274         }
 275         cfs->guarantee_more(5, CHECK);  // bsm_index, nt, tag/access_flags
 276         const u2 bootstrap_specifier_index = cfs->get_u2_fast();
 277         const u2 name_and_type_index = cfs->get_u2_fast();
 278         if (_max_bootstrap_specifier_index < (int) bootstrap_specifier_index) {
 279           _max_bootstrap_specifier_index = (int) bootstrap_specifier_index;  // collect for later
 280         }
 281         cp->invoke_dynamic_at_put(index, bootstrap_specifier_index, name_and_type_index);
 282         break;
 283       }
 284       case JVM_CONSTANT_Integer: {
 285         cfs->guarantee_more(5, CHECK);  // bytes, tag/access_flags
 286         const u4 bytes = cfs->get_u4_fast();
 287         cp->int_at_put(index, (jint)bytes);
 288         break;
 289       }
 290       case JVM_CONSTANT_Float: {
 291         cfs->guarantee_more(5, CHECK);  // bytes, tag/access_flags
 292         const u4 bytes = cfs->get_u4_fast();
 293         cp->float_at_put(index, *(jfloat*)&bytes);
 294         break;
 295       }
 296       case JVM_CONSTANT_Long: {
 297         // A mangled type might cause you to overrun allocated memory
 298         guarantee_property(index + 1 < length,
 299                            "Invalid constant pool entry %u in class file %s",
 300                            index,
 301                            CHECK);
 302         cfs->guarantee_more(9, CHECK);  // bytes, tag/access_flags
 303         const u8 bytes = cfs->get_u8_fast();
 304         cp->long_at_put(index, bytes);
 305         index++;   // Skip entry following eigth-byte constant, see JVM book p. 98
 306         break;
 307       }
 308       case JVM_CONSTANT_Double: {
 309         // A mangled type might cause you to overrun allocated memory
 310         guarantee_property(index+1 < length,
 311                            "Invalid constant pool entry %u in class file %s",
 312                            index,
 313                            CHECK);
 314         cfs->guarantee_more(9, CHECK);  // bytes, tag/access_flags
 315         const u8 bytes = cfs->get_u8_fast();
 316         cp->double_at_put(index, *(jdouble*)&bytes);
 317         index++;   // Skip entry following eigth-byte constant, see JVM book p. 98
 318         break;
 319       }
 320       case JVM_CONSTANT_NameAndType: {
 321         cfs->guarantee_more(5, CHECK);  // name_index, signature_index, tag/access_flags
 322         const u2 name_index = cfs->get_u2_fast();
 323         const u2 signature_index = cfs->get_u2_fast();
 324         cp->name_and_type_at_put(index, name_index, signature_index);
 325         break;
 326       }
 327       case JVM_CONSTANT_Utf8 : {
 328         cfs->guarantee_more(2, CHECK);  // utf8_length
 329         u2  utf8_length = cfs->get_u2_fast();
 330         const u1* utf8_buffer = cfs->current();
 331         assert(utf8_buffer != nullptr, "null utf8 buffer");
 332         // Got utf8 string, guarantee utf8_length+1 bytes, set stream position forward.
 333         cfs->guarantee_more(utf8_length+1, CHECK);  // utf8 string, tag/access_flags
 334         cfs->skip_u1_fast(utf8_length);
 335 
 336         // Before storing the symbol, make sure it's legal
 337         if (_need_verify) {
 338           verify_legal_utf8(utf8_buffer, utf8_length, CHECK);
 339         }
 340 
 341         unsigned int hash;
 342         Symbol* const result = SymbolTable::lookup_only((const char*)utf8_buffer,
 343                                                         utf8_length,
 344                                                         hash);
 345         if (result == nullptr) {
 346           names[names_count] = (const char*)utf8_buffer;
 347           lengths[names_count] = utf8_length;
 348           indices[names_count] = index;
 349           hashValues[names_count++] = hash;
 350           if (names_count == SymbolTable::symbol_alloc_batch_size) {
 351             SymbolTable::new_symbols(_loader_data,
 352                                      constantPoolHandle(THREAD, cp),
 353                                      names_count,
 354                                      names,
 355                                      lengths,
 356                                      indices,
 357                                      hashValues);
 358             names_count = 0;
 359           }
 360         } else {
 361           cp->symbol_at_put(index, result);
 362         }
 363         break;
 364       }
 365       case JVM_CONSTANT_Module:
 366       case JVM_CONSTANT_Package: {
 367         // Record that an error occurred in these two cases but keep parsing so
 368         // that ACC_Module can be checked for in the access_flags.  Need to
 369         // throw NoClassDefFoundError in that case.
 370         if (_major_version >= JAVA_9_VERSION) {
 371           cfs->guarantee_more(3, CHECK);
 372           cfs->get_u2_fast();
 373           set_class_bad_constant_seen(tag);
 374           break;
 375         }
 376       }
 377       default: {
 378         classfile_parse_error("Unknown constant tag %u in class file %s",
 379                               tag,
 380                               THREAD);
 381         return;
 382       }
 383     } // end of switch(tag)
 384   } // end of for
 385 
 386   // Allocate the remaining symbols
 387   if (names_count > 0) {
 388     SymbolTable::new_symbols(_loader_data,
 389                              constantPoolHandle(THREAD, cp),
 390                              names_count,
 391                              names,
 392                              lengths,
 393                              indices,
 394                              hashValues);
 395   }
 396 
 397   // Copy _current pointer of local copy back to stream.
 398   assert(stream->current() == old_current, "non-exclusive use of stream");
 399   stream->set_current(cfs1.current());
 400 
 401 }
 402 
 403 static inline bool valid_cp_range(int index, int length) {
 404   return (index > 0 && index < length);
 405 }
 406 
 407 static inline Symbol* check_symbol_at(const ConstantPool* cp, int index) {
 408   assert(cp != nullptr, "invariant");
 409   if (valid_cp_range(index, cp->length()) && cp->tag_at(index).is_utf8()) {
 410     return cp->symbol_at(index);
 411   }
 412   return nullptr;
 413 }
 414 
 415 void ClassFileParser::parse_constant_pool(const ClassFileStream* const stream,
 416                                          ConstantPool* const cp,
 417                                          const int length,
 418                                          TRAPS) {
 419   assert(cp != nullptr, "invariant");
 420   assert(stream != nullptr, "invariant");
 421 
 422   // parsing constant pool entries
 423   parse_constant_pool_entries(stream, cp, length, CHECK);
 424   if (class_bad_constant_seen() != 0) {
 425     // a bad CP entry has been detected previously so stop parsing and just return.
 426     return;
 427   }
 428 
 429   int index = 1;  // declared outside of loops for portability
 430   int num_klasses = 0;
 431 
 432   // first verification pass - validate cross references
 433   // and fixup class and string constants
 434   for (index = 1; index < length; index++) {          // Index 0 is unused
 435     const jbyte tag = cp->tag_at(index).value();
 436     switch (tag) {
 437       case JVM_CONSTANT_Class: {
 438         ShouldNotReachHere();     // Only JVM_CONSTANT_ClassIndex should be present
 439         break;
 440       }
 441       case JVM_CONSTANT_Fieldref:
 442         // fall through
 443       case JVM_CONSTANT_Methodref:
 444         // fall through
 445       case JVM_CONSTANT_InterfaceMethodref: {
 446         if (!_need_verify) break;
 447         const int klass_ref_index = cp->uncached_klass_ref_index_at(index);
 448         const int name_and_type_ref_index = cp->uncached_name_and_type_ref_index_at(index);
 449         guarantee_property(valid_klass_reference_at(klass_ref_index),
 450                        "Invalid constant pool index %u in class file %s",
 451                        klass_ref_index, CHECK);
 452         guarantee_property(valid_cp_range(name_and_type_ref_index, length) &&
 453           cp->tag_at(name_and_type_ref_index).is_name_and_type(),
 454           "Invalid constant pool index %u in class file %s",
 455           name_and_type_ref_index, CHECK);
 456         break;
 457       }
 458       case JVM_CONSTANT_String: {
 459         ShouldNotReachHere();     // Only JVM_CONSTANT_StringIndex should be present
 460         break;
 461       }
 462       case JVM_CONSTANT_Integer:
 463         break;
 464       case JVM_CONSTANT_Float:
 465         break;
 466       case JVM_CONSTANT_Long:
 467       case JVM_CONSTANT_Double: {
 468         index++;
 469         guarantee_property(
 470           (index < length && cp->tag_at(index).is_invalid()),
 471           "Improper constant pool long/double index %u in class file %s",
 472           index, CHECK);
 473         break;
 474       }
 475       case JVM_CONSTANT_NameAndType: {
 476         if (!_need_verify) break;
 477         const int name_ref_index = cp->name_ref_index_at(index);
 478         const int signature_ref_index = cp->signature_ref_index_at(index);
 479         guarantee_property(valid_symbol_at(name_ref_index),
 480           "Invalid constant pool index %u in class file %s",
 481           name_ref_index, CHECK);
 482         guarantee_property(valid_symbol_at(signature_ref_index),
 483           "Invalid constant pool index %u in class file %s",
 484           signature_ref_index, CHECK);
 485         break;
 486       }
 487       case JVM_CONSTANT_Utf8:
 488         break;
 489       case JVM_CONSTANT_UnresolvedClass:         // fall-through
 490       case JVM_CONSTANT_UnresolvedClassInError: {
 491         ShouldNotReachHere();     // Only JVM_CONSTANT_ClassIndex should be present
 492         break;
 493       }
 494       case JVM_CONSTANT_ClassIndex: {
 495         const int class_index = cp->klass_index_at(index);
 496         guarantee_property(valid_symbol_at(class_index),
 497           "Invalid constant pool index %u in class file %s",
 498           class_index, CHECK);
 499         cp->unresolved_klass_at_put(index, class_index, num_klasses++);
 500         break;
 501       }
 502       case JVM_CONSTANT_StringIndex: {
 503         const int string_index = cp->string_index_at(index);
 504         guarantee_property(valid_symbol_at(string_index),
 505           "Invalid constant pool index %u in class file %s",
 506           string_index, CHECK);
 507         Symbol* const sym = cp->symbol_at(string_index);
 508         cp->unresolved_string_at_put(index, sym);
 509         break;
 510       }
 511       case JVM_CONSTANT_MethodHandle: {
 512         const int ref_index = cp->method_handle_index_at(index);
 513         guarantee_property(valid_cp_range(ref_index, length),
 514           "Invalid constant pool index %u in class file %s",
 515           ref_index, CHECK);
 516         const constantTag tag = cp->tag_at(ref_index);
 517         const int ref_kind = cp->method_handle_ref_kind_at(index);
 518 
 519         switch (ref_kind) {
 520           case JVM_REF_getField:
 521           case JVM_REF_getStatic:
 522           case JVM_REF_putField:
 523           case JVM_REF_putStatic: {
 524             guarantee_property(
 525               tag.is_field(),
 526               "Invalid constant pool index %u in class file %s (not a field)",
 527               ref_index, CHECK);
 528             break;
 529           }
 530           case JVM_REF_invokeVirtual:
 531           case JVM_REF_newInvokeSpecial: {
 532             guarantee_property(
 533               tag.is_method(),
 534               "Invalid constant pool index %u in class file %s (not a method)",
 535               ref_index, CHECK);
 536             break;
 537           }
 538           case JVM_REF_invokeStatic:
 539           case JVM_REF_invokeSpecial: {
 540             guarantee_property(
 541               tag.is_method() ||
 542               ((_major_version >= JAVA_8_VERSION) && tag.is_interface_method()),
 543               "Invalid constant pool index %u in class file %s (not a method)",
 544               ref_index, CHECK);
 545             break;
 546           }
 547           case JVM_REF_invokeInterface: {
 548             guarantee_property(
 549               tag.is_interface_method(),
 550               "Invalid constant pool index %u in class file %s (not an interface method)",
 551               ref_index, CHECK);
 552             break;
 553           }
 554           default: {
 555             classfile_parse_error(
 556               "Bad method handle kind at constant pool index %u in class file %s",
 557               index, THREAD);
 558             return;
 559           }
 560         } // switch(refkind)
 561         // Keep the ref_index unchanged.  It will be indirected at link-time.
 562         break;
 563       } // case MethodHandle
 564       case JVM_CONSTANT_MethodType: {
 565         const int ref_index = cp->method_type_index_at(index);
 566         guarantee_property(valid_symbol_at(ref_index),
 567           "Invalid constant pool index %u in class file %s",
 568           ref_index, CHECK);
 569         break;
 570       }
 571       case JVM_CONSTANT_Dynamic: {
 572         const int name_and_type_ref_index =
 573           cp->bootstrap_name_and_type_ref_index_at(index);
 574 
 575         guarantee_property(valid_cp_range(name_and_type_ref_index, length) &&
 576           cp->tag_at(name_and_type_ref_index).is_name_and_type(),
 577           "Invalid constant pool index %u in class file %s",
 578           name_and_type_ref_index, CHECK);
 579         // bootstrap specifier index must be checked later,
 580         // when BootstrapMethods attr is available
 581 
 582         // Mark the constant pool as having a CONSTANT_Dynamic_info structure
 583         cp->set_has_dynamic_constant();
 584         break;
 585       }
 586       case JVM_CONSTANT_InvokeDynamic: {
 587         const int name_and_type_ref_index =
 588           cp->bootstrap_name_and_type_ref_index_at(index);
 589 
 590         guarantee_property(valid_cp_range(name_and_type_ref_index, length) &&
 591           cp->tag_at(name_and_type_ref_index).is_name_and_type(),
 592           "Invalid constant pool index %u in class file %s",
 593           name_and_type_ref_index, CHECK);
 594         // bootstrap specifier index must be checked later,
 595         // when BootstrapMethods attr is available
 596         break;
 597       }
 598       default: {
 599         fatal("bad constant pool tag value %u", cp->tag_at(index).value());
 600         ShouldNotReachHere();
 601         break;
 602       }
 603     } // switch(tag)
 604   } // end of for
 605 
 606   cp->allocate_resolved_klasses(_loader_data, num_klasses, CHECK);
 607 
 608   if (!_need_verify) {
 609     return;
 610   }
 611 
 612   // second verification pass - checks the strings are of the right format.
 613   // but not yet to the other entries
 614   for (index = 1; index < length; index++) {
 615     const jbyte tag = cp->tag_at(index).value();
 616     switch (tag) {
 617       case JVM_CONSTANT_UnresolvedClass: {
 618         const Symbol* const class_name = cp->klass_name_at(index);
 619         // check the name
 620         verify_legal_class_name(class_name, CHECK);
 621         break;
 622       }
 623       case JVM_CONSTANT_NameAndType: {
 624         if (_need_verify) {
 625           const int sig_index = cp->signature_ref_index_at(index);
 626           const int name_index = cp->name_ref_index_at(index);
 627           const Symbol* const name = cp->symbol_at(name_index);
 628           const Symbol* const sig = cp->symbol_at(sig_index);
 629           guarantee_property(sig->utf8_length() != 0,
 630             "Illegal zero length constant pool entry at %d in class %s",
 631             sig_index, CHECK);
 632           guarantee_property(name->utf8_length() != 0,
 633             "Illegal zero length constant pool entry at %d in class %s",
 634             name_index, CHECK);
 635 
 636           if (Signature::is_method(sig)) {
 637             // Format check method name and signature
 638             verify_legal_method_name(name, CHECK);
 639             verify_legal_method_signature(name, sig, CHECK);
 640           } else {
 641             // Format check field name and signature
 642             verify_legal_field_name(name, CHECK);
 643             verify_legal_field_signature(name, sig, CHECK);
 644           }
 645         }
 646         break;
 647       }
 648       case JVM_CONSTANT_Dynamic: {
 649         const int name_and_type_ref_index =
 650           cp->uncached_name_and_type_ref_index_at(index);
 651         // already verified to be utf8
 652         const int name_ref_index =
 653           cp->name_ref_index_at(name_and_type_ref_index);
 654         // already verified to be utf8
 655         const int signature_ref_index =
 656           cp->signature_ref_index_at(name_and_type_ref_index);
 657         const Symbol* const name = cp->symbol_at(name_ref_index);
 658         const Symbol* const signature = cp->symbol_at(signature_ref_index);
 659         if (_need_verify) {
 660           // CONSTANT_Dynamic's name and signature are verified above, when iterating NameAndType_info.
 661           // Need only to be sure signature is the right type.
 662           if (Signature::is_method(signature)) {
 663             throwIllegalSignature("CONSTANT_Dynamic", name, signature, CHECK);
 664           }
 665         }
 666         break;
 667       }
 668       case JVM_CONSTANT_InvokeDynamic:
 669       case JVM_CONSTANT_Fieldref:
 670       case JVM_CONSTANT_Methodref:
 671       case JVM_CONSTANT_InterfaceMethodref: {
 672         const int name_and_type_ref_index =
 673           cp->uncached_name_and_type_ref_index_at(index);
 674         // already verified to be utf8
 675         const int name_ref_index =
 676           cp->name_ref_index_at(name_and_type_ref_index);
 677         // already verified to be utf8
 678         const int signature_ref_index =
 679           cp->signature_ref_index_at(name_and_type_ref_index);
 680         const Symbol* const name = cp->symbol_at(name_ref_index);
 681         const Symbol* const signature = cp->symbol_at(signature_ref_index);
 682         if (tag == JVM_CONSTANT_Fieldref) {
 683           if (_need_verify) {
 684             // Field name and signature are verified above, when iterating NameAndType_info.
 685             // Need only to be sure signature is non-zero length and the right type.
 686             if (Signature::is_method(signature)) {
 687               throwIllegalSignature("Field", name, signature, CHECK);
 688             }
 689           }
 690         } else {
 691           if (_need_verify) {
 692             // Method name and signature are individually verified above, when iterating
 693             // NameAndType_info.  Need to check here that signature is non-zero length and
 694             // the right type.
 695             if (!Signature::is_method(signature)) {
 696               throwIllegalSignature("Method", name, signature, CHECK);
 697             }
 698           }
 699           // If a class method name begins with '<', it must be "<init>" and have void signature.
 700           const unsigned int name_len = name->utf8_length();
 701           if (tag == JVM_CONSTANT_Methodref && name_len != 0 &&
 702               name->char_at(0) == JVM_SIGNATURE_SPECIAL) {
 703             if (name != vmSymbols::object_initializer_name()) {
 704               classfile_parse_error(
 705                 "Bad method name at constant pool index %u in class file %s",
 706                 name_ref_index, THREAD);
 707               return;
 708             } else if (!Signature::is_void_method(signature)) { // must have void signature.
 709               throwIllegalSignature("Method", name, signature, CHECK);
 710             }
 711           }
 712         }
 713         break;
 714       }
 715       case JVM_CONSTANT_MethodHandle: {
 716         const int ref_index = cp->method_handle_index_at(index);
 717         const int ref_kind = cp->method_handle_ref_kind_at(index);
 718         switch (ref_kind) {
 719           case JVM_REF_invokeVirtual:
 720           case JVM_REF_invokeStatic:
 721           case JVM_REF_invokeSpecial:
 722           case JVM_REF_newInvokeSpecial: {
 723             const int name_and_type_ref_index =
 724               cp->uncached_name_and_type_ref_index_at(ref_index);
 725             const int name_ref_index =
 726               cp->name_ref_index_at(name_and_type_ref_index);
 727             const Symbol* const name = cp->symbol_at(name_ref_index);
 728             if (ref_kind == JVM_REF_newInvokeSpecial) {
 729               if (name != vmSymbols::object_initializer_name()) {
 730                 classfile_parse_error(
 731                   "Bad constructor name at constant pool index %u in class file %s",
 732                     name_ref_index, THREAD);
 733                 return;
 734               }
 735             } else {
 736               if (name == vmSymbols::object_initializer_name()) {
 737                 classfile_parse_error(
 738                   "Bad method name at constant pool index %u in class file %s",
 739                   name_ref_index, THREAD);
 740                 return;
 741               }
 742             }
 743             break;
 744           }
 745           // Other ref_kinds are already fully checked in previous pass.
 746         } // switch(ref_kind)
 747         break;
 748       }
 749       case JVM_CONSTANT_MethodType: {
 750         const Symbol* const no_name = vmSymbols::type_name(); // place holder
 751         const Symbol* const signature = cp->method_type_signature_at(index);
 752         verify_legal_method_signature(no_name, signature, CHECK);
 753         break;
 754       }
 755       case JVM_CONSTANT_Utf8: {
 756         assert(cp->symbol_at(index)->refcount() != 0, "count corrupted");
 757       }
 758     }  // switch(tag)
 759   }  // end of for
 760 }
 761 
 762 class NameSigHash: public ResourceObj {
 763  public:
 764   const Symbol*       _name;       // name
 765   const Symbol*       _sig;        // signature
 766 
 767   static const int HASH_ROW_SIZE = 256;
 768 
 769   NameSigHash(Symbol* name, Symbol* sig) :
 770     _name(name),
 771     _sig(sig) {}
 772 
 773   static unsigned int hash(NameSigHash const& namesig) {
 774     return namesig._name->identity_hash() ^ namesig._sig->identity_hash();
 775   }
 776 
 777   static bool equals(NameSigHash const& e0, NameSigHash const& e1) {
 778     return (e0._name == e1._name) &&
 779           (e0._sig  == e1._sig);
 780   }
 781 };
 782 
 783 using NameSigHashtable = HashTable<NameSigHash, int,
 784                                            NameSigHash::HASH_ROW_SIZE,
 785                                            AnyObj::RESOURCE_AREA, mtInternal,
 786                                            &NameSigHash::hash, &NameSigHash::equals>;
 787 
 788 // Side-effects: populates the _local_interfaces field
 789 void ClassFileParser::parse_interfaces(const ClassFileStream* const stream,
 790                                        const int itfs_len,
 791                                        ConstantPool* const cp,
 792                                        bool* const has_nonstatic_concrete_methods,
 793                                        TRAPS) {
 794   assert(stream != nullptr, "invariant");
 795   assert(cp != nullptr, "invariant");
 796   assert(has_nonstatic_concrete_methods != nullptr, "invariant");
 797 
 798   if (itfs_len == 0) {
 799     _local_interfaces = Universe::the_empty_instance_klass_array();
 800   } else {
 801     assert(itfs_len > 0, "only called for len>0");
 802     _local_interfaces = MetadataFactory::new_array<InstanceKlass*>(_loader_data, itfs_len, nullptr, CHECK);
 803 
 804     int index;
 805     for (index = 0; index < itfs_len; index++) {
 806       const u2 interface_index = stream->get_u2(CHECK);
 807       Klass* interf;
 808       guarantee_property(
 809         valid_klass_reference_at(interface_index),
 810         "Interface name has bad constant pool index %u in class file %s",
 811         interface_index, CHECK);
 812       if (cp->tag_at(interface_index).is_klass()) {
 813         interf = cp->resolved_klass_at(interface_index);
 814       } else {
 815         Symbol* const unresolved_klass  = cp->klass_name_at(interface_index);
 816 
 817         // Don't need to check legal name because it's checked when parsing constant pool.
 818         // But need to make sure it's not an array type.
 819         guarantee_property(unresolved_klass->char_at(0) != JVM_SIGNATURE_ARRAY,
 820                            "Bad interface name in class file %s", CHECK);
 821 
 822         // Call resolve on the interface class name with class circularity checking
 823         interf = SystemDictionary::resolve_super_or_fail(_class_name,
 824                                                          unresolved_klass,
 825                                                          Handle(THREAD, _loader_data->class_loader()),
 826                                                          false, CHECK);
 827       }
 828 
 829       if (!interf->is_interface()) {
 830         THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
 831                   err_msg("class %s can not implement %s, because it is not an interface (%s)",
 832                           _class_name->as_klass_external_name(),
 833                           interf->external_name(),
 834                           interf->class_in_module_of_loader()));
 835       }
 836 
 837       if (InstanceKlass::cast(interf)->has_nonstatic_concrete_methods()) {
 838         *has_nonstatic_concrete_methods = true;
 839       }
 840       _local_interfaces->at_put(index, InstanceKlass::cast(interf));
 841     }
 842 
 843     if (!_need_verify || itfs_len <= 1) {
 844       return;
 845     }
 846 
 847     // Check if there's any duplicates in interfaces
 848     ResourceMark rm(THREAD);
 849     // Set containing interface names
 850     HashTable<Symbol*, int>* interface_names = new HashTable<Symbol*, int>();
 851     for (index = 0; index < itfs_len; index++) {
 852       const InstanceKlass* const k = _local_interfaces->at(index);
 853       Symbol* interface_name = k->name();
 854       // If no duplicates, add (name, nullptr) in hashtable interface_names.
 855       if (!interface_names->put(interface_name, 0)) {
 856         classfile_parse_error("Duplicate interface name \"%s\" in class file %s",
 857                                interface_name->as_C_string(), THREAD);
 858         return;
 859       }
 860     }
 861   }
 862 }
 863 
 864 void ClassFileParser::verify_constantvalue(const ConstantPool* const cp,
 865                                            int constantvalue_index,
 866                                            int signature_index,
 867                                            TRAPS) const {
 868   // Make sure the constant pool entry is of a type appropriate to this field
 869   guarantee_property(
 870     (constantvalue_index > 0 &&
 871       constantvalue_index < cp->length()),
 872     "Bad initial value index %u in ConstantValue attribute in class file %s",
 873     constantvalue_index, CHECK);
 874 
 875   const constantTag value_type = cp->tag_at(constantvalue_index);
 876   switch(cp->basic_type_for_signature_at(signature_index)) {
 877     case T_LONG: {
 878       guarantee_property(value_type.is_long(),
 879                          "Inconsistent constant value type in class file %s",
 880                          CHECK);
 881       break;
 882     }
 883     case T_FLOAT: {
 884       guarantee_property(value_type.is_float(),
 885                          "Inconsistent constant value type in class file %s",
 886                          CHECK);
 887       break;
 888     }
 889     case T_DOUBLE: {
 890       guarantee_property(value_type.is_double(),
 891                          "Inconsistent constant value type in class file %s",
 892                          CHECK);
 893       break;
 894     }
 895     case T_BYTE:
 896     case T_CHAR:
 897     case T_SHORT:
 898     case T_BOOLEAN:
 899     case T_INT: {
 900       guarantee_property(value_type.is_int(),
 901                          "Inconsistent constant value type in class file %s",
 902                          CHECK);
 903       break;
 904     }
 905     case T_OBJECT: {
 906       guarantee_property((cp->symbol_at(signature_index)->equals("Ljava/lang/String;")
 907                          && value_type.is_string()),
 908                          "Bad string initial value in class file %s",
 909                          CHECK);
 910       break;
 911     }
 912     default: {
 913       classfile_parse_error("Unable to set initial value %u in class file %s",
 914                              constantvalue_index,
 915                              THREAD);
 916     }
 917   }
 918 }
 919 
 920 class AnnotationCollector : public ResourceObj{
 921 public:
 922   enum Location { _in_field, _in_method, _in_class };
 923   enum ID {
 924     _unknown = 0,
 925     _method_CallerSensitive,
 926     _method_ForceInline,
 927     _method_DontInline,
 928     _method_ChangesCurrentThread,
 929     _method_JvmtiHideEvents,
 930     _method_JvmtiMountTransition,
 931     _method_InjectedProfile,
 932     _method_LambdaForm_Compiled,
 933     _method_Hidden,
 934     _method_Scoped,
 935     _method_IntrinsicCandidate,
 936     _jdk_internal_vm_annotation_Contended,
 937     _field_Stable,
 938     _jdk_internal_vm_annotation_ReservedStackAccess,
 939     _jdk_internal_ValueBased,
 940     _java_lang_Deprecated,
 941     _java_lang_Deprecated_for_removal,
 942     _jdk_internal_vm_annotation_AOTSafeClassInitializer,
 943     _method_AOTRuntimeSetup,
 944     _jdk_internal_vm_annotation_TrustFinalFields,
 945     _annotation_LIMIT
 946   };
 947   const Location _location;
 948   int _annotations_present;
 949   u2 _contended_group;
 950 
 951   AnnotationCollector(Location location)
 952     : _location(location), _annotations_present(0), _contended_group(0)
 953   {
 954     assert((int)_annotation_LIMIT <= (int)sizeof(_annotations_present) * BitsPerByte, "");
 955   }
 956   // If this annotation name has an ID, report it (or _none).
 957   ID annotation_index(const ClassLoaderData* loader_data, const Symbol* name, bool can_access_vm_annotations);
 958   // Set the annotation name:
 959   void set_annotation(ID id) {
 960     assert((int)id >= 0 && (int)id < (int)_annotation_LIMIT, "oob");
 961     _annotations_present |= (int)nth_bit((int)id);
 962   }
 963 
 964   void remove_annotation(ID id) {
 965     assert((int)id >= 0 && (int)id < (int)_annotation_LIMIT, "oob");
 966     _annotations_present &= (int)~nth_bit((int)id);
 967   }
 968 
 969   // Report if the annotation is present.
 970   bool has_any_annotations() const { return _annotations_present != 0; }
 971   bool has_annotation(ID id) const { return (nth_bit((int)id) & _annotations_present) != 0; }
 972 
 973   void set_contended_group(u2 group) { _contended_group = group; }
 974   u2 contended_group() const { return _contended_group; }
 975 
 976   bool is_contended() const { return has_annotation(_jdk_internal_vm_annotation_Contended); }
 977 
 978   void set_stable(bool stable) { set_annotation(_field_Stable); }
 979   bool is_stable() const { return has_annotation(_field_Stable); }
 980 
 981   bool has_aot_runtime_setup() const { return has_annotation(_method_AOTRuntimeSetup); }
 982 };
 983 
 984 // This class also doubles as a holder for metadata cleanup.
 985 class ClassFileParser::FieldAnnotationCollector : public AnnotationCollector {
 986 private:
 987   ClassLoaderData* _loader_data;
 988   AnnotationArray* _field_annotations;
 989   AnnotationArray* _field_type_annotations;
 990 public:
 991   FieldAnnotationCollector(ClassLoaderData* loader_data) :
 992     AnnotationCollector(_in_field),
 993     _loader_data(loader_data),
 994     _field_annotations(nullptr),
 995     _field_type_annotations(nullptr) {}
 996   ~FieldAnnotationCollector();
 997   void apply_to(FieldInfo* f);
 998   AnnotationArray* field_annotations()      { return _field_annotations; }
 999   AnnotationArray* field_type_annotations() { return _field_type_annotations; }
1000 
1001   void set_field_annotations(AnnotationArray* a)      { _field_annotations = a; }
1002   void set_field_type_annotations(AnnotationArray* a) { _field_type_annotations = a; }
1003 };
1004 
1005 class MethodAnnotationCollector : public AnnotationCollector{
1006 public:
1007   MethodAnnotationCollector() : AnnotationCollector(_in_method) { }
1008   void apply_to(const methodHandle& m);
1009 };
1010 
1011 class ClassFileParser::ClassAnnotationCollector : public AnnotationCollector{
1012 public:
1013   ClassAnnotationCollector() : AnnotationCollector(_in_class) { }
1014   void apply_to(InstanceKlass* ik);
1015 };
1016 
1017 
1018 static int skip_annotation_value(const u1* buffer, int limit, int index, int recursion_depth); // fwd decl
1019 static const int max_recursion_depth = 5;
1020 
1021 // Safely increment index by val if does not pass limit
1022 #define SAFE_ADD(index, limit, val) \
1023 if (index >= limit - val) return limit; \
1024 index += val;
1025 
1026 // Skip an annotation.  Return >=limit if there is any problem.
1027 static int skip_annotation(const u1* buffer, int limit, int index, int recursion_depth = 0) {
1028   assert(buffer != nullptr, "invariant");
1029   if (recursion_depth > max_recursion_depth) {
1030     return limit;
1031   }
1032   // annotation := atype:u2 do(nmem:u2) {member:u2 value}
1033   // value := switch (tag:u1) { ... }
1034   SAFE_ADD(index, limit, 4); // skip atype and read nmem
1035   int nmem = Bytes::get_Java_u2((address)buffer + index - 2);
1036   while (--nmem >= 0 && index < limit) {
1037     SAFE_ADD(index, limit, 2); // skip member
1038     index = skip_annotation_value(buffer, limit, index, recursion_depth + 1);
1039   }
1040   return index;
1041 }
1042 
1043 // Skip an annotation value.  Return >=limit if there is any problem.
1044 static int skip_annotation_value(const u1* buffer, int limit, int index, int recursion_depth) {
1045   assert(buffer != nullptr, "invariant");
1046 
1047   if (recursion_depth > max_recursion_depth) {
1048     return limit;
1049   }
1050   // value := switch (tag:u1) {
1051   //   case B, C, I, S, Z, D, F, J, c: con:u2;
1052   //   case e: e_class:u2 e_name:u2;
1053   //   case s: s_con:u2;
1054   //   case [: do(nval:u2) {value};
1055   //   case @: annotation;
1056   //   case s: s_con:u2;
1057   // }
1058   SAFE_ADD(index, limit, 1); // read tag
1059   const u1 tag = buffer[index - 1];
1060   switch (tag) {
1061     case 'B':
1062     case 'C':
1063     case 'I':
1064     case 'S':
1065     case 'Z':
1066     case 'D':
1067     case 'F':
1068     case 'J':
1069     case 'c':
1070     case 's':
1071       SAFE_ADD(index, limit, 2);  // skip con or s_con
1072       break;
1073     case 'e':
1074       SAFE_ADD(index, limit, 4);  // skip e_class, e_name
1075       break;
1076     case '[':
1077     {
1078       SAFE_ADD(index, limit, 2); // read nval
1079       int nval = Bytes::get_Java_u2((address)buffer + index - 2);
1080       while (--nval >= 0 && index < limit) {
1081         index = skip_annotation_value(buffer, limit, index, recursion_depth + 1);
1082       }
1083     }
1084     break;
1085     case '@':
1086       index = skip_annotation(buffer, limit, index, recursion_depth + 1);
1087       break;
1088     default:
1089       return limit;  //  bad tag byte
1090   }
1091   return index;
1092 }
1093 
1094 // Sift through annotations, looking for those significant to the VM:
1095 static void parse_annotations(const ConstantPool* const cp,
1096                               const u1* buffer, int limit,
1097                               AnnotationCollector* coll,
1098                               ClassLoaderData* loader_data,
1099                               const bool can_access_vm_annotations) {
1100 
1101   assert(cp != nullptr, "invariant");
1102   assert(buffer != nullptr, "invariant");
1103   assert(coll != nullptr, "invariant");
1104   assert(loader_data != nullptr, "invariant");
1105 
1106   // annotations := do(nann:u2) {annotation}
1107   int index = 2; // read nann
1108   if (index >= limit)  return;
1109   int nann = Bytes::get_Java_u2((address)buffer + index - 2);
1110   enum {  // initial annotation layout
1111     atype_off = 0,      // utf8 such as 'Ljava/lang/annotation/Retention;'
1112     count_off = 2,      // u2   such as 1 (one value)
1113     member_off = 4,     // utf8 such as 'value'
1114     tag_off = 6,        // u1   such as 'c' (type) or 'e' (enum)
1115     e_tag_val = 'e',
1116     e_type_off = 7,   // utf8 such as 'Ljava/lang/annotation/RetentionPolicy;'
1117     e_con_off = 9,    // utf8 payload, such as 'SOURCE', 'CLASS', 'RUNTIME'
1118     e_size = 11,     // end of 'e' annotation
1119     c_tag_val = 'c',    // payload is type
1120     c_con_off = 7,    // utf8 payload, such as 'I'
1121     c_size = 9,       // end of 'c' annotation
1122     s_tag_val = 's',    // payload is String
1123     s_con_off = 7,    // utf8 payload, such as 'Ljava/lang/String;'
1124     s_size = 9,
1125     b_tag_val = 'Z',  // payload is boolean
1126     min_size = 6        // smallest possible size (zero members)
1127   };
1128   // Cannot add min_size to index in case of overflow MAX_INT
1129   while ((--nann) >= 0 && (index - 2 <= limit - min_size)) {
1130     int index0 = index;
1131     index = skip_annotation(buffer, limit, index);
1132     const u1* const abase = buffer + index0;
1133     const int atype = Bytes::get_Java_u2((address)abase + atype_off);
1134     const int count = Bytes::get_Java_u2((address)abase + count_off);
1135     const Symbol* const aname = check_symbol_at(cp, atype);
1136     if (aname == nullptr)  break;  // invalid annotation name
1137     const Symbol* member = nullptr;
1138     if (count >= 1) {
1139       const int member_index = Bytes::get_Java_u2((address)abase + member_off);
1140       member = check_symbol_at(cp, member_index);
1141       if (member == nullptr)  break;  // invalid member name
1142     }
1143 
1144     // Here is where parsing particular annotations will take place.
1145     AnnotationCollector::ID id = coll->annotation_index(loader_data, aname, can_access_vm_annotations);
1146     if (AnnotationCollector::_unknown == id)  continue;
1147     coll->set_annotation(id);
1148     if (AnnotationCollector::_java_lang_Deprecated == id) {
1149       // @Deprecated can specify forRemoval=true, which we need
1150       // to record for JFR to use. If the annotation is not well-formed
1151       // then we may not be able to determine that.
1152       const u1* offset = abase + member_off;
1153       // There are only 2 members in @Deprecated.
1154       int n_members = MIN2(count, 2);
1155       for (int i = 0; i < n_members; ++i) {
1156         int member_index = Bytes::get_Java_u2((address)offset);
1157         offset += 2;
1158         member = check_symbol_at(cp, member_index);
1159         if (member == vmSymbols::since() &&
1160             (*((address)offset) == s_tag_val)) {
1161           // Found `since` first so skip over it
1162           offset += 3;
1163         }
1164         else if (member == vmSymbols::for_removal() &&
1165                  (*((address)offset) == b_tag_val)) {
1166           const u2 boolean_value_index = Bytes::get_Java_u2((address)offset + 1);
1167           // No guarantee the entry is valid so check it refers to an int in the CP.
1168           if (cp->is_within_bounds(boolean_value_index) &&
1169               cp->tag_at(boolean_value_index).is_int() &&
1170               cp->int_at(boolean_value_index) == 1) {
1171             // forRemoval == true
1172             coll->set_annotation(AnnotationCollector::_java_lang_Deprecated_for_removal);
1173           }
1174           break; // no need to check further
1175         }
1176         else {
1177           // This @Deprecated annotation is malformed so we don't try to
1178           // determine whether forRemoval is set.
1179           break;
1180         }
1181       }
1182       continue; // proceed to next annotation
1183     }
1184 
1185     if (AnnotationCollector::_jdk_internal_vm_annotation_Contended == id) {
1186       // @Contended can optionally specify the contention group.
1187       //
1188       // Contended group defines the equivalence class over the fields:
1189       // the fields within the same contended group are not treated distinct.
1190       // The only exception is default group, which does not incur the
1191       // equivalence. Naturally, contention group for classes is meaningless.
1192       //
1193       // While the contention group is specified as String, annotation
1194       // values are already interned, and we might as well use the constant
1195       // pool index as the group tag.
1196       //
1197       u2 group_index = 0; // default contended group
1198       if (count == 1
1199         && s_size == (index - index0)  // match size
1200         && s_tag_val == *(abase + tag_off)
1201         && member == vmSymbols::value_name()) {
1202         group_index = Bytes::get_Java_u2((address)abase + s_con_off);
1203         // No guarantee the group_index is valid so check it refers to a
1204         // symbol in the CP.
1205         if (cp->is_within_bounds(group_index) &&
1206             cp->tag_at(group_index).is_utf8()) {
1207           // Seems valid, so check for empty string and reset
1208           if (cp->symbol_at(group_index)->utf8_length() == 0) {
1209             group_index = 0; // default contended group
1210           }
1211         } else {
1212           // Not valid so use the default
1213           group_index = 0;
1214         }
1215       }
1216       coll->set_contended_group(group_index);
1217       continue; // proceed to next annotation
1218     }
1219   }
1220 }
1221 
1222 
1223 // Parse attributes for a field.
1224 void ClassFileParser::parse_field_attributes(const ClassFileStream* const cfs,
1225                                              u2 attributes_count,
1226                                              bool is_static, u2 signature_index,
1227                                              u2* const constantvalue_index_addr,
1228                                              bool* const is_synthetic_addr,
1229                                              u2* const generic_signature_index_addr,
1230                                              ClassFileParser::FieldAnnotationCollector* parsed_annotations,
1231                                              TRAPS) {
1232   assert(cfs != nullptr, "invariant");
1233   assert(constantvalue_index_addr != nullptr, "invariant");
1234   assert(is_synthetic_addr != nullptr, "invariant");
1235   assert(generic_signature_index_addr != nullptr, "invariant");
1236   assert(parsed_annotations != nullptr, "invariant");
1237   assert(attributes_count > 0, "attributes_count should be greater than 0");
1238 
1239   u2 constantvalue_index = 0;
1240   u2 generic_signature_index = 0;
1241   bool is_synthetic = false;
1242   const u1* runtime_visible_annotations = nullptr;
1243   int runtime_visible_annotations_length = 0;
1244   const u1* runtime_visible_type_annotations = nullptr;
1245   int runtime_visible_type_annotations_length = 0;
1246   bool runtime_invisible_annotations_exists = false;
1247   bool runtime_invisible_type_annotations_exists = false;
1248   const ConstantPool* const cp = _cp;
1249 
1250   while (attributes_count--) {
1251     cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
1252     const u2 attribute_name_index = cfs->get_u2_fast();
1253     const u4 attribute_length = cfs->get_u4_fast();
1254     guarantee_property(valid_symbol_at(attribute_name_index),
1255                        "Invalid field attribute index %u in class file %s",
1256                        attribute_name_index,
1257                        CHECK);
1258 
1259     const Symbol* const attribute_name = cp->symbol_at(attribute_name_index);
1260     if (is_static && attribute_name == vmSymbols::tag_constant_value()) {
1261       // ignore if non-static
1262       if (constantvalue_index != 0) {
1263         classfile_parse_error("Duplicate ConstantValue attribute in class file %s", THREAD);
1264         return;
1265       }
1266       guarantee_property(
1267         attribute_length == 2,
1268         "Invalid ConstantValue field attribute length %u in class file %s",
1269         attribute_length, CHECK);
1270 
1271       constantvalue_index = cfs->get_u2(CHECK);
1272       if (_need_verify) {
1273         verify_constantvalue(cp, constantvalue_index, signature_index, CHECK);
1274       }
1275     } else if (attribute_name == vmSymbols::tag_synthetic()) {
1276       if (attribute_length != 0) {
1277         classfile_parse_error(
1278           "Invalid Synthetic field attribute length %u in class file %s",
1279           attribute_length, THREAD);
1280         return;
1281       }
1282       is_synthetic = true;
1283     } else if (attribute_name == vmSymbols::tag_deprecated()) { // 4276120
1284       if (attribute_length != 0) {
1285         classfile_parse_error(
1286           "Invalid Deprecated field attribute length %u in class file %s",
1287           attribute_length, THREAD);
1288         return;
1289       }
1290     } else if (_major_version >= JAVA_1_5_VERSION) {
1291       if (attribute_name == vmSymbols::tag_signature()) {
1292         if (generic_signature_index != 0) {
1293           classfile_parse_error(
1294             "Multiple Signature attributes for field in class file %s", THREAD);
1295           return;
1296         }
1297         if (attribute_length != 2) {
1298           classfile_parse_error(
1299             "Wrong size %u for field's Signature attribute in class file %s",
1300             attribute_length, THREAD);
1301           return;
1302         }
1303         generic_signature_index = parse_generic_signature_attribute(cfs, CHECK);
1304       } else if (attribute_name == vmSymbols::tag_runtime_visible_annotations()) {
1305         if (runtime_visible_annotations != nullptr) {
1306           classfile_parse_error(
1307             "Multiple RuntimeVisibleAnnotations attributes for field in class file %s", THREAD);
1308           return;
1309         }
1310         runtime_visible_annotations_length = attribute_length;
1311         runtime_visible_annotations = cfs->current();
1312         assert(runtime_visible_annotations != nullptr, "null visible annotations");
1313         cfs->guarantee_more(runtime_visible_annotations_length, CHECK);
1314         parse_annotations(cp,
1315                           runtime_visible_annotations,
1316                           runtime_visible_annotations_length,
1317                           parsed_annotations,
1318                           _loader_data,
1319                           _can_access_vm_annotations);
1320         cfs->skip_u1_fast(runtime_visible_annotations_length);
1321       } else if (attribute_name == vmSymbols::tag_runtime_invisible_annotations()) {
1322         if (runtime_invisible_annotations_exists) {
1323           classfile_parse_error(
1324             "Multiple RuntimeInvisibleAnnotations attributes for field in class file %s", THREAD);
1325           return;
1326         }
1327         runtime_invisible_annotations_exists = true;
1328         cfs->skip_u1(attribute_length, CHECK);
1329       } else if (attribute_name == vmSymbols::tag_runtime_visible_type_annotations()) {
1330         if (runtime_visible_type_annotations != nullptr) {
1331           classfile_parse_error(
1332             "Multiple RuntimeVisibleTypeAnnotations attributes for field in class file %s", THREAD);
1333           return;
1334         }
1335         runtime_visible_type_annotations_length = attribute_length;
1336         runtime_visible_type_annotations = cfs->current();
1337         assert(runtime_visible_type_annotations != nullptr, "null visible type annotations");
1338         cfs->skip_u1(runtime_visible_type_annotations_length, CHECK);
1339       } else if (attribute_name == vmSymbols::tag_runtime_invisible_type_annotations()) {
1340         if (runtime_invisible_type_annotations_exists) {
1341           classfile_parse_error(
1342             "Multiple RuntimeInvisibleTypeAnnotations attributes for field in class file %s", THREAD);
1343           return;
1344         } else {
1345           runtime_invisible_type_annotations_exists = true;
1346         }
1347         cfs->skip_u1(attribute_length, CHECK);
1348       } else {
1349         cfs->skip_u1(attribute_length, CHECK);  // Skip unknown attributes
1350       }
1351     } else {
1352       cfs->skip_u1(attribute_length, CHECK);  // Skip unknown attributes
1353     }
1354   }
1355 
1356   *constantvalue_index_addr = constantvalue_index;
1357   *is_synthetic_addr = is_synthetic;
1358   *generic_signature_index_addr = generic_signature_index;
1359   AnnotationArray* a = allocate_annotations(runtime_visible_annotations,
1360                                             runtime_visible_annotations_length,
1361                                             CHECK);
1362   parsed_annotations->set_field_annotations(a);
1363   a = allocate_annotations(runtime_visible_type_annotations,
1364                            runtime_visible_type_annotations_length,
1365                            CHECK);
1366   parsed_annotations->set_field_type_annotations(a);
1367   return;
1368 }
1369 
1370 
1371 // Side-effects: populates the _fields, _fields_annotations,
1372 // _fields_type_annotations fields
1373 void ClassFileParser::parse_fields(const ClassFileStream* const cfs,
1374                                    bool is_interface,
1375                                    ConstantPool* cp,
1376                                    const int cp_size,
1377                                    u2* const java_fields_count_ptr,
1378                                    TRAPS) {
1379 
1380   assert(cfs != nullptr, "invariant");
1381   assert(cp != nullptr, "invariant");
1382   assert(java_fields_count_ptr != nullptr, "invariant");
1383 
1384   assert(nullptr == _fields_annotations, "invariant");
1385   assert(nullptr == _fields_type_annotations, "invariant");
1386 
1387   cfs->guarantee_more(2, CHECK);  // length
1388   const u2 length = cfs->get_u2_fast();
1389   *java_fields_count_ptr = length;
1390 
1391   int num_injected = 0;
1392   const InjectedField* const injected = JavaClasses::get_injected(_class_name,
1393                                                                   &num_injected);
1394   const int total_fields = length + num_injected;
1395 
1396   // Allocate a temporary resource array to collect field data.
1397   // After parsing all fields, data are stored in a UNSIGNED5 compressed stream.
1398   _temp_field_info = new GrowableArray<FieldInfo>(total_fields);
1399 
1400   ResourceMark rm(THREAD);
1401   for (int n = 0; n < length; n++) {
1402     // access_flags, name_index, descriptor_index, attributes_count
1403     cfs->guarantee_more(8, CHECK);
1404 
1405     AccessFlags access_flags;
1406     const jint flags = cfs->get_u2_fast() & JVM_RECOGNIZED_FIELD_MODIFIERS;
1407     verify_legal_field_modifiers(flags, is_interface, CHECK);
1408     access_flags.set_flags(flags);
1409     FieldInfo::FieldFlags fieldFlags(0);
1410 
1411     const u2 name_index = cfs->get_u2_fast();
1412     guarantee_property(valid_symbol_at(name_index),
1413       "Invalid constant pool index %u for field name in class file %s",
1414       name_index, CHECK);
1415     const Symbol* const name = cp->symbol_at(name_index);
1416     verify_legal_field_name(name, CHECK);
1417 
1418     const u2 signature_index = cfs->get_u2_fast();
1419     guarantee_property(valid_symbol_at(signature_index),
1420       "Invalid constant pool index %u for field signature in class file %s",
1421       signature_index, CHECK);
1422     const Symbol* const sig = cp->symbol_at(signature_index);
1423     verify_legal_field_signature(name, sig, CHECK);
1424 
1425     u2 constantvalue_index = 0;
1426     bool is_synthetic = false;
1427     u2 generic_signature_index = 0;
1428     const bool is_static = access_flags.is_static();
1429     FieldAnnotationCollector parsed_annotations(_loader_data);
1430 
1431     const u2 attributes_count = cfs->get_u2_fast();
1432     if (attributes_count > 0) {
1433       parse_field_attributes(cfs,
1434                              attributes_count,
1435                              is_static,
1436                              signature_index,
1437                              &constantvalue_index,
1438                              &is_synthetic,
1439                              &generic_signature_index,
1440                              &parsed_annotations,
1441                              CHECK);
1442 
1443       if (parsed_annotations.field_annotations() != nullptr) {
1444         if (_fields_annotations == nullptr) {
1445           _fields_annotations = MetadataFactory::new_array<AnnotationArray*>(
1446                                              _loader_data, length, nullptr,
1447                                              CHECK);
1448         }
1449         _fields_annotations->at_put(n, parsed_annotations.field_annotations());
1450         parsed_annotations.set_field_annotations(nullptr);
1451       }
1452       if (parsed_annotations.field_type_annotations() != nullptr) {
1453         if (_fields_type_annotations == nullptr) {
1454           _fields_type_annotations =
1455             MetadataFactory::new_array<AnnotationArray*>(_loader_data,
1456                                                          length,
1457                                                          nullptr,
1458                                                          CHECK);
1459         }
1460         _fields_type_annotations->at_put(n, parsed_annotations.field_type_annotations());
1461         parsed_annotations.set_field_type_annotations(nullptr);
1462       }
1463 
1464       if (is_synthetic) {
1465         access_flags.set_is_synthetic();
1466       }
1467       if (generic_signature_index != 0) {
1468         fieldFlags.update_generic(true);
1469       }
1470     }
1471 
1472     const BasicType type = cp->basic_type_for_signature_at(signature_index);
1473 
1474     // Update number of static oop fields.
1475     if (is_static && is_reference_type(type)) {
1476       _static_oop_count++;
1477     }
1478 
1479     FieldInfo fi(access_flags, name_index, signature_index, constantvalue_index, fieldFlags);
1480     fi.set_index(n);
1481     if (fieldFlags.is_generic()) {
1482       fi.set_generic_signature_index(generic_signature_index);
1483     }
1484     parsed_annotations.apply_to(&fi);
1485     if (fi.field_flags().is_contended()) {
1486       _has_contended_fields = true;
1487     }
1488     _temp_field_info->append(fi);
1489   }
1490   assert(_temp_field_info->length() == length, "Must be");
1491 
1492   int index = length;
1493   if (num_injected != 0) {
1494     for (int n = 0; n < num_injected; n++) {
1495       // Check for duplicates
1496       if (injected[n].may_be_java) {
1497         const Symbol* const name      = injected[n].name();
1498         const Symbol* const signature = injected[n].signature();
1499         bool duplicate = false;
1500         for (int i = 0; i < length; i++) {
1501           const FieldInfo* const f = _temp_field_info->adr_at(i);
1502           if (name      == cp->symbol_at(f->name_index()) &&
1503               signature == cp->symbol_at(f->signature_index())) {
1504             // Symbol is desclared in Java so skip this one
1505             duplicate = true;
1506             break;
1507           }
1508         }
1509         if (duplicate) {
1510           // These will be removed from the field array at the end
1511           continue;
1512         }
1513       }
1514 
1515       // Injected field
1516       FieldInfo::FieldFlags fflags(0);
1517       fflags.update_injected(true);
1518       AccessFlags aflags;
1519       FieldInfo fi(aflags, (u2)(injected[n].name_index), (u2)(injected[n].signature_index), 0, fflags);
1520       fi.set_index(index);
1521       _temp_field_info->append(fi);
1522       index++;
1523     }
1524   }
1525 
1526   assert(_temp_field_info->length() == index, "Must be");
1527 
1528   if (_need_verify && length > 1) {
1529     // Check duplicated fields
1530     ResourceMark rm(THREAD);
1531     // Set containing name-signature pairs
1532     NameSigHashtable* names_and_sigs = new NameSigHashtable();
1533     for (int i = 0; i < _temp_field_info->length(); i++) {
1534       NameSigHash name_and_sig(_temp_field_info->adr_at(i)->name(_cp),
1535                                _temp_field_info->adr_at(i)->signature(_cp));
1536       // If no duplicates, add name/signature in hashtable names_and_sigs.
1537       if(!names_and_sigs->put(name_and_sig, 0)) {
1538         classfile_parse_error("Duplicate field name \"%s\" with signature \"%s\" in class file %s",
1539                                name_and_sig._name->as_C_string(), name_and_sig._sig->as_klass_external_name(), THREAD);
1540         return;
1541       }
1542     }
1543   }
1544 }
1545 
1546 
1547 const ClassFileParser::unsafe_u2* ClassFileParser::parse_exception_table(const ClassFileStream* const cfs,
1548                                                                          u4 code_length,
1549                                                                          u4 exception_table_length,
1550                                                                          TRAPS) {
1551   assert(cfs != nullptr, "invariant");
1552 
1553   const unsafe_u2* const exception_table_start = cfs->current();
1554   assert(exception_table_start != nullptr, "null exception table");
1555 
1556   cfs->guarantee_more(8 * exception_table_length, CHECK_NULL); // start_pc,
1557                                                                // end_pc,
1558                                                                // handler_pc,
1559                                                                // catch_type_index
1560 
1561   // Will check legal target after parsing code array in verifier.
1562   if (_need_verify) {
1563     for (unsigned int i = 0; i < exception_table_length; i++) {
1564       const u2 start_pc = cfs->get_u2_fast();
1565       const u2 end_pc = cfs->get_u2_fast();
1566       const u2 handler_pc = cfs->get_u2_fast();
1567       const u2 catch_type_index = cfs->get_u2_fast();
1568       guarantee_property((start_pc < end_pc) && (end_pc <= code_length),
1569                          "Illegal exception table range in class file %s",
1570                          CHECK_NULL);
1571       guarantee_property(handler_pc < code_length,
1572                          "Illegal exception table handler in class file %s",
1573                          CHECK_NULL);
1574       if (catch_type_index != 0) {
1575         guarantee_property(valid_klass_reference_at(catch_type_index),
1576                            "Catch type in exception table has bad constant type in class file %s", CHECK_NULL);
1577       }
1578     }
1579   } else {
1580     cfs->skip_u2_fast(exception_table_length * 4);
1581   }
1582   return exception_table_start;
1583 }
1584 
1585 void ClassFileParser::parse_linenumber_table(u4 code_attribute_length,
1586                                              u4 code_length,
1587                                              CompressedLineNumberWriteStream**const write_stream,
1588                                              TRAPS) {
1589 
1590   const ClassFileStream* const cfs = _stream;
1591   unsigned int num_entries = cfs->get_u2(CHECK);
1592 
1593   // Each entry is a u2 start_pc, and a u2 line_number
1594   const unsigned int length_in_bytes = num_entries * (sizeof(u2) * 2);
1595 
1596   // Verify line number attribute and table length
1597   guarantee_property(
1598     code_attribute_length == sizeof(u2) + length_in_bytes,
1599     "LineNumberTable attribute has wrong length in class file %s", CHECK);
1600 
1601   cfs->guarantee_more(length_in_bytes, CHECK);
1602 
1603   if ((*write_stream) == nullptr) {
1604     if (length_in_bytes > fixed_buffer_size) {
1605       (*write_stream) = new CompressedLineNumberWriteStream(length_in_bytes);
1606     } else {
1607       (*write_stream) = new CompressedLineNumberWriteStream(
1608         _linenumbertable_buffer, fixed_buffer_size);
1609     }
1610   }
1611 
1612   while (num_entries-- > 0) {
1613     const u2 bci  = cfs->get_u2_fast(); // start_pc
1614     const u2 line = cfs->get_u2_fast(); // line_number
1615     guarantee_property(bci < code_length,
1616         "Invalid pc in LineNumberTable in class file %s", CHECK);
1617     (*write_stream)->write_pair(bci, line);
1618   }
1619 }
1620 
1621 
1622 class LVT_Hash : public AllStatic {
1623  public:
1624 
1625   static bool equals(LocalVariableTableElement const& e0, LocalVariableTableElement const& e1) {
1626   /*
1627    * 3-tuple start_bci/length/slot has to be unique key,
1628    * so the following comparison seems to be redundant:
1629    *       && elem->name_cp_index == entry->_elem->name_cp_index
1630    */
1631     return (e0.start_bci     == e1.start_bci &&
1632             e0.length        == e1.length &&
1633             e0.name_cp_index == e1.name_cp_index &&
1634             e0.slot          == e1.slot);
1635   }
1636 
1637   static unsigned int hash(LocalVariableTableElement const& e0) {
1638     unsigned int raw_hash = e0.start_bci;
1639 
1640     raw_hash = e0.length        + raw_hash * 37;
1641     raw_hash = e0.name_cp_index + raw_hash * 37;
1642     raw_hash = e0.slot          + raw_hash * 37;
1643 
1644     return raw_hash;
1645   }
1646 };
1647 
1648 
1649 // Class file LocalVariableTable elements.
1650 class Classfile_LVT_Element {
1651  public:
1652   u2 start_bci;
1653   u2 length;
1654   u2 name_cp_index;
1655   u2 descriptor_cp_index;
1656   u2 slot;
1657 };
1658 
1659 static void copy_lvt_element(const Classfile_LVT_Element* const src,
1660                              LocalVariableTableElement* const lvt) {
1661   lvt->start_bci           = Bytes::get_Java_u2((u1*) &src->start_bci);
1662   lvt->length              = Bytes::get_Java_u2((u1*) &src->length);
1663   lvt->name_cp_index       = Bytes::get_Java_u2((u1*) &src->name_cp_index);
1664   lvt->descriptor_cp_index = Bytes::get_Java_u2((u1*) &src->descriptor_cp_index);
1665   lvt->signature_cp_index  = 0;
1666   lvt->slot                = Bytes::get_Java_u2((u1*) &src->slot);
1667 }
1668 
1669 // Function is used to parse both attributes:
1670 // LocalVariableTable (LVT) and LocalVariableTypeTable (LVTT)
1671 const ClassFileParser::unsafe_u2* ClassFileParser::parse_localvariable_table(const ClassFileStream* cfs,
1672                                                                              u4 code_length,
1673                                                                              u2 max_locals,
1674                                                                              u4 code_attribute_length,
1675                                                                              u2* const localvariable_table_length,
1676                                                                              bool isLVTT,
1677                                                                              TRAPS) {
1678   const char* const tbl_name = (isLVTT) ? "LocalVariableTypeTable" : "LocalVariableTable";
1679   *localvariable_table_length = cfs->get_u2(CHECK_NULL);
1680   const unsigned int size = checked_cast<unsigned>(
1681     (*localvariable_table_length) * sizeof(Classfile_LVT_Element) / sizeof(u2));
1682 
1683   const ConstantPool* const cp = _cp;
1684 
1685   // Verify local variable table attribute has right length
1686   if (_need_verify) {
1687     guarantee_property(code_attribute_length == (sizeof(*localvariable_table_length) + size * sizeof(u2)),
1688                        "%s has wrong length in class file %s", tbl_name, CHECK_NULL);
1689   }
1690 
1691   const unsafe_u2* const localvariable_table_start = cfs->current();
1692   assert(localvariable_table_start != nullptr, "null local variable table");
1693   if (!_need_verify) {
1694     cfs->skip_u2_fast(size);
1695   } else {
1696     cfs->guarantee_more(size * 2, CHECK_NULL);
1697     for(int i = 0; i < (*localvariable_table_length); i++) {
1698       const u2 start_pc = cfs->get_u2_fast();
1699       const u2 length = cfs->get_u2_fast();
1700       const u2 name_index = cfs->get_u2_fast();
1701       const u2 descriptor_index = cfs->get_u2_fast();
1702       const u2 index = cfs->get_u2_fast();
1703       // Assign to a u4 to avoid overflow
1704       const u4 end_pc = (u4)start_pc + (u4)length;
1705 
1706       if (start_pc >= code_length) {
1707         classfile_parse_error(
1708           "Invalid start_pc %u in %s in class file %s",
1709           start_pc, tbl_name, THREAD);
1710         return nullptr;
1711       }
1712       if (end_pc > code_length) {
1713         classfile_parse_error(
1714           "Invalid length %u in %s in class file %s",
1715           length, tbl_name, THREAD);
1716         return nullptr;
1717       }
1718       const int cp_size = cp->length();
1719       guarantee_property(valid_symbol_at(name_index),
1720         "Name index %u in %s has bad constant type in class file %s",
1721         name_index, tbl_name, CHECK_NULL);
1722       guarantee_property(valid_symbol_at(descriptor_index),
1723         "Signature index %u in %s has bad constant type in class file %s",
1724         descriptor_index, tbl_name, CHECK_NULL);
1725 
1726       const Symbol* const name = cp->symbol_at(name_index);
1727       const Symbol* const sig = cp->symbol_at(descriptor_index);
1728       verify_legal_field_name(name, CHECK_NULL);
1729       u2 extra_slot = 0;
1730       if (!isLVTT) {
1731         verify_legal_field_signature(name, sig, CHECK_NULL);
1732 
1733         // 4894874: check special cases for double and long local variables
1734         if (sig == vmSymbols::type_signature(T_DOUBLE) ||
1735             sig == vmSymbols::type_signature(T_LONG)) {
1736           extra_slot = 1;
1737         }
1738       }
1739       guarantee_property((index + extra_slot) < max_locals,
1740                           "Invalid index %u in %s in class file %s",
1741                           index, tbl_name, CHECK_NULL);
1742     }
1743   }
1744   return localvariable_table_start;
1745 }
1746 
1747 static const u1* parse_stackmap_table(const ClassFileStream* const cfs,
1748                                       u4 code_attribute_length,
1749                                       TRAPS) {
1750   assert(cfs != nullptr, "invariant");
1751 
1752   if (0 == code_attribute_length) {
1753     return nullptr;
1754   }
1755 
1756   const u1* const stackmap_table_start = cfs->current();
1757   assert(stackmap_table_start != nullptr, "null stackmap table");
1758 
1759   // check code_attribute_length
1760   cfs->skip_u1(code_attribute_length, CHECK_NULL);
1761 
1762   return stackmap_table_start;
1763 }
1764 
1765 const ClassFileParser::unsafe_u2* ClassFileParser::parse_checked_exceptions(const ClassFileStream* const cfs,
1766                                                                             u2* const checked_exceptions_length,
1767                                                                             u4 method_attribute_length,
1768                                                                             TRAPS) {
1769   assert(cfs != nullptr, "invariant");
1770   assert(checked_exceptions_length != nullptr, "invariant");
1771 
1772   cfs->guarantee_more(2, CHECK_NULL);  // checked_exceptions_length
1773   *checked_exceptions_length = cfs->get_u2_fast();
1774   const unsigned int size =
1775     (*checked_exceptions_length) * sizeof(CheckedExceptionElement) / sizeof(u2);
1776   const unsafe_u2* const checked_exceptions_start = cfs->current();
1777   assert(checked_exceptions_start != nullptr, "null checked exceptions");
1778   if (!_need_verify) {
1779     cfs->skip_u2_fast(size);
1780   } else {
1781     // Verify each value in the checked exception table
1782     u2 checked_exception;
1783     const u2 len = *checked_exceptions_length;
1784     cfs->guarantee_more(2 * len, CHECK_NULL);
1785     for (int i = 0; i < len; i++) {
1786       checked_exception = cfs->get_u2_fast();
1787       guarantee_property(
1788         valid_klass_reference_at(checked_exception),
1789         "Exception name has bad type at constant pool %u in class file %s",
1790         checked_exception, CHECK_NULL);
1791     }
1792   }
1793   // check exceptions attribute length
1794   if (_need_verify) {
1795     guarantee_property(method_attribute_length == (sizeof(*checked_exceptions_length) +
1796                                                    sizeof(u2) * size),
1797                       "Exceptions attribute has wrong length in class file %s", CHECK_NULL);
1798   }
1799   return checked_exceptions_start;
1800 }
1801 
1802 void ClassFileParser::throwIllegalSignature(const char* type,
1803                                             const Symbol* name,
1804                                             const Symbol* sig,
1805                                             TRAPS) const {
1806   assert(name != nullptr, "invariant");
1807   assert(sig != nullptr, "invariant");
1808 
1809   ResourceMark rm(THREAD);
1810   // Names are all known to be < 64k so we know this formatted message is not excessively large.
1811   Exceptions::fthrow(THREAD_AND_LOCATION,
1812       vmSymbols::java_lang_ClassFormatError(),
1813       "%s \"%s\" in class %s has illegal signature \"%s\"", type,
1814       name->as_C_string(), _class_name->as_C_string(), sig->as_C_string());
1815 }
1816 
1817 AnnotationCollector::ID
1818 AnnotationCollector::annotation_index(const ClassLoaderData* loader_data,
1819                                       const Symbol* name,
1820                                       const bool can_access_vm_annotations) {
1821   const vmSymbolID sid = vmSymbols::find_sid(name);
1822   // Privileged code can use all annotations.  Other code silently drops some.
1823   const bool privileged = loader_data->is_boot_class_loader_data() ||
1824                           loader_data->is_platform_class_loader_data() ||
1825                           can_access_vm_annotations;
1826   switch (sid) {
1827     case VM_SYMBOL_ENUM_NAME(reflect_CallerSensitive_signature): {
1828       if (_location != _in_method)  break;  // only allow for methods
1829       if (!privileged)              break;  // only allow in privileged code
1830       return _method_CallerSensitive;
1831     }
1832     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ForceInline_signature): {
1833       if (_location != _in_method)  break;  // only allow for methods
1834       if (!privileged)              break;  // only allow in privileged code
1835       return _method_ForceInline;
1836     }
1837     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_DontInline_signature): {
1838       if (_location != _in_method)  break;  // only allow for methods
1839       if (!privileged)              break;  // only allow in privileged code
1840       return _method_DontInline;
1841     }
1842     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ChangesCurrentThread_signature): {
1843       if (_location != _in_method)  break;  // only allow for methods
1844       if (!privileged)              break;  // only allow in privileged code
1845       return _method_ChangesCurrentThread;
1846     }
1847     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_JvmtiHideEvents_signature): {
1848       if (_location != _in_method)  break;  // only allow for methods
1849       if (!privileged)              break;  // only allow in privileged code
1850       return _method_JvmtiHideEvents;
1851     }
1852     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_JvmtiMountTransition_signature): {
1853       if (_location != _in_method)  break;  // only allow for methods
1854       if (!privileged)              break;  // only allow in privileged code
1855       return _method_JvmtiMountTransition;
1856     }
1857     case VM_SYMBOL_ENUM_NAME(java_lang_invoke_InjectedProfile_signature): {
1858       if (_location != _in_method)  break;  // only allow for methods
1859       if (!privileged)              break;  // only allow in privileged code
1860       return _method_InjectedProfile;
1861     }
1862     case VM_SYMBOL_ENUM_NAME(java_lang_invoke_LambdaForm_Compiled_signature): {
1863       if (_location != _in_method)  break;  // only allow for methods
1864       if (!privileged)              break;  // only allow in privileged code
1865       return _method_LambdaForm_Compiled;
1866     }
1867     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Hidden_signature): {
1868       if (_location != _in_method)  break;  // only allow for methods
1869       if (!privileged)              break;  // only allow in privileged code
1870       return _method_Hidden;
1871     }
1872     case VM_SYMBOL_ENUM_NAME(jdk_internal_misc_Scoped_signature): {
1873       if (_location != _in_method)  break;  // only allow for methods
1874       if (!privileged)              break;  // only allow in privileged code
1875       return _method_Scoped;
1876     }
1877     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_IntrinsicCandidate_signature): {
1878       if (_location != _in_method)  break;  // only allow for methods
1879       if (!privileged)              break;  // only allow in privileged code
1880       return _method_IntrinsicCandidate;
1881     }
1882     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Stable_signature): {
1883       if (_location != _in_field)   break;  // only allow for fields
1884       if (!privileged)              break;  // only allow in privileged code
1885       return _field_Stable;
1886     }
1887     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_TrustFinalFields_signature): {
1888       if (_location != _in_class)   break;  // only allow for classes
1889       if (!privileged)              break;  // only allow in privileged code
1890       return _jdk_internal_vm_annotation_TrustFinalFields;
1891     }
1892     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Contended_signature): {
1893       if (_location != _in_field && _location != _in_class) {
1894         break;  // only allow for fields and classes
1895       }
1896       if (!EnableContended || (RestrictContended && !privileged)) {
1897         break;  // honor privileges
1898       }
1899       return _jdk_internal_vm_annotation_Contended;
1900     }
1901     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ReservedStackAccess_signature): {
1902       if (_location != _in_method)  break;  // only allow for methods
1903       if (RestrictReservedStack && !privileged) break; // honor privileges
1904       return _jdk_internal_vm_annotation_ReservedStackAccess;
1905     }
1906     case VM_SYMBOL_ENUM_NAME(jdk_internal_ValueBased_signature): {
1907       if (_location != _in_class)   break;  // only allow for classes
1908       if (!privileged)              break;  // only allow in privileged code
1909       return _jdk_internal_ValueBased;
1910     }
1911     case VM_SYMBOL_ENUM_NAME(java_lang_Deprecated): {
1912       return _java_lang_Deprecated;
1913     }
1914     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_AOTSafeClassInitializer_signature): {
1915       if (_location != _in_class)   break;  // only allow for classes
1916       if (!privileged)              break;  // only allow in privileged code
1917       return _jdk_internal_vm_annotation_AOTSafeClassInitializer;
1918     }
1919     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_AOTRuntimeSetup_signature): {
1920       if (_location != _in_method)  break;  // only allow for methods
1921       if (!privileged)              break;  // only allow in privileged code
1922       return _method_AOTRuntimeSetup;
1923     }
1924     default: {
1925       break;
1926     }
1927   }
1928   return AnnotationCollector::_unknown;
1929 }
1930 
1931 void ClassFileParser::FieldAnnotationCollector::apply_to(FieldInfo* f) {
1932   if (is_contended())
1933     // Setting the contended group also sets the contended bit in field flags
1934     f->set_contended_group(contended_group());
1935   if (is_stable())
1936     (f->field_flags_addr())->update_stable(true);
1937 }
1938 
1939 ClassFileParser::FieldAnnotationCollector::~FieldAnnotationCollector() {
1940   // If there's an error deallocate metadata for field annotations
1941   MetadataFactory::free_array<u1>(_loader_data, _field_annotations);
1942   MetadataFactory::free_array<u1>(_loader_data, _field_type_annotations);
1943 }
1944 
1945 void MethodAnnotationCollector::apply_to(const methodHandle& m) {
1946   if (has_annotation(_method_CallerSensitive))
1947     m->set_caller_sensitive();
1948   if (has_annotation(_method_ForceInline))
1949     m->set_force_inline();
1950   if (has_annotation(_method_DontInline))
1951     m->set_dont_inline();
1952   if (has_annotation(_method_ChangesCurrentThread))
1953     m->set_changes_current_thread();
1954   if (has_annotation(_method_JvmtiHideEvents))
1955     m->set_jvmti_hide_events();
1956   if (has_annotation(_method_JvmtiMountTransition))
1957     m->set_jvmti_mount_transition();
1958   if (has_annotation(_method_InjectedProfile))
1959     m->set_has_injected_profile();
1960   if (has_annotation(_method_LambdaForm_Compiled) && m->intrinsic_id() == vmIntrinsics::_none)
1961     m->set_intrinsic_id(vmIntrinsics::_compiledLambdaForm);
1962   if (has_annotation(_method_Hidden))
1963     m->set_is_hidden();
1964   if (has_annotation(_method_Scoped))
1965     m->set_scoped();
1966   if (has_annotation(_method_IntrinsicCandidate) && !m->is_synthetic())
1967     m->set_intrinsic_candidate();
1968   if (has_annotation(_jdk_internal_vm_annotation_ReservedStackAccess))
1969     m->set_has_reserved_stack_access();
1970   if (has_annotation(_java_lang_Deprecated))
1971     m->set_deprecated();
1972   if (has_annotation(_java_lang_Deprecated_for_removal))
1973     m->set_deprecated_for_removal();
1974 }
1975 
1976 void ClassFileParser::ClassAnnotationCollector::apply_to(InstanceKlass* ik) {
1977   assert(ik != nullptr, "invariant");
1978   if (has_annotation(_jdk_internal_vm_annotation_Contended)) {
1979     ik->set_is_contended(is_contended());
1980   }
1981   if (has_annotation(_jdk_internal_ValueBased)) {
1982     ik->set_has_value_based_class_annotation();
1983     if (DiagnoseSyncOnValueBasedClasses) {
1984       ik->set_is_value_based();
1985     }
1986   }
1987   if (has_annotation(_java_lang_Deprecated)) {
1988     Array<Method*>* methods = ik->methods();
1989     int length = ik->methods()->length();
1990     for (int i = 0; i < length; i++) {
1991       Method* m = methods->at(i);
1992       m->set_deprecated();
1993     }
1994   }
1995   if (has_annotation(_java_lang_Deprecated_for_removal)) {
1996     Array<Method*>* methods = ik->methods();
1997     int length = ik->methods()->length();
1998     for (int i = 0; i < length; i++) {
1999       Method* m = methods->at(i);
2000       m->set_deprecated_for_removal();
2001     }
2002   }
2003   if (has_annotation(_jdk_internal_vm_annotation_AOTSafeClassInitializer)) {
2004     ik->set_has_aot_safe_initializer();
2005   }
2006   if (has_annotation(_jdk_internal_vm_annotation_TrustFinalFields)) {
2007     ik->set_trust_final_fields(true);
2008   }
2009 }
2010 
2011 #define MAX_ARGS_SIZE 255
2012 #define MAX_CODE_SIZE 65535
2013 #define INITIAL_MAX_LVT_NUMBER 256
2014 
2015 /* Copy class file LVT's/LVTT's into the HotSpot internal LVT.
2016  *
2017  * Rules for LVT's and LVTT's are:
2018  *   - There can be any number of LVT's and LVTT's.
2019  *   - If there are n LVT's, it is the same as if there was just
2020  *     one LVT containing all the entries from the n LVT's.
2021  *   - There may be no more than one LVT entry per local variable.
2022  *     Two LVT entries are 'equal' if these fields are the same:
2023  *        start_pc, length, name, slot
2024  *   - There may be no more than one LVTT entry per each LVT entry.
2025  *     Each LVTT entry has to match some LVT entry.
2026  *   - HotSpot internal LVT keeps natural ordering of class file LVT entries.
2027  */
2028 void ClassFileParser::copy_localvariable_table(const ConstMethod* cm,
2029                                                int lvt_cnt,
2030                                                u2* const localvariable_table_length,
2031                                                const unsafe_u2** const localvariable_table_start,
2032                                                int lvtt_cnt,
2033                                                u2* const localvariable_type_table_length,
2034                                                const unsafe_u2** const localvariable_type_table_start,
2035                                                TRAPS) {
2036 
2037   ResourceMark rm(THREAD);
2038 
2039   typedef HashTable<LocalVariableTableElement, LocalVariableTableElement*,
2040                             256, AnyObj::RESOURCE_AREA, mtInternal,
2041                             &LVT_Hash::hash, &LVT_Hash::equals> LVT_HashTable;
2042 
2043   LVT_HashTable* const table = new LVT_HashTable();
2044 
2045   // To fill LocalVariableTable in
2046   const Classfile_LVT_Element* cf_lvt;
2047   LocalVariableTableElement* lvt = cm->localvariable_table_start();
2048 
2049   for (int tbl_no = 0; tbl_no < lvt_cnt; tbl_no++) {
2050     cf_lvt = (Classfile_LVT_Element *) localvariable_table_start[tbl_no];
2051     for (int idx = 0; idx < localvariable_table_length[tbl_no]; idx++, lvt++) {
2052       copy_lvt_element(&cf_lvt[idx], lvt);
2053       // If no duplicates, add LVT elem in hashtable.
2054       if (table->put(*lvt, lvt) == false
2055           && _need_verify
2056           && _major_version >= JAVA_1_5_VERSION) {
2057         classfile_parse_error("Duplicated LocalVariableTable attribute "
2058                               "entry for '%s' in class file %s",
2059                                _cp->symbol_at(lvt->name_cp_index)->as_utf8(),
2060                                THREAD);
2061         return;
2062       }
2063     }
2064   }
2065 
2066   // To merge LocalVariableTable and LocalVariableTypeTable
2067   const Classfile_LVT_Element* cf_lvtt;
2068   LocalVariableTableElement lvtt_elem;
2069 
2070   for (int tbl_no = 0; tbl_no < lvtt_cnt; tbl_no++) {
2071     cf_lvtt = (Classfile_LVT_Element *) localvariable_type_table_start[tbl_no];
2072     for (int idx = 0; idx < localvariable_type_table_length[tbl_no]; idx++) {
2073       copy_lvt_element(&cf_lvtt[idx], &lvtt_elem);
2074       LocalVariableTableElement** entry = table->get(lvtt_elem);
2075       if (entry == nullptr) {
2076         if (_need_verify) {
2077           classfile_parse_error("LVTT entry for '%s' in class file %s "
2078                                 "does not match any LVT entry",
2079                                  _cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(),
2080                                  THREAD);
2081           return;
2082         }
2083       } else if ((*entry)->signature_cp_index != 0 && _need_verify) {
2084         classfile_parse_error("Duplicated LocalVariableTypeTable attribute "
2085                               "entry for '%s' in class file %s",
2086                                _cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(),
2087                                THREAD);
2088         return;
2089       } else {
2090         // to add generic signatures into LocalVariableTable
2091         (*entry)->signature_cp_index = lvtt_elem.descriptor_cp_index;
2092       }
2093     }
2094   }
2095 }
2096 
2097 
2098 void ClassFileParser::copy_method_annotations(ConstMethod* cm,
2099                                        const u1* runtime_visible_annotations,
2100                                        int runtime_visible_annotations_length,
2101                                        const u1* runtime_visible_parameter_annotations,
2102                                        int runtime_visible_parameter_annotations_length,
2103                                        const u1* runtime_visible_type_annotations,
2104                                        int runtime_visible_type_annotations_length,
2105                                        const u1* annotation_default,
2106                                        int annotation_default_length,
2107                                        TRAPS) {
2108 
2109   AnnotationArray* a;
2110 
2111   if (runtime_visible_annotations_length > 0) {
2112      a = allocate_annotations(runtime_visible_annotations,
2113                               runtime_visible_annotations_length,
2114                               CHECK);
2115      cm->set_method_annotations(a);
2116   }
2117 
2118   if (runtime_visible_parameter_annotations_length > 0) {
2119     a = allocate_annotations(runtime_visible_parameter_annotations,
2120                              runtime_visible_parameter_annotations_length,
2121                              CHECK);
2122     cm->set_parameter_annotations(a);
2123   }
2124 
2125   if (annotation_default_length > 0) {
2126     a = allocate_annotations(annotation_default,
2127                              annotation_default_length,
2128                              CHECK);
2129     cm->set_default_annotations(a);
2130   }
2131 
2132   if (runtime_visible_type_annotations_length > 0) {
2133     a = allocate_annotations(runtime_visible_type_annotations,
2134                              runtime_visible_type_annotations_length,
2135                              CHECK);
2136     cm->set_type_annotations(a);
2137   }
2138 }
2139 
2140 
2141 // Note: the parse_method below is big and clunky because all parsing of the code and exceptions
2142 // attribute is inlined. This is cumbersome to avoid since we inline most of the parts in the
2143 // Method* to save footprint, so we only know the size of the resulting Method* when the
2144 // entire method attribute is parsed.
2145 //
2146 // The has_localvariable_table parameter is used to pass up the value to InstanceKlass.
2147 
2148 Method* ClassFileParser::parse_method(const ClassFileStream* const cfs,
2149                                       bool is_interface,
2150                                       const ConstantPool* cp,
2151                                       bool* const has_localvariable_table,
2152                                       TRAPS) {
2153   assert(cfs != nullptr, "invariant");
2154   assert(cp != nullptr, "invariant");
2155   assert(has_localvariable_table != nullptr, "invariant");
2156 
2157   ResourceMark rm(THREAD);
2158   // Parse fixed parts:
2159   // access_flags, name_index, descriptor_index, attributes_count
2160   cfs->guarantee_more(8, CHECK_NULL);
2161 
2162   u2 flags = cfs->get_u2_fast();
2163   const u2 name_index = cfs->get_u2_fast();
2164   const int cp_size = cp->length();
2165   guarantee_property(
2166     valid_symbol_at(name_index),
2167     "Illegal constant pool index %u for method name in class file %s",
2168     name_index, CHECK_NULL);
2169   const Symbol* const name = cp->symbol_at(name_index);
2170   verify_legal_method_name(name, CHECK_NULL);
2171 
2172   const u2 signature_index = cfs->get_u2_fast();
2173   guarantee_property(
2174     valid_symbol_at(signature_index),
2175     "Illegal constant pool index %u for method signature in class file %s",
2176     signature_index, CHECK_NULL);
2177   const Symbol* const signature = cp->symbol_at(signature_index);
2178 
2179   if (name == vmSymbols::class_initializer_name()) {
2180     // We ignore the other access flags for a valid class initializer.
2181     // (JVM Spec 2nd ed., chapter 4.6)
2182     if (_major_version < 51) { // backward compatibility
2183       flags = JVM_ACC_STATIC;
2184     } else if ((flags & JVM_ACC_STATIC) == JVM_ACC_STATIC) {
2185       flags &= JVM_ACC_STATIC | (_major_version <= JAVA_16_VERSION ? JVM_ACC_STRICT : 0);
2186     } else {
2187       classfile_parse_error("Method <clinit> is not static in class file %s", THREAD);
2188       return nullptr;
2189     }
2190   } else {
2191     verify_legal_method_modifiers(flags, is_interface, name, CHECK_NULL);
2192   }
2193 
2194   if (name == vmSymbols::object_initializer_name() && is_interface) {
2195     classfile_parse_error("Interface cannot have a method named <init>, class file %s", THREAD);
2196     return nullptr;
2197   }
2198 
2199   int args_size = -1;  // only used when _need_verify is true
2200   if (_need_verify) {
2201     verify_legal_name_with_signature(name, signature, CHECK_NULL);
2202     args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) +
2203                  verify_legal_method_signature(name, signature, CHECK_NULL);
2204     if (args_size > MAX_ARGS_SIZE) {
2205       classfile_parse_error("Too many arguments in method signature in class file %s", THREAD);
2206       return nullptr;
2207     }
2208   }
2209 
2210   AccessFlags access_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS);
2211 
2212   // Default values for code and exceptions attribute elements
2213   u2 max_stack = 0;
2214   u2 max_locals = 0;
2215   u4 code_length = 0;
2216   const u1* code_start = nullptr;
2217   u2 exception_table_length = 0;
2218   const unsafe_u2* exception_table_start = nullptr; // (potentially unaligned) pointer to array of u2 elements
2219   Array<int>* exception_handlers = Universe::the_empty_int_array();
2220   u2 checked_exceptions_length = 0;
2221   const unsafe_u2* checked_exceptions_start = nullptr; // (potentially unaligned) pointer to array of u2 elements
2222   CompressedLineNumberWriteStream* linenumber_table = nullptr;
2223   int linenumber_table_length = 0;
2224   int total_lvt_length = 0;
2225   u2 lvt_cnt = 0;
2226   u2 lvtt_cnt = 0;
2227   bool lvt_allocated = false;
2228   u2 max_lvt_cnt = INITIAL_MAX_LVT_NUMBER;
2229   u2 max_lvtt_cnt = INITIAL_MAX_LVT_NUMBER;
2230   u2* localvariable_table_length = nullptr;
2231   const unsafe_u2** localvariable_table_start = nullptr; // (potentially unaligned) pointer to array of LVT attributes
2232   u2* localvariable_type_table_length = nullptr;
2233   const unsafe_u2** localvariable_type_table_start = nullptr; // (potentially unaligned) pointer to LVTT attributes
2234   int method_parameters_length = -1;
2235   const u1* method_parameters_data = nullptr;
2236   bool method_parameters_seen = false;
2237   bool parsed_code_attribute = false;
2238   bool parsed_checked_exceptions_attribute = false;
2239   bool parsed_stackmap_attribute = false;
2240   // stackmap attribute - JDK1.5
2241   const u1* stackmap_data = nullptr;
2242   int stackmap_data_length = 0;
2243   u2 generic_signature_index = 0;
2244   MethodAnnotationCollector parsed_annotations;
2245   const u1* runtime_visible_annotations = nullptr;
2246   int runtime_visible_annotations_length = 0;
2247   const u1* runtime_visible_parameter_annotations = nullptr;
2248   int runtime_visible_parameter_annotations_length = 0;
2249   const u1* runtime_visible_type_annotations = nullptr;
2250   int runtime_visible_type_annotations_length = 0;
2251   bool runtime_invisible_annotations_exists = false;
2252   bool runtime_invisible_type_annotations_exists = false;
2253   bool runtime_invisible_parameter_annotations_exists = false;
2254   const u1* annotation_default = nullptr;
2255   int annotation_default_length = 0;
2256 
2257   // Parse code and exceptions attribute
2258   u2 method_attributes_count = cfs->get_u2_fast();
2259   while (method_attributes_count--) {
2260     cfs->guarantee_more(6, CHECK_NULL);  // method_attribute_name_index, method_attribute_length
2261     const u2 method_attribute_name_index = cfs->get_u2_fast();
2262     const u4 method_attribute_length = cfs->get_u4_fast();
2263     guarantee_property(
2264       valid_symbol_at(method_attribute_name_index),
2265       "Invalid method attribute name index %u in class file %s",
2266       method_attribute_name_index, CHECK_NULL);
2267 
2268     const Symbol* const method_attribute_name = cp->symbol_at(method_attribute_name_index);
2269     if (method_attribute_name == vmSymbols::tag_code()) {
2270       // Parse Code attribute
2271       if (_need_verify) {
2272         guarantee_property(
2273             !access_flags.is_native() && !access_flags.is_abstract(),
2274                         "Code attribute in native or abstract methods in class file %s",
2275                          CHECK_NULL);
2276       }
2277       if (parsed_code_attribute) {
2278         classfile_parse_error("Multiple Code attributes in class file %s",
2279                               THREAD);
2280         return nullptr;
2281       }
2282       parsed_code_attribute = true;
2283 
2284       // Stack size, locals size, and code size
2285       cfs->guarantee_more(8, CHECK_NULL);
2286       max_stack = cfs->get_u2_fast();
2287       max_locals = cfs->get_u2_fast();
2288       code_length = cfs->get_u4_fast();
2289       if (_need_verify) {
2290         guarantee_property(args_size <= max_locals,
2291                            "Arguments can't fit into locals in class file %s",
2292                            CHECK_NULL);
2293         guarantee_property(code_length > 0 && code_length <= MAX_CODE_SIZE,
2294                            "Invalid method Code length %u in class file %s",
2295                            code_length, CHECK_NULL);
2296       }
2297       // Code pointer
2298       code_start = cfs->current();
2299       assert(code_start != nullptr, "null code start");
2300       cfs->guarantee_more(code_length, CHECK_NULL);
2301       cfs->skip_u1_fast(code_length);
2302 
2303       // Exception handler table
2304       cfs->guarantee_more(2, CHECK_NULL);  // exception_table_length
2305       exception_table_length = cfs->get_u2_fast();
2306       if (exception_table_length > 0) {
2307         exception_table_start = parse_exception_table(cfs,
2308                                                       code_length,
2309                                                       exception_table_length,
2310                                                       CHECK_NULL);
2311       }
2312 
2313       // Parse additional attributes in code attribute
2314       cfs->guarantee_more(2, CHECK_NULL);  // code_attributes_count
2315       u2 code_attributes_count = cfs->get_u2_fast();
2316 
2317       unsigned int calculated_attribute_length = 0;
2318 
2319       calculated_attribute_length =
2320           sizeof(max_stack) + sizeof(max_locals) + sizeof(code_length);
2321       calculated_attribute_length += checked_cast<unsigned int>(
2322         code_length +
2323         sizeof(exception_table_length) +
2324         sizeof(code_attributes_count) +
2325         exception_table_length *
2326             ( sizeof(u2) +   // start_pc
2327               sizeof(u2) +   // end_pc
2328               sizeof(u2) +   // handler_pc
2329               sizeof(u2) )); // catch_type_index
2330 
2331       while (code_attributes_count--) {
2332         cfs->guarantee_more(6, CHECK_NULL);  // code_attribute_name_index, code_attribute_length
2333         const u2 code_attribute_name_index = cfs->get_u2_fast();
2334         const u4 code_attribute_length = cfs->get_u4_fast();
2335         calculated_attribute_length += code_attribute_length +
2336                                        (unsigned)sizeof(code_attribute_name_index) +
2337                                        (unsigned)sizeof(code_attribute_length);
2338         guarantee_property(valid_symbol_at(code_attribute_name_index),
2339                            "Invalid code attribute name index %u in class file %s",
2340                            code_attribute_name_index,
2341                            CHECK_NULL);
2342         if (LoadLineNumberTables &&
2343             cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_line_number_table()) {
2344           // Parse and compress line number table
2345           parse_linenumber_table(code_attribute_length,
2346                                  code_length,
2347                                  &linenumber_table,
2348                                  CHECK_NULL);
2349 
2350         } else if (LoadLocalVariableTables &&
2351                    cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_table()) {
2352           // Parse local variable table
2353           if (!lvt_allocated) {
2354             localvariable_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2355               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
2356             localvariable_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2357               THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER);
2358             localvariable_type_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2359               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
2360             localvariable_type_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2361               THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER);
2362             lvt_allocated = true;
2363           }
2364           if (lvt_cnt == max_lvt_cnt) {
2365             max_lvt_cnt <<= 1;
2366             localvariable_table_length = REALLOC_RESOURCE_ARRAY(localvariable_table_length, lvt_cnt, max_lvt_cnt);
2367             localvariable_table_start  = REALLOC_RESOURCE_ARRAY(localvariable_table_start, lvt_cnt, max_lvt_cnt);
2368           }
2369           localvariable_table_start[lvt_cnt] =
2370             parse_localvariable_table(cfs,
2371                                       code_length,
2372                                       max_locals,
2373                                       code_attribute_length,
2374                                       &localvariable_table_length[lvt_cnt],
2375                                       false,    // is not LVTT
2376                                       CHECK_NULL);
2377           total_lvt_length += localvariable_table_length[lvt_cnt];
2378           lvt_cnt++;
2379         } else if (LoadLocalVariableTypeTables &&
2380                    _major_version >= JAVA_1_5_VERSION &&
2381                    cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_type_table()) {
2382           if (!lvt_allocated) {
2383             localvariable_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2384               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
2385             localvariable_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2386               THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER);
2387             localvariable_type_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2388               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
2389             localvariable_type_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2390               THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER);
2391             lvt_allocated = true;
2392           }
2393           // Parse local variable type table
2394           if (lvtt_cnt == max_lvtt_cnt) {
2395             max_lvtt_cnt <<= 1;
2396             localvariable_type_table_length = REALLOC_RESOURCE_ARRAY(localvariable_type_table_length, lvtt_cnt, max_lvtt_cnt);
2397             localvariable_type_table_start  = REALLOC_RESOURCE_ARRAY(localvariable_type_table_start, lvtt_cnt, max_lvtt_cnt);
2398           }
2399           localvariable_type_table_start[lvtt_cnt] =
2400             parse_localvariable_table(cfs,
2401                                       code_length,
2402                                       max_locals,
2403                                       code_attribute_length,
2404                                       &localvariable_type_table_length[lvtt_cnt],
2405                                       true,     // is LVTT
2406                                       CHECK_NULL);
2407           lvtt_cnt++;
2408         } else if (_major_version >= Verifier::STACKMAP_ATTRIBUTE_MAJOR_VERSION &&
2409                    cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_stack_map_table()) {
2410           // Stack map is only needed by the new verifier in JDK1.5.
2411           if (parsed_stackmap_attribute) {
2412             classfile_parse_error("Multiple StackMapTable attributes in class file %s", THREAD);
2413             return nullptr;
2414           }
2415           stackmap_data = parse_stackmap_table(cfs, code_attribute_length, CHECK_NULL);
2416           stackmap_data_length = code_attribute_length;
2417           parsed_stackmap_attribute = true;
2418         } else {
2419           // Skip unknown attributes
2420           cfs->skip_u1(code_attribute_length, CHECK_NULL);
2421         }
2422       }
2423       // check method attribute length
2424       if (_need_verify) {
2425         guarantee_property(method_attribute_length == calculated_attribute_length,
2426                            "Code segment has wrong length in class file %s",
2427                            CHECK_NULL);
2428       }
2429     } else if (method_attribute_name == vmSymbols::tag_exceptions()) {
2430       // Parse Exceptions attribute
2431       if (parsed_checked_exceptions_attribute) {
2432         classfile_parse_error("Multiple Exceptions attributes in class file %s",
2433                               THREAD);
2434         return nullptr;
2435       }
2436       parsed_checked_exceptions_attribute = true;
2437       checked_exceptions_start =
2438             parse_checked_exceptions(cfs,
2439                                      &checked_exceptions_length,
2440                                      method_attribute_length,
2441                                      CHECK_NULL);
2442     } else if (method_attribute_name == vmSymbols::tag_method_parameters()) {
2443       // reject multiple method parameters
2444       if (method_parameters_seen) {
2445         classfile_parse_error("Multiple MethodParameters attributes in class file %s",
2446                               THREAD);
2447         return nullptr;
2448       }
2449       method_parameters_seen = true;
2450       method_parameters_length = cfs->get_u1_fast();
2451       const u4 real_length = (method_parameters_length * 4u) + 1u;
2452       if (method_attribute_length != real_length) {
2453         classfile_parse_error(
2454           "Invalid MethodParameters method attribute length %u in class file",
2455           method_attribute_length, THREAD);
2456         return nullptr;
2457       }
2458       method_parameters_data = cfs->current();
2459       cfs->skip_u2_fast(method_parameters_length);
2460       cfs->skip_u2_fast(method_parameters_length);
2461       // ignore this attribute if it cannot be reflected
2462       if (!vmClasses::reflect_Parameter_klass_is_loaded())
2463         method_parameters_length = -1;
2464     } else if (method_attribute_name == vmSymbols::tag_synthetic()) {
2465       if (method_attribute_length != 0) {
2466         classfile_parse_error(
2467           "Invalid Synthetic method attribute length %u in class file %s",
2468           method_attribute_length, THREAD);
2469         return nullptr;
2470       }
2471       // Should we check that there hasn't already been a synthetic attribute?
2472       access_flags.set_is_synthetic();
2473     } else if (method_attribute_name == vmSymbols::tag_deprecated()) { // 4276120
2474       if (method_attribute_length != 0) {
2475         classfile_parse_error(
2476           "Invalid Deprecated method attribute length %u in class file %s",
2477           method_attribute_length, THREAD);
2478         return nullptr;
2479       }
2480     } else if (_major_version >= JAVA_1_5_VERSION) {
2481       if (method_attribute_name == vmSymbols::tag_signature()) {
2482         if (generic_signature_index != 0) {
2483           classfile_parse_error(
2484             "Multiple Signature attributes for method in class file %s",
2485             THREAD);
2486           return nullptr;
2487         }
2488         if (method_attribute_length != 2) {
2489           classfile_parse_error(
2490             "Invalid Signature attribute length %u in class file %s",
2491             method_attribute_length, THREAD);
2492           return nullptr;
2493         }
2494         generic_signature_index = parse_generic_signature_attribute(cfs, CHECK_NULL);
2495       } else if (method_attribute_name == vmSymbols::tag_runtime_visible_annotations()) {
2496         if (runtime_visible_annotations != nullptr) {
2497           classfile_parse_error(
2498             "Multiple RuntimeVisibleAnnotations attributes for method in class file %s",
2499             THREAD);
2500           return nullptr;
2501         }
2502         runtime_visible_annotations_length = method_attribute_length;
2503         runtime_visible_annotations = cfs->current();
2504         assert(runtime_visible_annotations != nullptr, "null visible annotations");
2505         cfs->guarantee_more(runtime_visible_annotations_length, CHECK_NULL);
2506         parse_annotations(cp,
2507                           runtime_visible_annotations,
2508                           runtime_visible_annotations_length,
2509                           &parsed_annotations,
2510                           _loader_data,
2511                           _can_access_vm_annotations);
2512         cfs->skip_u1_fast(runtime_visible_annotations_length);
2513       } else if (method_attribute_name == vmSymbols::tag_runtime_invisible_annotations()) {
2514         if (runtime_invisible_annotations_exists) {
2515           classfile_parse_error(
2516             "Multiple RuntimeInvisibleAnnotations attributes for method in class file %s",
2517             THREAD);
2518           return nullptr;
2519         }
2520         runtime_invisible_annotations_exists = true;
2521         cfs->skip_u1(method_attribute_length, CHECK_NULL);
2522       } else if (method_attribute_name == vmSymbols::tag_runtime_visible_parameter_annotations()) {
2523         if (runtime_visible_parameter_annotations != nullptr) {
2524           classfile_parse_error(
2525             "Multiple RuntimeVisibleParameterAnnotations attributes for method in class file %s",
2526             THREAD);
2527           return nullptr;
2528         }
2529         runtime_visible_parameter_annotations_length = method_attribute_length;
2530         runtime_visible_parameter_annotations = cfs->current();
2531         assert(runtime_visible_parameter_annotations != nullptr, "null visible parameter annotations");
2532         cfs->skip_u1(runtime_visible_parameter_annotations_length, CHECK_NULL);
2533       } else if (method_attribute_name == vmSymbols::tag_runtime_invisible_parameter_annotations()) {
2534         if (runtime_invisible_parameter_annotations_exists) {
2535           classfile_parse_error(
2536             "Multiple RuntimeInvisibleParameterAnnotations attributes for method in class file %s",
2537             THREAD);
2538           return nullptr;
2539         }
2540         runtime_invisible_parameter_annotations_exists = true;
2541         cfs->skip_u1(method_attribute_length, CHECK_NULL);
2542       } else if (method_attribute_name == vmSymbols::tag_annotation_default()) {
2543         if (annotation_default != nullptr) {
2544           classfile_parse_error(
2545             "Multiple AnnotationDefault attributes for method in class file %s",
2546             THREAD);
2547           return nullptr;
2548         }
2549         annotation_default_length = method_attribute_length;
2550         annotation_default = cfs->current();
2551         assert(annotation_default != nullptr, "null annotation default");
2552         cfs->skip_u1(annotation_default_length, CHECK_NULL);
2553       } else if (method_attribute_name == vmSymbols::tag_runtime_visible_type_annotations()) {
2554         if (runtime_visible_type_annotations != nullptr) {
2555           classfile_parse_error(
2556             "Multiple RuntimeVisibleTypeAnnotations attributes for method in class file %s",
2557             THREAD);
2558           return nullptr;
2559         }
2560         runtime_visible_type_annotations_length = method_attribute_length;
2561         runtime_visible_type_annotations = cfs->current();
2562         assert(runtime_visible_type_annotations != nullptr, "null visible type annotations");
2563         // No need for the VM to parse Type annotations
2564         cfs->skip_u1(runtime_visible_type_annotations_length, CHECK_NULL);
2565       } else if (method_attribute_name == vmSymbols::tag_runtime_invisible_type_annotations()) {
2566         if (runtime_invisible_type_annotations_exists) {
2567           classfile_parse_error(
2568             "Multiple RuntimeInvisibleTypeAnnotations attributes for method in class file %s",
2569             THREAD);
2570           return nullptr;
2571         }
2572         runtime_invisible_type_annotations_exists = true;
2573         cfs->skip_u1(method_attribute_length, CHECK_NULL);
2574       } else {
2575         // Skip unknown attributes
2576         cfs->skip_u1(method_attribute_length, CHECK_NULL);
2577       }
2578     } else {
2579       // Skip unknown attributes
2580       cfs->skip_u1(method_attribute_length, CHECK_NULL);
2581     }
2582   }
2583 
2584   if (linenumber_table != nullptr) {
2585     linenumber_table->write_terminator();
2586     linenumber_table_length = linenumber_table->position();
2587   }
2588 
2589   // Make sure there's at least one Code attribute in non-native/non-abstract method
2590   if (_need_verify) {
2591     guarantee_property(access_flags.is_native() ||
2592                        access_flags.is_abstract() ||
2593                        parsed_code_attribute,
2594                        "Absent Code attribute in method that is not native or abstract in class file %s",
2595                        CHECK_NULL);
2596   }
2597 
2598   // All sizing information for a Method* is finally available, now create it
2599   InlineTableSizes sizes(
2600       total_lvt_length,
2601       linenumber_table_length,
2602       exception_table_length,
2603       checked_exceptions_length,
2604       method_parameters_length,
2605       generic_signature_index,
2606       runtime_visible_annotations_length,
2607       runtime_visible_parameter_annotations_length,
2608       runtime_visible_type_annotations_length,
2609       annotation_default_length,
2610       0);
2611 
2612   Method* const m = Method::allocate(_loader_data,
2613                                      code_length,
2614                                      access_flags,
2615                                      &sizes,
2616                                      ConstMethod::NORMAL,
2617                                      _cp->symbol_at(name_index),
2618                                      CHECK_NULL);
2619 
2620   ClassLoadingService::add_class_method_size(m->size()*wordSize);
2621 
2622   // Fill in information from fixed part (access_flags already set)
2623   m->set_constants(_cp);
2624   m->set_name_index(name_index);
2625   m->set_signature_index(signature_index);
2626   m->constMethod()->compute_from_signature(cp->symbol_at(signature_index), access_flags.is_static());
2627   assert(args_size < 0 || args_size == m->size_of_parameters(), "");
2628 
2629   // Fill in code attribute information
2630   m->set_max_stack(max_stack);
2631   m->set_max_locals(max_locals);
2632   if (stackmap_data != nullptr) {
2633     m->constMethod()->copy_stackmap_data(_loader_data,
2634                                          (u1*)stackmap_data,
2635                                          stackmap_data_length,
2636                                          CHECK_NULL);
2637   }
2638 
2639   // Copy byte codes
2640   m->set_code((u1*)code_start);
2641 
2642   // Copy line number table
2643   if (linenumber_table != nullptr) {
2644     memcpy(m->compressed_linenumber_table(),
2645            linenumber_table->buffer(),
2646            linenumber_table_length);
2647   }
2648 
2649   // Copy exception table
2650   if (exception_table_length > 0) {
2651     Copy::conjoint_swap_if_needed<Endian::JAVA>(exception_table_start,
2652                                                 m->exception_table_start(),
2653                                                 exception_table_length * sizeof(ExceptionTableElement),
2654                                                 sizeof(u2));
2655   }
2656 
2657   // Copy method parameters
2658   if (method_parameters_length > 0) {
2659     MethodParametersElement* elem = m->constMethod()->method_parameters_start();
2660     for (int i = 0; i < method_parameters_length; i++) {
2661       elem[i].name_cp_index = Bytes::get_Java_u2((address)method_parameters_data);
2662       method_parameters_data += 2;
2663       elem[i].flags = Bytes::get_Java_u2((address)method_parameters_data);
2664       method_parameters_data += 2;
2665     }
2666   }
2667 
2668   // Copy checked exceptions
2669   if (checked_exceptions_length > 0) {
2670     Copy::conjoint_swap_if_needed<Endian::JAVA>(checked_exceptions_start,
2671                                                 m->checked_exceptions_start(),
2672                                                 checked_exceptions_length * sizeof(CheckedExceptionElement),
2673                                                 sizeof(u2));
2674   }
2675 
2676   // Copy class file LVT's/LVTT's into the HotSpot internal LVT.
2677   if (total_lvt_length > 0) {
2678     *has_localvariable_table = true;
2679     copy_localvariable_table(m->constMethod(),
2680                              lvt_cnt,
2681                              localvariable_table_length,
2682                              localvariable_table_start,
2683                              lvtt_cnt,
2684                              localvariable_type_table_length,
2685                              localvariable_type_table_start,
2686                              CHECK_NULL);
2687   }
2688 
2689   if (parsed_annotations.has_any_annotations())
2690     parsed_annotations.apply_to(methodHandle(THREAD, m));
2691 
2692   if (is_hidden()) { // Mark methods in hidden classes as 'hidden'.
2693     m->set_is_hidden();
2694   }
2695   if (parsed_annotations.has_aot_runtime_setup()) {
2696     if (name != vmSymbols::runtimeSetup() || signature != vmSymbols::void_method_signature() ||
2697         !access_flags.is_private() || !access_flags.is_static()) {
2698       classfile_parse_error("@AOTRuntimeSetup method must be declared private static void runtimeSetup() for class %s", CHECK_NULL);
2699     }
2700     _has_aot_runtime_setup_method = true;
2701   }
2702 
2703   // Copy annotations
2704   copy_method_annotations(m->constMethod(),
2705                           runtime_visible_annotations,
2706                           runtime_visible_annotations_length,
2707                           runtime_visible_parameter_annotations,
2708                           runtime_visible_parameter_annotations_length,
2709                           runtime_visible_type_annotations,
2710                           runtime_visible_type_annotations_length,
2711                           annotation_default,
2712                           annotation_default_length,
2713                           CHECK_NULL);
2714 
2715   if (InstanceKlass::is_finalization_enabled() &&
2716       name == vmSymbols::finalize_method_name() &&
2717       signature == vmSymbols::void_method_signature()) {
2718     if (m->is_empty_method()) {
2719       _has_empty_finalizer = true;
2720     } else {
2721       _has_finalizer = true;
2722     }
2723   }
2724 
2725   NOT_PRODUCT(m->verify());
2726   return m;
2727 }
2728 
2729 
2730 // Side-effects: populates the _methods field in the parser
2731 void ClassFileParser::parse_methods(const ClassFileStream* const cfs,
2732                                     bool is_interface,
2733                                     bool* const has_localvariable_table,
2734                                     bool* has_final_method,
2735                                     bool* declares_nonstatic_concrete_methods,
2736                                     TRAPS) {
2737   assert(cfs != nullptr, "invariant");
2738   assert(has_localvariable_table != nullptr, "invariant");
2739   assert(has_final_method != nullptr, "invariant");
2740   assert(declares_nonstatic_concrete_methods != nullptr, "invariant");
2741 
2742   assert(nullptr == _methods, "invariant");
2743 
2744   cfs->guarantee_more(2, CHECK);  // length
2745   const u2 length = cfs->get_u2_fast();
2746   if (length == 0) {
2747     _methods = Universe::the_empty_method_array();
2748   } else {
2749     _methods = MetadataFactory::new_array<Method*>(_loader_data,
2750                                                    length,
2751                                                    nullptr,
2752                                                    CHECK);
2753 
2754     for (int index = 0; index < length; index++) {
2755       Method* method = parse_method(cfs,
2756                                     is_interface,
2757                                     _cp,
2758                                     has_localvariable_table,
2759                                     CHECK);
2760 
2761       if (method->is_final()) {
2762         *has_final_method = true;
2763       }
2764       // declares_nonstatic_concrete_methods: declares concrete instance methods, any access flags
2765       // used for interface initialization, and default method inheritance analysis
2766       if (is_interface && !(*declares_nonstatic_concrete_methods)
2767         && !method->is_abstract() && !method->is_static()) {
2768         *declares_nonstatic_concrete_methods = true;
2769       }
2770       _methods->at_put(index, method);
2771     }
2772 
2773     if (_need_verify && length > 1) {
2774       // Check duplicated methods
2775       ResourceMark rm(THREAD);
2776       // Set containing name-signature pairs
2777       NameSigHashtable* names_and_sigs = new NameSigHashtable();
2778       for (int i = 0; i < length; i++) {
2779         const Method* const m = _methods->at(i);
2780         NameSigHash name_and_sig(m->name(), m->signature());
2781         // If no duplicates, add name/signature in hashtable names_and_sigs.
2782         if(!names_and_sigs->put(name_and_sig, 0)) {
2783           classfile_parse_error("Duplicate method name \"%s\" with signature \"%s\" in class file %s",
2784                                  name_and_sig._name->as_C_string(), name_and_sig._sig->as_klass_external_name(), THREAD);
2785           return;
2786         }
2787       }
2788     }
2789   }
2790 }
2791 
2792 static const intArray* sort_methods(Array<Method*>* methods) {
2793   const int length = methods->length();
2794   // If JVMTI original method ordering or sharing is enabled we have to
2795   // remember the original class file ordering.
2796   // We temporarily use the vtable_index field in the Method* to store the
2797   // class file index, so we can read in after calling qsort.
2798   // Put the method ordering in the shared archive.
2799   if (JvmtiExport::can_maintain_original_method_order() || CDSConfig::is_dumping_archive()) {
2800     for (int index = 0; index < length; index++) {
2801       Method* const m = methods->at(index);
2802       assert(!m->valid_vtable_index(), "vtable index should not be set");
2803       m->set_vtable_index(index);
2804     }
2805   }
2806   // Sort method array by ascending method name (for faster lookups & vtable construction)
2807   // Note that the ordering is not alphabetical, see Symbol::fast_compare
2808   Method::sort_methods(methods);
2809 
2810   intArray* method_ordering = nullptr;
2811   // If JVMTI original method ordering or sharing is enabled construct int
2812   // array remembering the original ordering
2813   if (JvmtiExport::can_maintain_original_method_order() || CDSConfig::is_dumping_archive()) {
2814     method_ordering = new intArray(length, length, -1);
2815     for (int index = 0; index < length; index++) {
2816       Method* const m = methods->at(index);
2817       const int old_index = m->vtable_index();
2818       assert(old_index >= 0 && old_index < length, "invalid method index");
2819       method_ordering->at_put(index, old_index);
2820       m->set_vtable_index(Method::invalid_vtable_index);
2821     }
2822   }
2823   return method_ordering;
2824 }
2825 
2826 // Parse generic_signature attribute for methods and fields
2827 u2 ClassFileParser::parse_generic_signature_attribute(const ClassFileStream* const cfs,
2828                                                       TRAPS) {
2829   assert(cfs != nullptr, "invariant");
2830 
2831   cfs->guarantee_more(2, CHECK_0);  // generic_signature_index
2832   const u2 generic_signature_index = cfs->get_u2_fast();
2833   guarantee_property(
2834     valid_symbol_at(generic_signature_index),
2835     "Invalid Signature attribute at constant pool index %u in class file %s",
2836     generic_signature_index, CHECK_0);
2837   return generic_signature_index;
2838 }
2839 
2840 void ClassFileParser::parse_classfile_sourcefile_attribute(const ClassFileStream* const cfs,
2841                                                            TRAPS) {
2842 
2843   assert(cfs != nullptr, "invariant");
2844 
2845   cfs->guarantee_more(2, CHECK);  // sourcefile_index
2846   const u2 sourcefile_index = cfs->get_u2_fast();
2847   guarantee_property(
2848     valid_symbol_at(sourcefile_index),
2849     "Invalid SourceFile attribute at constant pool index %u in class file %s",
2850     sourcefile_index, CHECK);
2851   set_class_sourcefile_index(sourcefile_index);
2852 }
2853 
2854 void ClassFileParser::parse_classfile_source_debug_extension_attribute(const ClassFileStream* const cfs,
2855                                                                        int length,
2856                                                                        TRAPS) {
2857   assert(cfs != nullptr, "invariant");
2858 
2859   const u1* const sde_buffer = cfs->current();
2860   assert(sde_buffer != nullptr, "null sde buffer");
2861 
2862   // Don't bother storing it if there is no way to retrieve it
2863   if (JvmtiExport::can_get_source_debug_extension()) {
2864     assert((length+1) > length, "Overflow checking");
2865     u1* const sde = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, u1, length+1);
2866     for (int i = 0; i < length; i++) {
2867       sde[i] = sde_buffer[i];
2868     }
2869     sde[length] = '\0';
2870     set_class_sde_buffer((const char*)sde, length);
2871   }
2872   // Got utf8 string, set stream position forward
2873   cfs->skip_u1(length, CHECK);
2874 }
2875 
2876 
2877 // Inner classes can be static, private or protected (classic VM does this)
2878 #define RECOGNIZED_INNER_CLASS_MODIFIERS ( JVM_RECOGNIZED_CLASS_MODIFIERS | \
2879                                            JVM_ACC_PRIVATE |                \
2880                                            JVM_ACC_PROTECTED |              \
2881                                            JVM_ACC_STATIC                   \
2882                                          )
2883 
2884 // Find index of the InnerClasses entry for the specified inner_class_info_index.
2885 // Return -1 if none is found.
2886 static int inner_classes_find_index(const Array<u2>* inner_classes, int inner, const ConstantPool* cp, int length) {
2887   Symbol* cp_klass_name =  cp->klass_name_at(inner);
2888   for (int idx = 0; idx < length; idx += InstanceKlass::inner_class_next_offset) {
2889     int idx_inner = inner_classes->at(idx + InstanceKlass::inner_class_inner_class_info_offset);
2890     if (cp->klass_name_at(idx_inner) == cp_klass_name) {
2891       return idx;
2892     }
2893   }
2894   return -1;
2895 }
2896 
2897 // Return the outer_class_info_index for the InnerClasses entry containing the
2898 // specified inner_class_info_index.  Return -1 if no InnerClasses entry is found.
2899 static int inner_classes_jump_to_outer(const Array<u2>* inner_classes, int inner, const ConstantPool* cp, int length) {
2900   if (inner == 0) return -1;
2901   int idx = inner_classes_find_index(inner_classes, inner, cp, length);
2902   if (idx == -1) return -1;
2903   int result = inner_classes->at(idx + InstanceKlass::inner_class_outer_class_info_offset);
2904   return result;
2905 }
2906 
2907 // Return true if circularity is found, false if no circularity is found.
2908 // Use Floyd's cycle finding algorithm.
2909 static bool inner_classes_check_loop_through_outer(const Array<u2>* inner_classes, int idx, const ConstantPool* cp, int length) {
2910   int slow = inner_classes->at(idx + InstanceKlass::inner_class_inner_class_info_offset);
2911   int fast = inner_classes->at(idx + InstanceKlass::inner_class_outer_class_info_offset);
2912 
2913   while (fast != -1 && fast != 0) {
2914     if (slow != 0 && (cp->klass_name_at(slow) == cp->klass_name_at(fast))) {
2915       return true;  // found a circularity
2916     }
2917     fast = inner_classes_jump_to_outer(inner_classes, fast, cp, length);
2918     if (fast == -1) return false;
2919     fast = inner_classes_jump_to_outer(inner_classes, fast, cp, length);
2920     if (fast == -1) return false;
2921     slow = inner_classes_jump_to_outer(inner_classes, slow, cp, length);
2922     assert(slow != -1, "sanity check");
2923   }
2924   return false;
2925 }
2926 
2927 // Loop through each InnerClasses entry checking for circularities and duplications
2928 // with other entries.  If duplicate entries are found then throw CFE.  Otherwise,
2929 // return true if a circularity or entries with duplicate inner_class_info_indexes
2930 // are found.
2931 bool ClassFileParser::check_inner_classes_circularity(const ConstantPool* cp, int length, TRAPS) {
2932   // Loop through each InnerClasses entry.
2933   for (int idx = 0; idx < length; idx += InstanceKlass::inner_class_next_offset) {
2934     // Return true if there are circular entries.
2935     if (inner_classes_check_loop_through_outer(_inner_classes, idx, cp, length)) {
2936       return true;
2937     }
2938     // Check if there are duplicate entries or entries with the same inner_class_info_index.
2939     for (int y = idx + InstanceKlass::inner_class_next_offset; y < length;
2940          y += InstanceKlass::inner_class_next_offset) {
2941 
2942       // 4347400: make sure there's no duplicate entry in the classes array
2943       if (_major_version >= JAVA_1_5_VERSION) {
2944         guarantee_property((_inner_classes->at(idx) != _inner_classes->at(y) ||
2945                             _inner_classes->at(idx+1) != _inner_classes->at(y+1) ||
2946                             _inner_classes->at(idx+2) != _inner_classes->at(y+2) ||
2947                             _inner_classes->at(idx+3) != _inner_classes->at(y+3)),
2948                            "Duplicate entry in InnerClasses attribute in class file %s",
2949                            CHECK_(true));
2950       }
2951       // Return true if there are two entries with the same inner_class_info_index.
2952       if (_inner_classes->at(y) == _inner_classes->at(idx)) {
2953         return true;
2954       }
2955     }
2956   }
2957   return false;
2958 }
2959 
2960 // Return number of classes in the inner classes attribute table
2961 u2 ClassFileParser::parse_classfile_inner_classes_attribute(const ClassFileStream* const cfs,
2962                                                             const ConstantPool* cp,
2963                                                             const u1* const inner_classes_attribute_start,
2964                                                             bool parsed_enclosingmethod_attribute,
2965                                                             u2 enclosing_method_class_index,
2966                                                             u2 enclosing_method_method_index,
2967                                                             TRAPS) {
2968   const u1* const current_mark = cfs->current();
2969   u2 length = 0;
2970   if (inner_classes_attribute_start != nullptr) {
2971     cfs->set_current(inner_classes_attribute_start);
2972     cfs->guarantee_more(2, CHECK_0);  // length
2973     length = cfs->get_u2_fast();
2974   }
2975 
2976   // 4-tuples of shorts of inner classes data and 2 shorts of enclosing
2977   // method data:
2978   //   [inner_class_info_index,
2979   //    outer_class_info_index,
2980   //    inner_name_index,
2981   //    inner_class_access_flags,
2982   //    ...
2983   //    enclosing_method_class_index,
2984   //    enclosing_method_method_index]
2985   const int size = length * 4 + (parsed_enclosingmethod_attribute ? 2 : 0);
2986   Array<u2>* inner_classes = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
2987   _inner_classes = inner_classes;
2988 
2989   int index = 0;
2990   cfs->guarantee_more(8 * length, CHECK_0);  // 4-tuples of u2
2991   for (int n = 0; n < length; n++) {
2992     // Inner class index
2993     const u2 inner_class_info_index = cfs->get_u2_fast();
2994     guarantee_property(
2995       valid_klass_reference_at(inner_class_info_index),
2996       "inner_class_info_index %u has bad constant type in class file %s",
2997       inner_class_info_index, CHECK_0);
2998     // Outer class index
2999     const u2 outer_class_info_index = cfs->get_u2_fast();
3000     guarantee_property(
3001       outer_class_info_index == 0 ||
3002         valid_klass_reference_at(outer_class_info_index),
3003       "outer_class_info_index %u has bad constant type in class file %s",
3004       outer_class_info_index, CHECK_0);
3005 
3006     if (outer_class_info_index != 0) {
3007       const Symbol* const outer_class_name = cp->klass_name_at(outer_class_info_index);
3008       char* bytes = (char*)outer_class_name->bytes();
3009       guarantee_property(bytes[0] != JVM_SIGNATURE_ARRAY,
3010                          "Outer class is an array class in class file %s", CHECK_0);
3011     }
3012     // Inner class name
3013     const u2 inner_name_index = cfs->get_u2_fast();
3014     guarantee_property(
3015       inner_name_index == 0 || valid_symbol_at(inner_name_index),
3016       "inner_name_index %u has bad constant type in class file %s",
3017       inner_name_index, CHECK_0);
3018     if (_need_verify) {
3019       guarantee_property(inner_class_info_index != outer_class_info_index,
3020                          "Class is both outer and inner class in class file %s", CHECK_0);
3021     }
3022     // Access flags
3023     u2 flags;
3024     // JVM_ACC_MODULE is defined in JDK-9 and later.
3025     if (_major_version >= JAVA_9_VERSION) {
3026       flags = cfs->get_u2_fast() & (RECOGNIZED_INNER_CLASS_MODIFIERS | JVM_ACC_MODULE);
3027     } else {
3028       flags = cfs->get_u2_fast() & RECOGNIZED_INNER_CLASS_MODIFIERS;
3029     }
3030     if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
3031       // Set abstract bit for old class files for backward compatibility
3032       flags |= JVM_ACC_ABSTRACT;
3033     }
3034 
3035     Symbol* inner_name_symbol = inner_name_index == 0 ? nullptr : cp->symbol_at(inner_name_index);
3036     verify_legal_class_modifiers(flags, inner_name_symbol, inner_name_index == 0, CHECK_0);
3037     AccessFlags inner_access_flags(flags);
3038 
3039     inner_classes->at_put(index++, inner_class_info_index);
3040     inner_classes->at_put(index++, outer_class_info_index);
3041     inner_classes->at_put(index++, inner_name_index);
3042     inner_classes->at_put(index++, inner_access_flags.as_unsigned_short());
3043   }
3044 
3045   // Check for circular and duplicate entries.
3046   bool has_circularity = false;
3047   if (_need_verify) {
3048     has_circularity = check_inner_classes_circularity(cp, length * 4, CHECK_0);
3049     if (has_circularity) {
3050       // If circularity check failed then ignore InnerClasses attribute.
3051       MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
3052       index = 0;
3053       if (parsed_enclosingmethod_attribute) {
3054         inner_classes = MetadataFactory::new_array<u2>(_loader_data, 2, CHECK_0);
3055         _inner_classes = inner_classes;
3056       } else {
3057         _inner_classes = Universe::the_empty_short_array();
3058       }
3059     }
3060   }
3061   // Set EnclosingMethod class and method indexes.
3062   if (parsed_enclosingmethod_attribute) {
3063     inner_classes->at_put(index++, enclosing_method_class_index);
3064     inner_classes->at_put(index++, enclosing_method_method_index);
3065   }
3066   assert(index == size || has_circularity, "wrong size");
3067 
3068   // Restore buffer's current position.
3069   cfs->set_current(current_mark);
3070 
3071   return length;
3072 }
3073 
3074 u2 ClassFileParser::parse_classfile_nest_members_attribute(const ClassFileStream* const cfs,
3075                                                            const u1* const nest_members_attribute_start,
3076                                                            TRAPS) {
3077   const u1* const current_mark = cfs->current();
3078   u2 length = 0;
3079   if (nest_members_attribute_start != nullptr) {
3080     cfs->set_current(nest_members_attribute_start);
3081     cfs->guarantee_more(2, CHECK_0);  // length
3082     length = cfs->get_u2_fast();
3083   }
3084   const int size = length;
3085   Array<u2>* const nest_members = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
3086   _nest_members = nest_members;
3087 
3088   int index = 0;
3089   cfs->guarantee_more(2 * length, CHECK_0);
3090   for (int n = 0; n < length; n++) {
3091     const u2 class_info_index = cfs->get_u2_fast();
3092     guarantee_property(
3093       valid_klass_reference_at(class_info_index),
3094       "Nest member class_info_index %u has bad constant type in class file %s",
3095       class_info_index, CHECK_0);
3096     nest_members->at_put(index++, class_info_index);
3097   }
3098   assert(index == size, "wrong size");
3099 
3100   // Restore buffer's current position.
3101   cfs->set_current(current_mark);
3102 
3103   return length;
3104 }
3105 
3106 u2 ClassFileParser::parse_classfile_permitted_subclasses_attribute(const ClassFileStream* const cfs,
3107                                                                    const u1* const permitted_subclasses_attribute_start,
3108                                                                    TRAPS) {
3109   const u1* const current_mark = cfs->current();
3110   u2 length = 0;
3111   if (permitted_subclasses_attribute_start != nullptr) {
3112     cfs->set_current(permitted_subclasses_attribute_start);
3113     cfs->guarantee_more(2, CHECK_0);  // length
3114     length = cfs->get_u2_fast();
3115   }
3116   const int size = length;
3117   Array<u2>* const permitted_subclasses = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
3118   _permitted_subclasses = permitted_subclasses;
3119 
3120   if (length > 0) {
3121     int index = 0;
3122     cfs->guarantee_more(2 * length, CHECK_0);
3123     for (int n = 0; n < length; n++) {
3124       const u2 class_info_index = cfs->get_u2_fast();
3125       guarantee_property(
3126         valid_klass_reference_at(class_info_index),
3127         "Permitted subclass class_info_index %u has bad constant type in class file %s",
3128         class_info_index, CHECK_0);
3129       permitted_subclasses->at_put(index++, class_info_index);
3130     }
3131     assert(index == size, "wrong size");
3132   }
3133 
3134   // Restore buffer's current position.
3135   cfs->set_current(current_mark);
3136 
3137   return length;
3138 }
3139 
3140 //  Record {
3141 //    u2 attribute_name_index;
3142 //    u4 attribute_length;
3143 //    u2 components_count;
3144 //    component_info components[components_count];
3145 //  }
3146 //  component_info {
3147 //    u2 name_index;
3148 //    u2 descriptor_index
3149 //    u2 attributes_count;
3150 //    attribute_info_attributes[attributes_count];
3151 //  }
3152 u4 ClassFileParser::parse_classfile_record_attribute(const ClassFileStream* const cfs,
3153                                                      const ConstantPool* cp,
3154                                                      const u1* const record_attribute_start,
3155                                                      TRAPS) {
3156   const u1* const current_mark = cfs->current();
3157   int components_count = 0;
3158   unsigned int calculate_attr_size = 0;
3159   if (record_attribute_start != nullptr) {
3160     cfs->set_current(record_attribute_start);
3161     cfs->guarantee_more(2, CHECK_0);  // num of components
3162     components_count = (int)cfs->get_u2_fast();
3163     calculate_attr_size = 2;
3164   }
3165 
3166   Array<RecordComponent*>* const record_components =
3167     MetadataFactory::new_array<RecordComponent*>(_loader_data, components_count, nullptr, CHECK_0);
3168   _record_components = record_components;
3169 
3170   for (int x = 0; x < components_count; x++) {
3171     cfs->guarantee_more(6, CHECK_0); // name_index, descriptor_index, attributes_count
3172 
3173     const u2 name_index = cfs->get_u2_fast();
3174     guarantee_property(valid_symbol_at(name_index),
3175       "Invalid constant pool index %u for name in Record attribute in class file %s",
3176       name_index, CHECK_0);
3177     const Symbol* const name = cp->symbol_at(name_index);
3178     verify_legal_field_name(name, CHECK_0);
3179 
3180     const u2 descriptor_index = cfs->get_u2_fast();
3181     guarantee_property(valid_symbol_at(descriptor_index),
3182       "Invalid constant pool index %u for descriptor in Record attribute in class file %s",
3183       descriptor_index, CHECK_0);
3184     const Symbol* const descr = cp->symbol_at(descriptor_index);
3185     verify_legal_field_signature(name, descr, CHECK_0);
3186 
3187     const u2 attributes_count = cfs->get_u2_fast();
3188     calculate_attr_size += 6;
3189     u2 generic_sig_index = 0;
3190     const u1* runtime_visible_annotations = nullptr;
3191     int runtime_visible_annotations_length = 0;
3192     bool runtime_invisible_annotations_exists = false;
3193     const u1* runtime_visible_type_annotations = nullptr;
3194     int runtime_visible_type_annotations_length = 0;
3195     bool runtime_invisible_type_annotations_exists = false;
3196 
3197     // Expected attributes for record components are Signature, Runtime(In)VisibleAnnotations,
3198     // and Runtime(In)VisibleTypeAnnotations.  Other attributes are ignored.
3199     for (int y = 0; y < attributes_count; y++) {
3200       cfs->guarantee_more(6, CHECK_0);  // attribute_name_index, attribute_length
3201       const u2 attribute_name_index = cfs->get_u2_fast();
3202       const u4 attribute_length = cfs->get_u4_fast();
3203       calculate_attr_size += 6;
3204       guarantee_property(
3205         valid_symbol_at(attribute_name_index),
3206         "Invalid Record attribute name index %u in class file %s",
3207         attribute_name_index, CHECK_0);
3208 
3209       const Symbol* const attribute_name = cp->symbol_at(attribute_name_index);
3210       if (attribute_name == vmSymbols::tag_signature()) {
3211         if (generic_sig_index != 0) {
3212           classfile_parse_error(
3213             "Multiple Signature attributes for Record component in class file %s",
3214             THREAD);
3215           return 0;
3216         }
3217         if (attribute_length != 2) {
3218           classfile_parse_error(
3219             "Invalid Signature attribute length %u in Record component in class file %s",
3220             attribute_length, THREAD);
3221           return 0;
3222         }
3223         generic_sig_index = parse_generic_signature_attribute(cfs, CHECK_0);
3224 
3225       } else if (attribute_name == vmSymbols::tag_runtime_visible_annotations()) {
3226         if (runtime_visible_annotations != nullptr) {
3227           classfile_parse_error(
3228             "Multiple RuntimeVisibleAnnotations attributes for Record component in class file %s", THREAD);
3229           return 0;
3230         }
3231         runtime_visible_annotations_length = attribute_length;
3232         runtime_visible_annotations = cfs->current();
3233 
3234         assert(runtime_visible_annotations != nullptr, "null record component visible annotation");
3235         cfs->guarantee_more(runtime_visible_annotations_length, CHECK_0);
3236         cfs->skip_u1_fast(runtime_visible_annotations_length);
3237 
3238       } else if (attribute_name == vmSymbols::tag_runtime_invisible_annotations()) {
3239         if (runtime_invisible_annotations_exists) {
3240           classfile_parse_error(
3241             "Multiple RuntimeInvisibleAnnotations attributes for Record component in class file %s", THREAD);
3242           return 0;
3243         }
3244         runtime_invisible_annotations_exists = true;
3245         cfs->skip_u1(attribute_length, CHECK_0);
3246 
3247       } else if (attribute_name == vmSymbols::tag_runtime_visible_type_annotations()) {
3248         if (runtime_visible_type_annotations != nullptr) {
3249           classfile_parse_error(
3250             "Multiple RuntimeVisibleTypeAnnotations attributes for Record component in class file %s", THREAD);
3251           return 0;
3252         }
3253         runtime_visible_type_annotations_length = attribute_length;
3254         runtime_visible_type_annotations = cfs->current();
3255 
3256         assert(runtime_visible_type_annotations != nullptr, "null record component visible type annotation");
3257         cfs->guarantee_more(runtime_visible_type_annotations_length, CHECK_0);
3258         cfs->skip_u1_fast(runtime_visible_type_annotations_length);
3259 
3260       } else if (attribute_name == vmSymbols::tag_runtime_invisible_type_annotations()) {
3261         if (runtime_invisible_type_annotations_exists) {
3262           classfile_parse_error(
3263             "Multiple RuntimeInvisibleTypeAnnotations attributes for Record component in class file %s", THREAD);
3264           return 0;
3265         }
3266         runtime_invisible_type_annotations_exists = true;
3267         cfs->skip_u1(attribute_length, CHECK_0);
3268 
3269       } else {
3270         // Skip unknown attributes
3271         cfs->skip_u1(attribute_length, CHECK_0);
3272       }
3273       calculate_attr_size += attribute_length;
3274     } // End of attributes For loop
3275 
3276     AnnotationArray* annotations = allocate_annotations(runtime_visible_annotations,
3277                                                         runtime_visible_annotations_length,
3278                                                         CHECK_0);
3279     AnnotationArray* type_annotations = allocate_annotations(runtime_visible_type_annotations,
3280                                                              runtime_visible_type_annotations_length,
3281                                                              CHECK_0);
3282 
3283     RecordComponent* record_component =
3284       RecordComponent::allocate(_loader_data, name_index, descriptor_index, generic_sig_index,
3285                                 annotations, type_annotations, CHECK_0);
3286     record_components->at_put(x, record_component);
3287   }  // End of component processing loop
3288 
3289   // Restore buffer's current position.
3290   cfs->set_current(current_mark);
3291   return calculate_attr_size;
3292 }
3293 
3294 void ClassFileParser::parse_classfile_synthetic_attribute() {
3295   set_class_synthetic_flag(true);
3296 }
3297 
3298 void ClassFileParser::parse_classfile_signature_attribute(const ClassFileStream* const cfs, TRAPS) {
3299   assert(cfs != nullptr, "invariant");
3300 
3301   const u2 signature_index = cfs->get_u2(CHECK);
3302   guarantee_property(
3303     valid_symbol_at(signature_index),
3304     "Invalid constant pool index %u in Signature attribute in class file %s",
3305     signature_index, CHECK);
3306   set_class_generic_signature_index(signature_index);
3307 }
3308 
3309 void ClassFileParser::parse_classfile_bootstrap_methods_attribute(const ClassFileStream* const cfs,
3310                                                                   ConstantPool* cp,
3311                                                                   u4 attribute_byte_length,
3312                                                                   TRAPS) {
3313   assert(cfs != nullptr, "invariant");
3314   assert(cp != nullptr, "invariant");
3315   const int cp_size = cp->length();
3316 
3317   const u1* const current_before_parsing = cfs->current();
3318 
3319   guarantee_property(attribute_byte_length >= sizeof(u2),
3320                      "Invalid BootstrapMethods attribute length %u in class file %s",
3321                      attribute_byte_length,
3322                      CHECK);
3323 
3324   cfs->guarantee_more(attribute_byte_length, CHECK);
3325 
3326   const int num_bootstrap_methods = cfs->get_u2_fast();
3327 
3328   guarantee_property(_max_bootstrap_specifier_index < num_bootstrap_methods,
3329                      "Short length on BootstrapMethods in class file %s",
3330                      CHECK);
3331 
3332   const u4 bootstrap_methods_u2_len = (attribute_byte_length - sizeof(u2)) / sizeof(u2);
3333 
3334   // Eagerly assign the arrays so that they will be deallocated with the constant
3335   // pool if there is an error.
3336   BSMAttributeEntries::InsertionIterator iter =
3337     cp->bsm_entries().start_extension(num_bootstrap_methods,
3338                                       bootstrap_methods_u2_len,
3339                                       _loader_data,
3340                                       CHECK);
3341 
3342   for (int i = 0; i < num_bootstrap_methods; i++) {
3343     cfs->guarantee_more(sizeof(u2) * 2, CHECK);  // bsm, argc
3344     u2 bootstrap_method_ref = cfs->get_u2_fast();
3345     u2 num_bootstrap_arguments = cfs->get_u2_fast();
3346     guarantee_property(
3347        valid_cp_range(bootstrap_method_ref, cp_size) &&
3348        cp->tag_at(bootstrap_method_ref).is_method_handle(),
3349        "bootstrap_method_index %u has bad constant type in class file %s",
3350        bootstrap_method_ref,
3351        CHECK);
3352     cfs->guarantee_more(sizeof(u2) * num_bootstrap_arguments, CHECK); // argv[argc]
3353 
3354     BSMAttributeEntry* entry = iter.reserve_new_entry(bootstrap_method_ref, num_bootstrap_arguments);
3355     guarantee_property(entry != nullptr,
3356                        "Invalid BootstrapMethods num_bootstrap_methods."
3357                        " The total amount of space reserved for the BootstrapMethod attribute was not sufficient", CHECK);
3358 
3359     for (int argi = 0; argi < num_bootstrap_arguments; argi++) {
3360       const u2 argument_index = cfs->get_u2_fast();
3361       guarantee_property(
3362         valid_cp_range(argument_index, cp_size) &&
3363         cp->tag_at(argument_index).is_loadable_constant(),
3364         "argument_index %u has bad constant type in class file %s",
3365         argument_index,
3366         CHECK);
3367       entry->set_argument(argi, argument_index);
3368     }
3369   }
3370   cp->bsm_entries().end_extension(iter, _loader_data, CHECK);
3371   guarantee_property(current_before_parsing + attribute_byte_length == cfs->current(),
3372                      "Bad length on BootstrapMethods in class file %s",
3373                      CHECK);
3374 }
3375 
3376 void ClassFileParser::parse_classfile_attributes(const ClassFileStream* const cfs,
3377                                                  ConstantPool* cp,
3378                  ClassFileParser::ClassAnnotationCollector* parsed_annotations,
3379                                                  TRAPS) {
3380   assert(cfs != nullptr, "invariant");
3381   assert(cp != nullptr, "invariant");
3382   assert(parsed_annotations != nullptr, "invariant");
3383 
3384   // Set inner classes attribute to default sentinel
3385   _inner_classes = Universe::the_empty_short_array();
3386   // Set nest members attribute to default sentinel
3387   _nest_members = Universe::the_empty_short_array();
3388   // Set _permitted_subclasses attribute to default sentinel
3389   _permitted_subclasses = Universe::the_empty_short_array();
3390   cfs->guarantee_more(2, CHECK);  // attributes_count
3391   u2 attributes_count = cfs->get_u2_fast();
3392   bool parsed_sourcefile_attribute = false;
3393   bool parsed_innerclasses_attribute = false;
3394   bool parsed_nest_members_attribute = false;
3395   bool parsed_permitted_subclasses_attribute = false;
3396   bool parsed_nest_host_attribute = false;
3397   bool parsed_record_attribute = false;
3398   bool parsed_enclosingmethod_attribute = false;
3399   bool parsed_bootstrap_methods_attribute = false;
3400   const u1* runtime_visible_annotations = nullptr;
3401   int runtime_visible_annotations_length = 0;
3402   const u1* runtime_visible_type_annotations = nullptr;
3403   int runtime_visible_type_annotations_length = 0;
3404   bool runtime_invisible_type_annotations_exists = false;
3405   bool runtime_invisible_annotations_exists = false;
3406   bool parsed_source_debug_ext_annotations_exist = false;
3407   const u1* inner_classes_attribute_start = nullptr;
3408   u4  inner_classes_attribute_length = 0;
3409   u2  enclosing_method_class_index = 0;
3410   u2  enclosing_method_method_index = 0;
3411   const u1* nest_members_attribute_start = nullptr;
3412   u4  nest_members_attribute_length = 0;
3413   const u1* record_attribute_start = nullptr;
3414   u4  record_attribute_length = 0;
3415   const u1* permitted_subclasses_attribute_start = nullptr;
3416   u4  permitted_subclasses_attribute_length = 0;
3417 
3418   // Iterate over attributes
3419   while (attributes_count--) {
3420     cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
3421     const u2 attribute_name_index = cfs->get_u2_fast();
3422     const u4 attribute_length = cfs->get_u4_fast();
3423     guarantee_property(
3424       valid_symbol_at(attribute_name_index),
3425       "Attribute name has bad constant pool index %u in class file %s",
3426       attribute_name_index, CHECK);
3427     const Symbol* const tag = cp->symbol_at(attribute_name_index);
3428     if (tag == vmSymbols::tag_source_file()) {
3429       // Check for SourceFile tag
3430       if (_need_verify) {
3431         guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
3432       }
3433       if (parsed_sourcefile_attribute) {
3434         classfile_parse_error("Multiple SourceFile attributes in class file %s", THREAD);
3435         return;
3436       } else {
3437         parsed_sourcefile_attribute = true;
3438       }
3439       parse_classfile_sourcefile_attribute(cfs, CHECK);
3440     } else if (tag == vmSymbols::tag_source_debug_extension()) {
3441       // Check for SourceDebugExtension tag
3442       if (parsed_source_debug_ext_annotations_exist) {
3443         classfile_parse_error(
3444           "Multiple SourceDebugExtension attributes in class file %s", THREAD);
3445         return;
3446       }
3447       parsed_source_debug_ext_annotations_exist = true;
3448       parse_classfile_source_debug_extension_attribute(cfs, (int)attribute_length, CHECK);
3449     } else if (tag == vmSymbols::tag_inner_classes()) {
3450       // Check for InnerClasses tag
3451       if (parsed_innerclasses_attribute) {
3452         classfile_parse_error("Multiple InnerClasses attributes in class file %s", THREAD);
3453         return;
3454       } else {
3455         parsed_innerclasses_attribute = true;
3456       }
3457       inner_classes_attribute_start = cfs->current();
3458       inner_classes_attribute_length = attribute_length;
3459       cfs->skip_u1(inner_classes_attribute_length, CHECK);
3460     } else if (tag == vmSymbols::tag_synthetic()) {
3461       // Check for Synthetic tag
3462       // Shouldn't we check that the synthetic flags wasn't already set? - not required in spec
3463       if (attribute_length != 0) {
3464         classfile_parse_error(
3465           "Invalid Synthetic classfile attribute length %u in class file %s",
3466           attribute_length, THREAD);
3467         return;
3468       }
3469       parse_classfile_synthetic_attribute();
3470     } else if (tag == vmSymbols::tag_deprecated()) {
3471       // Check for Deprecated tag - 4276120
3472       if (attribute_length != 0) {
3473         classfile_parse_error(
3474           "Invalid Deprecated classfile attribute length %u in class file %s",
3475           attribute_length, THREAD);
3476         return;
3477       }
3478     } else if (_major_version >= JAVA_1_5_VERSION) {
3479       if (tag == vmSymbols::tag_signature()) {
3480         if (_generic_signature_index != 0) {
3481           classfile_parse_error(
3482             "Multiple Signature attributes in class file %s", THREAD);
3483           return;
3484         }
3485         if (attribute_length != 2) {
3486           classfile_parse_error(
3487             "Wrong Signature attribute length %u in class file %s",
3488             attribute_length, THREAD);
3489           return;
3490         }
3491         parse_classfile_signature_attribute(cfs, CHECK);
3492       } else if (tag == vmSymbols::tag_runtime_visible_annotations()) {
3493         if (runtime_visible_annotations != nullptr) {
3494           classfile_parse_error(
3495             "Multiple RuntimeVisibleAnnotations attributes in class file %s", THREAD);
3496           return;
3497         }
3498         runtime_visible_annotations_length = attribute_length;
3499         runtime_visible_annotations = cfs->current();
3500         assert(runtime_visible_annotations != nullptr, "null visible annotations");
3501         cfs->guarantee_more(runtime_visible_annotations_length, CHECK);
3502         parse_annotations(cp,
3503                           runtime_visible_annotations,
3504                           runtime_visible_annotations_length,
3505                           parsed_annotations,
3506                           _loader_data,
3507                           _can_access_vm_annotations);
3508         cfs->skip_u1_fast(runtime_visible_annotations_length);
3509       } else if (tag == vmSymbols::tag_runtime_invisible_annotations()) {
3510         if (runtime_invisible_annotations_exists) {
3511           classfile_parse_error(
3512             "Multiple RuntimeInvisibleAnnotations attributes in class file %s", THREAD);
3513           return;
3514         }
3515         runtime_invisible_annotations_exists = true;
3516         cfs->skip_u1(attribute_length, CHECK);
3517       } else if (tag == vmSymbols::tag_enclosing_method()) {
3518         if (parsed_enclosingmethod_attribute) {
3519           classfile_parse_error("Multiple EnclosingMethod attributes in class file %s", THREAD);
3520           return;
3521         } else {
3522           parsed_enclosingmethod_attribute = true;
3523         }
3524         guarantee_property(attribute_length == 4,
3525           "Wrong EnclosingMethod attribute length %u in class file %s",
3526           attribute_length, CHECK);
3527         cfs->guarantee_more(4, CHECK);  // class_index, method_index
3528         enclosing_method_class_index  = cfs->get_u2_fast();
3529         enclosing_method_method_index = cfs->get_u2_fast();
3530         if (enclosing_method_class_index == 0) {
3531           classfile_parse_error("Invalid class index in EnclosingMethod attribute in class file %s", THREAD);
3532           return;
3533         }
3534         // Validate the constant pool indices and types
3535         guarantee_property(valid_klass_reference_at(enclosing_method_class_index),
3536           "Invalid or out-of-bounds class index in EnclosingMethod attribute in class file %s", CHECK);
3537         if (enclosing_method_method_index != 0 &&
3538             (!cp->is_within_bounds(enclosing_method_method_index) ||
3539              !cp->tag_at(enclosing_method_method_index).is_name_and_type())) {
3540           classfile_parse_error("Invalid or out-of-bounds method index in EnclosingMethod attribute in class file %s", THREAD);
3541           return;
3542         }
3543       } else if (tag == vmSymbols::tag_bootstrap_methods() &&
3544                  _major_version >= Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {
3545         if (parsed_bootstrap_methods_attribute) {
3546           classfile_parse_error("Multiple BootstrapMethods attributes in class file %s", THREAD);
3547           return;
3548         }
3549         parsed_bootstrap_methods_attribute = true;
3550         parse_classfile_bootstrap_methods_attribute(cfs, cp, attribute_length, CHECK);
3551       } else if (tag == vmSymbols::tag_runtime_visible_type_annotations()) {
3552         if (runtime_visible_type_annotations != nullptr) {
3553           classfile_parse_error(
3554             "Multiple RuntimeVisibleTypeAnnotations attributes in class file %s", THREAD);
3555           return;
3556         }
3557         runtime_visible_type_annotations_length = attribute_length;
3558         runtime_visible_type_annotations = cfs->current();
3559         assert(runtime_visible_type_annotations != nullptr, "null visible type annotations");
3560         // No need for the VM to parse Type annotations
3561         cfs->skip_u1(runtime_visible_type_annotations_length, CHECK);
3562       } else if (tag == vmSymbols::tag_runtime_invisible_type_annotations()) {
3563         if (runtime_invisible_type_annotations_exists) {
3564           classfile_parse_error(
3565             "Multiple RuntimeInvisibleTypeAnnotations attributes in class file %s", THREAD);
3566           return;
3567         }
3568         runtime_invisible_type_annotations_exists = true;
3569         cfs->skip_u1(attribute_length, CHECK);
3570       } else if (_major_version >= JAVA_11_VERSION) {
3571         if (tag == vmSymbols::tag_nest_members()) {
3572           // Check for NestMembers tag
3573           if (parsed_nest_members_attribute) {
3574             classfile_parse_error("Multiple NestMembers attributes in class file %s", THREAD);
3575             return;
3576           } else {
3577             parsed_nest_members_attribute = true;
3578           }
3579           if (parsed_nest_host_attribute) {
3580             classfile_parse_error("Conflicting NestHost and NestMembers attributes in class file %s", THREAD);
3581             return;
3582           }
3583           nest_members_attribute_start = cfs->current();
3584           nest_members_attribute_length = attribute_length;
3585           cfs->skip_u1(nest_members_attribute_length, CHECK);
3586         } else if (tag == vmSymbols::tag_nest_host()) {
3587           if (parsed_nest_host_attribute) {
3588             classfile_parse_error("Multiple NestHost attributes in class file %s", THREAD);
3589             return;
3590           } else {
3591             parsed_nest_host_attribute = true;
3592           }
3593           if (parsed_nest_members_attribute) {
3594             classfile_parse_error("Conflicting NestMembers and NestHost attributes in class file %s", THREAD);
3595             return;
3596           }
3597           if (_need_verify) {
3598             guarantee_property(attribute_length == 2, "Wrong NestHost attribute length in class file %s", CHECK);
3599           }
3600           cfs->guarantee_more(2, CHECK);
3601           u2 class_info_index = cfs->get_u2_fast();
3602           guarantee_property(
3603                          valid_klass_reference_at(class_info_index),
3604                          "Nest-host class_info_index %u has bad constant type in class file %s",
3605                          class_info_index, CHECK);
3606           _nest_host = class_info_index;
3607 
3608         } else if (_major_version >= JAVA_16_VERSION) {
3609           if (tag == vmSymbols::tag_record()) {
3610             if (parsed_record_attribute) {
3611               classfile_parse_error("Multiple Record attributes in class file %s", THREAD);
3612               return;
3613             }
3614             parsed_record_attribute = true;
3615             record_attribute_start = cfs->current();
3616             record_attribute_length = attribute_length;
3617           } else if (_major_version >= JAVA_17_VERSION) {
3618             if (tag == vmSymbols::tag_permitted_subclasses()) {
3619               if (parsed_permitted_subclasses_attribute) {
3620                 classfile_parse_error("Multiple PermittedSubclasses attributes in class file %s", CHECK);
3621                 return;
3622               }
3623               // Classes marked ACC_FINAL cannot have a PermittedSubclasses attribute.
3624               if (_access_flags.is_final()) {
3625                 classfile_parse_error("PermittedSubclasses attribute in final class file %s", CHECK);
3626                 return;
3627               }
3628               parsed_permitted_subclasses_attribute = true;
3629               permitted_subclasses_attribute_start = cfs->current();
3630               permitted_subclasses_attribute_length = attribute_length;
3631             }
3632           }
3633           // Skip attribute_length for any attribute where major_verson >= JAVA_17_VERSION
3634           cfs->skip_u1(attribute_length, CHECK);
3635         } else {
3636           // Unknown attribute
3637           cfs->skip_u1(attribute_length, CHECK);
3638         }
3639       } else {
3640         // Unknown attribute
3641         cfs->skip_u1(attribute_length, CHECK);
3642       }
3643     } else {
3644       // Unknown attribute
3645       cfs->skip_u1(attribute_length, CHECK);
3646     }
3647   }
3648   _class_annotations = allocate_annotations(runtime_visible_annotations,
3649                                             runtime_visible_annotations_length,
3650                                             CHECK);
3651   _class_type_annotations = allocate_annotations(runtime_visible_type_annotations,
3652                                                  runtime_visible_type_annotations_length,
3653                                                  CHECK);
3654 
3655   if (parsed_innerclasses_attribute || parsed_enclosingmethod_attribute) {
3656     const u2 num_of_classes = parse_classfile_inner_classes_attribute(
3657                             cfs,
3658                             cp,
3659                             inner_classes_attribute_start,
3660                             parsed_innerclasses_attribute,
3661                             enclosing_method_class_index,
3662                             enclosing_method_method_index,
3663                             CHECK);
3664     if (parsed_innerclasses_attribute && _need_verify && _major_version >= JAVA_1_5_VERSION) {
3665       guarantee_property(
3666         inner_classes_attribute_length == sizeof(num_of_classes) + 4 * sizeof(u2) * num_of_classes,
3667         "Wrong InnerClasses attribute length in class file %s", CHECK);
3668     }
3669   }
3670 
3671   if (parsed_nest_members_attribute) {
3672     const u2 num_of_classes = parse_classfile_nest_members_attribute(
3673                             cfs,
3674                             nest_members_attribute_start,
3675                             CHECK);
3676     if (_need_verify) {
3677       guarantee_property(
3678         nest_members_attribute_length == sizeof(num_of_classes) + sizeof(u2) * num_of_classes,
3679         "Wrong NestMembers attribute length in class file %s", CHECK);
3680     }
3681   }
3682 
3683   if (parsed_record_attribute) {
3684     const unsigned int calculated_attr_length = parse_classfile_record_attribute(
3685                             cfs,
3686                             cp,
3687                             record_attribute_start,
3688                             CHECK);
3689     if (_need_verify) {
3690       guarantee_property(record_attribute_length == calculated_attr_length,
3691                          "Record attribute has wrong length in class file %s",
3692                          CHECK);
3693     }
3694   }
3695 
3696   if (parsed_permitted_subclasses_attribute) {
3697     const u2 num_subclasses = parse_classfile_permitted_subclasses_attribute(
3698                             cfs,
3699                             permitted_subclasses_attribute_start,
3700                             CHECK);
3701     if (_need_verify) {
3702       guarantee_property(
3703         permitted_subclasses_attribute_length == sizeof(num_subclasses) + sizeof(u2) * num_subclasses,
3704         "Wrong PermittedSubclasses attribute length in class file %s", CHECK);
3705     }
3706   }
3707 
3708   if (_max_bootstrap_specifier_index >= 0) {
3709     guarantee_property(parsed_bootstrap_methods_attribute,
3710                        "Missing BootstrapMethods attribute in class file %s", CHECK);
3711   }
3712 }
3713 
3714 void ClassFileParser::apply_parsed_class_attributes(InstanceKlass* k) {
3715   assert(k != nullptr, "invariant");
3716 
3717   if (_synthetic_flag)
3718     k->set_is_synthetic();
3719   if (_sourcefile_index != 0) {
3720     k->set_source_file_name_index(_sourcefile_index);
3721   }
3722   if (_generic_signature_index != 0) {
3723     k->set_generic_signature_index(_generic_signature_index);
3724   }
3725   if (_sde_buffer != nullptr) {
3726     k->set_source_debug_extension(_sde_buffer, _sde_length);
3727   }
3728 }
3729 
3730 // Create the Annotations object that will
3731 // hold the annotations array for the Klass.
3732 void ClassFileParser::create_combined_annotations(TRAPS) {
3733     if (_class_annotations == nullptr &&
3734         _class_type_annotations == nullptr &&
3735         _fields_annotations == nullptr &&
3736         _fields_type_annotations == nullptr) {
3737       // Don't create the Annotations object unnecessarily.
3738       return;
3739     }
3740 
3741     Annotations* const annotations = Annotations::allocate(_loader_data, CHECK);
3742     annotations->set_class_annotations(_class_annotations);
3743     annotations->set_class_type_annotations(_class_type_annotations);
3744     annotations->set_fields_annotations(_fields_annotations);
3745     annotations->set_fields_type_annotations(_fields_type_annotations);
3746 
3747     // This is the Annotations object that will be
3748     // assigned to InstanceKlass being constructed.
3749     _combined_annotations = annotations;
3750 
3751     // The annotations arrays below has been transferred the
3752     // _combined_annotations so these fields can now be cleared.
3753     _class_annotations       = nullptr;
3754     _class_type_annotations  = nullptr;
3755     _fields_annotations      = nullptr;
3756     _fields_type_annotations = nullptr;
3757 }
3758 
3759 // Transfer ownership of metadata allocated to the InstanceKlass.
3760 void ClassFileParser::apply_parsed_class_metadata(
3761                                             InstanceKlass* this_klass,
3762                                             int java_fields_count) {
3763   assert(this_klass != nullptr, "invariant");
3764 
3765   _cp->set_pool_holder(this_klass);
3766   this_klass->set_constants(_cp);
3767   this_klass->set_fieldinfo_stream(_fieldinfo_stream);
3768   this_klass->set_fieldinfo_search_table(_fieldinfo_search_table);
3769   this_klass->set_fields_status(_fields_status);
3770   this_klass->set_methods(_methods);
3771   this_klass->set_inner_classes(_inner_classes);
3772   this_klass->set_nest_members(_nest_members);
3773   this_klass->set_nest_host_index(_nest_host);
3774   this_klass->set_annotations(_combined_annotations);
3775   this_klass->set_permitted_subclasses(_permitted_subclasses);
3776   this_klass->set_record_components(_record_components);
3777 
3778   DEBUG_ONLY(FieldInfoStream::validate_search_table(_cp, _fieldinfo_stream, _fieldinfo_search_table));
3779 
3780   // Delay the setting of _local_interfaces and _transitive_interfaces until after
3781   // initialize_supers() in fill_instance_klass(). It is because the _local_interfaces could
3782   // be shared with _transitive_interfaces and _transitive_interfaces may be shared with
3783   // its _super. If an OOM occurs while loading the current klass, its _super field
3784   // may not have been set. When GC tries to free the klass, the _transitive_interfaces
3785   // may be deallocated mistakenly in InstanceKlass::deallocate_interfaces(). Subsequent
3786   // dereferences to the deallocated _transitive_interfaces will result in a crash.
3787 
3788   // Clear out these fields so they don't get deallocated by the destructor
3789   clear_class_metadata();
3790 }
3791 
3792 AnnotationArray* ClassFileParser::allocate_annotations(const u1* const anno,
3793                                                        int anno_length,
3794                                                        TRAPS) {
3795   AnnotationArray* annotations = nullptr;
3796   if (anno != nullptr) {
3797     annotations = MetadataFactory::new_array<u1>(_loader_data,
3798                                                  anno_length,
3799                                                  CHECK_(annotations));
3800     for (int i = 0; i < anno_length; i++) {
3801       annotations->at_put(i, anno[i]);
3802     }
3803   }
3804   return annotations;
3805 }
3806 
3807 void ClassFileParser::check_super_class(ConstantPool* const cp,
3808                                         const int super_class_index,
3809                                         const bool need_verify,
3810                                         TRAPS) {
3811   assert(cp != nullptr, "invariant");
3812 
3813   if (super_class_index == 0) {
3814     guarantee_property(_class_name == vmSymbols::java_lang_Object(),
3815                        "Invalid superclass index %u in class file %s",
3816                        super_class_index,
3817                        CHECK);
3818   } else {
3819     guarantee_property(valid_klass_reference_at(super_class_index),
3820                        "Invalid superclass index %u in class file %s",
3821                        super_class_index,
3822                        CHECK);
3823 
3824     // The class name should be legal because it is checked when parsing constant pool.
3825     // However, make sure it is not an array type.
3826     if (need_verify) {
3827       guarantee_property(cp->klass_name_at(super_class_index)->char_at(0) != JVM_SIGNATURE_ARRAY,
3828                         "Bad superclass name in class file %s", CHECK);
3829     }
3830   }
3831 }
3832 
3833 OopMapBlocksBuilder::OopMapBlocksBuilder(unsigned int max_blocks) {
3834   _max_nonstatic_oop_maps = max_blocks;
3835   _nonstatic_oop_map_count = 0;
3836   if (max_blocks == 0) {
3837     _nonstatic_oop_maps = nullptr;
3838   } else {
3839     _nonstatic_oop_maps =
3840         NEW_RESOURCE_ARRAY(OopMapBlock, _max_nonstatic_oop_maps);
3841     memset(_nonstatic_oop_maps, 0, sizeof(OopMapBlock) * max_blocks);
3842   }
3843 }
3844 
3845 OopMapBlock* OopMapBlocksBuilder::last_oop_map() const {
3846   assert(_nonstatic_oop_map_count > 0, "Has no oop maps");
3847   return _nonstatic_oop_maps + (_nonstatic_oop_map_count - 1);
3848 }
3849 
3850 // addition of super oop maps
3851 void OopMapBlocksBuilder::initialize_inherited_blocks(OopMapBlock* blocks, unsigned int nof_blocks) {
3852   assert(nof_blocks && _nonstatic_oop_map_count == 0 &&
3853          nof_blocks <= _max_nonstatic_oop_maps, "invariant");
3854 
3855   memcpy(_nonstatic_oop_maps, blocks, sizeof(OopMapBlock) * nof_blocks);
3856   _nonstatic_oop_map_count += nof_blocks;
3857 }
3858 
3859 // collection of oops
3860 void OopMapBlocksBuilder::add(int offset, int count) {
3861   if (_nonstatic_oop_map_count == 0) {
3862     _nonstatic_oop_map_count++;
3863   }
3864   OopMapBlock* nonstatic_oop_map = last_oop_map();
3865   if (nonstatic_oop_map->count() == 0) {  // Unused map, set it up
3866     nonstatic_oop_map->set_offset(offset);
3867     nonstatic_oop_map->set_count(count);
3868   } else if (nonstatic_oop_map->is_contiguous(offset)) { // contiguous, add
3869     nonstatic_oop_map->increment_count(count);
3870   } else { // Need a new one...
3871     _nonstatic_oop_map_count++;
3872     assert(_nonstatic_oop_map_count <= _max_nonstatic_oop_maps, "range check");
3873     nonstatic_oop_map = last_oop_map();
3874     nonstatic_oop_map->set_offset(offset);
3875     nonstatic_oop_map->set_count(count);
3876   }
3877 }
3878 
3879 // general purpose copy, e.g. into allocated instanceKlass
3880 void OopMapBlocksBuilder::copy(OopMapBlock* dst) {
3881   if (_nonstatic_oop_map_count != 0) {
3882     memcpy(dst, _nonstatic_oop_maps, sizeof(OopMapBlock) * _nonstatic_oop_map_count);
3883   }
3884 }
3885 
3886 // Sort and compact adjacent blocks
3887 void OopMapBlocksBuilder::compact() {
3888   if (_nonstatic_oop_map_count <= 1) {
3889     return;
3890   }
3891   /*
3892    * Since field layout sneaks in oops before values, we will be able to condense
3893    * blocks. There is potential to compact between super, own refs and values
3894    * containing refs.
3895    *
3896    * Currently compaction is slightly limited due to values being 8 byte aligned.
3897    * This may well change: FixMe if it doesn't, the code below is fairly general purpose
3898    * and maybe it doesn't need to be.
3899    */
3900   qsort(_nonstatic_oop_maps, _nonstatic_oop_map_count, sizeof(OopMapBlock),
3901         (_sort_Fn)OopMapBlock::compare_offset);
3902   if (_nonstatic_oop_map_count < 2) {
3903     return;
3904   }
3905 
3906   // Make a temp copy, and iterate through and copy back into the original
3907   ResourceMark rm;
3908   OopMapBlock* oop_maps_copy =
3909       NEW_RESOURCE_ARRAY(OopMapBlock, _nonstatic_oop_map_count);
3910   OopMapBlock* oop_maps_copy_end = oop_maps_copy + _nonstatic_oop_map_count;
3911   copy(oop_maps_copy);
3912   OopMapBlock* nonstatic_oop_map = _nonstatic_oop_maps;
3913   unsigned int new_count = 1;
3914   oop_maps_copy++;
3915   while(oop_maps_copy < oop_maps_copy_end) {
3916     assert(nonstatic_oop_map->offset() < oop_maps_copy->offset(), "invariant");
3917     if (nonstatic_oop_map->is_contiguous(oop_maps_copy->offset())) {
3918       nonstatic_oop_map->increment_count(oop_maps_copy->count());
3919     } else {
3920       nonstatic_oop_map++;
3921       new_count++;
3922       nonstatic_oop_map->set_offset(oop_maps_copy->offset());
3923       nonstatic_oop_map->set_count(oop_maps_copy->count());
3924     }
3925     oop_maps_copy++;
3926   }
3927   assert(new_count <= _nonstatic_oop_map_count, "end up with more maps after compact() ?");
3928   _nonstatic_oop_map_count = new_count;
3929 }
3930 
3931 void OopMapBlocksBuilder::print_on(outputStream* st) const {
3932   st->print_cr("  OopMapBlocks: %3d  /%3d", _nonstatic_oop_map_count, _max_nonstatic_oop_maps);
3933   if (_nonstatic_oop_map_count > 0) {
3934     OopMapBlock* map = _nonstatic_oop_maps;
3935     OopMapBlock* last_map = last_oop_map();
3936     assert(map <= last_map, "Last less than first");
3937     while (map <= last_map) {
3938       st->print_cr("    Offset: %3d  -%3d Count: %3d", map->offset(),
3939                    map->offset() + map->offset_span() - heapOopSize, map->count());
3940       map++;
3941     }
3942   }
3943 }
3944 
3945 void OopMapBlocksBuilder::print_value_on(outputStream* st) const {
3946   print_on(st);
3947 }
3948 
3949 void ClassFileParser::set_precomputed_flags(InstanceKlass* ik) {
3950   assert(ik != nullptr, "invariant");
3951 
3952   const InstanceKlass* const super = ik->super();
3953 
3954   // Check if this klass has an empty finalize method (i.e. one with return bytecode only),
3955   // in which case we don't have to register objects as finalizable
3956   if (!_has_empty_finalizer) {
3957     if (_has_finalizer ||
3958         (super != nullptr && super->has_finalizer())) {
3959       ik->set_has_finalizer();
3960     }
3961   }
3962 
3963 #ifdef ASSERT
3964   bool f = false;
3965   const Method* const m = ik->lookup_method(vmSymbols::finalize_method_name(),
3966                                            vmSymbols::void_method_signature());
3967   if (InstanceKlass::is_finalization_enabled() &&
3968       (m != nullptr) && !m->is_empty_method()) {
3969       f = true;
3970   }
3971 
3972   // Spec doesn't prevent agent from redefinition of empty finalizer.
3973   // Despite the fact that it's generally bad idea and redefined finalizer
3974   // will not work as expected we shouldn't abort vm in this case
3975   if (!ik->has_redefined_this_or_super()) {
3976     assert(ik->has_finalizer() == f, "inconsistent has_finalizer");
3977   }
3978 #endif
3979 
3980   // Check if this klass supports the java.lang.Cloneable interface
3981   if (vmClasses::Cloneable_klass_is_loaded()) {
3982     if (ik->is_subtype_of(vmClasses::Cloneable_klass())) {
3983       ik->set_is_cloneable();
3984     }
3985   }
3986 
3987   // If it cannot be fast-path allocated, set a bit in the layout helper.
3988   // See documentation of InstanceKlass::can_be_fastpath_allocated().
3989   assert(ik->size_helper() > 0, "layout_helper is initialized");
3990   if (ik->is_abstract() || ik->is_interface()
3991       || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == nullptr)
3992       || ik->size_helper() >= FastAllocateSizeLimit) {
3993     // Forbid fast-path allocation.
3994     const jint lh = Klass::instance_layout_helper(ik->size_helper(), true);
3995     ik->set_layout_helper(lh);
3996   }
3997 
3998   // Propagate the AOT runtimeSetup method discovery
3999   if (_has_aot_runtime_setup_method) {
4000     ik->set_is_runtime_setup_required();
4001     if (log_is_enabled(Info, aot, init)) {
4002       ResourceMark rm;
4003       log_info(aot, init)("Found @AOTRuntimeSetup class %s", ik->external_name());
4004     }
4005   }
4006 }
4007 
4008 // utility methods for appending an array with check for duplicates
4009 
4010 static void append_interfaces(GrowableArray<InstanceKlass*>* result,
4011                               const Array<InstanceKlass*>* const ifs) {
4012   // iterate over new interfaces
4013   for (int i = 0; i < ifs->length(); i++) {
4014     InstanceKlass* const e = ifs->at(i);
4015     assert(e->is_klass() && e->is_interface(), "just checking");
4016     // add new interface
4017     result->append_if_missing(e);
4018   }
4019 }
4020 
4021 static Array<InstanceKlass*>* compute_transitive_interfaces(const InstanceKlass* super,
4022                                                             Array<InstanceKlass*>* local_ifs,
4023                                                             ClassLoaderData* loader_data,
4024                                                             TRAPS) {
4025   assert(local_ifs != nullptr, "invariant");
4026   assert(loader_data != nullptr, "invariant");
4027 
4028   // Compute maximum size for transitive interfaces
4029   int max_transitive_size = 0;
4030   int super_size = 0;
4031   // Add superclass transitive interfaces size
4032   if (super != nullptr) {
4033     super_size = super->transitive_interfaces()->length();
4034     max_transitive_size += super_size;
4035   }
4036   // Add local interfaces' super interfaces
4037   const int local_size = local_ifs->length();
4038   for (int i = 0; i < local_size; i++) {
4039     InstanceKlass* const l = local_ifs->at(i);
4040     max_transitive_size += l->transitive_interfaces()->length();
4041   }
4042   // Finally add local interfaces
4043   max_transitive_size += local_size;
4044   // Construct array
4045   if (max_transitive_size == 0) {
4046     // no interfaces, use canonicalized array
4047     return Universe::the_empty_instance_klass_array();
4048   } else if (max_transitive_size == super_size) {
4049     // no new local interfaces added, share superklass' transitive interface array
4050     return super->transitive_interfaces();
4051   } else if (max_transitive_size == local_size) {
4052     // only local interfaces added, share local interface array
4053     return local_ifs;
4054   } else {
4055     ResourceMark rm;
4056     GrowableArray<InstanceKlass*>* const result = new GrowableArray<InstanceKlass*>(max_transitive_size);
4057 
4058     // Copy down from superclass
4059     if (super != nullptr) {
4060       append_interfaces(result, super->transitive_interfaces());
4061     }
4062 
4063     // Copy down from local interfaces' superinterfaces
4064     for (int i = 0; i < local_size; i++) {
4065       InstanceKlass* const l = local_ifs->at(i);
4066       append_interfaces(result, l->transitive_interfaces());
4067     }
4068     // Finally add local interfaces
4069     append_interfaces(result, local_ifs);
4070 
4071     // length will be less than the max_transitive_size if duplicates were removed
4072     const int length = result->length();
4073     assert(length <= max_transitive_size, "just checking");
4074     Array<InstanceKlass*>* const new_result =
4075       MetadataFactory::new_array<InstanceKlass*>(loader_data, length, CHECK_NULL);
4076     for (int i = 0; i < length; i++) {
4077       InstanceKlass* const e = result->at(i);
4078       assert(e != nullptr, "just checking");
4079       new_result->at_put(i, e);
4080     }
4081     return new_result;
4082   }
4083 }
4084 
4085 void ClassFileParser::check_super_class_access(const InstanceKlass* this_klass, TRAPS) {
4086   assert(this_klass != nullptr, "invariant");
4087   const InstanceKlass* const super = this_klass->super();
4088 
4089   if (super != nullptr) {
4090     if (super->is_final()) {
4091       classfile_icce_error("class %s cannot inherit from final class %s", super, THREAD);
4092       return;
4093     }
4094 
4095     if (super->is_sealed()) {
4096       stringStream ss;
4097       ResourceMark rm(THREAD);
4098       if (!super->has_as_permitted_subclass(this_klass, ss)) {
4099         classfile_icce_error(ss.as_string(), THREAD);
4100         return;
4101       }
4102     }
4103 
4104     Reflection::VerifyClassAccessResults vca_result =
4105       Reflection::verify_class_access(this_klass, super, false);
4106     if (vca_result != Reflection::ACCESS_OK) {
4107       ResourceMark rm(THREAD);
4108       char* msg = Reflection::verify_class_access_msg(this_klass,
4109                                                       super,
4110                                                       vca_result);
4111 
4112       // Names are all known to be < 64k so we know this formatted message is not excessively large.
4113       if (msg == nullptr) {
4114         bool same_module = (this_klass->module() == super->module());
4115         Exceptions::fthrow(
4116           THREAD_AND_LOCATION,
4117           vmSymbols::java_lang_IllegalAccessError(),
4118           "class %s cannot access its %ssuperclass %s (%s%s%s)",
4119           this_klass->external_name(),
4120           super->is_abstract() ? "abstract " : "",
4121           super->external_name(),
4122           (same_module) ? this_klass->joint_in_module_of_loader(super) : this_klass->class_in_module_of_loader(),
4123           (same_module) ? "" : "; ",
4124           (same_module) ? "" : super->class_in_module_of_loader());
4125       } else {
4126         // Add additional message content.
4127         Exceptions::fthrow(
4128           THREAD_AND_LOCATION,
4129           vmSymbols::java_lang_IllegalAccessError(),
4130           "superclass access check failed: %s",
4131           msg);
4132       }
4133     }
4134   }
4135 }
4136 
4137 
4138 void ClassFileParser::check_super_interface_access(const InstanceKlass* this_klass, TRAPS) {
4139   assert(this_klass != nullptr, "invariant");
4140   const Array<InstanceKlass*>* const local_interfaces = this_klass->local_interfaces();
4141   const int lng = local_interfaces->length();
4142   for (int i = lng - 1; i >= 0; i--) {
4143     InstanceKlass* const k = local_interfaces->at(i);
4144     assert (k != nullptr && k->is_interface(), "invalid interface");
4145 
4146     if (k->is_sealed()) {
4147       stringStream ss;
4148       ResourceMark rm(THREAD);
4149       if (!k->has_as_permitted_subclass(this_klass, ss)) {
4150         classfile_icce_error(ss.as_string(), THREAD);
4151         return;
4152       }
4153     }
4154 
4155     Reflection::VerifyClassAccessResults vca_result =
4156       Reflection::verify_class_access(this_klass, k, false);
4157     if (vca_result != Reflection::ACCESS_OK) {
4158       ResourceMark rm(THREAD);
4159       char* msg = Reflection::verify_class_access_msg(this_klass,
4160                                                       k,
4161                                                       vca_result);
4162 
4163       // Names are all known to be < 64k so we know this formatted message is not excessively large.
4164       if (msg == nullptr) {
4165         bool same_module = (this_klass->module() == k->module());
4166         Exceptions::fthrow(
4167           THREAD_AND_LOCATION,
4168           vmSymbols::java_lang_IllegalAccessError(),
4169           "class %s cannot access its superinterface %s (%s%s%s)",
4170           this_klass->external_name(),
4171           k->external_name(),
4172           (same_module) ? this_klass->joint_in_module_of_loader(k) : this_klass->class_in_module_of_loader(),
4173           (same_module) ? "" : "; ",
4174           (same_module) ? "" : k->class_in_module_of_loader());
4175         return;
4176       } else {
4177         // Add additional message content.
4178         Exceptions::fthrow(
4179           THREAD_AND_LOCATION,
4180           vmSymbols::java_lang_IllegalAccessError(),
4181           "superinterface check failed: %s",
4182           msg);
4183         return;
4184       }
4185     }
4186   }
4187 }
4188 
4189 
4190 static void check_final_method_override(const InstanceKlass* this_klass, TRAPS) {
4191   assert(this_klass != nullptr, "invariant");
4192   const Array<Method*>* const methods = this_klass->methods();
4193   const int num_methods = methods->length();
4194 
4195   // go thru each method and check if it overrides a final method
4196   for (int index = 0; index < num_methods; index++) {
4197     const Method* const m = methods->at(index);
4198 
4199     // skip private, static, and <init> methods
4200     if ((!m->is_private() && !m->is_static()) &&
4201         (m->name() != vmSymbols::object_initializer_name())) {
4202 
4203       const Symbol* const name = m->name();
4204       const Symbol* const signature = m->signature();
4205       const InstanceKlass* k = this_klass->super();
4206       const Method* super_m = nullptr;
4207       while (k != nullptr) {
4208         // skip supers that don't have final methods.
4209         if (k->has_final_method()) {
4210           // lookup a matching method in the super class hierarchy
4211           super_m = k->lookup_method(name, signature);
4212           if (super_m == nullptr) {
4213             break; // didn't find any match; get out
4214           }
4215 
4216           if (super_m->is_final() && !super_m->is_static() &&
4217               !super_m->access_flags().is_private()) {
4218             // matching method in super is final, and not static or private
4219             bool can_access = Reflection::verify_member_access(this_klass,
4220                                                                super_m->method_holder(),
4221                                                                super_m->method_holder(),
4222                                                                super_m->access_flags(),
4223                                                               false, false, CHECK);
4224             if (can_access) {
4225               // this class can access super final method and therefore override
4226               ResourceMark rm(THREAD);
4227               THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
4228                         err_msg("class %s overrides final method %s.%s%s",
4229                                 this_klass->external_name(),
4230                                 super_m->method_holder()->external_name(),
4231                                 name->as_C_string(),
4232                                 signature->as_C_string()));
4233             }
4234           }
4235 
4236           // continue to look from super_m's holder's super.
4237           k = super_m->method_holder()->super();
4238           continue;
4239         }
4240 
4241         k = k->super();
4242       }
4243     }
4244   }
4245 }
4246 
4247 
4248 // assumes that this_klass is an interface
4249 static void check_illegal_static_method(const InstanceKlass* this_klass, TRAPS) {
4250   assert(this_klass != nullptr, "invariant");
4251   assert(this_klass->is_interface(), "not an interface");
4252   const Array<Method*>* methods = this_klass->methods();
4253   const int num_methods = methods->length();
4254 
4255   for (int index = 0; index < num_methods; index++) {
4256     const Method* const m = methods->at(index);
4257     // if m is static and not the init method, throw a verify error
4258     if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) {
4259       ResourceMark rm(THREAD);
4260 
4261       // Names are all known to be < 64k so we know this formatted message is not excessively large.
4262       Exceptions::fthrow(
4263         THREAD_AND_LOCATION,
4264         vmSymbols::java_lang_VerifyError(),
4265         "Illegal static method %s in interface %s",
4266         m->name()->as_C_string(),
4267         this_klass->external_name()
4268       );
4269       return;
4270     }
4271   }
4272 }
4273 
4274 // utility methods for format checking
4275 
4276 // Verify the class modifiers for the current class, or an inner class if inner_name is non-null.
4277 void ClassFileParser::verify_legal_class_modifiers(jint flags, Symbol* inner_name, bool is_anonymous_inner_class, TRAPS) const {
4278   const bool is_module = (flags & JVM_ACC_MODULE) != 0;
4279   assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");
4280   if (is_module) {
4281     ResourceMark rm(THREAD);
4282     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4283     Exceptions::fthrow(
4284       THREAD_AND_LOCATION,
4285       vmSymbols::java_lang_NoClassDefFoundError(),
4286       "%s is not a class because access_flag ACC_MODULE is set",
4287       _class_name->as_C_string());
4288     return;
4289   }
4290 
4291   if (!_need_verify) { return; }
4292 
4293   const bool is_interface  = (flags & JVM_ACC_INTERFACE)  != 0;
4294   const bool is_abstract   = (flags & JVM_ACC_ABSTRACT)   != 0;
4295   const bool is_final      = (flags & JVM_ACC_FINAL)      != 0;
4296   const bool is_super      = (flags & JVM_ACC_SUPER)      != 0;
4297   const bool is_enum       = (flags & JVM_ACC_ENUM)       != 0;
4298   const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4299   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4300 
4301   if ((is_abstract && is_final) ||
4302       (is_interface && !is_abstract) ||
4303       (is_interface && major_gte_1_5 && (is_super || is_enum)) ||
4304       (!is_interface && major_gte_1_5 && is_annotation)) {
4305     ResourceMark rm(THREAD);
4306     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4307     if (inner_name == nullptr && !is_anonymous_inner_class) {
4308       Exceptions::fthrow(
4309         THREAD_AND_LOCATION,
4310         vmSymbols::java_lang_ClassFormatError(),
4311         "Illegal class modifiers in class %s: 0x%X",
4312         _class_name->as_C_string(), flags
4313       );
4314     } else {
4315       if (is_anonymous_inner_class) {
4316         Exceptions::fthrow(
4317           THREAD_AND_LOCATION,
4318           vmSymbols::java_lang_ClassFormatError(),
4319           "Illegal class modifiers in anonymous inner class of class %s: 0x%X",
4320           _class_name->as_C_string(), flags
4321         );
4322       } else {
4323         Exceptions::fthrow(
4324           THREAD_AND_LOCATION,
4325           vmSymbols::java_lang_ClassFormatError(),
4326           "Illegal class modifiers in inner class %s of class %s: 0x%X",
4327           inner_name->as_C_string(), _class_name->as_C_string(), flags
4328         );
4329       }
4330     }
4331     return;
4332   }
4333 }
4334 
4335 static bool has_illegal_visibility(jint flags) {
4336   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4337   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4338   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4339 
4340   return ((is_public && is_protected) ||
4341           (is_public && is_private) ||
4342           (is_protected && is_private));
4343 }
4344 
4345 // A legal major_version.minor_version must be one of the following:
4346 //
4347 //  Major_version >= 45 and major_version < 56, any minor_version.
4348 //  Major_version >= 56 and major_version <= JVM_CLASSFILE_MAJOR_VERSION and minor_version = 0.
4349 //  Major_version = JVM_CLASSFILE_MAJOR_VERSION and minor_version = 65535 and --enable-preview is present.
4350 //
4351 void ClassFileParser::verify_class_version(u2 major, u2 minor, Symbol* class_name, TRAPS){
4352   ResourceMark rm(THREAD);
4353   const u2 max_version = JVM_CLASSFILE_MAJOR_VERSION;
4354   if (major < JAVA_MIN_SUPPORTED_VERSION) {
4355     classfile_ucve_error("%s (class file version %u.%u) was compiled with an invalid major version",
4356                          class_name, major, minor, THREAD);
4357     return;
4358   }
4359 
4360   if (major > max_version) {
4361     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4362     Exceptions::fthrow(
4363       THREAD_AND_LOCATION,
4364       vmSymbols::java_lang_UnsupportedClassVersionError(),
4365       "%s has been compiled by a more recent version of the Java Runtime (class file version %u.%u), "
4366       "this version of the Java Runtime only recognizes class file versions up to %u.0",
4367       class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION);
4368     return;
4369   }
4370 
4371   if (major < JAVA_12_VERSION || minor == 0) {
4372     return;
4373   }
4374 
4375   if (minor == JAVA_PREVIEW_MINOR_VERSION) {
4376     if (major != max_version) {
4377       // Names are all known to be < 64k so we know this formatted message is not excessively large.
4378       Exceptions::fthrow(
4379         THREAD_AND_LOCATION,
4380         vmSymbols::java_lang_UnsupportedClassVersionError(),
4381         "%s (class file version %u.%u) was compiled with preview features that are unsupported. "
4382         "This version of the Java Runtime only recognizes preview features for class file version %u.%u",
4383         class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION, JAVA_PREVIEW_MINOR_VERSION);
4384       return;
4385     }
4386 
4387     if (!Arguments::enable_preview()) {
4388       classfile_ucve_error("Preview features are not enabled for %s (class file version %u.%u). Try running with '--enable-preview'",
4389                            class_name, major, minor, THREAD);
4390       return;
4391     }
4392 
4393   } else { // minor != JAVA_PREVIEW_MINOR_VERSION
4394     classfile_ucve_error("%s (class file version %u.%u) was compiled with an invalid non-zero minor version",
4395                          class_name, major, minor, THREAD);
4396   }
4397 }
4398 
4399 void ClassFileParser::verify_legal_field_modifiers(jint flags,
4400                                                    bool is_interface,
4401                                                    TRAPS) const {
4402   if (!_need_verify) { return; }
4403 
4404   const bool is_public    = (flags & JVM_ACC_PUBLIC)      != 0;
4405   const bool is_protected = (flags & JVM_ACC_PROTECTED)   != 0;
4406   const bool is_private   = (flags & JVM_ACC_PRIVATE)     != 0;
4407   const bool is_static    = (flags & JVM_ACC_STATIC)      != 0;
4408   const bool is_final     = (flags & JVM_ACC_FINAL)       != 0;
4409   const bool is_volatile  = (flags & JVM_ACC_VOLATILE)    != 0;
4410   const bool is_transient = (flags & JVM_ACC_TRANSIENT)   != 0;
4411   const bool is_enum      = (flags & JVM_ACC_ENUM)        != 0;
4412   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4413 
4414   bool is_illegal = false;
4415 
4416   if (is_interface) {
4417     if (!is_public || !is_static || !is_final || is_private ||
4418         is_protected || is_volatile || is_transient ||
4419         (major_gte_1_5 && is_enum)) {
4420       is_illegal = true;
4421     }
4422   } else { // not interface
4423     if (has_illegal_visibility(flags) || (is_final && is_volatile)) {
4424       is_illegal = true;
4425     }
4426   }
4427 
4428   if (is_illegal) {
4429     ResourceMark rm(THREAD);
4430     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4431     Exceptions::fthrow(
4432       THREAD_AND_LOCATION,
4433       vmSymbols::java_lang_ClassFormatError(),
4434       "Illegal field modifiers in class %s: 0x%X",
4435       _class_name->as_C_string(), flags);
4436     return;
4437   }
4438 }
4439 
4440 void ClassFileParser::verify_legal_method_modifiers(jint flags,
4441                                                     bool is_interface,
4442                                                     const Symbol* name,
4443                                                     TRAPS) const {
4444   if (!_need_verify) { return; }
4445 
4446   const bool is_public       = (flags & JVM_ACC_PUBLIC)       != 0;
4447   const bool is_private      = (flags & JVM_ACC_PRIVATE)      != 0;
4448   const bool is_static       = (flags & JVM_ACC_STATIC)       != 0;
4449   const bool is_final        = (flags & JVM_ACC_FINAL)        != 0;
4450   const bool is_native       = (flags & JVM_ACC_NATIVE)       != 0;
4451   const bool is_abstract     = (flags & JVM_ACC_ABSTRACT)     != 0;
4452   const bool is_bridge       = (flags & JVM_ACC_BRIDGE)       != 0;
4453   const bool is_strict       = (flags & JVM_ACC_STRICT)       != 0;
4454   const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
4455   const bool is_protected    = (flags & JVM_ACC_PROTECTED)    != 0;
4456   const bool major_gte_1_5   = _major_version >= JAVA_1_5_VERSION;
4457   const bool major_gte_8     = _major_version >= JAVA_8_VERSION;
4458   const bool major_gte_17    = _major_version >= JAVA_17_VERSION;
4459   const bool is_initializer  = (name == vmSymbols::object_initializer_name());
4460 
4461   bool is_illegal = false;
4462 
4463   if (is_interface) {
4464     if (major_gte_8) {
4465       // Class file version is JAVA_8_VERSION or later Methods of
4466       // interfaces may set any of the flags except ACC_PROTECTED,
4467       // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must
4468       // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.
4469       if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
4470           (is_native || is_protected || is_final || is_synchronized) ||
4471           // If a specific method of a class or interface has its
4472           // ACC_ABSTRACT flag set, it must not have any of its
4473           // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,
4474           // ACC_STRICT, or ACC_SYNCHRONIZED flags set.  No need to
4475           // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as
4476           // those flags are illegal irrespective of ACC_ABSTRACT being set or not.
4477           (is_abstract && (is_private || is_static || (!major_gte_17 && is_strict)))) {
4478         is_illegal = true;
4479       }
4480     } else if (major_gte_1_5) {
4481       // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)
4482       if (!is_public || is_private || is_protected || is_static || is_final ||
4483           is_synchronized || is_native || !is_abstract || is_strict) {
4484         is_illegal = true;
4485       }
4486     } else {
4487       // Class file version is pre-JAVA_1_5_VERSION
4488       if (!is_public || is_static || is_final || is_native || !is_abstract) {
4489         is_illegal = true;
4490       }
4491     }
4492   } else { // not interface
4493     if (has_illegal_visibility(flags)) {
4494       is_illegal = true;
4495     } else {
4496       if (is_initializer) {
4497         if (is_static || is_final || is_synchronized || is_native ||
4498             is_abstract || (major_gte_1_5 && is_bridge)) {
4499           is_illegal = true;
4500         }
4501       } else { // not initializer
4502         if (is_abstract) {
4503           if ((is_final || is_native || is_private || is_static ||
4504               (major_gte_1_5 && (is_synchronized || (!major_gte_17 && is_strict))))) {
4505             is_illegal = true;
4506           }
4507         }
4508       }
4509     }
4510   }
4511 
4512   if (is_illegal) {
4513     ResourceMark rm(THREAD);
4514     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4515     Exceptions::fthrow(
4516       THREAD_AND_LOCATION,
4517       vmSymbols::java_lang_ClassFormatError(),
4518       "Method %s in class %s has illegal modifiers: 0x%X",
4519       name->as_C_string(), _class_name->as_C_string(), flags);
4520     return;
4521   }
4522 }
4523 
4524 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer,
4525                                         int length,
4526                                         TRAPS) const {
4527   assert(_need_verify, "only called when _need_verify is true");
4528   // Note: 0 <= length < 64K, as it comes from a u2 entry in the CP.
4529   if (!UTF8::is_legal_utf8(buffer, static_cast<size_t>(length), _major_version <= 47)) {
4530     classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", THREAD);
4531   }
4532 }
4533 
4534 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
4535 // In class names, '/' separates unqualified names.  This is verified in this function also.
4536 // Method names also may not contain the characters '<' or '>', unless <init>
4537 // or <clinit>.  Note that method names may not be <init> or <clinit> in this
4538 // method.  Because these names have been checked as special cases before
4539 // calling this method in verify_legal_method_name.
4540 //
4541 // This method is also called from the modular system APIs in modules.cpp
4542 // to verify the validity of module and package names.
4543 bool ClassFileParser::verify_unqualified_name(const char* name,
4544                                               unsigned int length,
4545                                               int type) {
4546   if (length == 0) return false;  // Must have at least one char.
4547   for (const char* p = name; p != name + length; p++) {
4548     switch(*p) {
4549       case JVM_SIGNATURE_DOT:
4550       case JVM_SIGNATURE_ENDCLASS:
4551       case JVM_SIGNATURE_ARRAY:
4552         // do not permit '.', ';', or '['
4553         return false;
4554       case JVM_SIGNATURE_SLASH:
4555         // check for '//' or leading or trailing '/' which are not legal
4556         // unqualified name must not be empty
4557         if (type == ClassFileParser::LegalClass) {
4558           if (p == name || p+1 >= name+length ||
4559               *(p+1) == JVM_SIGNATURE_SLASH) {
4560             return false;
4561           }
4562         } else {
4563           return false;   // do not permit '/' unless it's class name
4564         }
4565         break;
4566       case JVM_SIGNATURE_SPECIAL:
4567       case JVM_SIGNATURE_ENDSPECIAL:
4568         // do not permit '<' or '>' in method names
4569         if (type == ClassFileParser::LegalMethod) {
4570           return false;
4571         }
4572     }
4573   }
4574   return true;
4575 }
4576 
4577 // Take pointer to a UTF8 byte string (not NUL-terminated).
4578 // Skip over the longest part of the string that could
4579 // be taken as a fieldname. Allow non-trailing '/'s if slash_ok is true.
4580 // Return a pointer to just past the fieldname.
4581 // Return null if no fieldname at all was found, or in the case of slash_ok
4582 // being true, we saw consecutive slashes (meaning we were looking for a
4583 // qualified path but found something that was badly-formed).
4584 static const char* skip_over_field_name(const char* const name,
4585                                         bool slash_ok,
4586                                         unsigned int length) {
4587   const char* p;
4588   jboolean last_is_slash = false;
4589   jboolean not_first_ch = false;
4590 
4591   for (p = name; p != name + length; not_first_ch = true) {
4592     const char* old_p = p;
4593     jchar ch = *p;
4594     if (ch < 128) {
4595       p++;
4596       // quick check for ascii
4597       if ((ch >= 'a' && ch <= 'z') ||
4598         (ch >= 'A' && ch <= 'Z') ||
4599         (ch == '_' || ch == '$') ||
4600         (not_first_ch && ch >= '0' && ch <= '9')) {
4601         last_is_slash = false;
4602         continue;
4603       }
4604       if (slash_ok && ch == JVM_SIGNATURE_SLASH) {
4605         if (last_is_slash) {
4606           return nullptr;  // Don't permit consecutive slashes
4607         }
4608         last_is_slash = true;
4609         continue;
4610       }
4611     }
4612     else {
4613       jint unicode_ch;
4614       char* tmp_p = UTF8::next_character(p, &unicode_ch);
4615       p = tmp_p;
4616       last_is_slash = false;
4617       // Check if ch is Java identifier start or is Java identifier part
4618       // 4672820: call java.lang.Character methods directly without generating separate tables.
4619       EXCEPTION_MARK;
4620       // return value
4621       JavaValue result(T_BOOLEAN);
4622       // Set up the arguments to isJavaIdentifierStart or isJavaIdentifierPart
4623       JavaCallArguments args;
4624       args.push_int(unicode_ch);
4625 
4626       if (not_first_ch) {
4627         // public static boolean isJavaIdentifierPart(char ch);
4628         JavaCalls::call_static(&result,
4629           vmClasses::Character_klass(),
4630           vmSymbols::isJavaIdentifierPart_name(),
4631           vmSymbols::int_bool_signature(),
4632           &args,
4633           THREAD);
4634       } else {
4635         // public static boolean isJavaIdentifierStart(char ch);
4636         JavaCalls::call_static(&result,
4637           vmClasses::Character_klass(),
4638           vmSymbols::isJavaIdentifierStart_name(),
4639           vmSymbols::int_bool_signature(),
4640           &args,
4641           THREAD);
4642       }
4643       if (HAS_PENDING_EXCEPTION) {
4644         CLEAR_PENDING_EXCEPTION;
4645         return nullptr;
4646       }
4647       if(result.get_jboolean()) {
4648         continue;
4649       }
4650     }
4651     return (not_first_ch) ? old_p : nullptr;
4652   }
4653   return (not_first_ch && !last_is_slash) ? p : nullptr;
4654 }
4655 
4656 // Take pointer to a UTF8 byte string (not NUL-terminated).
4657 // Skip over the longest part of the string that could
4658 // be taken as a field signature. Allow "void" if void_ok.
4659 // Return a pointer to just past the signature.
4660 // Return null if no legal signature is found.
4661 const char* ClassFileParser::skip_over_field_signature(const char* signature,
4662                                                        bool void_ok,
4663                                                        unsigned int length,
4664                                                        TRAPS) const {
4665   unsigned int array_dim = 0;
4666   while (length > 0) {
4667     switch (signature[0]) {
4668     case JVM_SIGNATURE_VOID: if (!void_ok) { return nullptr; }
4669     case JVM_SIGNATURE_BOOLEAN:
4670     case JVM_SIGNATURE_BYTE:
4671     case JVM_SIGNATURE_CHAR:
4672     case JVM_SIGNATURE_SHORT:
4673     case JVM_SIGNATURE_INT:
4674     case JVM_SIGNATURE_FLOAT:
4675     case JVM_SIGNATURE_LONG:
4676     case JVM_SIGNATURE_DOUBLE:
4677       return signature + 1;
4678     case JVM_SIGNATURE_CLASS: {
4679       if (_major_version < JAVA_1_5_VERSION) {
4680         signature++;
4681         length--;
4682         // Skip over the class name if one is there
4683         const char* const p = skip_over_field_name(signature, true, length);
4684         assert(p == nullptr || p > signature, "must parse one character at least");
4685         // The next character better be a semicolon
4686         if (p != nullptr                             && // Parse of field name succeeded.
4687             p - signature < static_cast<int>(length) && // There is at least one character left to parse.
4688             p[0] == JVM_SIGNATURE_ENDCLASS) {
4689           return p + 1;
4690         }
4691       }
4692       else {
4693         // Skip leading 'L' and ignore first appearance of ';'
4694         signature++;
4695         const char* c = (const char*) memchr(signature, JVM_SIGNATURE_ENDCLASS, length - 1);
4696         // Format check signature
4697         if (c != nullptr) {
4698           int newlen = pointer_delta_as_int(c, (char*) signature);
4699           bool legal = verify_unqualified_name(signature, newlen, LegalClass);
4700           if (!legal) {
4701             classfile_parse_error("Class name is empty or contains illegal character "
4702                                   "in descriptor in class file %s",
4703                                   THREAD);
4704             return nullptr;
4705           }
4706           return signature + newlen + 1;
4707         }
4708       }
4709       return nullptr;
4710     }
4711     case JVM_SIGNATURE_ARRAY:
4712       array_dim++;
4713       if (array_dim > 255) {
4714         // 4277370: array descriptor is valid only if it represents 255 or fewer dimensions.
4715         classfile_parse_error("Array type descriptor has more than 255 dimensions in class file %s", THREAD);
4716         return nullptr;
4717       }
4718       // The rest of what's there better be a legal signature
4719       signature++;
4720       length--;
4721       void_ok = false;
4722       break;
4723     default:
4724       return nullptr;
4725     }
4726   }
4727   return nullptr;
4728 }
4729 
4730 // Checks if name is a legal class name.
4731 void ClassFileParser::verify_legal_class_name(const Symbol* name, TRAPS) const {
4732   if (!_need_verify) { return; }
4733 
4734   assert(name->refcount() > 0, "symbol must be kept alive");
4735   char* bytes = (char*)name->bytes();
4736   unsigned int length = name->utf8_length();
4737   bool legal = false;
4738 
4739   if (length > 0) {
4740     const char* p;
4741     if (bytes[0] == JVM_SIGNATURE_ARRAY) {
4742       p = skip_over_field_signature(bytes, false, length, CHECK);
4743       legal = (p != nullptr) && ((p - bytes) == (int)length);
4744     } else if (_major_version < JAVA_1_5_VERSION) {
4745       if (bytes[0] != JVM_SIGNATURE_SPECIAL) {
4746         p = skip_over_field_name(bytes, true, length);
4747         legal = (p != nullptr) && ((p - bytes) == (int)length);
4748       }
4749     } else {
4750       // 4900761: relax the constraints based on JSR202 spec
4751       // Class names may be drawn from the entire Unicode character set.
4752       // Identifiers between '/' must be unqualified names.
4753       // The utf8 string has been verified when parsing cpool entries.
4754       legal = verify_unqualified_name(bytes, length, LegalClass);
4755     }
4756   }
4757   if (!legal) {
4758     ResourceMark rm(THREAD);
4759     assert(_class_name != nullptr, "invariant");
4760     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4761     Exceptions::fthrow(
4762       THREAD_AND_LOCATION,
4763       vmSymbols::java_lang_ClassFormatError(),
4764       "Illegal class name \"%.*s\" in class file %s", length, bytes,
4765       _class_name->as_C_string()
4766     );
4767     return;
4768   }
4769 }
4770 
4771 // Checks if name is a legal field name.
4772 void ClassFileParser::verify_legal_field_name(const Symbol* name, TRAPS) const {
4773   if (!_need_verify) { return; }
4774 
4775   char* bytes = (char*)name->bytes();
4776   unsigned int length = name->utf8_length();
4777   bool legal = false;
4778 
4779   if (length > 0) {
4780     if (_major_version < JAVA_1_5_VERSION) {
4781       if (bytes[0] != JVM_SIGNATURE_SPECIAL) {
4782         const char* p = skip_over_field_name(bytes, false, length);
4783         legal = (p != nullptr) && ((p - bytes) == (int)length);
4784       }
4785     } else {
4786       // 4881221: relax the constraints based on JSR202 spec
4787       legal = verify_unqualified_name(bytes, length, LegalField);
4788     }
4789   }
4790 
4791   if (!legal) {
4792     ResourceMark rm(THREAD);
4793     assert(_class_name != nullptr, "invariant");
4794     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4795     Exceptions::fthrow(
4796       THREAD_AND_LOCATION,
4797       vmSymbols::java_lang_ClassFormatError(),
4798       "Illegal field name \"%.*s\" in class %s", length, bytes,
4799       _class_name->as_C_string()
4800     );
4801     return;
4802   }
4803 }
4804 
4805 // Checks if name is a legal method name.
4806 void ClassFileParser::verify_legal_method_name(const Symbol* name, TRAPS) const {
4807   if (!_need_verify) { return; }
4808 
4809   assert(name != nullptr, "method name is null");
4810   char* bytes = (char*)name->bytes();
4811   unsigned int length = name->utf8_length();
4812   bool legal = false;
4813 
4814   if (length > 0) {
4815     if (bytes[0] == JVM_SIGNATURE_SPECIAL) {
4816       if (name == vmSymbols::object_initializer_name() || name == vmSymbols::class_initializer_name()) {
4817         legal = true;
4818       }
4819     } else if (_major_version < JAVA_1_5_VERSION) {
4820       const char* p;
4821       p = skip_over_field_name(bytes, false, length);
4822       legal = (p != nullptr) && ((p - bytes) == (int)length);
4823     } else {
4824       // 4881221: relax the constraints based on JSR202 spec
4825       legal = verify_unqualified_name(bytes, length, LegalMethod);
4826     }
4827   }
4828 
4829   if (!legal) {
4830     ResourceMark rm(THREAD);
4831     assert(_class_name != nullptr, "invariant");
4832     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4833     Exceptions::fthrow(
4834       THREAD_AND_LOCATION,
4835       vmSymbols::java_lang_ClassFormatError(),
4836       "Illegal method name \"%.*s\" in class %s", length, bytes,
4837       _class_name->as_C_string()
4838     );
4839     return;
4840   }
4841 }
4842 
4843 
4844 // Checks if signature is a legal field signature.
4845 void ClassFileParser::verify_legal_field_signature(const Symbol* name,
4846                                                    const Symbol* signature,
4847                                                    TRAPS) const {
4848   if (!_need_verify) { return; }
4849 
4850   const char* const bytes = (const char*)signature->bytes();
4851   const unsigned int length = signature->utf8_length();
4852   const char* const p = skip_over_field_signature(bytes, false, length, CHECK);
4853 
4854   if (p == nullptr || (p - bytes) != (int)length) {
4855     throwIllegalSignature("Field", name, signature, CHECK);
4856   }
4857 }
4858 
4859 // Check that the signature is compatible with the method name.  For example,
4860 // check that <init> has a void signature.
4861 void ClassFileParser::verify_legal_name_with_signature(const Symbol* name,
4862                                                        const Symbol* signature,
4863                                                        TRAPS) const {
4864   if (!_need_verify) {
4865     return;
4866   }
4867 
4868   // Class initializers cannot have args for class format version >= 51.
4869   if (name == vmSymbols::class_initializer_name() &&
4870       signature != vmSymbols::void_method_signature() &&
4871       _major_version >= JAVA_7_VERSION) {
4872     throwIllegalSignature("Method", name, signature, THREAD);
4873     return;
4874   }
4875 
4876   int sig_length = signature->utf8_length();
4877   if (name->utf8_length() > 0 &&
4878       name->char_at(0) == JVM_SIGNATURE_SPECIAL &&
4879       sig_length > 0 &&
4880       signature->char_at(sig_length - 1) != JVM_SIGNATURE_VOID) {
4881     throwIllegalSignature("Method", name, signature, THREAD);
4882   }
4883 }
4884 
4885 // Checks if signature is a legal method signature.
4886 // Returns number of parameters
4887 int ClassFileParser::verify_legal_method_signature(const Symbol* name,
4888                                                    const Symbol* signature,
4889                                                    TRAPS) const {
4890   if (!_need_verify) {
4891     // make sure caller's args_size will be less than 0 even for non-static
4892     // method so it will be recomputed in compute_size_of_parameters().
4893     return -2;
4894   }
4895 
4896   unsigned int args_size = 0;
4897   const char* p = (const char*)signature->bytes();
4898   unsigned int length = signature->utf8_length();
4899   const char* nextp;
4900 
4901   // The first character must be a '('
4902   if ((length > 0) && (*p++ == JVM_SIGNATURE_FUNC)) {
4903     length--;
4904     // Skip over legal field signatures
4905     nextp = skip_over_field_signature(p, false, length, CHECK_0);
4906     while ((length > 0) && (nextp != nullptr)) {
4907       args_size++;
4908       if (p[0] == 'J' || p[0] == 'D') {
4909         args_size++;
4910       }
4911       length -= pointer_delta_as_int(nextp, p);
4912       p = nextp;
4913       nextp = skip_over_field_signature(p, false, length, CHECK_0);
4914     }
4915     // The first non-signature thing better be a ')'
4916     if ((length > 0) && (*p++ == JVM_SIGNATURE_ENDFUNC)) {
4917       length--;
4918       // Now we better just have a return value
4919       nextp = skip_over_field_signature(p, true, length, CHECK_0);
4920       if (nextp && ((int)length == (nextp - p))) {
4921         return args_size;
4922       }
4923     }
4924   }
4925   // Report error
4926   throwIllegalSignature("Method", name, signature, THREAD);
4927   return 0;
4928 }
4929 
4930 int ClassFileParser::static_field_size() const {
4931   assert(_field_info != nullptr, "invariant");
4932   return _field_info->_static_field_size;
4933 }
4934 
4935 int ClassFileParser::total_oop_map_count() const {
4936   assert(_field_info != nullptr, "invariant");
4937   return _field_info->oop_map_blocks->_nonstatic_oop_map_count;
4938 }
4939 
4940 jint ClassFileParser::layout_size() const {
4941   assert(_field_info != nullptr, "invariant");
4942   return _field_info->_instance_size;
4943 }
4944 
4945 static void check_methods_for_intrinsics(const InstanceKlass* ik,
4946                                          const Array<Method*>* methods) {
4947   assert(ik != nullptr, "invariant");
4948   assert(methods != nullptr, "invariant");
4949 
4950   // Set up Method*::intrinsic_id as soon as we know the names of methods.
4951   // (We used to do this lazily, but now we query it in Rewriter,
4952   // which is eagerly done for every method, so we might as well do it now,
4953   // when everything is fresh in memory.)
4954   const vmSymbolID klass_id = Method::klass_id_for_intrinsics(ik);
4955 
4956   if (klass_id != vmSymbolID::NO_SID) {
4957     for (int j = 0; j < methods->length(); ++j) {
4958       Method* method = methods->at(j);
4959       method->init_intrinsic_id(klass_id);
4960 
4961       if (CheckIntrinsics) {
4962         // Check if an intrinsic is defined for method 'method',
4963         // but the method is not annotated with @IntrinsicCandidate.
4964         if (method->intrinsic_id() != vmIntrinsics::_none &&
4965             !method->intrinsic_candidate()) {
4966               tty->print("Compiler intrinsic is defined for method [%s], "
4967               "but the method is not annotated with @IntrinsicCandidate.%s",
4968               method->name_and_sig_as_C_string(),
4969               NOT_DEBUG(" Method will not be inlined.") DEBUG_ONLY(" Exiting.")
4970             );
4971           tty->cr();
4972           DEBUG_ONLY(vm_exit(1));
4973         }
4974         // Check is the method 'method' is annotated with @IntrinsicCandidate,
4975         // but there is no intrinsic available for it.
4976         if (method->intrinsic_candidate() &&
4977           method->intrinsic_id() == vmIntrinsics::_none) {
4978             tty->print("Method [%s] is annotated with @IntrinsicCandidate, "
4979               "but no compiler intrinsic is defined for the method.%s",
4980               method->name_and_sig_as_C_string(),
4981               NOT_DEBUG("") DEBUG_ONLY(" Exiting.")
4982             );
4983           tty->cr();
4984           DEBUG_ONLY(vm_exit(1));
4985         }
4986       }
4987     } // end for
4988 
4989 #ifdef ASSERT
4990     if (CheckIntrinsics) {
4991       // Check for orphan methods in the current class. A method m
4992       // of a class C is orphan if an intrinsic is defined for method m,
4993       // but class C does not declare m.
4994       // The check is potentially expensive, therefore it is available
4995       // only in debug builds.
4996 
4997       for (auto id : EnumRange<vmIntrinsicID>{}) {
4998         if (vmIntrinsics::_compiledLambdaForm == id) {
4999           // The _compiledLamdbdaForm intrinsic is a special marker for bytecode
5000           // generated for the JVM from a LambdaForm and therefore no method
5001           // is defined for it.
5002           continue;
5003         }
5004         if (vmIntrinsics::_blackhole == id) {
5005           // The _blackhole intrinsic is a special marker. No explicit method
5006           // is defined for it.
5007           continue;
5008         }
5009 
5010         if (vmIntrinsics::class_for(id) == klass_id) {
5011           // Check if the current class contains a method with the same
5012           // name, flags, signature.
5013           bool match = false;
5014           for (int j = 0; j < methods->length(); ++j) {
5015             const Method* method = methods->at(j);
5016             if (method->intrinsic_id() == id) {
5017               match = true;
5018               break;
5019             }
5020           }
5021 
5022           if (!match) {
5023             char buf[1000];
5024             tty->print("Compiler intrinsic is defined for method [%s], "
5025                        "but the method is not available in class [%s].%s",
5026                         vmIntrinsics::short_name_as_C_string(id, buf, sizeof(buf)),
5027                         ik->name()->as_C_string(),
5028                         NOT_DEBUG("") DEBUG_ONLY(" Exiting.")
5029             );
5030             tty->cr();
5031             DEBUG_ONLY(vm_exit(1));
5032           }
5033         }
5034       } // end for
5035     } // CheckIntrinsics
5036 #endif // ASSERT
5037   }
5038 }
5039 
5040 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook,
5041                                                       const ClassInstanceInfo& cl_inst_info,
5042                                                       TRAPS) {
5043   if (_klass != nullptr) {
5044     return _klass;
5045   }
5046 
5047   InstanceKlass* const ik =
5048     InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
5049 
5050   if (is_hidden()) {
5051     mangle_hidden_class_name(ik);
5052   }
5053 
5054   fill_instance_klass(ik, changed_by_loadhook, cl_inst_info, CHECK_NULL);
5055 
5056   assert(_klass == ik, "invariant");
5057 
5058   return ik;
5059 }
5060 
5061 void ClassFileParser::fill_instance_klass(InstanceKlass* ik,
5062                                           bool changed_by_loadhook,
5063                                           const ClassInstanceInfo& cl_inst_info,
5064                                           TRAPS) {
5065   assert(ik != nullptr, "invariant");
5066 
5067   // Set name and CLD before adding to CLD
5068   ik->set_class_loader_data(_loader_data);
5069   ik->set_class_loader_type();
5070   ik->set_name(_class_name);
5071 
5072   // Add all classes to our internal class loader list here,
5073   // including classes in the bootstrap (null) class loader.
5074   const bool publicize = !is_internal();
5075 
5076   _loader_data->add_class(ik, publicize);
5077 
5078   set_klass_to_deallocate(ik);
5079 
5080   assert(_field_info != nullptr, "invariant");
5081   assert(ik->static_field_size() == _field_info->_static_field_size, "sanity");
5082   assert(ik->nonstatic_oop_map_count() == _field_info->oop_map_blocks->_nonstatic_oop_map_count,
5083          "sanity");
5084 
5085   assert(ik->is_instance_klass(), "sanity");
5086   assert(ik->size_helper() == _field_info->_instance_size, "sanity");
5087 
5088   // Fill in information already parsed
5089   ik->set_should_verify_class(_need_verify);
5090 
5091   // Not yet: supers are done below to support the new subtype-checking fields
5092   ik->set_nonstatic_field_size(_field_info->_nonstatic_field_size);
5093   ik->set_has_nonstatic_fields(_field_info->_has_nonstatic_fields);
5094   ik->set_static_oop_field_count(_static_oop_count);
5095 
5096   // this transfers ownership of a lot of arrays from
5097   // the parser onto the InstanceKlass*
5098   apply_parsed_class_metadata(ik, _java_fields_count);
5099 
5100   // can only set dynamic nest-host after static nest information is set
5101   if (cl_inst_info.dynamic_nest_host() != nullptr) {
5102     ik->set_nest_host(cl_inst_info.dynamic_nest_host());
5103   }
5104 
5105   // note that is not safe to use the fields in the parser from this point on
5106   assert(nullptr == _cp, "invariant");
5107   assert(nullptr == _fieldinfo_stream, "invariant");
5108   assert(nullptr == _fieldinfo_search_table, "invariant");
5109   assert(nullptr == _fields_status, "invariant");
5110   assert(nullptr == _methods, "invariant");
5111   assert(nullptr == _inner_classes, "invariant");
5112   assert(nullptr == _nest_members, "invariant");
5113   assert(nullptr == _combined_annotations, "invariant");
5114   assert(nullptr == _record_components, "invariant");
5115   assert(nullptr == _permitted_subclasses, "invariant");
5116 
5117   if (_has_localvariable_table) {
5118     ik->set_has_localvariable_table(true);
5119   }
5120 
5121   if (_has_final_method) {
5122     ik->set_has_final_method();
5123   }
5124 
5125   ik->copy_method_ordering(_method_ordering, CHECK);
5126   // The InstanceKlass::_methods_jmethod_ids cache
5127   // is managed on the assumption that the initial cache
5128   // size is equal to the number of methods in the class. If
5129   // that changes, then InstanceKlass::idnum_can_increment()
5130   // has to be changed accordingly.
5131   ik->set_initial_method_idnum(checked_cast<u2>(ik->methods()->length()));
5132 
5133   ik->set_this_class_index(_this_class_index);
5134 
5135   if (_is_hidden) {
5136     // _this_class_index is a CONSTANT_Class entry that refers to this
5137     // hidden class itself. If this class needs to refer to its own methods
5138     // or fields, it would use a CONSTANT_MethodRef, etc, which would reference
5139     // _this_class_index. However, because this class is hidden (it's
5140     // not stored in SystemDictionary), _this_class_index cannot be resolved
5141     // with ConstantPool::klass_at_impl, which does a SystemDictionary lookup.
5142     // Therefore, we must eagerly resolve _this_class_index now.
5143     ik->constants()->klass_at_put(_this_class_index, ik);
5144   }
5145 
5146   ik->set_minor_version(_minor_version);
5147   ik->set_major_version(_major_version);
5148   ik->set_has_nonstatic_concrete_methods(_has_nonstatic_concrete_methods);
5149   ik->set_declares_nonstatic_concrete_methods(_declares_nonstatic_concrete_methods);
5150 
5151   assert(!_is_hidden || ik->is_hidden(), "must be set already");
5152 
5153   // Set PackageEntry for this_klass
5154   oop cl = ik->class_loader();
5155   Handle clh = Handle(THREAD, cl);
5156   ClassLoaderData* cld = ClassLoaderData::class_loader_data_or_null(clh());
5157   ik->set_package(cld, nullptr, CHECK);
5158 
5159   const Array<Method*>* const methods = ik->methods();
5160   assert(methods != nullptr, "invariant");
5161   const int methods_len = methods->length();
5162 
5163   check_methods_for_intrinsics(ik, methods);
5164 
5165   // Fill in field values obtained by parse_classfile_attributes
5166   if (_parsed_annotations->has_any_annotations())
5167     _parsed_annotations->apply_to(ik);
5168 
5169   apply_parsed_class_attributes(ik);
5170 
5171   // Miranda methods
5172   if ((_num_miranda_methods > 0) ||
5173       // if this class introduced new miranda methods or
5174       (_super_klass != nullptr && _super_klass->has_miranda_methods())
5175         // super class exists and this class inherited miranda methods
5176      ) {
5177        ik->set_has_miranda_methods(); // then set a flag
5178   }
5179 
5180   // Fill in information needed to compute superclasses.
5181   ik->initialize_supers(const_cast<InstanceKlass*>(_super_klass), _transitive_interfaces, CHECK);
5182   ik->set_transitive_interfaces(_transitive_interfaces);
5183   ik->set_local_interfaces(_local_interfaces);
5184   _transitive_interfaces = nullptr;
5185   _local_interfaces = nullptr;
5186 
5187   // Initialize itable offset tables
5188   klassItable::setup_itable_offset_table(ik);
5189 
5190   // Compute transitive closure of interfaces this class implements
5191   // Do final class setup
5192   OopMapBlocksBuilder* oop_map_blocks = _field_info->oop_map_blocks;
5193   if (oop_map_blocks->_nonstatic_oop_map_count > 0) {
5194     oop_map_blocks->copy(ik->start_of_nonstatic_oop_maps());
5195   }
5196 
5197   if (_has_contended_fields || _parsed_annotations->is_contended() ||
5198       ( _super_klass != nullptr && _super_klass->has_contended_annotations())) {
5199     ik->set_has_contended_annotations(true);
5200   }
5201 
5202   // Fill in has_finalizer and layout_helper
5203   set_precomputed_flags(ik);
5204 
5205   // check if this class can access its super class
5206   check_super_class_access(ik, CHECK);
5207 
5208   // check if this class can access its superinterfaces
5209   check_super_interface_access(ik, CHECK);
5210 
5211   // check if this class overrides any final method
5212   check_final_method_override(ik, CHECK);
5213 
5214   // reject static interface methods prior to Java 8
5215   if (ik->is_interface() && _major_version < JAVA_8_VERSION) {
5216     check_illegal_static_method(ik, CHECK);
5217   }
5218 
5219   // Obtain this_klass' module entry
5220   ModuleEntry* module_entry = ik->module();
5221   assert(module_entry != nullptr, "module_entry should always be set");
5222 
5223   // Obtain java.lang.Module
5224   Handle module_handle(THREAD, module_entry->module_oop());
5225 
5226   // Allocate mirror and initialize static fields
5227   java_lang_Class::create_mirror(ik,
5228                                  Handle(THREAD, _loader_data->class_loader()),
5229                                  module_handle,
5230                                  _protection_domain,
5231                                  cl_inst_info.class_data(),
5232                                  CHECK);
5233 
5234   assert(_all_mirandas != nullptr, "invariant");
5235 
5236   // Generate any default methods - default methods are public interface methods
5237   // that have a default implementation.  This is new with Java 8.
5238   if (_has_nonstatic_concrete_methods) {
5239     DefaultMethods::generate_default_methods(ik,
5240                                              _all_mirandas,
5241                                              CHECK);
5242   }
5243 
5244   // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5245   if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5246       !module_entry->has_default_read_edges()) {
5247     if (!module_entry->set_has_default_read_edges()) {
5248       // We won a potential race
5249       JvmtiExport::add_default_read_edges(module_handle, THREAD);
5250     }
5251   }
5252 
5253   ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5254 
5255   if (!is_internal()) {
5256     ik->print_class_load_logging(_loader_data, module_entry, _stream);
5257     if (CDSConfig::is_dumping_archive()) {
5258       SystemDictionaryShared::check_code_source(ik, _stream);
5259     }
5260 
5261     if (ik->minor_version() == JAVA_PREVIEW_MINOR_VERSION &&
5262         ik->major_version() == JVM_CLASSFILE_MAJOR_VERSION &&
5263         log_is_enabled(Info, class, preview)) {
5264       ResourceMark rm;
5265       log_info(class, preview)("Loading class %s that depends on preview features (class file version %d.65535)",
5266                                ik->external_name(), JVM_CLASSFILE_MAJOR_VERSION);
5267     }
5268 
5269     if (log_is_enabled(Debug, class, resolve))  {
5270       ResourceMark rm;
5271       // print out the superclass.
5272       const char * from = ik->external_name();
5273       if (ik->super() != nullptr) {
5274         log_debug(class, resolve)("%s %s (super)",
5275                    from,
5276                    ik->super()->external_name());
5277       }
5278       // print out each of the interface classes referred to by this class.
5279       const Array<InstanceKlass*>* const local_interfaces = ik->local_interfaces();
5280       if (local_interfaces != nullptr) {
5281         const int length = local_interfaces->length();
5282         for (int i = 0; i < length; i++) {
5283           const InstanceKlass* const k = local_interfaces->at(i);
5284           const char * to = k->external_name();
5285           log_debug(class, resolve)("%s %s (interface)", from, to);
5286         }
5287       }
5288     }
5289   }
5290 
5291   // If we reach here, all is well.
5292   // Now remove the InstanceKlass* from the _klass_to_deallocate field
5293   // in order for it to not be destroyed in the ClassFileParser destructor.
5294   set_klass_to_deallocate(nullptr);
5295 
5296   // it's official
5297   set_klass(ik);
5298 
5299   DEBUG_ONLY(ik->verify();)
5300 }
5301 
5302 void ClassFileParser::update_class_name(Symbol* new_class_name) {
5303   // Decrement the refcount in the old name, since we're clobbering it.
5304   _class_name->decrement_refcount();
5305 
5306   _class_name = new_class_name;
5307   // Increment the refcount of the new name.
5308   // Now the ClassFileParser owns this name and will decrement in
5309   // the destructor.
5310   _class_name->increment_refcount();
5311 }
5312 
5313 ClassFileParser::ClassFileParser(ClassFileStream* stream,
5314                                  Symbol* name,
5315                                  ClassLoaderData* loader_data,
5316                                  const ClassLoadInfo* cl_info,
5317                                  Publicity pub_level,
5318                                  TRAPS) :
5319   _stream(stream),
5320   _class_name(nullptr),
5321   _loader_data(loader_data),
5322   _is_hidden(cl_info->is_hidden()),
5323   _can_access_vm_annotations(cl_info->can_access_vm_annotations()),
5324   _orig_cp_size(0),
5325   _static_oop_count(0),
5326   _super_klass(),
5327   _cp(nullptr),
5328   _fieldinfo_stream(nullptr),
5329   _fieldinfo_search_table(nullptr),
5330   _fields_status(nullptr),
5331   _methods(nullptr),
5332   _inner_classes(nullptr),
5333   _nest_members(nullptr),
5334   _nest_host(0),
5335   _permitted_subclasses(nullptr),
5336   _record_components(nullptr),
5337   _local_interfaces(nullptr),
5338   _transitive_interfaces(nullptr),
5339   _combined_annotations(nullptr),
5340   _class_annotations(nullptr),
5341   _class_type_annotations(nullptr),
5342   _fields_annotations(nullptr),
5343   _fields_type_annotations(nullptr),
5344   _klass(nullptr),
5345   _klass_to_deallocate(nullptr),
5346   _parsed_annotations(nullptr),
5347   _field_info(nullptr),
5348   _temp_field_info(nullptr),
5349   _method_ordering(nullptr),
5350   _all_mirandas(nullptr),
5351   _vtable_size(0),
5352   _itable_size(0),
5353   _num_miranda_methods(0),
5354   _protection_domain(cl_info->protection_domain()),
5355   _access_flags(),
5356   _pub_level(pub_level),
5357   _bad_constant_seen(0),
5358   _synthetic_flag(false),
5359   _sde_length(false),
5360   _sde_buffer(nullptr),
5361   _sourcefile_index(0),
5362   _generic_signature_index(0),
5363   _major_version(0),
5364   _minor_version(0),
5365   _this_class_index(0),
5366   _super_class_index(0),
5367   _itfs_len(0),
5368   _java_fields_count(0),
5369   _need_verify(false),
5370   _has_nonstatic_concrete_methods(false),
5371   _declares_nonstatic_concrete_methods(false),
5372   _has_localvariable_table(false),
5373   _has_final_method(false),
5374   _has_contended_fields(false),
5375   _has_aot_runtime_setup_method(false),
5376   _has_finalizer(false),
5377   _has_empty_finalizer(false),
5378   _max_bootstrap_specifier_index(-1) {
5379 
5380   _class_name = name != nullptr ? name : vmSymbols::unknown_class_name();
5381   _class_name->increment_refcount();
5382 
5383   assert(_loader_data != nullptr, "invariant");
5384   assert(stream != nullptr, "invariant");
5385   assert(_stream != nullptr, "invariant");
5386   assert(_stream->buffer() == _stream->current(), "invariant");
5387   assert(_class_name != nullptr, "invariant");
5388   assert(0 == _access_flags.as_unsigned_short(), "invariant");
5389 
5390   // Figure out whether we can skip format checking (matching classic VM behavior)
5391   // Always verify CFLH bytes from the user agents.
5392   _need_verify = stream->from_class_file_load_hook() ? true : Verifier::should_verify_for(_loader_data->class_loader());
5393 
5394   // synch back verification state to stream to check for truncation.
5395   stream->set_need_verify(_need_verify);
5396 
5397   parse_stream(stream, CHECK);
5398 
5399   post_process_parsed_stream(stream, _cp, CHECK);
5400 }
5401 
5402 void ClassFileParser::clear_class_metadata() {
5403   // metadata created before the instance klass is created.  Must be
5404   // deallocated if classfile parsing returns an error.
5405   _cp = nullptr;
5406   _fieldinfo_stream = nullptr;
5407   _fieldinfo_search_table = nullptr;
5408   _fields_status = nullptr;
5409   _methods = nullptr;
5410   _inner_classes = nullptr;
5411   _nest_members = nullptr;
5412   _permitted_subclasses = nullptr;
5413   _combined_annotations = nullptr;
5414   _class_annotations = _class_type_annotations = nullptr;
5415   _fields_annotations = _fields_type_annotations = nullptr;
5416   _record_components = nullptr;
5417 }
5418 
5419 // Destructor to clean up
5420 ClassFileParser::~ClassFileParser() {
5421   _class_name->decrement_refcount();
5422 
5423   if (_cp != nullptr) {
5424     MetadataFactory::free_metadata(_loader_data, _cp);
5425   }
5426 
5427   if (_fieldinfo_stream != nullptr) {
5428     MetadataFactory::free_array<u1>(_loader_data, _fieldinfo_stream);
5429   }
5430   MetadataFactory::free_array<u1>(_loader_data, _fieldinfo_search_table);
5431 
5432   if (_fields_status != nullptr) {
5433     MetadataFactory::free_array<FieldStatus>(_loader_data, _fields_status);
5434   }
5435 
5436   if (_methods != nullptr) {
5437     // Free methods
5438     InstanceKlass::deallocate_methods(_loader_data, _methods);
5439   }
5440 
5441   // beware of the Universe::empty_blah_array!!
5442   if (_inner_classes != nullptr && _inner_classes != Universe::the_empty_short_array()) {
5443     MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
5444   }
5445 
5446   if (_nest_members != nullptr && _nest_members != Universe::the_empty_short_array()) {
5447     MetadataFactory::free_array<u2>(_loader_data, _nest_members);
5448   }
5449 
5450   if (_record_components != nullptr) {
5451     InstanceKlass::deallocate_record_components(_loader_data, _record_components);
5452   }
5453 
5454   if (_permitted_subclasses != nullptr && _permitted_subclasses != Universe::the_empty_short_array()) {
5455     MetadataFactory::free_array<u2>(_loader_data, _permitted_subclasses);
5456   }
5457 
5458   // Free interfaces
5459   InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
5460                                        _local_interfaces, _transitive_interfaces);
5461 
5462   if (_combined_annotations != nullptr) {
5463     // After all annotations arrays have been created, they are installed into the
5464     // Annotations object that will be assigned to the InstanceKlass being created.
5465 
5466     // Deallocate the Annotations object and the installed annotations arrays.
5467     _combined_annotations->deallocate_contents(_loader_data);
5468 
5469     // If the _combined_annotations pointer is non-null,
5470     // then the other annotations fields should have been cleared.
5471     assert(_class_annotations       == nullptr, "Should have been cleared");
5472     assert(_class_type_annotations  == nullptr, "Should have been cleared");
5473     assert(_fields_annotations      == nullptr, "Should have been cleared");
5474     assert(_fields_type_annotations == nullptr, "Should have been cleared");
5475   } else {
5476     // If the annotations arrays were not installed into the Annotations object,
5477     // then they have to be deallocated explicitly.
5478     MetadataFactory::free_array<u1>(_loader_data, _class_annotations);
5479     MetadataFactory::free_array<u1>(_loader_data, _class_type_annotations);
5480     Annotations::free_contents(_loader_data, _fields_annotations);
5481     Annotations::free_contents(_loader_data, _fields_type_annotations);
5482   }
5483 
5484   clear_class_metadata();
5485   _transitive_interfaces = nullptr;
5486   _local_interfaces = nullptr;
5487 
5488   // deallocate the klass if already created.  Don't directly deallocate, but add
5489   // to the deallocate list so that the klass is removed from the CLD::_klasses list
5490   // at a safepoint.
5491   if (_klass_to_deallocate != nullptr) {
5492     _loader_data->add_to_deallocate_list(_klass_to_deallocate);
5493   }
5494 }
5495 
5496 void ClassFileParser::parse_stream(const ClassFileStream* const stream,
5497                                    TRAPS) {
5498 
5499   assert(stream != nullptr, "invariant");
5500   assert(_class_name != nullptr, "invariant");
5501 
5502   // BEGIN STREAM PARSING
5503   stream->guarantee_more(8, CHECK);  // magic, major, minor
5504   // Magic value
5505   const u4 magic = stream->get_u4_fast();
5506   guarantee_property(magic == JAVA_CLASSFILE_MAGIC,
5507                      "Incompatible magic value %u in class file %s",
5508                      magic, CHECK);
5509 
5510   // Version numbers
5511   _minor_version = stream->get_u2_fast();
5512   _major_version = stream->get_u2_fast();
5513 
5514   // Check version numbers - we check this even with verifier off
5515   verify_class_version(_major_version, _minor_version, _class_name, CHECK);
5516 
5517   stream->guarantee_more(3, CHECK); // length, first cp tag
5518   u2 cp_size = stream->get_u2_fast();
5519 
5520   guarantee_property(
5521     cp_size >= 1, "Illegal constant pool size %u in class file %s",
5522     cp_size, CHECK);
5523 
5524   _orig_cp_size = cp_size;
5525   if (is_hidden()) { // Add a slot for hidden class name.
5526     guarantee_property((u4)cp_size < 0xffff, "Overflow in constant pool size for hidden class %s", CHECK);
5527     cp_size++;
5528   }
5529 
5530   _cp = ConstantPool::allocate(_loader_data,
5531                                cp_size,
5532                                CHECK);
5533 
5534   ConstantPool* const cp = _cp;
5535 
5536   parse_constant_pool(stream, cp, _orig_cp_size, CHECK);
5537 
5538   assert(cp_size == (u2)cp->length(), "invariant");
5539 
5540   // ACCESS FLAGS
5541   stream->guarantee_more(8, CHECK);  // flags, this_class, super_class, infs_len
5542 
5543   // Access flags
5544   u2 flags;
5545   // JVM_ACC_MODULE is defined in JDK-9 and later.
5546   if (_major_version >= JAVA_9_VERSION) {
5547     flags = stream->get_u2_fast() & (JVM_RECOGNIZED_CLASS_MODIFIERS | JVM_ACC_MODULE);
5548   } else {
5549     flags = stream->get_u2_fast() & JVM_RECOGNIZED_CLASS_MODIFIERS;
5550   }
5551 
5552   if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
5553     // Set abstract bit for old class files for backward compatibility
5554     flags |= JVM_ACC_ABSTRACT;
5555   }
5556 
5557   verify_legal_class_modifiers(flags, nullptr, false, CHECK);
5558 
5559   short bad_constant = class_bad_constant_seen();
5560   if (bad_constant != 0) {
5561     // Do not throw CFE until after the access_flags are checked because if
5562     // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
5563     classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, THREAD);
5564     return;
5565   }
5566 
5567   _access_flags.set_flags(flags);
5568 
5569   // This class and superclass
5570   _this_class_index = stream->get_u2_fast();
5571   guarantee_property(
5572     valid_cp_range(_this_class_index, cp_size) &&
5573       cp->tag_at(_this_class_index).is_unresolved_klass(),
5574     "Invalid this class index %u in constant pool in class file %s",
5575     _this_class_index, CHECK);
5576 
5577   Symbol* const class_name_in_cp = cp->klass_name_at(_this_class_index);
5578   assert(class_name_in_cp != nullptr, "class_name can't be null");
5579 
5580   // Don't need to check whether this class name is legal or not.
5581   // It has been checked when constant pool is parsed.
5582   // However, make sure it is not an array type.
5583   if (_need_verify) {
5584     guarantee_property(class_name_in_cp->char_at(0) != JVM_SIGNATURE_ARRAY,
5585                        "Bad class name in class file %s",
5586                        CHECK);
5587   }
5588 
5589 #ifdef ASSERT
5590   // Basic sanity checks
5591   if (_is_hidden) {
5592     assert(_class_name != vmSymbols::unknown_class_name(), "hidden classes should have a special name");
5593   }
5594 #endif
5595 
5596   // Update the _class_name as needed depending on whether this is a named, un-named, or hidden class.
5597 
5598   if (_is_hidden) {
5599     assert(_class_name != nullptr, "Unexpected null _class_name");
5600 #ifdef ASSERT
5601     if (_need_verify) {
5602       verify_legal_class_name(_class_name, CHECK);
5603     }
5604 #endif
5605 
5606   } else {
5607     // Check if name in class file matches given name
5608     if (_class_name != class_name_in_cp) {
5609       if (_class_name != vmSymbols::unknown_class_name()) {
5610         ResourceMark rm(THREAD);
5611         // Names are all known to be < 64k so we know this formatted message is not excessively large.
5612         Exceptions::fthrow(THREAD_AND_LOCATION,
5613                            vmSymbols::java_lang_NoClassDefFoundError(),
5614                            "%s (wrong name: %s)",
5615                            _class_name->as_C_string(),
5616                            class_name_in_cp->as_C_string()
5617                            );
5618         return;
5619       } else {
5620         // The class name was not known by the caller so we set it from
5621         // the value in the CP.
5622         update_class_name(class_name_in_cp);
5623       }
5624       // else nothing to do: the expected class name matches what is in the CP
5625     }
5626   }
5627 
5628   // Verification prevents us from creating names with dots in them, this
5629   // asserts that that's the case.
5630   assert(is_internal_format(_class_name), "external class name format used internally");
5631 
5632   if (!is_internal()) {
5633     LogTarget(Debug, class, preorder) lt;
5634     if (lt.is_enabled()){
5635       ResourceMark rm(THREAD);
5636       LogStream ls(lt);
5637       ls.print("%s", _class_name->as_klass_external_name());
5638       if (stream->source() != nullptr) {
5639         ls.print(" source: %s", stream->source());
5640       }
5641       ls.cr();
5642     }
5643   }
5644 
5645   // SUPERKLASS
5646   _super_class_index = stream->get_u2_fast();
5647   check_super_class(cp,
5648                     _super_class_index,
5649                     _need_verify,
5650                     CHECK);
5651 
5652   // Interfaces
5653   _itfs_len = stream->get_u2_fast();
5654   parse_interfaces(stream,
5655                    _itfs_len,
5656                    cp,
5657                    &_has_nonstatic_concrete_methods,
5658                    CHECK);
5659 
5660   assert(_local_interfaces != nullptr, "invariant");
5661 
5662   // Fields (offsets are filled in later)
5663   parse_fields(stream,
5664                _access_flags.is_interface(),
5665                cp,
5666                cp_size,
5667                &_java_fields_count,
5668                CHECK);
5669 
5670   assert(_temp_field_info != nullptr, "invariant");
5671 
5672   // Methods
5673   parse_methods(stream,
5674                 _access_flags.is_interface(),
5675                 &_has_localvariable_table,
5676                 &_has_final_method,
5677                 &_declares_nonstatic_concrete_methods,
5678                 CHECK);
5679 
5680   assert(_methods != nullptr, "invariant");
5681 
5682   if (_declares_nonstatic_concrete_methods) {
5683     _has_nonstatic_concrete_methods = true;
5684   }
5685 
5686   // Additional attributes/annotations
5687   _parsed_annotations = new ClassAnnotationCollector();
5688   parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK);
5689 
5690   assert(_inner_classes != nullptr, "invariant");
5691 
5692   // Finalize the Annotations metadata object,
5693   // now that all annotation arrays have been created.
5694   create_combined_annotations(CHECK);
5695 
5696   // Make sure this is the end of class file stream
5697   guarantee_property(stream->at_eos(),
5698                      "Extra bytes at the end of class file %s",
5699                      CHECK);
5700 
5701   // all bytes in stream read and parsed
5702 }
5703 
5704 void ClassFileParser::mangle_hidden_class_name(InstanceKlass* const ik) {
5705   ResourceMark rm;
5706   // Construct hidden name from _class_name, "+", and &ik. Note that we can't
5707   // use a '/' because that confuses finding the class's package.  Also, can't
5708   // use an illegal char such as ';' because that causes serialization issues
5709   // and issues with hidden classes that create their own hidden classes.
5710   char addr_buf[20];
5711   if (CDSConfig::is_dumping_static_archive()) {
5712     // We want stable names for the archived hidden classes (only for static
5713     // archive for now). Spaces under default_SharedBaseAddress() will be
5714     // occupied by the archive at run time, so we know that no dynamically
5715     // loaded InstanceKlass will be placed under there.
5716     static volatile size_t counter = 0;
5717     AtomicAccess::cmpxchg(&counter, (size_t)0, Arguments::default_SharedBaseAddress()); // initialize it
5718     size_t new_id = AtomicAccess::add(&counter, (size_t)1);
5719     jio_snprintf(addr_buf, 20, "0x%zx", new_id);
5720   } else {
5721     jio_snprintf(addr_buf, 20, INTPTR_FORMAT, p2i(ik));
5722   }
5723   size_t new_name_len = _class_name->utf8_length() + 2 + strlen(addr_buf);
5724   char* new_name = NEW_RESOURCE_ARRAY(char, new_name_len);
5725   jio_snprintf(new_name, new_name_len, "%s+%s",
5726                _class_name->as_C_string(), addr_buf);
5727   update_class_name(SymbolTable::new_symbol(new_name));
5728 
5729   // Add a Utf8 entry containing the hidden name.
5730   assert(_class_name != nullptr, "Unexpected null _class_name");
5731   int hidden_index = _orig_cp_size; // this is an extra slot we added
5732   _cp->symbol_at_put(hidden_index, _class_name);
5733 
5734   // Update this_class_index's slot in the constant pool with the new Utf8 entry.
5735   // We have to update the resolved_klass_index and the name_index together
5736   // so extract the existing resolved_klass_index first.
5737   CPKlassSlot cp_klass_slot = _cp->klass_slot_at(_this_class_index);
5738   int resolved_klass_index = cp_klass_slot.resolved_klass_index();
5739   _cp->unresolved_klass_at_put(_this_class_index, hidden_index, resolved_klass_index);
5740   assert(_cp->klass_slot_at(_this_class_index).name_index() == _orig_cp_size,
5741          "Bad name_index");
5742 }
5743 
5744 void ClassFileParser::post_process_parsed_stream(const ClassFileStream* const stream,
5745                                                  ConstantPool* cp,
5746                                                  TRAPS) {
5747   assert(stream != nullptr, "invariant");
5748   assert(stream->at_eos(), "invariant");
5749   assert(cp != nullptr, "invariant");
5750   assert(_loader_data != nullptr, "invariant");
5751 
5752   if (_class_name == vmSymbols::java_lang_Object()) {
5753     precond(_super_class_index == 0);
5754     precond(_super_klass == nullptr);
5755     guarantee_property(_local_interfaces == Universe::the_empty_instance_klass_array(),
5756                        "java.lang.Object cannot implement an interface in class file %s",
5757                        CHECK);
5758   } else {
5759     // Set _super_klass after class file is parsed and format is checked
5760     assert(_super_class_index > 0, "any class other than Object must have a super class");
5761     Symbol* const super_class_name = cp->klass_name_at(_super_class_index);
5762     if (_access_flags.is_interface()) {
5763       // Before attempting to resolve the superclass, check for class format
5764       // errors not checked yet.
5765       guarantee_property(super_class_name == vmSymbols::java_lang_Object(),
5766         "Interfaces must have java.lang.Object as superclass in class file %s",
5767         CHECK);
5768     }
5769     Handle loader(THREAD, _loader_data->class_loader());
5770     if (loader.is_null() && super_class_name == vmSymbols::java_lang_Object()) {
5771       // fast path to avoid lookup
5772       _super_klass = vmClasses::Object_klass();
5773     } else {
5774       _super_klass = (const InstanceKlass*)
5775                        SystemDictionary::resolve_super_or_fail(_class_name,
5776                                                                super_class_name,
5777                                                                loader,
5778                                                                true,
5779                                                                CHECK);
5780     }
5781   }
5782 
5783   if (_super_klass != nullptr) {
5784     if (_super_klass->has_nonstatic_concrete_methods()) {
5785       _has_nonstatic_concrete_methods = true;
5786     }
5787 
5788     if (_super_klass->is_interface()) {
5789       classfile_icce_error("class %s has interface %s as super class", _super_klass, THREAD);
5790       return;
5791     }
5792   }
5793 
5794   // Compute the transitive list of all unique interfaces implemented by this class
5795   _transitive_interfaces =
5796     compute_transitive_interfaces(_super_klass,
5797                                   _local_interfaces,
5798                                   _loader_data,
5799                                   CHECK);
5800 
5801   assert(_transitive_interfaces != nullptr, "invariant");
5802 
5803   // sort methods
5804   _method_ordering = sort_methods(_methods);
5805 
5806   _all_mirandas = new GrowableArray<Method*>(20);
5807 
5808   Handle loader(THREAD, _loader_data->class_loader());
5809   klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
5810                                                     &_num_miranda_methods,
5811                                                     _all_mirandas,
5812                                                     _super_klass,
5813                                                     _methods,
5814                                                     _access_flags,
5815                                                     _major_version,
5816                                                     loader,
5817                                                     _class_name,
5818                                                     _local_interfaces);
5819 
5820   // Size of Java itable (in words)
5821   _itable_size = _access_flags.is_interface() ? 0 :
5822     klassItable::compute_itable_size(_transitive_interfaces);
5823 
5824   assert(_parsed_annotations != nullptr, "invariant");
5825 
5826   _field_info = new FieldLayoutInfo();
5827   FieldLayoutBuilder lb(class_name(), super_klass(), _cp, /*_fields*/ _temp_field_info,
5828                         _parsed_annotations->is_contended(), _field_info);
5829   lb.build_layout();
5830 
5831   int injected_fields_count = _temp_field_info->length() - _java_fields_count;
5832   _fieldinfo_stream =
5833     FieldInfoStream::create_FieldInfoStream(_temp_field_info, _java_fields_count,
5834                                             injected_fields_count, loader_data(), CHECK);
5835   _fieldinfo_search_table = FieldInfoStream::create_search_table(_cp, _fieldinfo_stream, _loader_data, CHECK);
5836   _fields_status =
5837     MetadataFactory::new_array<FieldStatus>(_loader_data, _temp_field_info->length(),
5838                                             FieldStatus(0), CHECK);
5839 }
5840 
5841 void ClassFileParser::set_klass(InstanceKlass* klass) {
5842 
5843 #ifdef ASSERT
5844   if (klass != nullptr) {
5845     assert(nullptr == _klass, "leaking?");
5846   }
5847 #endif
5848 
5849   _klass = klass;
5850 }
5851 
5852 void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) {
5853 
5854 #ifdef ASSERT
5855   if (klass != nullptr) {
5856     assert(nullptr == _klass_to_deallocate, "leaking?");
5857   }
5858 #endif
5859 
5860   _klass_to_deallocate = klass;
5861 }
5862 
5863 // Caller responsible for ResourceMark
5864 // clone stream with rewound position
5865 const ClassFileStream* ClassFileParser::clone_stream() const {
5866   assert(_stream != nullptr, "invariant");
5867 
5868   return _stream->clone();
5869 }
5870 
5871 ReferenceType ClassFileParser::super_reference_type() const {
5872   return _super_klass == nullptr ? REF_NONE : _super_klass->reference_type();
5873 }
5874 
5875 bool ClassFileParser::is_instance_ref_klass() const {
5876   // Only the subclasses of j.l.r.Reference are InstanceRefKlass.
5877   // j.l.r.Reference itself is InstanceKlass because InstanceRefKlass denotes a
5878   // klass requiring special treatment in ref-processing. The abstract
5879   // j.l.r.Reference cannot be instantiated so doesn't partake in
5880   // ref-processing.
5881   return is_java_lang_ref_Reference_subclass();
5882 }
5883 
5884 bool ClassFileParser::is_java_lang_ref_Reference_subclass() const {
5885   if (_super_klass == nullptr) {
5886     return false;
5887   }
5888 
5889   if (_super_klass->name() == vmSymbols::java_lang_ref_Reference()) {
5890     // Direct subclass of j.l.r.Reference: Soft|Weak|Final|Phantom
5891     return true;
5892   }
5893 
5894   return _super_klass->reference_type() != REF_NONE;
5895 }
5896 
5897 // ----------------------------------------------------------------------------
5898 // debugging
5899 
5900 #ifdef ASSERT
5901 
5902 // return true if class_name contains no '.' (internal format is '/')
5903 bool ClassFileParser::is_internal_format(Symbol* class_name) {
5904   if (class_name != nullptr) {
5905     ResourceMark rm;
5906     char* name = class_name->as_C_string();
5907     return strchr(name, JVM_SIGNATURE_DOT) == nullptr;
5908   } else {
5909     return true;
5910   }
5911 }
5912 
5913 #endif