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