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