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