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