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