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