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