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