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