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