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