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