1 /*
   2  * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "jvm.h"
  27 #include "classfile/classFileParser.hpp"
  28 #include "classfile/classFileStream.hpp"
  29 #include "classfile/classLoader.hpp"
  30 #include "classfile/classLoaderData.inline.hpp"
  31 #include "classfile/classLoadInfo.hpp"
  32 #include "classfile/defaultMethods.hpp"
  33 #include "classfile/fieldLayoutBuilder.hpp"
  34 #include "classfile/javaClasses.inline.hpp"
  35 #include "classfile/moduleEntry.hpp"
  36 #include "classfile/packageEntry.hpp"
  37 #include "classfile/symbolTable.hpp"
  38 #include "classfile/systemDictionary.hpp"
  39 #include "classfile/verificationType.hpp"
  40 #include "classfile/verifier.hpp"
  41 #include "classfile/vmClasses.hpp"
  42 #include "classfile/vmSymbols.hpp"
  43 #include "logging/log.hpp"
  44 #include "logging/logStream.hpp"
  45 #include "memory/allocation.hpp"
  46 #include "memory/metadataFactory.hpp"
  47 #include "memory/oopFactory.hpp"
  48 #include "memory/resourceArea.hpp"
  49 #include "memory/universe.hpp"
  50 #include "oops/annotations.hpp"
  51 #include "oops/constantPool.inline.hpp"
  52 #include "oops/fieldStreams.inline.hpp"
  53 #include "oops/inlineKlass.inline.hpp"
  54 #include "oops/instanceKlass.inline.hpp"
  55 #include "oops/instanceMirrorKlass.hpp"
  56 #include "oops/klass.inline.hpp"
  57 #include "oops/klassVtable.hpp"
  58 #include "oops/metadata.hpp"
  59 #include "oops/method.inline.hpp"
  60 #include "oops/oop.inline.hpp"
  61 #include "oops/recordComponent.hpp"
  62 #include "oops/symbol.hpp"
  63 #include "prims/jvmtiExport.hpp"
  64 #include "prims/jvmtiThreadState.hpp"
  65 #include "runtime/arguments.hpp"
  66 #include "runtime/fieldDescriptor.inline.hpp"
  67 #include "runtime/handles.inline.hpp"
  68 #include "runtime/javaCalls.hpp"
  69 #include "runtime/os.hpp"
  70 #include "runtime/perfData.hpp"
  71 #include "runtime/reflection.hpp"
  72 #include "runtime/safepointVerifiers.hpp"
  73 #include "runtime/signature.hpp"
  74 #include "runtime/timer.hpp"
  75 #include "services/classLoadingService.hpp"
  76 #include "services/threadService.hpp"
  77 #include "utilities/align.hpp"
  78 #include "utilities/bitMap.inline.hpp"
  79 #include "utilities/copy.hpp"
  80 #include "utilities/formatBuffer.hpp"
  81 #include "utilities/exceptions.hpp"
  82 #include "utilities/globalDefinitions.hpp"
  83 #include "utilities/growableArray.hpp"
  84 #include "utilities/macros.hpp"
  85 #include "utilities/ostream.hpp"
  86 #include "utilities/resourceHash.hpp"
  87 #include "utilities/stringUtils.hpp"
  88 #include "utilities/utf8.hpp"
  89 
  90 #if INCLUDE_CDS
  91 #include "classfile/systemDictionaryShared.hpp"
  92 #endif
  93 #if INCLUDE_JFR
  94 #include "jfr/support/jfrTraceIdExtension.hpp"
  95 #endif
  96 
  97 // We generally try to create the oops directly when parsing, rather than
  98 // allocating temporary data structures and copying the bytes twice. A
  99 // temporary area is only needed when parsing utf8 entries in the constant
 100 // pool and when parsing line number tables.
 101 
 102 // We add assert in debug mode when class format is not checked.
 103 
 104 #define JAVA_CLASSFILE_MAGIC              0xCAFEBABE
 105 #define JAVA_MIN_SUPPORTED_VERSION        45
 106 #define JAVA_PREVIEW_MINOR_VERSION        65535
 107 
 108 // Used for two backward compatibility reasons:
 109 // - to check for new additions to the class file format in JDK1.5
 110 // - to check for bug fixes in the format checker in JDK1.5
 111 #define JAVA_1_5_VERSION                  49
 112 
 113 // Used for backward compatibility reasons:
 114 // - to check for javac bug fixes that happened after 1.5
 115 // - also used as the max version when running in jdk6
 116 #define JAVA_6_VERSION                    50
 117 
 118 // Used for backward compatibility reasons:
 119 // - to disallow argument and require ACC_STATIC for <clinit> methods
 120 #define JAVA_7_VERSION                    51
 121 
 122 // Extension method support.
 123 #define JAVA_8_VERSION                    52
 124 
 125 #define JAVA_9_VERSION                    53
 126 
 127 #define JAVA_10_VERSION                   54
 128 
 129 #define JAVA_11_VERSION                   55
 130 
 131 #define JAVA_12_VERSION                   56
 132 
 133 #define JAVA_13_VERSION                   57
 134 
 135 #define JAVA_14_VERSION                   58
 136 
 137 #define JAVA_15_VERSION                   59
 138 
 139 #define JAVA_16_VERSION                   60
 140 
 141 #define JAVA_17_VERSION                   61
 142 
 143 #define JAVA_18_VERSION                   62
 144 
 145 #define CONSTANT_CLASS_DESCRIPTORS        62
 146 
 147 
 148 void ClassFileParser::set_class_bad_constant_seen(short bad_constant) {
 149   assert((bad_constant == JVM_CONSTANT_Module ||
 150           bad_constant == JVM_CONSTANT_Package) && _major_version >= JAVA_9_VERSION,
 151          "Unexpected bad constant pool entry");
 152   if (_bad_constant_seen == 0) _bad_constant_seen = bad_constant;
 153 }
 154 
 155 void ClassFileParser::parse_constant_pool_entries(const ClassFileStream* const stream,
 156                                                   ConstantPool* cp,
 157                                                   const int length,
 158                                                   TRAPS) {
 159   assert(stream != NULL, "invariant");
 160   assert(cp != NULL, "invariant");
 161 
 162   // Use a local copy of ClassFileStream. It helps the C++ compiler to optimize
 163   // this function (_current can be allocated in a register, with scalar
 164   // replacement of aggregates). The _current pointer is copied back to
 165   // stream() when this function returns. DON'T call another method within
 166   // this method that uses stream().
 167   const ClassFileStream cfs1 = *stream;
 168   const ClassFileStream* const cfs = &cfs1;
 169 
 170   assert(cfs->allocated_on_stack(), "should be local");
 171   debug_only(const u1* const old_current = stream->current();)
 172 
 173   // Used for batching symbol allocations.
 174   const char* names[SymbolTable::symbol_alloc_batch_size];
 175   int lengths[SymbolTable::symbol_alloc_batch_size];
 176   int indices[SymbolTable::symbol_alloc_batch_size];
 177   unsigned int hashValues[SymbolTable::symbol_alloc_batch_size];
 178   int names_count = 0;
 179 
 180   // parsing  Index 0 is unused
 181   for (int index = 1; index < length; index++) {
 182     // Each of the following case guarantees one more byte in the stream
 183     // for the following tag or the access_flags following constant pool,
 184     // so we don't need bounds-check for reading tag.
 185     const u1 tag = cfs->get_u1_fast();
 186     switch (tag) {
 187       case JVM_CONSTANT_Class: {
 188         cfs->guarantee_more(3, CHECK);  // name_index, tag/access_flags
 189         const u2 name_index = cfs->get_u2_fast();
 190         cp->klass_index_at_put(index, name_index);
 191         break;
 192       }
 193       case JVM_CONSTANT_Fieldref: {
 194         cfs->guarantee_more(5, CHECK);  // class_index, name_and_type_index, tag/access_flags
 195         const u2 class_index = cfs->get_u2_fast();
 196         const u2 name_and_type_index = cfs->get_u2_fast();
 197         cp->field_at_put(index, class_index, name_and_type_index);
 198         break;
 199       }
 200       case JVM_CONSTANT_Methodref: {
 201         cfs->guarantee_more(5, CHECK);  // class_index, name_and_type_index, tag/access_flags
 202         const u2 class_index = cfs->get_u2_fast();
 203         const u2 name_and_type_index = cfs->get_u2_fast();
 204         cp->method_at_put(index, class_index, name_and_type_index);
 205         break;
 206       }
 207       case JVM_CONSTANT_InterfaceMethodref: {
 208         cfs->guarantee_more(5, CHECK);  // class_index, name_and_type_index, tag/access_flags
 209         const u2 class_index = cfs->get_u2_fast();
 210         const u2 name_and_type_index = cfs->get_u2_fast();
 211         cp->interface_method_at_put(index, class_index, name_and_type_index);
 212         break;
 213       }
 214       case JVM_CONSTANT_String : {
 215         cfs->guarantee_more(3, CHECK);  // string_index, tag/access_flags
 216         const u2 string_index = cfs->get_u2_fast();
 217         cp->string_index_at_put(index, string_index);
 218         break;
 219       }
 220       case JVM_CONSTANT_MethodHandle :
 221       case JVM_CONSTANT_MethodType: {
 222         if (_major_version < Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {
 223           classfile_parse_error(
 224             "Class file version does not support constant tag %u in class file %s",
 225             tag, THREAD);
 226           return;
 227         }
 228         if (tag == JVM_CONSTANT_MethodHandle) {
 229           cfs->guarantee_more(4, CHECK);  // ref_kind, method_index, tag/access_flags
 230           const u1 ref_kind = cfs->get_u1_fast();
 231           const u2 method_index = cfs->get_u2_fast();
 232           cp->method_handle_index_at_put(index, ref_kind, method_index);
 233         }
 234         else if (tag == JVM_CONSTANT_MethodType) {
 235           cfs->guarantee_more(3, CHECK);  // signature_index, tag/access_flags
 236           const u2 signature_index = cfs->get_u2_fast();
 237           cp->method_type_index_at_put(index, signature_index);
 238         }
 239         else {
 240           ShouldNotReachHere();
 241         }
 242         break;
 243       }
 244       case JVM_CONSTANT_Dynamic : {
 245         if (_major_version < Verifier::DYNAMICCONSTANT_MAJOR_VERSION) {
 246           classfile_parse_error(
 247               "Class file version does not support constant tag %u in class file %s",
 248               tag, THREAD);
 249           return;
 250         }
 251         cfs->guarantee_more(5, CHECK);  // bsm_index, nt, tag/access_flags
 252         const u2 bootstrap_specifier_index = cfs->get_u2_fast();
 253         const u2 name_and_type_index = cfs->get_u2_fast();
 254         if (_max_bootstrap_specifier_index < (int) bootstrap_specifier_index) {
 255           _max_bootstrap_specifier_index = (int) bootstrap_specifier_index;  // collect for later
 256         }
 257         cp->dynamic_constant_at_put(index, bootstrap_specifier_index, name_and_type_index);
 258         break;
 259       }
 260       case JVM_CONSTANT_InvokeDynamic : {
 261         if (_major_version < Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {
 262           classfile_parse_error(
 263               "Class file version does not support constant tag %u in class file %s",
 264               tag, THREAD);
 265           return;
 266         }
 267         cfs->guarantee_more(5, CHECK);  // bsm_index, nt, tag/access_flags
 268         const u2 bootstrap_specifier_index = cfs->get_u2_fast();
 269         const u2 name_and_type_index = cfs->get_u2_fast();
 270         if (_max_bootstrap_specifier_index < (int) bootstrap_specifier_index) {
 271           _max_bootstrap_specifier_index = (int) bootstrap_specifier_index;  // collect for later
 272         }
 273         cp->invoke_dynamic_at_put(index, bootstrap_specifier_index, name_and_type_index);
 274         break;
 275       }
 276       case JVM_CONSTANT_Integer: {
 277         cfs->guarantee_more(5, CHECK);  // bytes, tag/access_flags
 278         const u4 bytes = cfs->get_u4_fast();
 279         cp->int_at_put(index, (jint)bytes);
 280         break;
 281       }
 282       case JVM_CONSTANT_Float: {
 283         cfs->guarantee_more(5, CHECK);  // bytes, tag/access_flags
 284         const u4 bytes = cfs->get_u4_fast();
 285         cp->float_at_put(index, *(jfloat*)&bytes);
 286         break;
 287       }
 288       case JVM_CONSTANT_Long: {
 289         // A mangled type might cause you to overrun allocated memory
 290         guarantee_property(index + 1 < length,
 291                            "Invalid constant pool entry %u in class file %s",
 292                            index,
 293                            CHECK);
 294         cfs->guarantee_more(9, CHECK);  // bytes, tag/access_flags
 295         const u8 bytes = cfs->get_u8_fast();
 296         cp->long_at_put(index, bytes);
 297         index++;   // Skip entry following eigth-byte constant, see JVM book p. 98
 298         break;
 299       }
 300       case JVM_CONSTANT_Double: {
 301         // A mangled type might cause you to overrun allocated memory
 302         guarantee_property(index+1 < length,
 303                            "Invalid constant pool entry %u in class file %s",
 304                            index,
 305                            CHECK);
 306         cfs->guarantee_more(9, CHECK);  // bytes, tag/access_flags
 307         const u8 bytes = cfs->get_u8_fast();
 308         cp->double_at_put(index, *(jdouble*)&bytes);
 309         index++;   // Skip entry following eigth-byte constant, see JVM book p. 98
 310         break;
 311       }
 312       case JVM_CONSTANT_NameAndType: {
 313         cfs->guarantee_more(5, CHECK);  // name_index, signature_index, tag/access_flags
 314         const u2 name_index = cfs->get_u2_fast();
 315         const u2 signature_index = cfs->get_u2_fast();
 316         cp->name_and_type_at_put(index, name_index, signature_index);
 317         break;
 318       }
 319       case JVM_CONSTANT_Utf8 : {
 320         cfs->guarantee_more(2, CHECK);  // utf8_length
 321         u2  utf8_length = cfs->get_u2_fast();
 322         const u1* utf8_buffer = cfs->current();
 323         assert(utf8_buffer != NULL, "null utf8 buffer");
 324         // Got utf8 string, guarantee utf8_length+1 bytes, set stream position forward.
 325         cfs->guarantee_more(utf8_length+1, CHECK);  // utf8 string, tag/access_flags
 326         cfs->skip_u1_fast(utf8_length);
 327 
 328         // Before storing the symbol, make sure it's legal
 329         if (_need_verify) {
 330           verify_legal_utf8(utf8_buffer, utf8_length, CHECK);
 331         }
 332 
 333         unsigned int hash;
 334         Symbol* const result = SymbolTable::lookup_only((const char*)utf8_buffer,
 335                                                         utf8_length,
 336                                                         hash);
 337         if (result == NULL) {
 338           names[names_count] = (const char*)utf8_buffer;
 339           lengths[names_count] = utf8_length;
 340           indices[names_count] = index;
 341           hashValues[names_count++] = hash;
 342           if (names_count == SymbolTable::symbol_alloc_batch_size) {
 343             SymbolTable::new_symbols(_loader_data,
 344                                      constantPoolHandle(THREAD, cp),
 345                                      names_count,
 346                                      names,
 347                                      lengths,
 348                                      indices,
 349                                      hashValues);
 350             names_count = 0;
 351           }
 352         } else {
 353           cp->symbol_at_put(index, result);
 354         }
 355         break;
 356       }
 357       case JVM_CONSTANT_Module:
 358       case JVM_CONSTANT_Package: {
 359         // Record that an error occurred in these two cases but keep parsing so
 360         // that ACC_Module can be checked for in the access_flags.  Need to
 361         // throw NoClassDefFoundError in that case.
 362         if (_major_version >= JAVA_9_VERSION) {
 363           cfs->guarantee_more(3, CHECK);
 364           cfs->get_u2_fast();
 365           set_class_bad_constant_seen(tag);
 366           break;
 367         }
 368       }
 369       default: {
 370         classfile_parse_error("Unknown constant tag %u in class file %s",
 371                               tag,
 372                               THREAD);
 373         return;
 374       }
 375     } // end of switch(tag)
 376   } // end of for
 377 
 378   // Allocate the remaining symbols
 379   if (names_count > 0) {
 380     SymbolTable::new_symbols(_loader_data,
 381                              constantPoolHandle(THREAD, cp),
 382                              names_count,
 383                              names,
 384                              lengths,
 385                              indices,
 386                              hashValues);
 387   }
 388 
 389   // Copy _current pointer of local copy back to stream.
 390   assert(stream->current() == old_current, "non-exclusive use of stream");
 391   stream->set_current(cfs1.current());
 392 
 393 }
 394 
 395 static inline bool valid_cp_range(int index, int length) {
 396   return (index > 0 && index < length);
 397 }
 398 
 399 static inline Symbol* check_symbol_at(const ConstantPool* cp, int index) {
 400   assert(cp != NULL, "invariant");
 401   if (valid_cp_range(index, cp->length()) && cp->tag_at(index).is_utf8()) {
 402     return cp->symbol_at(index);
 403   }
 404   return NULL;
 405 }
 406 
 407 #ifdef ASSERT
 408 PRAGMA_DIAG_PUSH
 409 PRAGMA_FORMAT_NONLITERAL_IGNORED
 410 void ClassFileParser::report_assert_property_failure(const char* msg, TRAPS) const {
 411   ResourceMark rm(THREAD);
 412   fatal(msg, _class_name->as_C_string());
 413 }
 414 
 415 void ClassFileParser::report_assert_property_failure(const char* msg,
 416                                                      int index,
 417                                                      TRAPS) const {
 418   ResourceMark rm(THREAD);
 419   fatal(msg, index, _class_name->as_C_string());
 420 }
 421 PRAGMA_DIAG_POP
 422 #endif
 423 
 424 void ClassFileParser::parse_constant_pool(const ClassFileStream* const stream,
 425                                          ConstantPool* const cp,
 426                                          const int length,
 427                                          TRAPS) {
 428   assert(cp != NULL, "invariant");
 429   assert(stream != NULL, "invariant");
 430 
 431   // parsing constant pool entries
 432   parse_constant_pool_entries(stream, cp, length, CHECK);
 433   if (class_bad_constant_seen() != 0) {
 434     // a bad CP entry has been detected previously so stop parsing and just return.
 435     return;
 436   }
 437 
 438   int index = 1;  // declared outside of loops for portability
 439   int num_klasses = 0;
 440 
 441   // first verification pass - validate cross references
 442   // and fixup class and string constants
 443   for (index = 1; index < length; index++) {          // Index 0 is unused
 444     const jbyte tag = cp->tag_at(index).value();
 445     switch (tag) {
 446       case JVM_CONSTANT_Class: {
 447         ShouldNotReachHere();     // Only JVM_CONSTANT_ClassIndex should be present
 448         break;
 449       }
 450       case JVM_CONSTANT_Fieldref:
 451         // fall through
 452       case JVM_CONSTANT_Methodref:
 453         // fall through
 454       case JVM_CONSTANT_InterfaceMethodref: {
 455         if (!_need_verify) break;
 456         const int klass_ref_index = cp->klass_ref_index_at(index);
 457         const int name_and_type_ref_index = cp->name_and_type_ref_index_at(index);
 458         check_property(valid_klass_reference_at(klass_ref_index),
 459                        "Invalid constant pool index %u in class file %s",
 460                        klass_ref_index, CHECK);
 461         check_property(valid_cp_range(name_and_type_ref_index, length) &&
 462           cp->tag_at(name_and_type_ref_index).is_name_and_type(),
 463           "Invalid constant pool index %u in class file %s",
 464           name_and_type_ref_index, CHECK);
 465         break;
 466       }
 467       case JVM_CONSTANT_String: {
 468         ShouldNotReachHere();     // Only JVM_CONSTANT_StringIndex should be present
 469         break;
 470       }
 471       case JVM_CONSTANT_Integer:
 472         break;
 473       case JVM_CONSTANT_Float:
 474         break;
 475       case JVM_CONSTANT_Long:
 476       case JVM_CONSTANT_Double: {
 477         index++;
 478         check_property(
 479           (index < length && cp->tag_at(index).is_invalid()),
 480           "Improper constant pool long/double index %u in class file %s",
 481           index, CHECK);
 482         break;
 483       }
 484       case JVM_CONSTANT_NameAndType: {
 485         if (!_need_verify) break;
 486         const int name_ref_index = cp->name_ref_index_at(index);
 487         const int signature_ref_index = cp->signature_ref_index_at(index);
 488         check_property(valid_symbol_at(name_ref_index),
 489           "Invalid constant pool index %u in class file %s",
 490           name_ref_index, CHECK);
 491         check_property(valid_symbol_at(signature_ref_index),
 492           "Invalid constant pool index %u in class file %s",
 493           signature_ref_index, CHECK);
 494         break;
 495       }
 496       case JVM_CONSTANT_Utf8:
 497         break;
 498       case JVM_CONSTANT_UnresolvedClass:         // fall-through
 499       case JVM_CONSTANT_UnresolvedClassInError: {
 500         ShouldNotReachHere();     // Only JVM_CONSTANT_ClassIndex should be present
 501         break;
 502       }
 503       case JVM_CONSTANT_ClassIndex: {
 504         const int class_index = cp->klass_index_at(index);
 505         check_property(valid_symbol_at(class_index),
 506           "Invalid constant pool index %u in class file %s",
 507           class_index, CHECK);
 508 
 509         Symbol* const name = cp->symbol_at(class_index);
 510         const unsigned int name_len = name->utf8_length();
 511         if (name->is_Q_signature()) {
 512           cp->unresolved_qdescriptor_at_put(index, class_index, num_klasses++);
 513         } else {
 514           cp->unresolved_klass_at_put(index, class_index, num_klasses++);
 515         }
 516         break;
 517       }
 518       case JVM_CONSTANT_StringIndex: {
 519         const int string_index = cp->string_index_at(index);
 520         check_property(valid_symbol_at(string_index),
 521           "Invalid constant pool index %u in class file %s",
 522           string_index, CHECK);
 523         Symbol* const sym = cp->symbol_at(string_index);
 524         cp->unresolved_string_at_put(index, sym);
 525         break;
 526       }
 527       case JVM_CONSTANT_MethodHandle: {
 528         const int ref_index = cp->method_handle_index_at(index);
 529         check_property(valid_cp_range(ref_index, length),
 530           "Invalid constant pool index %u in class file %s",
 531           ref_index, CHECK);
 532         const constantTag tag = cp->tag_at(ref_index);
 533         const int ref_kind = cp->method_handle_ref_kind_at(index);
 534 
 535         switch (ref_kind) {
 536           case JVM_REF_getField:
 537           case JVM_REF_getStatic:
 538           case JVM_REF_putField:
 539           case JVM_REF_putStatic: {
 540             check_property(
 541               tag.is_field(),
 542               "Invalid constant pool index %u in class file %s (not a field)",
 543               ref_index, CHECK);
 544             break;
 545           }
 546           case JVM_REF_invokeVirtual:
 547           case JVM_REF_newInvokeSpecial: {
 548             check_property(
 549               tag.is_method(),
 550               "Invalid constant pool index %u in class file %s (not a method)",
 551               ref_index, CHECK);
 552             break;
 553           }
 554           case JVM_REF_invokeStatic:
 555           case JVM_REF_invokeSpecial: {
 556             check_property(
 557               tag.is_method() ||
 558               ((_major_version >= JAVA_8_VERSION) && tag.is_interface_method()),
 559               "Invalid constant pool index %u in class file %s (not a method)",
 560               ref_index, CHECK);
 561             break;
 562           }
 563           case JVM_REF_invokeInterface: {
 564             check_property(
 565               tag.is_interface_method(),
 566               "Invalid constant pool index %u in class file %s (not an interface method)",
 567               ref_index, CHECK);
 568             break;
 569           }
 570           default: {
 571             classfile_parse_error(
 572               "Bad method handle kind at constant pool index %u in class file %s",
 573               index, THREAD);
 574             return;
 575           }
 576         } // switch(refkind)
 577         // Keep the ref_index unchanged.  It will be indirected at link-time.
 578         break;
 579       } // case MethodHandle
 580       case JVM_CONSTANT_MethodType: {
 581         const int ref_index = cp->method_type_index_at(index);
 582         check_property(valid_symbol_at(ref_index),
 583           "Invalid constant pool index %u in class file %s",
 584           ref_index, CHECK);
 585         break;
 586       }
 587       case JVM_CONSTANT_Dynamic: {
 588         const int name_and_type_ref_index =
 589           cp->bootstrap_name_and_type_ref_index_at(index);
 590 
 591         check_property(valid_cp_range(name_and_type_ref_index, length) &&
 592           cp->tag_at(name_and_type_ref_index).is_name_and_type(),
 593           "Invalid constant pool index %u in class file %s",
 594           name_and_type_ref_index, CHECK);
 595         // bootstrap specifier index must be checked later,
 596         // when BootstrapMethods attr is available
 597 
 598         // Mark the constant pool as having a CONSTANT_Dynamic_info structure
 599         cp->set_has_dynamic_constant();
 600         break;
 601       }
 602       case JVM_CONSTANT_InvokeDynamic: {
 603         const int name_and_type_ref_index =
 604           cp->bootstrap_name_and_type_ref_index_at(index);
 605 
 606         check_property(valid_cp_range(name_and_type_ref_index, length) &&
 607           cp->tag_at(name_and_type_ref_index).is_name_and_type(),
 608           "Invalid constant pool index %u in class file %s",
 609           name_and_type_ref_index, CHECK);
 610         // bootstrap specifier index must be checked later,
 611         // when BootstrapMethods attr is available
 612         break;
 613       }
 614       default: {
 615         fatal("bad constant pool tag value %u", cp->tag_at(index).value());
 616         ShouldNotReachHere();
 617         break;
 618       }
 619     } // switch(tag)
 620   } // end of for
 621 
 622   cp->allocate_resolved_klasses(_loader_data, num_klasses, CHECK);
 623 
 624   if (!_need_verify) {
 625     return;
 626   }
 627 
 628   // second verification pass - checks the strings are of the right format.
 629   // but not yet to the other entries
 630   for (index = 1; index < length; index++) {
 631     const jbyte tag = cp->tag_at(index).value();
 632     switch (tag) {
 633       case JVM_CONSTANT_UnresolvedClass: {
 634         const Symbol* const class_name = cp->klass_name_at(index);
 635         // check the name
 636         verify_legal_class_name(class_name, CHECK);
 637         break;
 638       }
 639       case JVM_CONSTANT_NameAndType: {
 640         if (_need_verify) {
 641           const int sig_index = cp->signature_ref_index_at(index);
 642           const int name_index = cp->name_ref_index_at(index);
 643           const Symbol* const name = cp->symbol_at(name_index);
 644           const Symbol* const sig = cp->symbol_at(sig_index);
 645           guarantee_property(sig->utf8_length() != 0,
 646             "Illegal zero length constant pool entry at %d in class %s",
 647             sig_index, CHECK);
 648           guarantee_property(name->utf8_length() != 0,
 649             "Illegal zero length constant pool entry at %d in class %s",
 650             name_index, CHECK);
 651 
 652           if (Signature::is_method(sig)) {
 653             // Format check method name and signature
 654             verify_legal_method_name(name, CHECK);
 655             verify_legal_method_signature(name, sig, CHECK);
 656           } else {
 657             // Format check field name and signature
 658             verify_legal_field_name(name, CHECK);
 659             verify_legal_field_signature(name, sig, CHECK);
 660           }
 661         }
 662         break;
 663       }
 664       case JVM_CONSTANT_Dynamic: {
 665         const int name_and_type_ref_index =
 666           cp->name_and_type_ref_index_at(index);
 667         // already verified to be utf8
 668         const int name_ref_index =
 669           cp->name_ref_index_at(name_and_type_ref_index);
 670         // already verified to be utf8
 671         const int signature_ref_index =
 672           cp->signature_ref_index_at(name_and_type_ref_index);
 673         const Symbol* const name = cp->symbol_at(name_ref_index);
 674         const Symbol* const signature = cp->symbol_at(signature_ref_index);
 675         if (_need_verify) {
 676           // CONSTANT_Dynamic's name and signature are verified above, when iterating NameAndType_info.
 677           // Need only to be sure signature is the right type.
 678           if (Signature::is_method(signature)) {
 679             throwIllegalSignature("CONSTANT_Dynamic", name, signature, CHECK);
 680           }
 681         }
 682         break;
 683       }
 684       case JVM_CONSTANT_InvokeDynamic:
 685       case JVM_CONSTANT_Fieldref:
 686       case JVM_CONSTANT_Methodref:
 687       case JVM_CONSTANT_InterfaceMethodref: {
 688         const int name_and_type_ref_index =
 689           cp->name_and_type_ref_index_at(index);
 690         // already verified to be utf8
 691         const int name_ref_index =
 692           cp->name_ref_index_at(name_and_type_ref_index);
 693         // already verified to be utf8
 694         const int signature_ref_index =
 695           cp->signature_ref_index_at(name_and_type_ref_index);
 696         const Symbol* const name = cp->symbol_at(name_ref_index);
 697         const Symbol* const signature = cp->symbol_at(signature_ref_index);
 698         if (tag == JVM_CONSTANT_Fieldref) {
 699           if (_need_verify) {
 700             // Field name and signature are verified above, when iterating NameAndType_info.
 701             // Need only to be sure signature is non-zero length and the right type.
 702             if (Signature::is_method(signature)) {
 703               throwIllegalSignature("Field", name, signature, CHECK);
 704             }
 705           }
 706         } else {
 707           if (_need_verify) {
 708             // Method name and signature are individually verified above, when iterating
 709             // NameAndType_info.  Need to check here that signature is non-zero length and
 710             // the right type.
 711             if (!Signature::is_method(signature)) {
 712               throwIllegalSignature("Method", name, signature, CHECK);
 713             }
 714           }
 715           // If a class method name begins with '<', it must be "<init>" and have void signature
 716           // unless it's an inline type.
 717           const unsigned int name_len = name->utf8_length();
 718           if (tag == JVM_CONSTANT_Methodref && name_len != 0 &&
 719               name->char_at(0) == JVM_SIGNATURE_SPECIAL) {
 720             if (name != vmSymbols::object_initializer_name()) {
 721               classfile_parse_error(
 722                 "Bad method name at constant pool index %u in class file %s",
 723                 name_ref_index, THREAD);
 724               return;
 725             } else if (!Signature::is_void_method(signature)) {
 726               // if return type is non-void then it cannot be a basic primitive
 727               // and primitve types must be supported.
 728               if (!signature->ends_with(JVM_SIGNATURE_ENDCLASS) || !EnableValhalla) {
 729                 throwIllegalSignature("Method", name, signature, CHECK);
 730               }
 731             }
 732           }
 733         }
 734         break;
 735       }
 736       case JVM_CONSTANT_MethodHandle: {
 737         const int ref_index = cp->method_handle_index_at(index);
 738         const int ref_kind = cp->method_handle_ref_kind_at(index);
 739         switch (ref_kind) {
 740           case JVM_REF_invokeVirtual:
 741           case JVM_REF_invokeStatic:
 742           case JVM_REF_invokeSpecial:
 743           case JVM_REF_newInvokeSpecial: {
 744             const int name_and_type_ref_index =
 745               cp->name_and_type_ref_index_at(ref_index);
 746             const int name_ref_index =
 747               cp->name_ref_index_at(name_and_type_ref_index);
 748             const Symbol* const name = cp->symbol_at(name_ref_index);
 749             if (name != vmSymbols::object_initializer_name()) {
 750               if (ref_kind == JVM_REF_newInvokeSpecial) {
 751                 classfile_parse_error(
 752                   "Bad constructor name at constant pool index %u in class file %s",
 753                     name_ref_index, THREAD);
 754                 return;
 755               }
 756             } else {
 757               // The allowed invocation mode of <init> depends on its signature.
 758               // This test corresponds to verify_invoke_instructions in the verifier.
 759               const int signature_ref_index =
 760                 cp->signature_ref_index_at(name_and_type_ref_index);
 761               const Symbol* const signature = cp->symbol_at(signature_ref_index);
 762               if (signature->is_void_method_signature()
 763                   && ref_kind == JVM_REF_newInvokeSpecial) {
 764                 // OK, could be a constructor call
 765               } else if (!signature->is_void_method_signature()
 766                          && ref_kind == JVM_REF_invokeStatic) {
 767                 // also OK, could be a static factory call
 768               } else {
 769                 classfile_parse_error(
 770                   "Bad method name at constant pool index %u in class file %s",
 771                   name_ref_index, THREAD);
 772                 return;
 773               }
 774             }
 775             break;
 776           }
 777           // Other ref_kinds are already fully checked in previous pass.
 778         } // switch(ref_kind)
 779         break;
 780       }
 781       case JVM_CONSTANT_MethodType: {
 782         const Symbol* const no_name = vmSymbols::type_name(); // place holder
 783         const Symbol* const signature = cp->method_type_signature_at(index);
 784         verify_legal_method_signature(no_name, signature, CHECK);
 785         break;
 786       }
 787       case JVM_CONSTANT_Utf8: {
 788         assert(cp->symbol_at(index)->refcount() != 0, "count corrupted");
 789       }
 790     }  // switch(tag)
 791   }  // end of for
 792 }
 793 
 794 class NameSigHash: public ResourceObj {
 795  public:
 796   const Symbol*       _name;       // name
 797   const Symbol*       _sig;        // signature
 798   NameSigHash*  _next;             // Next entry in hash table
 799 };
 800 
 801 static const int HASH_ROW_SIZE = 256;
 802 
 803 static unsigned int hash(const Symbol* name, const Symbol* sig) {
 804   unsigned int raw_hash = 0;
 805   raw_hash += ((unsigned int)(uintptr_t)name) >> (LogHeapWordSize + 2);
 806   raw_hash += ((unsigned int)(uintptr_t)sig) >> LogHeapWordSize;
 807 
 808   return (raw_hash + (unsigned int)(uintptr_t)name) % HASH_ROW_SIZE;
 809 }
 810 
 811 
 812 static void initialize_hashtable(NameSigHash** table) {
 813   memset((void*)table, 0, sizeof(NameSigHash*) * HASH_ROW_SIZE);
 814 }
 815 // Return false if the name/sig combination is found in table.
 816 // Return true if no duplicate is found. And name/sig is added as a new entry in table.
 817 // The old format checker uses heap sort to find duplicates.
 818 // NOTE: caller should guarantee that GC doesn't happen during the life cycle
 819 // of table since we don't expect Symbol*'s to move.
 820 static bool put_after_lookup(const Symbol* name, const Symbol* sig, NameSigHash** table) {
 821   assert(name != NULL, "name in constant pool is NULL");
 822 
 823   // First lookup for duplicates
 824   int index = hash(name, sig);
 825   NameSigHash* entry = table[index];
 826   while (entry != NULL) {
 827     if (entry->_name == name && entry->_sig == sig) {
 828       return false;
 829     }
 830     entry = entry->_next;
 831   }
 832 
 833   // No duplicate is found, allocate a new entry and fill it.
 834   entry = new NameSigHash();
 835   entry->_name = name;
 836   entry->_sig = sig;
 837 
 838   // Insert into hash table
 839   entry->_next = table[index];
 840   table[index] = entry;
 841 
 842   return true;
 843 }
 844 
 845 // Side-effects: populates the _local_interfaces field
 846 void ClassFileParser::parse_interfaces(const ClassFileStream* stream,
 847                                        int itfs_len,
 848                                        ConstantPool* cp,
 849                                        bool* const has_nonstatic_concrete_methods,
 850                                        // FIXME: lots of these functions
 851                                        // declare their parameters as const,
 852                                        // which adds only noise to the code.
 853                                        // Remove the spurious const modifiers.
 854                                        // Many are of the form "const int x"
 855                                        // or "T* const x".
 856                                        bool* const is_declared_atomic,
 857                                        TRAPS) {
 858   assert(stream != NULL, "invariant");
 859   assert(cp != NULL, "invariant");
 860   assert(has_nonstatic_concrete_methods != NULL, "invariant");
 861 
 862   if (itfs_len == 0) {
 863     _temp_local_interfaces = new GrowableArray<InstanceKlass*>(0);
 864   } else {
 865     assert(itfs_len > 0, "only called for len>0");
 866     _temp_local_interfaces = new GrowableArray<InstanceKlass*>(itfs_len);
 867     int index = 0;

 868     for (index = 0; index < itfs_len; index++) {
 869       const u2 interface_index = stream->get_u2(CHECK);
 870       Klass* interf;
 871       check_property(
 872         valid_klass_reference_at(interface_index),
 873         "Interface name has bad constant pool index %u in class file %s",
 874         interface_index, CHECK);
 875       if (cp->tag_at(interface_index).is_klass()) {
 876         interf = cp->resolved_klass_at(interface_index);
 877       } else {
 878         Symbol* const unresolved_klass  = cp->klass_name_at(interface_index);
 879 
 880         // Don't need to check legal name because it's checked when parsing constant pool.
 881         // But need to make sure it's not an array type.
 882         guarantee_property(unresolved_klass->char_at(0) != JVM_SIGNATURE_ARRAY,
 883                            "Bad interface name in class file %s", CHECK);
 884 
 885         // Call resolve_super so class circularity is checked
 886         interf = SystemDictionary::resolve_super_or_fail(
 887                                                   _class_name,
 888                                                   unresolved_klass,
 889                                                   Handle(THREAD, _loader_data->class_loader()),
 890                                                   _protection_domain,
 891                                                   false,
 892                                                   CHECK);
 893       }
 894 
 895       if (!interf->is_interface()) {
 896         THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
 897                   err_msg("class %s can not implement %s, because it is not an interface (%s)",
 898                           _class_name->as_klass_external_name(),
 899                           interf->external_name(),
 900                           interf->class_in_module_of_loader()));
 901       }
 902 
 903       InstanceKlass* ik = InstanceKlass::cast(interf);
 904       if (is_inline_type() && ik->invalid_inline_super()) {
 905         ResourceMark rm(THREAD);
 906         Exceptions::fthrow(
 907           THREAD_AND_LOCATION,
 908           vmSymbols::java_lang_IncompatibleClassChangeError(),
 909           "Inline type %s attempts to implement interface java.lang.IdentityObject",
 910           _class_name->as_klass_external_name());
 911         return;
 912       }
 913       if (ik->invalid_inline_super()) {
 914         set_invalid_inline_super();
 915       }
 916       if (ik->has_nonstatic_concrete_methods()) {
 917         *has_nonstatic_concrete_methods = true;
 918       }
 919       if (ik->is_declared_atomic()) {
 920         *is_declared_atomic = true;
 921       }
 922       if (ik->name() == vmSymbols::java_lang_IdentityObject()) {
 923         _implements_identityObject = true;
 924       }
 925       if (ik->name() == vmSymbols::java_lang_PrimitiveObject()) {
 926         // further checks for "is_invalid_super_for_inline_type()" needed later
 927         // needs field parsing, delay unitl post_process_parse_stream()
 928         _implements_primitiveObject = true;
 929       }
 930       _temp_local_interfaces->append(ik);
 931     }
 932 
 933     if (!_need_verify || itfs_len <= 1) {
 934       return;
 935     }
 936 
 937     // Check if there's any duplicates in interfaces
 938     ResourceMark rm(THREAD);
 939     NameSigHash** interface_names = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD,
 940                                                                  NameSigHash*,
 941                                                                  HASH_ROW_SIZE);
 942     initialize_hashtable(interface_names);
 943     bool dup = false;
 944     const Symbol* name = NULL;
 945     {
 946       debug_only(NoSafepointVerifier nsv;)
 947       for (index = 0; index < itfs_len; index++) {
 948         const InstanceKlass* const k = _temp_local_interfaces->at(index);
 949         name = k->name();
 950         // If no duplicates, add (name, NULL) in hashtable interface_names.
 951         if (!put_after_lookup(name, NULL, interface_names)) {
 952           dup = true;
 953           break;
 954         }
 955       }
 956     }
 957     if (dup) {
 958       classfile_parse_error("Duplicate interface name \"%s\" in class file %s",
 959                              name->as_C_string(), THREAD);
 960     }
 961   }
 962 }
 963 
 964 void ClassFileParser::verify_constantvalue(const ConstantPool* const cp,
 965                                            int constantvalue_index,
 966                                            int signature_index,
 967                                            TRAPS) const {
 968   // Make sure the constant pool entry is of a type appropriate to this field
 969   guarantee_property(
 970     (constantvalue_index > 0 &&
 971       constantvalue_index < cp->length()),
 972     "Bad initial value index %u in ConstantValue attribute in class file %s",
 973     constantvalue_index, CHECK);
 974 
 975   const constantTag value_type = cp->tag_at(constantvalue_index);
 976   switch(cp->basic_type_for_signature_at(signature_index)) {
 977     case T_LONG: {
 978       guarantee_property(value_type.is_long(),
 979                          "Inconsistent constant value type in class file %s",
 980                          CHECK);
 981       break;
 982     }
 983     case T_FLOAT: {
 984       guarantee_property(value_type.is_float(),
 985                          "Inconsistent constant value type in class file %s",
 986                          CHECK);
 987       break;
 988     }
 989     case T_DOUBLE: {
 990       guarantee_property(value_type.is_double(),
 991                          "Inconsistent constant value type in class file %s",
 992                          CHECK);
 993       break;
 994     }
 995     case T_BYTE:
 996     case T_CHAR:
 997     case T_SHORT:
 998     case T_BOOLEAN:
 999     case T_INT: {
1000       guarantee_property(value_type.is_int(),
1001                          "Inconsistent constant value type in class file %s",
1002                          CHECK);
1003       break;
1004     }
1005     case T_OBJECT: {
1006       guarantee_property((cp->symbol_at(signature_index)->equals("Ljava/lang/String;")
1007                          && value_type.is_string()),
1008                          "Bad string initial value in class file %s",
1009                          CHECK);
1010       break;
1011     }
1012     default: {
1013       classfile_parse_error("Unable to set initial value %u in class file %s",
1014                              constantvalue_index,
1015                              THREAD);
1016     }
1017   }
1018 }
1019 
1020 class AnnotationCollector : public ResourceObj{
1021 public:
1022   enum Location { _in_field, _in_method, _in_class };
1023   enum ID {
1024     _unknown = 0,
1025     _method_CallerSensitive,
1026     _method_ForceInline,
1027     _method_DontInline,
1028     _method_InjectedProfile,
1029     _method_LambdaForm_Compiled,
1030     _method_Hidden,
1031     _method_Scoped,
1032     _method_IntrinsicCandidate,
1033     _jdk_internal_vm_annotation_Contended,
1034     _field_Stable,
1035     _jdk_internal_vm_annotation_ReservedStackAccess,
1036     _jdk_internal_ValueBased,
1037     _annotation_LIMIT
1038   };
1039   const Location _location;
1040   int _annotations_present;
1041   u2 _contended_group;
1042 
1043   AnnotationCollector(Location location)
1044     : _location(location), _annotations_present(0), _contended_group(0)
1045   {
1046     assert((int)_annotation_LIMIT <= (int)sizeof(_annotations_present) * BitsPerByte, "");
1047   }
1048   // If this annotation name has an ID, report it (or _none).
1049   ID annotation_index(const ClassLoaderData* loader_data, const Symbol* name, bool can_access_vm_annotations);
1050   // Set the annotation name:
1051   void set_annotation(ID id) {
1052     assert((int)id >= 0 && (int)id < (int)_annotation_LIMIT, "oob");
1053     _annotations_present |= nth_bit((int)id);
1054   }
1055 
1056   void remove_annotation(ID id) {
1057     assert((int)id >= 0 && (int)id < (int)_annotation_LIMIT, "oob");
1058     _annotations_present &= ~nth_bit((int)id);
1059   }
1060 
1061   // Report if the annotation is present.
1062   bool has_any_annotations() const { return _annotations_present != 0; }
1063   bool has_annotation(ID id) const { return (nth_bit((int)id) & _annotations_present) != 0; }
1064 
1065   void set_contended_group(u2 group) { _contended_group = group; }
1066   u2 contended_group() const { return _contended_group; }
1067 
1068   bool is_contended() const { return has_annotation(_jdk_internal_vm_annotation_Contended); }
1069 
1070   void set_stable(bool stable) { set_annotation(_field_Stable); }
1071   bool is_stable() const { return has_annotation(_field_Stable); }
1072 };
1073 
1074 // This class also doubles as a holder for metadata cleanup.
1075 class ClassFileParser::FieldAnnotationCollector : public AnnotationCollector {
1076 private:
1077   ClassLoaderData* _loader_data;
1078   AnnotationArray* _field_annotations;
1079   AnnotationArray* _field_type_annotations;
1080 public:
1081   FieldAnnotationCollector(ClassLoaderData* loader_data) :
1082     AnnotationCollector(_in_field),
1083     _loader_data(loader_data),
1084     _field_annotations(NULL),
1085     _field_type_annotations(NULL) {}
1086   ~FieldAnnotationCollector();
1087   void apply_to(FieldInfo* f);
1088   AnnotationArray* field_annotations()      { return _field_annotations; }
1089   AnnotationArray* field_type_annotations() { return _field_type_annotations; }
1090 
1091   void set_field_annotations(AnnotationArray* a)      { _field_annotations = a; }
1092   void set_field_type_annotations(AnnotationArray* a) { _field_type_annotations = a; }
1093 };
1094 
1095 class MethodAnnotationCollector : public AnnotationCollector{
1096 public:
1097   MethodAnnotationCollector() : AnnotationCollector(_in_method) { }
1098   void apply_to(const methodHandle& m);
1099 };
1100 
1101 class ClassFileParser::ClassAnnotationCollector : public AnnotationCollector{
1102 public:
1103   ClassAnnotationCollector() : AnnotationCollector(_in_class) { }
1104   void apply_to(InstanceKlass* ik);
1105 };
1106 
1107 
1108 static int skip_annotation_value(const u1*, int, int); // fwd decl
1109 
1110 // Safely increment index by val if does not pass limit
1111 #define SAFE_ADD(index, limit, val) \
1112 if (index >= limit - val) return limit; \
1113 index += val;
1114 
1115 // Skip an annotation.  Return >=limit if there is any problem.
1116 static int skip_annotation(const u1* buffer, int limit, int index) {
1117   assert(buffer != NULL, "invariant");
1118   // annotation := atype:u2 do(nmem:u2) {member:u2 value}
1119   // value := switch (tag:u1) { ... }
1120   SAFE_ADD(index, limit, 4); // skip atype and read nmem
1121   int nmem = Bytes::get_Java_u2((address)buffer + index - 2);
1122   while (--nmem >= 0 && index < limit) {
1123     SAFE_ADD(index, limit, 2); // skip member
1124     index = skip_annotation_value(buffer, limit, index);
1125   }
1126   return index;
1127 }
1128 
1129 // Skip an annotation value.  Return >=limit if there is any problem.
1130 static int skip_annotation_value(const u1* buffer, int limit, int index) {
1131   assert(buffer != NULL, "invariant");
1132 
1133   // value := switch (tag:u1) {
1134   //   case B, C, I, S, Z, D, F, J, c: con:u2;
1135   //   case e: e_class:u2 e_name:u2;
1136   //   case s: s_con:u2;
1137   //   case [: do(nval:u2) {value};
1138   //   case @: annotation;
1139   //   case s: s_con:u2;
1140   // }
1141   SAFE_ADD(index, limit, 1); // read tag
1142   const u1 tag = buffer[index - 1];
1143   switch (tag) {
1144     case 'B':
1145     case 'C':
1146     case 'I':
1147     case 'S':
1148     case 'Z':
1149     case 'D':
1150     case 'F':
1151     case 'J':
1152     case 'c':
1153     case 's':
1154       SAFE_ADD(index, limit, 2);  // skip con or s_con
1155       break;
1156     case 'e':
1157       SAFE_ADD(index, limit, 4);  // skip e_class, e_name
1158       break;
1159     case '[':
1160     {
1161       SAFE_ADD(index, limit, 2); // read nval
1162       int nval = Bytes::get_Java_u2((address)buffer + index - 2);
1163       while (--nval >= 0 && index < limit) {
1164         index = skip_annotation_value(buffer, limit, index);
1165       }
1166     }
1167     break;
1168     case '@':
1169       index = skip_annotation(buffer, limit, index);
1170       break;
1171     default:
1172       return limit;  //  bad tag byte
1173   }
1174   return index;
1175 }
1176 
1177 // Sift through annotations, looking for those significant to the VM:
1178 static void parse_annotations(const ConstantPool* const cp,
1179                               const u1* buffer, int limit,
1180                               AnnotationCollector* coll,
1181                               ClassLoaderData* loader_data,
1182                               const bool can_access_vm_annotations) {
1183 
1184   assert(cp != NULL, "invariant");
1185   assert(buffer != NULL, "invariant");
1186   assert(coll != NULL, "invariant");
1187   assert(loader_data != NULL, "invariant");
1188 
1189   // annotations := do(nann:u2) {annotation}
1190   int index = 2; // read nann
1191   if (index >= limit)  return;
1192   int nann = Bytes::get_Java_u2((address)buffer + index - 2);
1193   enum {  // initial annotation layout
1194     atype_off = 0,      // utf8 such as 'Ljava/lang/annotation/Retention;'
1195     count_off = 2,      // u2   such as 1 (one value)
1196     member_off = 4,     // utf8 such as 'value'
1197     tag_off = 6,        // u1   such as 'c' (type) or 'e' (enum)
1198     e_tag_val = 'e',
1199     e_type_off = 7,   // utf8 such as 'Ljava/lang/annotation/RetentionPolicy;'
1200     e_con_off = 9,    // utf8 payload, such as 'SOURCE', 'CLASS', 'RUNTIME'
1201     e_size = 11,     // end of 'e' annotation
1202     c_tag_val = 'c',    // payload is type
1203     c_con_off = 7,    // utf8 payload, such as 'I'
1204     c_size = 9,       // end of 'c' annotation
1205     s_tag_val = 's',    // payload is String
1206     s_con_off = 7,    // utf8 payload, such as 'Ljava/lang/String;'
1207     s_size = 9,
1208     min_size = 6        // smallest possible size (zero members)
1209   };
1210   // Cannot add min_size to index in case of overflow MAX_INT
1211   while ((--nann) >= 0 && (index - 2 <= limit - min_size)) {
1212     int index0 = index;
1213     index = skip_annotation(buffer, limit, index);
1214     const u1* const abase = buffer + index0;
1215     const int atype = Bytes::get_Java_u2((address)abase + atype_off);
1216     const int count = Bytes::get_Java_u2((address)abase + count_off);
1217     const Symbol* const aname = check_symbol_at(cp, atype);
1218     if (aname == NULL)  break;  // invalid annotation name
1219     const Symbol* member = NULL;
1220     if (count >= 1) {
1221       const int member_index = Bytes::get_Java_u2((address)abase + member_off);
1222       member = check_symbol_at(cp, member_index);
1223       if (member == NULL)  break;  // invalid member name
1224     }
1225 
1226     // Here is where parsing particular annotations will take place.
1227     AnnotationCollector::ID id = coll->annotation_index(loader_data, aname, can_access_vm_annotations);
1228     if (AnnotationCollector::_unknown == id)  continue;
1229     coll->set_annotation(id);
1230 
1231     if (AnnotationCollector::_jdk_internal_vm_annotation_Contended == id) {
1232       // @Contended can optionally specify the contention group.
1233       //
1234       // Contended group defines the equivalence class over the fields:
1235       // the fields within the same contended group are not treated distinct.
1236       // The only exception is default group, which does not incur the
1237       // equivalence. Naturally, contention group for classes is meaningless.
1238       //
1239       // While the contention group is specified as String, annotation
1240       // values are already interned, and we might as well use the constant
1241       // pool index as the group tag.
1242       //
1243       u2 group_index = 0; // default contended group
1244       if (count == 1
1245         && s_size == (index - index0)  // match size
1246         && s_tag_val == *(abase + tag_off)
1247         && member == vmSymbols::value_name()) {
1248         group_index = Bytes::get_Java_u2((address)abase + s_con_off);
1249         if (cp->symbol_at(group_index)->utf8_length() == 0) {
1250           group_index = 0; // default contended group
1251         }
1252       }
1253       coll->set_contended_group(group_index);
1254     }
1255   }
1256 }
1257 
1258 
1259 // Parse attributes for a field.
1260 void ClassFileParser::parse_field_attributes(const ClassFileStream* const cfs,
1261                                              u2 attributes_count,
1262                                              bool is_static, u2 signature_index,
1263                                              u2* const constantvalue_index_addr,
1264                                              bool* const is_synthetic_addr,
1265                                              u2* const generic_signature_index_addr,
1266                                              ClassFileParser::FieldAnnotationCollector* parsed_annotations,
1267                                              TRAPS) {
1268   assert(cfs != NULL, "invariant");
1269   assert(constantvalue_index_addr != NULL, "invariant");
1270   assert(is_synthetic_addr != NULL, "invariant");
1271   assert(generic_signature_index_addr != NULL, "invariant");
1272   assert(parsed_annotations != NULL, "invariant");
1273   assert(attributes_count > 0, "attributes_count should be greater than 0");
1274 
1275   u2 constantvalue_index = 0;
1276   u2 generic_signature_index = 0;
1277   bool is_synthetic = false;
1278   const u1* runtime_visible_annotations = NULL;
1279   int runtime_visible_annotations_length = 0;
1280   const u1* runtime_invisible_annotations = NULL;
1281   int runtime_invisible_annotations_length = 0;
1282   const u1* runtime_visible_type_annotations = NULL;
1283   int runtime_visible_type_annotations_length = 0;
1284   const u1* runtime_invisible_type_annotations = NULL;
1285   int runtime_invisible_type_annotations_length = 0;
1286   bool runtime_invisible_annotations_exists = false;
1287   bool runtime_invisible_type_annotations_exists = false;
1288   const ConstantPool* const cp = _cp;
1289 
1290   while (attributes_count--) {
1291     cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
1292     const u2 attribute_name_index = cfs->get_u2_fast();
1293     const u4 attribute_length = cfs->get_u4_fast();
1294     check_property(valid_symbol_at(attribute_name_index),
1295                    "Invalid field attribute index %u in class file %s",
1296                    attribute_name_index,
1297                    CHECK);
1298 
1299     const Symbol* const attribute_name = cp->symbol_at(attribute_name_index);
1300     if (is_static && attribute_name == vmSymbols::tag_constant_value()) {
1301       // ignore if non-static
1302       if (constantvalue_index != 0) {
1303         classfile_parse_error("Duplicate ConstantValue attribute in class file %s", THREAD);
1304         return;
1305       }
1306       check_property(
1307         attribute_length == 2,
1308         "Invalid ConstantValue field attribute length %u in class file %s",
1309         attribute_length, CHECK);
1310 
1311       constantvalue_index = cfs->get_u2(CHECK);
1312       if (_need_verify) {
1313         verify_constantvalue(cp, constantvalue_index, signature_index, CHECK);
1314       }
1315     } else if (attribute_name == vmSymbols::tag_synthetic()) {
1316       if (attribute_length != 0) {
1317         classfile_parse_error(
1318           "Invalid Synthetic field attribute length %u in class file %s",
1319           attribute_length, THREAD);
1320         return;
1321       }
1322       is_synthetic = true;
1323     } else if (attribute_name == vmSymbols::tag_deprecated()) { // 4276120
1324       if (attribute_length != 0) {
1325         classfile_parse_error(
1326           "Invalid Deprecated field attribute length %u in class file %s",
1327           attribute_length, THREAD);
1328         return;
1329       }
1330     } else if (_major_version >= JAVA_1_5_VERSION) {
1331       if (attribute_name == vmSymbols::tag_signature()) {
1332         if (generic_signature_index != 0) {
1333           classfile_parse_error(
1334             "Multiple Signature attributes for field in class file %s", THREAD);
1335           return;
1336         }
1337         if (attribute_length != 2) {
1338           classfile_parse_error(
1339             "Wrong size %u for field's Signature attribute in class file %s",
1340             attribute_length, THREAD);
1341           return;
1342         }
1343         generic_signature_index = parse_generic_signature_attribute(cfs, CHECK);
1344       } else if (attribute_name == vmSymbols::tag_runtime_visible_annotations()) {
1345         if (runtime_visible_annotations != NULL) {
1346           classfile_parse_error(
1347             "Multiple RuntimeVisibleAnnotations attributes for field in class file %s", THREAD);
1348           return;
1349         }
1350         runtime_visible_annotations_length = attribute_length;
1351         runtime_visible_annotations = cfs->current();
1352         assert(runtime_visible_annotations != NULL, "null visible annotations");
1353         cfs->guarantee_more(runtime_visible_annotations_length, CHECK);
1354         parse_annotations(cp,
1355                           runtime_visible_annotations,
1356                           runtime_visible_annotations_length,
1357                           parsed_annotations,
1358                           _loader_data,
1359                           _can_access_vm_annotations);
1360         cfs->skip_u1_fast(runtime_visible_annotations_length);
1361       } else if (attribute_name == vmSymbols::tag_runtime_invisible_annotations()) {
1362         if (runtime_invisible_annotations_exists) {
1363           classfile_parse_error(
1364             "Multiple RuntimeInvisibleAnnotations attributes for field in class file %s", THREAD);
1365           return;
1366         }
1367         runtime_invisible_annotations_exists = true;
1368         if (PreserveAllAnnotations) {
1369           runtime_invisible_annotations_length = attribute_length;
1370           runtime_invisible_annotations = cfs->current();
1371           assert(runtime_invisible_annotations != NULL, "null invisible annotations");
1372         }
1373         cfs->skip_u1(attribute_length, CHECK);
1374       } else if (attribute_name == vmSymbols::tag_runtime_visible_type_annotations()) {
1375         if (runtime_visible_type_annotations != NULL) {
1376           classfile_parse_error(
1377             "Multiple RuntimeVisibleTypeAnnotations attributes for field in class file %s", THREAD);
1378           return;
1379         }
1380         runtime_visible_type_annotations_length = attribute_length;
1381         runtime_visible_type_annotations = cfs->current();
1382         assert(runtime_visible_type_annotations != NULL, "null visible type annotations");
1383         cfs->skip_u1(runtime_visible_type_annotations_length, CHECK);
1384       } else if (attribute_name == vmSymbols::tag_runtime_invisible_type_annotations()) {
1385         if (runtime_invisible_type_annotations_exists) {
1386           classfile_parse_error(
1387             "Multiple RuntimeInvisibleTypeAnnotations attributes for field in class file %s", THREAD);
1388           return;
1389         } else {
1390           runtime_invisible_type_annotations_exists = true;
1391         }
1392         if (PreserveAllAnnotations) {
1393           runtime_invisible_type_annotations_length = attribute_length;
1394           runtime_invisible_type_annotations = cfs->current();
1395           assert(runtime_invisible_type_annotations != NULL, "null invisible type annotations");
1396         }
1397         cfs->skip_u1(attribute_length, CHECK);
1398       } else {
1399         cfs->skip_u1(attribute_length, CHECK);  // Skip unknown attributes
1400       }
1401     } else {
1402       cfs->skip_u1(attribute_length, CHECK);  // Skip unknown attributes
1403     }
1404   }
1405 
1406   *constantvalue_index_addr = constantvalue_index;
1407   *is_synthetic_addr = is_synthetic;
1408   *generic_signature_index_addr = generic_signature_index;
1409   AnnotationArray* a = assemble_annotations(runtime_visible_annotations,
1410                                             runtime_visible_annotations_length,
1411                                             runtime_invisible_annotations,
1412                                             runtime_invisible_annotations_length,
1413                                             CHECK);
1414   parsed_annotations->set_field_annotations(a);
1415   a = assemble_annotations(runtime_visible_type_annotations,
1416                            runtime_visible_type_annotations_length,
1417                            runtime_invisible_type_annotations,
1418                            runtime_invisible_type_annotations_length,
1419                            CHECK);
1420   parsed_annotations->set_field_type_annotations(a);
1421   return;
1422 }
1423 
1424 
1425 // Field allocation types. Used for computing field offsets.
1426 
1427 enum FieldAllocationType {
1428   STATIC_OOP,           // Oops
1429   STATIC_BYTE,          // Boolean, Byte, char
1430   STATIC_SHORT,         // shorts
1431   STATIC_WORD,          // ints
1432   STATIC_DOUBLE,        // aligned long or double
1433   STATIC_INLINE,        // inline type field
1434   NONSTATIC_OOP,
1435   NONSTATIC_BYTE,
1436   NONSTATIC_SHORT,
1437   NONSTATIC_WORD,
1438   NONSTATIC_DOUBLE,
1439   NONSTATIC_INLINE,
1440   MAX_FIELD_ALLOCATION_TYPE,
1441   BAD_ALLOCATION_TYPE = -1
1442 };
1443 
1444 static FieldAllocationType _basic_type_to_atype[2 * (T_CONFLICT + 1)] = {
1445   BAD_ALLOCATION_TYPE, // 0
1446   BAD_ALLOCATION_TYPE, // 1
1447   BAD_ALLOCATION_TYPE, // 2
1448   BAD_ALLOCATION_TYPE, // 3
1449   NONSTATIC_BYTE ,     // T_BOOLEAN     =  4,
1450   NONSTATIC_SHORT,     // T_CHAR        =  5,
1451   NONSTATIC_WORD,      // T_FLOAT       =  6,
1452   NONSTATIC_DOUBLE,    // T_DOUBLE      =  7,
1453   NONSTATIC_BYTE,      // T_BYTE        =  8,
1454   NONSTATIC_SHORT,     // T_SHORT       =  9,
1455   NONSTATIC_WORD,      // T_INT         = 10,
1456   NONSTATIC_DOUBLE,    // T_LONG        = 11,
1457   NONSTATIC_OOP,       // T_OBJECT      = 12,
1458   NONSTATIC_OOP,       // T_ARRAY       = 13,
1459   NONSTATIC_OOP,       // T_INLINE_TYPE = 14,
1460   BAD_ALLOCATION_TYPE, // T_VOID        = 15,
1461   BAD_ALLOCATION_TYPE, // T_ADDRESS     = 16,
1462   BAD_ALLOCATION_TYPE, // T_NARROWOOP   = 17,
1463   BAD_ALLOCATION_TYPE, // T_METADATA    = 18,
1464   BAD_ALLOCATION_TYPE, // T_NARROWKLASS = 19,
1465   BAD_ALLOCATION_TYPE, // T_CONFLICT    = 20,
1466   BAD_ALLOCATION_TYPE, // 0
1467   BAD_ALLOCATION_TYPE, // 1
1468   BAD_ALLOCATION_TYPE, // 2
1469   BAD_ALLOCATION_TYPE, // 3
1470   STATIC_BYTE ,        // T_BOOLEAN     =  4,
1471   STATIC_SHORT,        // T_CHAR        =  5,
1472   STATIC_WORD,         // T_FLOAT       =  6,
1473   STATIC_DOUBLE,       // T_DOUBLE      =  7,
1474   STATIC_BYTE,         // T_BYTE        =  8,
1475   STATIC_SHORT,        // T_SHORT       =  9,
1476   STATIC_WORD,         // T_INT         = 10,
1477   STATIC_DOUBLE,       // T_LONG        = 11,
1478   STATIC_OOP,          // T_OBJECT      = 12,
1479   STATIC_OOP,          // T_ARRAY       = 13,
1480   STATIC_OOP,          // T_INLINE_TYPE = 14,
1481   BAD_ALLOCATION_TYPE, // T_VOID        = 15,
1482   BAD_ALLOCATION_TYPE, // T_ADDRESS     = 16,
1483   BAD_ALLOCATION_TYPE, // T_NARROWOOP   = 17,
1484   BAD_ALLOCATION_TYPE, // T_METADATA    = 18,
1485   BAD_ALLOCATION_TYPE, // T_NARROWKLASS = 19,
1486   BAD_ALLOCATION_TYPE, // T_CONFLICT    = 20
1487 };
1488 
1489 static FieldAllocationType basic_type_to_atype(bool is_static, BasicType type, bool is_inline_type) {
1490   assert(type >= T_BOOLEAN && type < T_VOID, "only allowable values");
1491   FieldAllocationType result = _basic_type_to_atype[type + (is_static ? (T_CONFLICT + 1) : 0)];
1492   assert(result != BAD_ALLOCATION_TYPE, "bad type");
1493   if (is_inline_type) {
1494     result = is_static ? STATIC_INLINE : NONSTATIC_INLINE;
1495   }
1496   return result;
1497 }
1498 
1499 class ClassFileParser::FieldAllocationCount : public ResourceObj {
1500  public:
1501   u2 count[MAX_FIELD_ALLOCATION_TYPE];
1502 
1503   FieldAllocationCount() {
1504     for (int i = 0; i < MAX_FIELD_ALLOCATION_TYPE; i++) {
1505       count[i] = 0;
1506     }
1507   }
1508 
1509   void update(bool is_static, BasicType type, bool is_inline_type) {
1510     FieldAllocationType atype = basic_type_to_atype(is_static, type, is_inline_type);
1511     if (atype != BAD_ALLOCATION_TYPE) {
1512       // Make sure there is no overflow with injected fields.
1513       assert(count[atype] < 0xFFFF, "More than 65535 fields");
1514       count[atype]++;
1515     }
1516   }
1517 };
1518 
1519 // Side-effects: populates the _fields, _fields_annotations,
1520 // _fields_type_annotations fields
1521 void ClassFileParser::parse_fields(const ClassFileStream* const cfs,
1522                                    bool is_interface,
1523                                    bool is_inline_type,
1524                                    FieldAllocationCount* const fac,
1525                                    ConstantPool* cp,
1526                                    const int cp_size,
1527                                    u2* const java_fields_count_ptr,
1528                                    TRAPS) {
1529 
1530   assert(cfs != NULL, "invariant");
1531   assert(fac != NULL, "invariant");
1532   assert(cp != NULL, "invariant");
1533   assert(java_fields_count_ptr != NULL, "invariant");
1534 
1535   assert(NULL == _fields, "invariant");
1536   assert(NULL == _fields_annotations, "invariant");
1537   assert(NULL == _fields_type_annotations, "invariant");
1538 
1539   cfs->guarantee_more(2, CHECK);  // length
1540   const u2 length = cfs->get_u2_fast();
1541   *java_fields_count_ptr = length;
1542 
1543   int num_injected = 0;
1544   const InjectedField* const injected = JavaClasses::get_injected(_class_name,
1545                                                                   &num_injected);
1546 
1547   // two more slots are required for inline classes:
1548   // one for the static field with a reference to the pre-allocated default value
1549   // one for the field the JVM injects when detecting an empty inline class
1550   const int total_fields = length + num_injected + (is_inline_type ? 2 : 0);
1551 
1552   // The field array starts with tuples of shorts
1553   // [access, name index, sig index, initial value index, byte offset].
1554   // A generic signature slot only exists for field with generic
1555   // signature attribute. And the access flag is set with
1556   // JVM_ACC_FIELD_HAS_GENERIC_SIGNATURE for that field. The generic
1557   // signature slots are at the end of the field array and after all
1558   // other fields data.
1559   //
1560   //   f1: [access, name index, sig index, initial value index, low_offset, high_offset]
1561   //   f2: [access, name index, sig index, initial value index, low_offset, high_offset]
1562   //       ...
1563   //   fn: [access, name index, sig index, initial value index, low_offset, high_offset]
1564   //       [generic signature index]
1565   //       [generic signature index]
1566   //       ...
1567   //
1568   // Allocate a temporary resource array for field data. For each field,
1569   // a slot is reserved in the temporary array for the generic signature
1570   // index. After parsing all fields, the data are copied to a permanent
1571   // array and any unused slots will be discarded.
1572   ResourceMark rm(THREAD);
1573   u2* const fa = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD,
1574                                               u2,
1575                                               total_fields * (FieldInfo::field_slots + 1));
1576 
1577   // The generic signature slots start after all other fields' data.
1578   int generic_signature_slot = total_fields * FieldInfo::field_slots;
1579   int num_generic_signature = 0;
1580   int instance_fields_count = 0;
1581   for (int n = 0; n < length; n++) {
1582     // access_flags, name_index, descriptor_index, attributes_count
1583     cfs->guarantee_more(8, CHECK);
1584 
1585     jint recognized_modifiers = JVM_RECOGNIZED_FIELD_MODIFIERS;
1586 
1587     const jint flags = cfs->get_u2_fast() & recognized_modifiers;
1588     verify_legal_field_modifiers(flags, is_interface, is_inline_type, CHECK);
1589     AccessFlags access_flags;


1590     access_flags.set_flags(flags);
1591 
1592     const u2 name_index = cfs->get_u2_fast();
1593     check_property(valid_symbol_at(name_index),
1594       "Invalid constant pool index %u for field name in class file %s",
1595       name_index, CHECK);
1596     const Symbol* const name = cp->symbol_at(name_index);
1597     verify_legal_field_name(name, CHECK);
1598 
1599     const u2 signature_index = cfs->get_u2_fast();
1600     check_property(valid_symbol_at(signature_index),
1601       "Invalid constant pool index %u for field signature in class file %s",
1602       signature_index, CHECK);
1603     const Symbol* const sig = cp->symbol_at(signature_index);
1604     verify_legal_field_signature(name, sig, CHECK);
1605     if (!access_flags.is_static()) instance_fields_count++;
1606 
1607     u2 constantvalue_index = 0;
1608     bool is_synthetic = false;
1609     u2 generic_signature_index = 0;
1610     const bool is_static = access_flags.is_static();
1611     FieldAnnotationCollector parsed_annotations(_loader_data);
1612 
1613     const u2 attributes_count = cfs->get_u2_fast();
1614     if (attributes_count > 0) {
1615       parse_field_attributes(cfs,
1616                              attributes_count,
1617                              is_static,
1618                              signature_index,
1619                              &constantvalue_index,
1620                              &is_synthetic,
1621                              &generic_signature_index,
1622                              &parsed_annotations,
1623                              CHECK);
1624 
1625       if (parsed_annotations.field_annotations() != NULL) {
1626         if (_fields_annotations == NULL) {
1627           _fields_annotations = MetadataFactory::new_array<AnnotationArray*>(
1628                                              _loader_data, length, NULL,
1629                                              CHECK);
1630         }
1631         _fields_annotations->at_put(n, parsed_annotations.field_annotations());
1632         parsed_annotations.set_field_annotations(NULL);
1633       }
1634       if (parsed_annotations.field_type_annotations() != NULL) {
1635         if (_fields_type_annotations == NULL) {
1636           _fields_type_annotations =
1637             MetadataFactory::new_array<AnnotationArray*>(_loader_data,
1638                                                          length,
1639                                                          NULL,
1640                                                          CHECK);
1641         }
1642         _fields_type_annotations->at_put(n, parsed_annotations.field_type_annotations());
1643         parsed_annotations.set_field_type_annotations(NULL);
1644       }
1645 
1646       if (is_synthetic) {
1647         access_flags.set_is_synthetic();
1648       }
1649       if (generic_signature_index != 0) {
1650         access_flags.set_field_has_generic_signature();
1651         fa[generic_signature_slot] = generic_signature_index;
1652         generic_signature_slot ++;
1653         num_generic_signature ++;
1654       }
1655     }
1656 
1657     FieldInfo* const field = FieldInfo::from_field_array(fa, n);
1658     field->initialize(access_flags.as_short(),
1659                       name_index,
1660                       signature_index,
1661                       constantvalue_index);
1662     const BasicType type = cp->basic_type_for_signature_at(signature_index);
1663 
1664     // Update FieldAllocationCount for this kind of field
1665     fac->update(is_static, type, type == T_INLINE_TYPE);
1666 
1667     // After field is initialized with type, we can augment it with aux info
1668     if (parsed_annotations.has_any_annotations()) {
1669       parsed_annotations.apply_to(field);
1670       if (field->is_contended()) {
1671         _has_contended_fields = true;
1672       }
1673     }
1674   }
1675 
1676   int index = length;
1677   if (num_injected != 0) {
1678     for (int n = 0; n < num_injected; n++) {
1679       // Check for duplicates
1680       if (injected[n].may_be_java) {
1681         const Symbol* const name      = injected[n].name();
1682         const Symbol* const signature = injected[n].signature();
1683         bool duplicate = false;
1684         for (int i = 0; i < length; i++) {
1685           const FieldInfo* const f = FieldInfo::from_field_array(fa, i);
1686           if (name      == cp->symbol_at(f->name_index()) &&
1687               signature == cp->symbol_at(f->signature_index())) {
1688             // Symbol is desclared in Java so skip this one
1689             duplicate = true;
1690             break;
1691           }
1692         }
1693         if (duplicate) {
1694           // These will be removed from the field array at the end
1695           continue;
1696         }
1697       }
1698 
1699       // Injected field
1700       FieldInfo* const field = FieldInfo::from_field_array(fa, index);
1701       field->initialize((u2)JVM_ACC_FIELD_INTERNAL,
1702                         (u2)(injected[n].name_index),
1703                         (u2)(injected[n].signature_index),
1704                         0);
1705 
1706       const BasicType type = Signature::basic_type(injected[n].signature());
1707 
1708       // Update FieldAllocationCount for this kind of field
1709       fac->update(false, type, false);
1710       index++;
1711     }
1712   }
1713 
1714   if (is_inline_type) {
1715     FieldInfo* const field = FieldInfo::from_field_array(fa, index);
1716     field->initialize(JVM_ACC_FIELD_INTERNAL | JVM_ACC_STATIC,
1717                       (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(default_value_name)),
1718                       (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(object_signature)),
1719                       0);
1720     const BasicType type = Signature::basic_type(vmSymbols::object_signature());
1721     fac->update(true, type, false);
1722     index++;
1723   }
1724 
1725   if (is_inline_type && instance_fields_count == 0) {
1726     _is_empty_inline_type = true;
1727     FieldInfo* const field = FieldInfo::from_field_array(fa, index);
1728     field->initialize(JVM_ACC_FIELD_INTERNAL,
1729         (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(empty_marker_name)),
1730         (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(byte_signature)),
1731         0);
1732     const BasicType type = Signature::basic_type(vmSymbols::byte_signature());
1733     fac->update(false, type, false);
1734     index++;
1735   }
1736 
1737   if (instance_fields_count > 0) {
1738     _has_nonstatic_fields = true;
1739   }
1740 
1741   assert(NULL == _fields, "invariant");
1742 
1743   _fields =
1744     MetadataFactory::new_array<u2>(_loader_data,
1745                                    index * FieldInfo::field_slots + num_generic_signature,
1746                                    CHECK);
1747   // Sometimes injected fields already exist in the Java source so
1748   // the fields array could be too long.  In that case the
1749   // fields array is trimed. Also unused slots that were reserved
1750   // for generic signature indexes are discarded.
1751   {
1752     int i = 0;
1753     for (; i < index * FieldInfo::field_slots; i++) {
1754       _fields->at_put(i, fa[i]);
1755     }
1756     for (int j = total_fields * FieldInfo::field_slots;
1757          j < generic_signature_slot; j++) {
1758       _fields->at_put(i++, fa[j]);
1759     }
1760     assert(_fields->length() == i, "");
1761   }
1762 
1763   if (_need_verify && length > 1) {
1764     // Check duplicated fields
1765     ResourceMark rm(THREAD);
1766     NameSigHash** names_and_sigs = NEW_RESOURCE_ARRAY_IN_THREAD(
1767       THREAD, NameSigHash*, HASH_ROW_SIZE);
1768     initialize_hashtable(names_and_sigs);
1769     bool dup = false;
1770     const Symbol* name = NULL;
1771     const Symbol* sig = NULL;
1772     {
1773       debug_only(NoSafepointVerifier nsv;)
1774       for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
1775         name = fs.name();
1776         sig = fs.signature();
1777         // If no duplicates, add name/signature in hashtable names_and_sigs.
1778         if (!put_after_lookup(name, sig, names_and_sigs)) {
1779           dup = true;
1780           break;
1781         }
1782       }
1783     }
1784     if (dup) {
1785       classfile_parse_error("Duplicate field name \"%s\" with signature \"%s\" in class file %s",
1786                              name->as_C_string(), sig->as_klass_external_name(), THREAD);
1787     }
1788   }
1789 }
1790 
1791 
1792 const ClassFileParser::unsafe_u2* ClassFileParser::parse_exception_table(const ClassFileStream* const cfs,
1793                                                                          u4 code_length,
1794                                                                          u4 exception_table_length,
1795                                                                          TRAPS) {
1796   assert(cfs != NULL, "invariant");
1797 
1798   const unsafe_u2* const exception_table_start = cfs->current();
1799   assert(exception_table_start != NULL, "null exception table");
1800 
1801   cfs->guarantee_more(8 * exception_table_length, CHECK_NULL); // start_pc,
1802                                                                // end_pc,
1803                                                                // handler_pc,
1804                                                                // catch_type_index
1805 
1806   // Will check legal target after parsing code array in verifier.
1807   if (_need_verify) {
1808     for (unsigned int i = 0; i < exception_table_length; i++) {
1809       const u2 start_pc = cfs->get_u2_fast();
1810       const u2 end_pc = cfs->get_u2_fast();
1811       const u2 handler_pc = cfs->get_u2_fast();
1812       const u2 catch_type_index = cfs->get_u2_fast();
1813       guarantee_property((start_pc < end_pc) && (end_pc <= code_length),
1814                          "Illegal exception table range in class file %s",
1815                          CHECK_NULL);
1816       guarantee_property(handler_pc < code_length,
1817                          "Illegal exception table handler in class file %s",
1818                          CHECK_NULL);
1819       if (catch_type_index != 0) {
1820         guarantee_property(valid_klass_reference_at(catch_type_index),
1821                            "Catch type in exception table has bad constant type in class file %s", CHECK_NULL);
1822       }
1823     }
1824   } else {
1825     cfs->skip_u2_fast(exception_table_length * 4);
1826   }
1827   return exception_table_start;
1828 }
1829 
1830 void ClassFileParser::parse_linenumber_table(u4 code_attribute_length,
1831                                              u4 code_length,
1832                                              CompressedLineNumberWriteStream**const write_stream,
1833                                              TRAPS) {
1834 
1835   const ClassFileStream* const cfs = _stream;
1836   unsigned int num_entries = cfs->get_u2(CHECK);
1837 
1838   // Each entry is a u2 start_pc, and a u2 line_number
1839   const unsigned int length_in_bytes = num_entries * (sizeof(u2) * 2);
1840 
1841   // Verify line number attribute and table length
1842   check_property(
1843     code_attribute_length == sizeof(u2) + length_in_bytes,
1844     "LineNumberTable attribute has wrong length in class file %s", CHECK);
1845 
1846   cfs->guarantee_more(length_in_bytes, CHECK);
1847 
1848   if ((*write_stream) == NULL) {
1849     if (length_in_bytes > fixed_buffer_size) {
1850       (*write_stream) = new CompressedLineNumberWriteStream(length_in_bytes);
1851     } else {
1852       (*write_stream) = new CompressedLineNumberWriteStream(
1853         _linenumbertable_buffer, fixed_buffer_size);
1854     }
1855   }
1856 
1857   while (num_entries-- > 0) {
1858     const u2 bci  = cfs->get_u2_fast(); // start_pc
1859     const u2 line = cfs->get_u2_fast(); // line_number
1860     guarantee_property(bci < code_length,
1861         "Invalid pc in LineNumberTable in class file %s", CHECK);
1862     (*write_stream)->write_pair(bci, line);
1863   }
1864 }
1865 
1866 
1867 class LVT_Hash : public AllStatic {
1868  public:
1869 
1870   static bool equals(LocalVariableTableElement const& e0, LocalVariableTableElement const& e1) {
1871   /*
1872    * 3-tuple start_bci/length/slot has to be unique key,
1873    * so the following comparison seems to be redundant:
1874    *       && elem->name_cp_index == entry->_elem->name_cp_index
1875    */
1876     return (e0.start_bci     == e1.start_bci &&
1877             e0.length        == e1.length &&
1878             e0.name_cp_index == e1.name_cp_index &&
1879             e0.slot          == e1.slot);
1880   }
1881 
1882   static unsigned int hash(LocalVariableTableElement const& e0) {
1883     unsigned int raw_hash = e0.start_bci;
1884 
1885     raw_hash = e0.length        + raw_hash * 37;
1886     raw_hash = e0.name_cp_index + raw_hash * 37;
1887     raw_hash = e0.slot          + raw_hash * 37;
1888 
1889     return raw_hash;
1890   }
1891 };
1892 
1893 
1894 // Class file LocalVariableTable elements.
1895 class Classfile_LVT_Element {
1896  public:
1897   u2 start_bci;
1898   u2 length;
1899   u2 name_cp_index;
1900   u2 descriptor_cp_index;
1901   u2 slot;
1902 };
1903 
1904 static void copy_lvt_element(const Classfile_LVT_Element* const src,
1905                              LocalVariableTableElement* const lvt) {
1906   lvt->start_bci           = Bytes::get_Java_u2((u1*) &src->start_bci);
1907   lvt->length              = Bytes::get_Java_u2((u1*) &src->length);
1908   lvt->name_cp_index       = Bytes::get_Java_u2((u1*) &src->name_cp_index);
1909   lvt->descriptor_cp_index = Bytes::get_Java_u2((u1*) &src->descriptor_cp_index);
1910   lvt->signature_cp_index  = 0;
1911   lvt->slot                = Bytes::get_Java_u2((u1*) &src->slot);
1912 }
1913 
1914 // Function is used to parse both attributes:
1915 // LocalVariableTable (LVT) and LocalVariableTypeTable (LVTT)
1916 const ClassFileParser::unsafe_u2* ClassFileParser::parse_localvariable_table(const ClassFileStream* cfs,
1917                                                                              u4 code_length,
1918                                                                              u2 max_locals,
1919                                                                              u4 code_attribute_length,
1920                                                                              u2* const localvariable_table_length,
1921                                                                              bool isLVTT,
1922                                                                              TRAPS) {
1923   const char* const tbl_name = (isLVTT) ? "LocalVariableTypeTable" : "LocalVariableTable";
1924   *localvariable_table_length = cfs->get_u2(CHECK_NULL);
1925   const unsigned int size =
1926     (*localvariable_table_length) * sizeof(Classfile_LVT_Element) / sizeof(u2);
1927 
1928   const ConstantPool* const cp = _cp;
1929 
1930   // Verify local variable table attribute has right length
1931   if (_need_verify) {
1932     guarantee_property(code_attribute_length == (sizeof(*localvariable_table_length) + size * sizeof(u2)),
1933                        "%s has wrong length in class file %s", tbl_name, CHECK_NULL);
1934   }
1935 
1936   const unsafe_u2* const localvariable_table_start = cfs->current();
1937   assert(localvariable_table_start != NULL, "null local variable table");
1938   if (!_need_verify) {
1939     cfs->skip_u2_fast(size);
1940   } else {
1941     cfs->guarantee_more(size * 2, CHECK_NULL);
1942     for(int i = 0; i < (*localvariable_table_length); i++) {
1943       const u2 start_pc = cfs->get_u2_fast();
1944       const u2 length = cfs->get_u2_fast();
1945       const u2 name_index = cfs->get_u2_fast();
1946       const u2 descriptor_index = cfs->get_u2_fast();
1947       const u2 index = cfs->get_u2_fast();
1948       // Assign to a u4 to avoid overflow
1949       const u4 end_pc = (u4)start_pc + (u4)length;
1950 
1951       if (start_pc >= code_length) {
1952         classfile_parse_error(
1953           "Invalid start_pc %u in %s in class file %s",
1954           start_pc, tbl_name, THREAD);
1955         return NULL;
1956       }
1957       if (end_pc > code_length) {
1958         classfile_parse_error(
1959           "Invalid length %u in %s in class file %s",
1960           length, tbl_name, THREAD);
1961         return NULL;
1962       }
1963       const int cp_size = cp->length();
1964       guarantee_property(valid_symbol_at(name_index),
1965         "Name index %u in %s has bad constant type in class file %s",
1966         name_index, tbl_name, CHECK_NULL);
1967       guarantee_property(valid_symbol_at(descriptor_index),
1968         "Signature index %u in %s has bad constant type in class file %s",
1969         descriptor_index, tbl_name, CHECK_NULL);
1970 
1971       const Symbol* const name = cp->symbol_at(name_index);
1972       const Symbol* const sig = cp->symbol_at(descriptor_index);
1973       verify_legal_field_name(name, CHECK_NULL);
1974       u2 extra_slot = 0;
1975       if (!isLVTT) {
1976         verify_legal_field_signature(name, sig, CHECK_NULL);
1977 
1978         // 4894874: check special cases for double and long local variables
1979         if (sig == vmSymbols::type_signature(T_DOUBLE) ||
1980             sig == vmSymbols::type_signature(T_LONG)) {
1981           extra_slot = 1;
1982         }
1983       }
1984       guarantee_property((index + extra_slot) < max_locals,
1985                           "Invalid index %u in %s in class file %s",
1986                           index, tbl_name, CHECK_NULL);
1987     }
1988   }
1989   return localvariable_table_start;
1990 }
1991 
1992 static const u1* parse_stackmap_table(const ClassFileStream* const cfs,
1993                                       u4 code_attribute_length,
1994                                       bool need_verify,
1995                                       TRAPS) {
1996   assert(cfs != NULL, "invariant");
1997 
1998   if (0 == code_attribute_length) {
1999     return NULL;
2000   }
2001 
2002   const u1* const stackmap_table_start = cfs->current();
2003   assert(stackmap_table_start != NULL, "null stackmap table");
2004 
2005   // check code_attribute_length first
2006   cfs->skip_u1(code_attribute_length, CHECK_NULL);
2007 
2008   if (!need_verify && !DumpSharedSpaces) {
2009     return NULL;
2010   }
2011   return stackmap_table_start;
2012 }
2013 
2014 const ClassFileParser::unsafe_u2* ClassFileParser::parse_checked_exceptions(const ClassFileStream* const cfs,
2015                                                                             u2* const checked_exceptions_length,
2016                                                                             u4 method_attribute_length,
2017                                                                             TRAPS) {
2018   assert(cfs != NULL, "invariant");
2019   assert(checked_exceptions_length != NULL, "invariant");
2020 
2021   cfs->guarantee_more(2, CHECK_NULL);  // checked_exceptions_length
2022   *checked_exceptions_length = cfs->get_u2_fast();
2023   const unsigned int size =
2024     (*checked_exceptions_length) * sizeof(CheckedExceptionElement) / sizeof(u2);
2025   const unsafe_u2* const checked_exceptions_start = cfs->current();
2026   assert(checked_exceptions_start != NULL, "null checked exceptions");
2027   if (!_need_verify) {
2028     cfs->skip_u2_fast(size);
2029   } else {
2030     // Verify each value in the checked exception table
2031     u2 checked_exception;
2032     const u2 len = *checked_exceptions_length;
2033     cfs->guarantee_more(2 * len, CHECK_NULL);
2034     for (int i = 0; i < len; i++) {
2035       checked_exception = cfs->get_u2_fast();
2036       check_property(
2037         valid_klass_reference_at(checked_exception),
2038         "Exception name has bad type at constant pool %u in class file %s",
2039         checked_exception, CHECK_NULL);
2040     }
2041   }
2042   // check exceptions attribute length
2043   if (_need_verify) {
2044     guarantee_property(method_attribute_length == (sizeof(*checked_exceptions_length) +
2045                                                    sizeof(u2) * size),
2046                       "Exceptions attribute has wrong length in class file %s", CHECK_NULL);
2047   }
2048   return checked_exceptions_start;
2049 }
2050 
2051 void ClassFileParser::throwIllegalSignature(const char* type,
2052                                             const Symbol* name,
2053                                             const Symbol* sig,
2054                                             TRAPS) const {
2055   assert(name != NULL, "invariant");
2056   assert(sig != NULL, "invariant");
2057 
2058   const char* class_note = "";
2059   if (is_inline_type() && name == vmSymbols::object_initializer_name()) {
2060     class_note = " (an inline class)";
2061   }
2062 
2063   ResourceMark rm(THREAD);
2064   Exceptions::fthrow(THREAD_AND_LOCATION,
2065       vmSymbols::java_lang_ClassFormatError(),
2066       "%s \"%s\" in class %s%s has illegal signature \"%s\"", type,
2067       name->as_C_string(), _class_name->as_C_string(), class_note, sig->as_C_string());
2068 }
2069 
2070 AnnotationCollector::ID
2071 AnnotationCollector::annotation_index(const ClassLoaderData* loader_data,
2072                                       const Symbol* name,
2073                                       const bool can_access_vm_annotations) {
2074   const vmSymbolID sid = vmSymbols::find_sid(name);
2075   // Privileged code can use all annotations.  Other code silently drops some.
2076   const bool privileged = loader_data->is_boot_class_loader_data() ||
2077                           loader_data->is_platform_class_loader_data() ||
2078                           can_access_vm_annotations;
2079   switch (sid) {
2080     case VM_SYMBOL_ENUM_NAME(reflect_CallerSensitive_signature): {
2081       if (_location != _in_method)  break;  // only allow for methods
2082       if (!privileged)              break;  // only allow in privileged code
2083       return _method_CallerSensitive;
2084     }
2085     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ForceInline_signature): {
2086       if (_location != _in_method)  break;  // only allow for methods
2087       if (!privileged)              break;  // only allow in privileged code
2088       return _method_ForceInline;
2089     }
2090     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_DontInline_signature): {
2091       if (_location != _in_method)  break;  // only allow for methods
2092       if (!privileged)              break;  // only allow in privileged code
2093       return _method_DontInline;
2094     }
2095     case VM_SYMBOL_ENUM_NAME(java_lang_invoke_InjectedProfile_signature): {
2096       if (_location != _in_method)  break;  // only allow for methods
2097       if (!privileged)              break;  // only allow in privileged code
2098       return _method_InjectedProfile;
2099     }
2100     case VM_SYMBOL_ENUM_NAME(java_lang_invoke_LambdaForm_Compiled_signature): {
2101       if (_location != _in_method)  break;  // only allow for methods
2102       if (!privileged)              break;  // only allow in privileged code
2103       return _method_LambdaForm_Compiled;
2104     }
2105     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Hidden_signature): {
2106       if (_location != _in_method)  break;  // only allow for methods
2107       if (!privileged)              break;  // only allow in privileged code
2108       return _method_Hidden;
2109     }
2110     case VM_SYMBOL_ENUM_NAME(jdk_internal_misc_Scoped_signature): {
2111       if (_location != _in_method)  break;  // only allow for methods
2112       if (!privileged)              break;  // only allow in privileged code
2113       return _method_Scoped;
2114     }
2115     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_IntrinsicCandidate_signature): {
2116       if (_location != _in_method)  break;  // only allow for methods
2117       if (!privileged)              break;  // only allow in privileged code
2118       return _method_IntrinsicCandidate;
2119     }
2120     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Stable_signature): {
2121       if (_location != _in_field)   break;  // only allow for fields
2122       if (!privileged)              break;  // only allow in privileged code
2123       return _field_Stable;
2124     }
2125     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Contended_signature): {
2126       if (_location != _in_field && _location != _in_class) {
2127         break;  // only allow for fields and classes
2128       }
2129       if (!EnableContended || (RestrictContended && !privileged)) {
2130         break;  // honor privileges
2131       }
2132       return _jdk_internal_vm_annotation_Contended;
2133     }
2134     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ReservedStackAccess_signature): {
2135       if (_location != _in_method)  break;  // only allow for methods
2136       if (RestrictReservedStack && !privileged) break; // honor privileges
2137       return _jdk_internal_vm_annotation_ReservedStackAccess;
2138     }
2139     case VM_SYMBOL_ENUM_NAME(jdk_internal_ValueBased_signature): {
2140       if (_location != _in_class)   break;  // only allow for classes
2141       if (!privileged)              break;  // only allow in priviledged code
2142       return _jdk_internal_ValueBased;
2143     }
2144     default: {
2145       break;
2146     }
2147   }
2148   return AnnotationCollector::_unknown;
2149 }
2150 
2151 void ClassFileParser::FieldAnnotationCollector::apply_to(FieldInfo* f) {
2152   if (is_contended())
2153     f->set_contended_group(contended_group());
2154   if (is_stable())
2155     f->set_stable(true);
2156 }
2157 
2158 ClassFileParser::FieldAnnotationCollector::~FieldAnnotationCollector() {
2159   // If there's an error deallocate metadata for field annotations
2160   MetadataFactory::free_array<u1>(_loader_data, _field_annotations);
2161   MetadataFactory::free_array<u1>(_loader_data, _field_type_annotations);
2162 }
2163 
2164 void MethodAnnotationCollector::apply_to(const methodHandle& m) {
2165   if (has_annotation(_method_CallerSensitive))
2166     m->set_caller_sensitive(true);
2167   if (has_annotation(_method_ForceInline))
2168     m->set_force_inline(true);
2169   if (has_annotation(_method_DontInline))
2170     m->set_dont_inline(true);
2171   if (has_annotation(_method_InjectedProfile))
2172     m->set_has_injected_profile(true);
2173   if (has_annotation(_method_LambdaForm_Compiled) && m->intrinsic_id() == vmIntrinsics::_none)
2174     m->set_intrinsic_id(vmIntrinsics::_compiledLambdaForm);
2175   if (has_annotation(_method_Hidden))
2176     m->set_hidden(true);
2177   if (has_annotation(_method_Scoped))
2178     m->set_scoped(true);
2179   if (has_annotation(_method_IntrinsicCandidate) && !m->is_synthetic())
2180     m->set_intrinsic_candidate(true);
2181   if (has_annotation(_jdk_internal_vm_annotation_ReservedStackAccess))
2182     m->set_has_reserved_stack_access(true);
2183 }
2184 
2185 void ClassFileParser::ClassAnnotationCollector::apply_to(InstanceKlass* ik) {
2186   assert(ik != NULL, "invariant");
2187   if (has_annotation(_jdk_internal_vm_annotation_Contended)) {
2188     ik->set_is_contended(is_contended());
2189   }
2190   if (has_annotation(_jdk_internal_ValueBased)) {
2191     ik->set_has_value_based_class_annotation();
2192     if (DiagnoseSyncOnValueBasedClasses) {
2193       ik->set_is_value_based();
2194     }
2195   }
2196 }
2197 
2198 #define MAX_ARGS_SIZE 255
2199 #define MAX_CODE_SIZE 65535
2200 #define INITIAL_MAX_LVT_NUMBER 256
2201 
2202 /* Copy class file LVT's/LVTT's into the HotSpot internal LVT.
2203  *
2204  * Rules for LVT's and LVTT's are:
2205  *   - There can be any number of LVT's and LVTT's.
2206  *   - If there are n LVT's, it is the same as if there was just
2207  *     one LVT containing all the entries from the n LVT's.
2208  *   - There may be no more than one LVT entry per local variable.
2209  *     Two LVT entries are 'equal' if these fields are the same:
2210  *        start_pc, length, name, slot
2211  *   - There may be no more than one LVTT entry per each LVT entry.
2212  *     Each LVTT entry has to match some LVT entry.
2213  *   - HotSpot internal LVT keeps natural ordering of class file LVT entries.
2214  */
2215 void ClassFileParser::copy_localvariable_table(const ConstMethod* cm,
2216                                                int lvt_cnt,
2217                                                u2* const localvariable_table_length,
2218                                                const unsafe_u2** const localvariable_table_start,
2219                                                int lvtt_cnt,
2220                                                u2* const localvariable_type_table_length,
2221                                                const unsafe_u2** const localvariable_type_table_start,
2222                                                TRAPS) {
2223 
2224   ResourceMark rm(THREAD);
2225 
2226   typedef ResourceHashtable<LocalVariableTableElement, LocalVariableTableElement*,
2227                             256, ResourceObj::RESOURCE_AREA, mtInternal,
2228                             &LVT_Hash::hash, &LVT_Hash::equals> LVT_HashTable;
2229 
2230   LVT_HashTable* const table = new LVT_HashTable();
2231 
2232   // To fill LocalVariableTable in
2233   const Classfile_LVT_Element* cf_lvt;
2234   LocalVariableTableElement* lvt = cm->localvariable_table_start();
2235 
2236   for (int tbl_no = 0; tbl_no < lvt_cnt; tbl_no++) {
2237     cf_lvt = (Classfile_LVT_Element *) localvariable_table_start[tbl_no];
2238     for (int idx = 0; idx < localvariable_table_length[tbl_no]; idx++, lvt++) {
2239       copy_lvt_element(&cf_lvt[idx], lvt);
2240       // If no duplicates, add LVT elem in hashtable.
2241       if (table->put(*lvt, lvt) == false
2242           && _need_verify
2243           && _major_version >= JAVA_1_5_VERSION) {
2244         classfile_parse_error("Duplicated LocalVariableTable attribute "
2245                               "entry for '%s' in class file %s",
2246                                _cp->symbol_at(lvt->name_cp_index)->as_utf8(),
2247                                THREAD);
2248         return;
2249       }
2250     }
2251   }
2252 
2253   // To merge LocalVariableTable and LocalVariableTypeTable
2254   const Classfile_LVT_Element* cf_lvtt;
2255   LocalVariableTableElement lvtt_elem;
2256 
2257   for (int tbl_no = 0; tbl_no < lvtt_cnt; tbl_no++) {
2258     cf_lvtt = (Classfile_LVT_Element *) localvariable_type_table_start[tbl_no];
2259     for (int idx = 0; idx < localvariable_type_table_length[tbl_no]; idx++) {
2260       copy_lvt_element(&cf_lvtt[idx], &lvtt_elem);
2261       LocalVariableTableElement** entry = table->get(lvtt_elem);
2262       if (entry == NULL) {
2263         if (_need_verify) {
2264           classfile_parse_error("LVTT entry for '%s' in class file %s "
2265                                 "does not match any LVT entry",
2266                                  _cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(),
2267                                  THREAD);
2268           return;
2269         }
2270       } else if ((*entry)->signature_cp_index != 0 && _need_verify) {
2271         classfile_parse_error("Duplicated LocalVariableTypeTable attribute "
2272                               "entry for '%s' in class file %s",
2273                                _cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(),
2274                                THREAD);
2275         return;
2276       } else {
2277         // to add generic signatures into LocalVariableTable
2278         (*entry)->signature_cp_index = lvtt_elem.descriptor_cp_index;
2279       }
2280     }
2281   }
2282 }
2283 
2284 
2285 void ClassFileParser::copy_method_annotations(ConstMethod* cm,
2286                                        const u1* runtime_visible_annotations,
2287                                        int runtime_visible_annotations_length,
2288                                        const u1* runtime_invisible_annotations,
2289                                        int runtime_invisible_annotations_length,
2290                                        const u1* runtime_visible_parameter_annotations,
2291                                        int runtime_visible_parameter_annotations_length,
2292                                        const u1* runtime_invisible_parameter_annotations,
2293                                        int runtime_invisible_parameter_annotations_length,
2294                                        const u1* runtime_visible_type_annotations,
2295                                        int runtime_visible_type_annotations_length,
2296                                        const u1* runtime_invisible_type_annotations,
2297                                        int runtime_invisible_type_annotations_length,
2298                                        const u1* annotation_default,
2299                                        int annotation_default_length,
2300                                        TRAPS) {
2301 
2302   AnnotationArray* a;
2303 
2304   if (runtime_visible_annotations_length +
2305       runtime_invisible_annotations_length > 0) {
2306      a = assemble_annotations(runtime_visible_annotations,
2307                               runtime_visible_annotations_length,
2308                               runtime_invisible_annotations,
2309                               runtime_invisible_annotations_length,
2310                               CHECK);
2311      cm->set_method_annotations(a);
2312   }
2313 
2314   if (runtime_visible_parameter_annotations_length +
2315       runtime_invisible_parameter_annotations_length > 0) {
2316     a = assemble_annotations(runtime_visible_parameter_annotations,
2317                              runtime_visible_parameter_annotations_length,
2318                              runtime_invisible_parameter_annotations,
2319                              runtime_invisible_parameter_annotations_length,
2320                              CHECK);
2321     cm->set_parameter_annotations(a);
2322   }
2323 
2324   if (annotation_default_length > 0) {
2325     a = assemble_annotations(annotation_default,
2326                              annotation_default_length,
2327                              NULL,
2328                              0,
2329                              CHECK);
2330     cm->set_default_annotations(a);
2331   }
2332 
2333   if (runtime_visible_type_annotations_length +
2334       runtime_invisible_type_annotations_length > 0) {
2335     a = assemble_annotations(runtime_visible_type_annotations,
2336                              runtime_visible_type_annotations_length,
2337                              runtime_invisible_type_annotations,
2338                              runtime_invisible_type_annotations_length,
2339                              CHECK);
2340     cm->set_type_annotations(a);
2341   }
2342 }
2343 
2344 
2345 // Note: the parse_method below is big and clunky because all parsing of the code and exceptions
2346 // attribute is inlined. This is cumbersome to avoid since we inline most of the parts in the
2347 // Method* to save footprint, so we only know the size of the resulting Method* when the
2348 // entire method attribute is parsed.
2349 //
2350 // The promoted_flags parameter is used to pass relevant access_flags
2351 // from the method back up to the containing klass. These flag values
2352 // are added to klass's access_flags.
2353 
2354 Method* ClassFileParser::parse_method(const ClassFileStream* const cfs,
2355                                       bool is_interface,
2356                                       bool is_inline_type,
2357                                       const ConstantPool* cp,
2358                                       AccessFlags* const promoted_flags,
2359                                       TRAPS) {
2360   assert(cfs != NULL, "invariant");
2361   assert(cp != NULL, "invariant");
2362   assert(promoted_flags != NULL, "invariant");
2363 
2364   ResourceMark rm(THREAD);
2365   // Parse fixed parts:
2366   // access_flags, name_index, descriptor_index, attributes_count
2367   cfs->guarantee_more(8, CHECK_NULL);
2368 
2369   int flags = cfs->get_u2_fast();
2370   const u2 name_index = cfs->get_u2_fast();
2371   const int cp_size = cp->length();
2372   check_property(
2373     valid_symbol_at(name_index),
2374     "Illegal constant pool index %u for method name in class file %s",
2375     name_index, CHECK_NULL);
2376   const Symbol* const name = cp->symbol_at(name_index);
2377   verify_legal_method_name(name, CHECK_NULL);
2378 
2379   const u2 signature_index = cfs->get_u2_fast();
2380   guarantee_property(
2381     valid_symbol_at(signature_index),
2382     "Illegal constant pool index %u for method signature in class file %s",
2383     signature_index, CHECK_NULL);
2384   const Symbol* const signature = cp->symbol_at(signature_index);
2385 
2386   if (name == vmSymbols::class_initializer_name()) {
2387     // We ignore the other access flags for a valid class initializer.
2388     // (JVM Spec 2nd ed., chapter 4.6)
2389     if (_major_version < 51) { // backward compatibility
2390       flags = JVM_ACC_STATIC;
2391     } else if ((flags & JVM_ACC_STATIC) == JVM_ACC_STATIC) {
2392       flags &= JVM_ACC_STATIC | (_major_version <= JAVA_16_VERSION ? JVM_ACC_STRICT : 0);
2393     } else {
2394       classfile_parse_error("Method <clinit> is not static in class file %s", THREAD);
2395       return NULL;
2396     }
2397   } else {
2398     verify_legal_method_modifiers(flags, is_interface, is_inline_type, name, CHECK_NULL);
2399   }
2400 
2401   if (name == vmSymbols::object_initializer_name()) {
2402     if (is_interface) {
2403       classfile_parse_error("Interface cannot have a method named <init>, class file %s", THREAD);
2404       return NULL;
2405     } else if (!is_inline_type && signature->is_void_method_signature()) {
2406       // OK, a constructor
2407     } else if (is_inline_type && !signature->is_void_method_signature()) {
2408       // also OK, a static factory, as long as the return value is good
2409       bool ok = false;
2410       SignatureStream ss((Symbol*) signature, true);
2411       while (!ss.at_return_type())  ss.next();
2412       if (ss.is_reference()) {
2413         Symbol* ret = ss.as_symbol();
2414         const Symbol* required = class_name();
2415         if (is_hidden()) {
2416           // The original class name in hidden classes gets changed.  So using
2417           // the original name in the return type is no longer valid.
2418           // Note that expecting the return type for inline hidden class factory
2419           // methods to be java.lang.Object works around a JVM Spec issue for
2420           // hidden classes.
2421           required = vmSymbols::java_lang_Object();
2422         }
2423         ok = (ret == required);
2424       }
2425       if (!ok) {
2426         throwIllegalSignature("Method", name, signature, CHECK_0);
2427       }
2428     } else {
2429       // not OK, so throw the same error as in verify_legal_method_signature.
2430       throwIllegalSignature("Method", name, signature, CHECK_0);
2431     }
2432     // A declared <init> method must always be either a non-static
2433     // object constructor, with a void return, or else it must be a
2434     // static factory method, with a non-void return.  No other
2435     // definition of <init> is possible.
2436     //
2437     // The verifier (in verify_invoke_instructions) will inspect the
2438     // signature of any attempt to invoke <init>, and ensures that it
2439     // returns non-void if and only if it is being invoked by
2440     // invokestatic, and void if and only if it is being invoked by
2441     // invokespecial.
2442     //
2443     // When a symbolic reference to <init> is resolved for a
2444     // particular invocation mode (special or static), the mode is
2445     // matched to the JVM_ACC_STATIC modifier of the <init> method.
2446     // Thus, it is impossible to statically invoke a constructor, and
2447     // impossible to "new + invokespecial" a static factory, either
2448     // through bytecode or through reflection.
2449   }
2450 
2451   int args_size = -1;  // only used when _need_verify is true
2452   if (_need_verify) {
2453     verify_legal_name_with_signature(name, signature, CHECK_NULL);
2454     args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) +
2455                  verify_legal_method_signature(name, signature, CHECK_NULL);
2456     if (args_size > MAX_ARGS_SIZE) {
2457       classfile_parse_error("Too many arguments in method signature in class file %s", THREAD);
2458       return NULL;
2459     }
2460   }
2461 
2462   AccessFlags access_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS);
2463 
2464   // Default values for code and exceptions attribute elements
2465   u2 max_stack = 0;
2466   u2 max_locals = 0;
2467   u4 code_length = 0;
2468   const u1* code_start = 0;
2469   u2 exception_table_length = 0;
2470   const unsafe_u2* exception_table_start = NULL; // (potentially unaligned) pointer to array of u2 elements
2471   Array<int>* exception_handlers = Universe::the_empty_int_array();
2472   u2 checked_exceptions_length = 0;
2473   const unsafe_u2* checked_exceptions_start = NULL; // (potentially unaligned) pointer to array of u2 elements
2474   CompressedLineNumberWriteStream* linenumber_table = NULL;
2475   int linenumber_table_length = 0;
2476   int total_lvt_length = 0;
2477   u2 lvt_cnt = 0;
2478   u2 lvtt_cnt = 0;
2479   bool lvt_allocated = false;
2480   u2 max_lvt_cnt = INITIAL_MAX_LVT_NUMBER;
2481   u2 max_lvtt_cnt = INITIAL_MAX_LVT_NUMBER;
2482   u2* localvariable_table_length = NULL;
2483   const unsafe_u2** localvariable_table_start = NULL; // (potentially unaligned) pointer to array of LVT attributes
2484   u2* localvariable_type_table_length = NULL;
2485   const unsafe_u2** localvariable_type_table_start = NULL; // (potentially unaligned) pointer to LVTT attributes
2486   int method_parameters_length = -1;
2487   const u1* method_parameters_data = NULL;
2488   bool method_parameters_seen = false;
2489   bool parsed_code_attribute = false;
2490   bool parsed_checked_exceptions_attribute = false;
2491   bool parsed_stackmap_attribute = false;
2492   // stackmap attribute - JDK1.5
2493   const u1* stackmap_data = NULL;
2494   int stackmap_data_length = 0;
2495   u2 generic_signature_index = 0;
2496   MethodAnnotationCollector parsed_annotations;
2497   const u1* runtime_visible_annotations = NULL;
2498   int runtime_visible_annotations_length = 0;
2499   const u1* runtime_invisible_annotations = NULL;
2500   int runtime_invisible_annotations_length = 0;
2501   const u1* runtime_visible_parameter_annotations = NULL;
2502   int runtime_visible_parameter_annotations_length = 0;
2503   const u1* runtime_invisible_parameter_annotations = NULL;
2504   int runtime_invisible_parameter_annotations_length = 0;
2505   const u1* runtime_visible_type_annotations = NULL;
2506   int runtime_visible_type_annotations_length = 0;
2507   const u1* runtime_invisible_type_annotations = NULL;
2508   int runtime_invisible_type_annotations_length = 0;
2509   bool runtime_invisible_annotations_exists = false;
2510   bool runtime_invisible_type_annotations_exists = false;
2511   bool runtime_invisible_parameter_annotations_exists = false;
2512   const u1* annotation_default = NULL;
2513   int annotation_default_length = 0;
2514 
2515   // Parse code and exceptions attribute
2516   u2 method_attributes_count = cfs->get_u2_fast();
2517   while (method_attributes_count--) {
2518     cfs->guarantee_more(6, CHECK_NULL);  // method_attribute_name_index, method_attribute_length
2519     const u2 method_attribute_name_index = cfs->get_u2_fast();
2520     const u4 method_attribute_length = cfs->get_u4_fast();
2521     check_property(
2522       valid_symbol_at(method_attribute_name_index),
2523       "Invalid method attribute name index %u in class file %s",
2524       method_attribute_name_index, CHECK_NULL);
2525 
2526     const Symbol* const method_attribute_name = cp->symbol_at(method_attribute_name_index);
2527     if (method_attribute_name == vmSymbols::tag_code()) {
2528       // Parse Code attribute
2529       if (_need_verify) {
2530         guarantee_property(
2531             !access_flags.is_native() && !access_flags.is_abstract(),
2532                         "Code attribute in native or abstract methods in class file %s",
2533                          CHECK_NULL);
2534       }
2535       if (parsed_code_attribute) {
2536         classfile_parse_error("Multiple Code attributes in class file %s",
2537                               THREAD);
2538         return NULL;
2539       }
2540       parsed_code_attribute = true;
2541 
2542       // Stack size, locals size, and code size
2543       cfs->guarantee_more(8, CHECK_NULL);
2544       max_stack = cfs->get_u2_fast();
2545       max_locals = cfs->get_u2_fast();
2546       code_length = cfs->get_u4_fast();
2547       if (_need_verify) {
2548         guarantee_property(args_size <= max_locals,
2549                            "Arguments can't fit into locals in class file %s",
2550                            CHECK_NULL);
2551         guarantee_property(code_length > 0 && code_length <= MAX_CODE_SIZE,
2552                            "Invalid method Code length %u in class file %s",
2553                            code_length, CHECK_NULL);
2554       }
2555       // Code pointer
2556       code_start = cfs->current();
2557       assert(code_start != NULL, "null code start");
2558       cfs->guarantee_more(code_length, CHECK_NULL);
2559       cfs->skip_u1_fast(code_length);
2560 
2561       // Exception handler table
2562       cfs->guarantee_more(2, CHECK_NULL);  // exception_table_length
2563       exception_table_length = cfs->get_u2_fast();
2564       if (exception_table_length > 0) {
2565         exception_table_start = parse_exception_table(cfs,
2566                                                       code_length,
2567                                                       exception_table_length,
2568                                                       CHECK_NULL);
2569       }
2570 
2571       // Parse additional attributes in code attribute
2572       cfs->guarantee_more(2, CHECK_NULL);  // code_attributes_count
2573       u2 code_attributes_count = cfs->get_u2_fast();
2574 
2575       unsigned int calculated_attribute_length = 0;
2576 
2577       calculated_attribute_length =
2578           sizeof(max_stack) + sizeof(max_locals) + sizeof(code_length);
2579       calculated_attribute_length +=
2580         code_length +
2581         sizeof(exception_table_length) +
2582         sizeof(code_attributes_count) +
2583         exception_table_length *
2584             ( sizeof(u2) +   // start_pc
2585               sizeof(u2) +   // end_pc
2586               sizeof(u2) +   // handler_pc
2587               sizeof(u2) );  // catch_type_index
2588 
2589       while (code_attributes_count--) {
2590         cfs->guarantee_more(6, CHECK_NULL);  // code_attribute_name_index, code_attribute_length
2591         const u2 code_attribute_name_index = cfs->get_u2_fast();
2592         const u4 code_attribute_length = cfs->get_u4_fast();
2593         calculated_attribute_length += code_attribute_length +
2594                                        sizeof(code_attribute_name_index) +
2595                                        sizeof(code_attribute_length);
2596         check_property(valid_symbol_at(code_attribute_name_index),
2597                        "Invalid code attribute name index %u in class file %s",
2598                        code_attribute_name_index,
2599                        CHECK_NULL);
2600         if (LoadLineNumberTables &&
2601             cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_line_number_table()) {
2602           // Parse and compress line number table
2603           parse_linenumber_table(code_attribute_length,
2604                                  code_length,
2605                                  &linenumber_table,
2606                                  CHECK_NULL);
2607 
2608         } else if (LoadLocalVariableTables &&
2609                    cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_table()) {
2610           // Parse local variable table
2611           if (!lvt_allocated) {
2612             localvariable_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2613               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
2614             localvariable_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2615               THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER);
2616             localvariable_type_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2617               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
2618             localvariable_type_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2619               THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER);
2620             lvt_allocated = true;
2621           }
2622           if (lvt_cnt == max_lvt_cnt) {
2623             max_lvt_cnt <<= 1;
2624             localvariable_table_length = REALLOC_RESOURCE_ARRAY(u2, localvariable_table_length, lvt_cnt, max_lvt_cnt);
2625             localvariable_table_start  = REALLOC_RESOURCE_ARRAY(const unsafe_u2*, localvariable_table_start, lvt_cnt, max_lvt_cnt);
2626           }
2627           localvariable_table_start[lvt_cnt] =
2628             parse_localvariable_table(cfs,
2629                                       code_length,
2630                                       max_locals,
2631                                       code_attribute_length,
2632                                       &localvariable_table_length[lvt_cnt],
2633                                       false,    // is not LVTT
2634                                       CHECK_NULL);
2635           total_lvt_length += localvariable_table_length[lvt_cnt];
2636           lvt_cnt++;
2637         } else if (LoadLocalVariableTypeTables &&
2638                    _major_version >= JAVA_1_5_VERSION &&
2639                    cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_type_table()) {
2640           if (!lvt_allocated) {
2641             localvariable_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2642               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
2643             localvariable_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2644               THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER);
2645             localvariable_type_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2646               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
2647             localvariable_type_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2648               THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER);
2649             lvt_allocated = true;
2650           }
2651           // Parse local variable type table
2652           if (lvtt_cnt == max_lvtt_cnt) {
2653             max_lvtt_cnt <<= 1;
2654             localvariable_type_table_length = REALLOC_RESOURCE_ARRAY(u2, localvariable_type_table_length, lvtt_cnt, max_lvtt_cnt);
2655             localvariable_type_table_start  = REALLOC_RESOURCE_ARRAY(const unsafe_u2*, localvariable_type_table_start, lvtt_cnt, max_lvtt_cnt);
2656           }
2657           localvariable_type_table_start[lvtt_cnt] =
2658             parse_localvariable_table(cfs,
2659                                       code_length,
2660                                       max_locals,
2661                                       code_attribute_length,
2662                                       &localvariable_type_table_length[lvtt_cnt],
2663                                       true,     // is LVTT
2664                                       CHECK_NULL);
2665           lvtt_cnt++;
2666         } else if (_major_version >= Verifier::STACKMAP_ATTRIBUTE_MAJOR_VERSION &&
2667                    cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_stack_map_table()) {
2668           // Stack map is only needed by the new verifier in JDK1.5.
2669           if (parsed_stackmap_attribute) {
2670             classfile_parse_error("Multiple StackMapTable attributes in class file %s", THREAD);
2671             return NULL;
2672           }
2673           stackmap_data = parse_stackmap_table(cfs, code_attribute_length, _need_verify, CHECK_NULL);
2674           stackmap_data_length = code_attribute_length;
2675           parsed_stackmap_attribute = true;
2676         } else {
2677           // Skip unknown attributes
2678           cfs->skip_u1(code_attribute_length, CHECK_NULL);
2679         }
2680       }
2681       // check method attribute length
2682       if (_need_verify) {
2683         guarantee_property(method_attribute_length == calculated_attribute_length,
2684                            "Code segment has wrong length in class file %s",
2685                            CHECK_NULL);
2686       }
2687     } else if (method_attribute_name == vmSymbols::tag_exceptions()) {
2688       // Parse Exceptions attribute
2689       if (parsed_checked_exceptions_attribute) {
2690         classfile_parse_error("Multiple Exceptions attributes in class file %s",
2691                               THREAD);
2692         return NULL;
2693       }
2694       parsed_checked_exceptions_attribute = true;
2695       checked_exceptions_start =
2696             parse_checked_exceptions(cfs,
2697                                      &checked_exceptions_length,
2698                                      method_attribute_length,
2699                                      CHECK_NULL);
2700     } else if (method_attribute_name == vmSymbols::tag_method_parameters()) {
2701       // reject multiple method parameters
2702       if (method_parameters_seen) {
2703         classfile_parse_error("Multiple MethodParameters attributes in class file %s",
2704                               THREAD);
2705         return NULL;
2706       }
2707       method_parameters_seen = true;
2708       method_parameters_length = cfs->get_u1_fast();
2709       const u2 real_length = (method_parameters_length * 4u) + 1u;
2710       if (method_attribute_length != real_length) {
2711         classfile_parse_error(
2712           "Invalid MethodParameters method attribute length %u in class file",
2713           method_attribute_length, THREAD);
2714         return NULL;
2715       }
2716       method_parameters_data = cfs->current();
2717       cfs->skip_u2_fast(method_parameters_length);
2718       cfs->skip_u2_fast(method_parameters_length);
2719       // ignore this attribute if it cannot be reflected
2720       if (!vmClasses::Parameter_klass_loaded())
2721         method_parameters_length = -1;
2722     } else if (method_attribute_name == vmSymbols::tag_synthetic()) {
2723       if (method_attribute_length != 0) {
2724         classfile_parse_error(
2725           "Invalid Synthetic method attribute length %u in class file %s",
2726           method_attribute_length, THREAD);
2727         return NULL;
2728       }
2729       // Should we check that there hasn't already been a synthetic attribute?
2730       access_flags.set_is_synthetic();
2731     } else if (method_attribute_name == vmSymbols::tag_deprecated()) { // 4276120
2732       if (method_attribute_length != 0) {
2733         classfile_parse_error(
2734           "Invalid Deprecated method attribute length %u in class file %s",
2735           method_attribute_length, THREAD);
2736         return NULL;
2737       }
2738     } else if (_major_version >= JAVA_1_5_VERSION) {
2739       if (method_attribute_name == vmSymbols::tag_signature()) {
2740         if (generic_signature_index != 0) {
2741           classfile_parse_error(
2742             "Multiple Signature attributes for method in class file %s",
2743             THREAD);
2744           return NULL;
2745         }
2746         if (method_attribute_length != 2) {
2747           classfile_parse_error(
2748             "Invalid Signature attribute length %u in class file %s",
2749             method_attribute_length, THREAD);
2750           return NULL;
2751         }
2752         generic_signature_index = parse_generic_signature_attribute(cfs, CHECK_NULL);
2753       } else if (method_attribute_name == vmSymbols::tag_runtime_visible_annotations()) {
2754         if (runtime_visible_annotations != NULL) {
2755           classfile_parse_error(
2756             "Multiple RuntimeVisibleAnnotations attributes for method in class file %s",
2757             THREAD);
2758           return NULL;
2759         }
2760         runtime_visible_annotations_length = method_attribute_length;
2761         runtime_visible_annotations = cfs->current();
2762         assert(runtime_visible_annotations != NULL, "null visible annotations");
2763         cfs->guarantee_more(runtime_visible_annotations_length, CHECK_NULL);
2764         parse_annotations(cp,
2765                           runtime_visible_annotations,
2766                           runtime_visible_annotations_length,
2767                           &parsed_annotations,
2768                           _loader_data,
2769                           _can_access_vm_annotations);
2770         cfs->skip_u1_fast(runtime_visible_annotations_length);
2771       } else if (method_attribute_name == vmSymbols::tag_runtime_invisible_annotations()) {
2772         if (runtime_invisible_annotations_exists) {
2773           classfile_parse_error(
2774             "Multiple RuntimeInvisibleAnnotations attributes for method in class file %s",
2775             THREAD);
2776           return NULL;
2777         }
2778         runtime_invisible_annotations_exists = true;
2779         if (PreserveAllAnnotations) {
2780           runtime_invisible_annotations_length = method_attribute_length;
2781           runtime_invisible_annotations = cfs->current();
2782           assert(runtime_invisible_annotations != NULL, "null invisible annotations");
2783         }
2784         cfs->skip_u1(method_attribute_length, CHECK_NULL);
2785       } else if (method_attribute_name == vmSymbols::tag_runtime_visible_parameter_annotations()) {
2786         if (runtime_visible_parameter_annotations != NULL) {
2787           classfile_parse_error(
2788             "Multiple RuntimeVisibleParameterAnnotations attributes for method in class file %s",
2789             THREAD);
2790           return NULL;
2791         }
2792         runtime_visible_parameter_annotations_length = method_attribute_length;
2793         runtime_visible_parameter_annotations = cfs->current();
2794         assert(runtime_visible_parameter_annotations != NULL, "null visible parameter annotations");
2795         cfs->skip_u1(runtime_visible_parameter_annotations_length, CHECK_NULL);
2796       } else if (method_attribute_name == vmSymbols::tag_runtime_invisible_parameter_annotations()) {
2797         if (runtime_invisible_parameter_annotations_exists) {
2798           classfile_parse_error(
2799             "Multiple RuntimeInvisibleParameterAnnotations attributes for method in class file %s",
2800             THREAD);
2801           return NULL;
2802         }
2803         runtime_invisible_parameter_annotations_exists = true;
2804         if (PreserveAllAnnotations) {
2805           runtime_invisible_parameter_annotations_length = method_attribute_length;
2806           runtime_invisible_parameter_annotations = cfs->current();
2807           assert(runtime_invisible_parameter_annotations != NULL,
2808             "null invisible parameter annotations");
2809         }
2810         cfs->skip_u1(method_attribute_length, CHECK_NULL);
2811       } else if (method_attribute_name == vmSymbols::tag_annotation_default()) {
2812         if (annotation_default != NULL) {
2813           classfile_parse_error(
2814             "Multiple AnnotationDefault attributes for method in class file %s",
2815             THREAD);
2816           return NULL;
2817         }
2818         annotation_default_length = method_attribute_length;
2819         annotation_default = cfs->current();
2820         assert(annotation_default != NULL, "null annotation default");
2821         cfs->skip_u1(annotation_default_length, CHECK_NULL);
2822       } else if (method_attribute_name == vmSymbols::tag_runtime_visible_type_annotations()) {
2823         if (runtime_visible_type_annotations != NULL) {
2824           classfile_parse_error(
2825             "Multiple RuntimeVisibleTypeAnnotations attributes for method in class file %s",
2826             THREAD);
2827           return NULL;
2828         }
2829         runtime_visible_type_annotations_length = method_attribute_length;
2830         runtime_visible_type_annotations = cfs->current();
2831         assert(runtime_visible_type_annotations != NULL, "null visible type annotations");
2832         // No need for the VM to parse Type annotations
2833         cfs->skip_u1(runtime_visible_type_annotations_length, CHECK_NULL);
2834       } else if (method_attribute_name == vmSymbols::tag_runtime_invisible_type_annotations()) {
2835         if (runtime_invisible_type_annotations_exists) {
2836           classfile_parse_error(
2837             "Multiple RuntimeInvisibleTypeAnnotations attributes for method in class file %s",
2838             THREAD);
2839           return NULL;
2840         } else {
2841           runtime_invisible_type_annotations_exists = true;
2842         }
2843         if (PreserveAllAnnotations) {
2844           runtime_invisible_type_annotations_length = method_attribute_length;
2845           runtime_invisible_type_annotations = cfs->current();
2846           assert(runtime_invisible_type_annotations != NULL, "null invisible type annotations");
2847         }
2848         cfs->skip_u1(method_attribute_length, CHECK_NULL);
2849       } else {
2850         // Skip unknown attributes
2851         cfs->skip_u1(method_attribute_length, CHECK_NULL);
2852       }
2853     } else {
2854       // Skip unknown attributes
2855       cfs->skip_u1(method_attribute_length, CHECK_NULL);
2856     }
2857   }
2858 
2859   if (linenumber_table != NULL) {
2860     linenumber_table->write_terminator();
2861     linenumber_table_length = linenumber_table->position();
2862   }
2863 
2864   // Make sure there's at least one Code attribute in non-native/non-abstract method
2865   if (_need_verify) {
2866     guarantee_property(access_flags.is_native() ||
2867                        access_flags.is_abstract() ||
2868                        parsed_code_attribute,
2869                        "Absent Code attribute in method that is not native or abstract in class file %s",
2870                        CHECK_NULL);
2871   }
2872 
2873   // All sizing information for a Method* is finally available, now create it
2874   InlineTableSizes sizes(
2875       total_lvt_length,
2876       linenumber_table_length,
2877       exception_table_length,
2878       checked_exceptions_length,
2879       method_parameters_length,
2880       generic_signature_index,
2881       runtime_visible_annotations_length +
2882            runtime_invisible_annotations_length,
2883       runtime_visible_parameter_annotations_length +
2884            runtime_invisible_parameter_annotations_length,
2885       runtime_visible_type_annotations_length +
2886            runtime_invisible_type_annotations_length,
2887       annotation_default_length,
2888       0);
2889 
2890   Method* const m = Method::allocate(_loader_data,
2891                                      code_length,
2892                                      access_flags,
2893                                      &sizes,
2894                                      ConstMethod::NORMAL,
2895                                      CHECK_NULL);
2896 
2897   ClassLoadingService::add_class_method_size(m->size()*wordSize);
2898 
2899   // Fill in information from fixed part (access_flags already set)
2900   m->set_constants(_cp);
2901   m->set_name_index(name_index);
2902   m->set_signature_index(signature_index);
2903   m->compute_from_signature(cp->symbol_at(signature_index));
2904   assert(args_size < 0 || args_size == m->size_of_parameters(), "");
2905 
2906   // Fill in code attribute information
2907   m->set_max_stack(max_stack);
2908   m->set_max_locals(max_locals);
2909   if (stackmap_data != NULL) {
2910     m->constMethod()->copy_stackmap_data(_loader_data,
2911                                          (u1*)stackmap_data,
2912                                          stackmap_data_length,
2913                                          CHECK_NULL);
2914   }
2915 
2916   // Copy byte codes
2917   m->set_code((u1*)code_start);
2918 
2919   // Copy line number table
2920   if (linenumber_table != NULL) {
2921     memcpy(m->compressed_linenumber_table(),
2922            linenumber_table->buffer(),
2923            linenumber_table_length);
2924   }
2925 
2926   // Copy exception table
2927   if (exception_table_length > 0) {
2928     Copy::conjoint_swap_if_needed<Endian::JAVA>(exception_table_start,
2929                                                 m->exception_table_start(),
2930                                                 exception_table_length * sizeof(ExceptionTableElement),
2931                                                 sizeof(u2));
2932   }
2933 
2934   // Copy method parameters
2935   if (method_parameters_length > 0) {
2936     MethodParametersElement* elem = m->constMethod()->method_parameters_start();
2937     for (int i = 0; i < method_parameters_length; i++) {
2938       elem[i].name_cp_index = Bytes::get_Java_u2((address)method_parameters_data);
2939       method_parameters_data += 2;
2940       elem[i].flags = Bytes::get_Java_u2((address)method_parameters_data);
2941       method_parameters_data += 2;
2942     }
2943   }
2944 
2945   // Copy checked exceptions
2946   if (checked_exceptions_length > 0) {
2947     Copy::conjoint_swap_if_needed<Endian::JAVA>(checked_exceptions_start,
2948                                                 m->checked_exceptions_start(),
2949                                                 checked_exceptions_length * sizeof(CheckedExceptionElement),
2950                                                 sizeof(u2));
2951   }
2952 
2953   // Copy class file LVT's/LVTT's into the HotSpot internal LVT.
2954   if (total_lvt_length > 0) {
2955     promoted_flags->set_has_localvariable_table();
2956     copy_localvariable_table(m->constMethod(),
2957                              lvt_cnt,
2958                              localvariable_table_length,
2959                              localvariable_table_start,
2960                              lvtt_cnt,
2961                              localvariable_type_table_length,
2962                              localvariable_type_table_start,
2963                              CHECK_NULL);
2964   }
2965 
2966   if (parsed_annotations.has_any_annotations())
2967     parsed_annotations.apply_to(methodHandle(THREAD, m));
2968 
2969   if (is_hidden()) { // Mark methods in hidden classes as 'hidden'.
2970     m->set_hidden(true);
2971   }
2972 
2973   // Copy annotations
2974   copy_method_annotations(m->constMethod(),
2975                           runtime_visible_annotations,
2976                           runtime_visible_annotations_length,
2977                           runtime_invisible_annotations,
2978                           runtime_invisible_annotations_length,
2979                           runtime_visible_parameter_annotations,
2980                           runtime_visible_parameter_annotations_length,
2981                           runtime_invisible_parameter_annotations,
2982                           runtime_invisible_parameter_annotations_length,
2983                           runtime_visible_type_annotations,
2984                           runtime_visible_type_annotations_length,
2985                           runtime_invisible_type_annotations,
2986                           runtime_invisible_type_annotations_length,
2987                           annotation_default,
2988                           annotation_default_length,
2989                           CHECK_NULL);
2990 
2991   if (name == vmSymbols::finalize_method_name() &&
2992       signature == vmSymbols::void_method_signature()) {
2993     if (m->is_empty_method()) {
2994       _has_empty_finalizer = true;
2995     } else {
2996       _has_finalizer = true;
2997     }
2998   }
2999   if (name == vmSymbols::object_initializer_name() &&
3000       signature == vmSymbols::void_method_signature() &&
3001       m->is_vanilla_constructor()) {
3002     _has_vanilla_constructor = true;
3003   }
3004 
3005   NOT_PRODUCT(m->verify());
3006   return m;
3007 }
3008 
3009 
3010 // The promoted_flags parameter is used to pass relevant access_flags
3011 // from the methods back up to the containing klass. These flag values
3012 // are added to klass's access_flags.
3013 // Side-effects: populates the _methods field in the parser
3014 void ClassFileParser::parse_methods(const ClassFileStream* const cfs,
3015                                     bool is_interface,
3016                                     bool is_inline_type,
3017                                     AccessFlags* promoted_flags,
3018                                     bool* has_final_method,
3019                                     bool* declares_nonstatic_concrete_methods,
3020                                     TRAPS) {
3021   assert(cfs != NULL, "invariant");
3022   assert(promoted_flags != NULL, "invariant");
3023   assert(has_final_method != NULL, "invariant");
3024   assert(declares_nonstatic_concrete_methods != NULL, "invariant");
3025 
3026   assert(NULL == _methods, "invariant");
3027 
3028   cfs->guarantee_more(2, CHECK);  // length
3029   const u2 length = cfs->get_u2_fast();
3030   if (length == 0) {
3031     _methods = Universe::the_empty_method_array();
3032   } else {
3033     _methods = MetadataFactory::new_array<Method*>(_loader_data,
3034                                                    length,
3035                                                    NULL,
3036                                                    CHECK);
3037 
3038     for (int index = 0; index < length; index++) {
3039       Method* method = parse_method(cfs,
3040                                     is_interface,
3041                                     is_inline_type,
3042                                     _cp,
3043                                     promoted_flags,
3044                                     CHECK);
3045 
3046       if (method->is_final()) {
3047         *has_final_method = true;
3048       }
3049       // declares_nonstatic_concrete_methods: declares concrete instance methods, any access flags
3050       // used for interface initialization, and default method inheritance analysis
3051       if (is_interface && !(*declares_nonstatic_concrete_methods)
3052         && !method->is_abstract() && !method->is_static()) {
3053         *declares_nonstatic_concrete_methods = true;
3054       }
3055       _methods->at_put(index, method);
3056     }
3057 
3058     if (_need_verify && length > 1) {
3059       // Check duplicated methods
3060       ResourceMark rm(THREAD);
3061       NameSigHash** names_and_sigs = NEW_RESOURCE_ARRAY_IN_THREAD(
3062         THREAD, NameSigHash*, HASH_ROW_SIZE);
3063       initialize_hashtable(names_and_sigs);
3064       bool dup = false;
3065       const Symbol* name = NULL;
3066       const Symbol* sig = NULL;
3067       {
3068         debug_only(NoSafepointVerifier nsv;)
3069         for (int i = 0; i < length; i++) {
3070           const Method* const m = _methods->at(i);
3071           name = m->name();
3072           sig = m->signature();
3073           // If no duplicates, add name/signature in hashtable names_and_sigs.
3074           if (!put_after_lookup(name, sig, names_and_sigs)) {
3075             dup = true;
3076             break;
3077           }
3078         }
3079       }
3080       if (dup) {
3081         classfile_parse_error("Duplicate method name \"%s\" with signature \"%s\" in class file %s",
3082                                name->as_C_string(), sig->as_klass_external_name(), THREAD);
3083       }
3084     }
3085   }
3086 }
3087 
3088 static const intArray* sort_methods(Array<Method*>* methods) {
3089   const int length = methods->length();
3090   // If JVMTI original method ordering or sharing is enabled we have to
3091   // remember the original class file ordering.
3092   // We temporarily use the vtable_index field in the Method* to store the
3093   // class file index, so we can read in after calling qsort.
3094   // Put the method ordering in the shared archive.
3095   if (JvmtiExport::can_maintain_original_method_order() || Arguments::is_dumping_archive()) {
3096     for (int index = 0; index < length; index++) {
3097       Method* const m = methods->at(index);
3098       assert(!m->valid_vtable_index(), "vtable index should not be set");
3099       m->set_vtable_index(index);
3100     }
3101   }
3102   // Sort method array by ascending method name (for faster lookups & vtable construction)
3103   // Note that the ordering is not alphabetical, see Symbol::fast_compare
3104   Method::sort_methods(methods);
3105 
3106   intArray* method_ordering = NULL;
3107   // If JVMTI original method ordering or sharing is enabled construct int
3108   // array remembering the original ordering
3109   if (JvmtiExport::can_maintain_original_method_order() || Arguments::is_dumping_archive()) {
3110     method_ordering = new intArray(length, length, -1);
3111     for (int index = 0; index < length; index++) {
3112       Method* const m = methods->at(index);
3113       const int old_index = m->vtable_index();
3114       assert(old_index >= 0 && old_index < length, "invalid method index");
3115       method_ordering->at_put(index, old_index);
3116       m->set_vtable_index(Method::invalid_vtable_index);
3117     }
3118   }
3119   return method_ordering;
3120 }
3121 
3122 // Parse generic_signature attribute for methods and fields
3123 u2 ClassFileParser::parse_generic_signature_attribute(const ClassFileStream* const cfs,
3124                                                       TRAPS) {
3125   assert(cfs != NULL, "invariant");
3126 
3127   cfs->guarantee_more(2, CHECK_0);  // generic_signature_index
3128   const u2 generic_signature_index = cfs->get_u2_fast();
3129   check_property(
3130     valid_symbol_at(generic_signature_index),
3131     "Invalid Signature attribute at constant pool index %u in class file %s",
3132     generic_signature_index, CHECK_0);
3133   return generic_signature_index;
3134 }
3135 
3136 void ClassFileParser::parse_classfile_sourcefile_attribute(const ClassFileStream* const cfs,
3137                                                            TRAPS) {
3138 
3139   assert(cfs != NULL, "invariant");
3140 
3141   cfs->guarantee_more(2, CHECK);  // sourcefile_index
3142   const u2 sourcefile_index = cfs->get_u2_fast();
3143   check_property(
3144     valid_symbol_at(sourcefile_index),
3145     "Invalid SourceFile attribute at constant pool index %u in class file %s",
3146     sourcefile_index, CHECK);
3147   set_class_sourcefile_index(sourcefile_index);
3148 }
3149 
3150 void ClassFileParser::parse_classfile_source_debug_extension_attribute(const ClassFileStream* const cfs,
3151                                                                        int length,
3152                                                                        TRAPS) {
3153   assert(cfs != NULL, "invariant");
3154 
3155   const u1* const sde_buffer = cfs->current();
3156   assert(sde_buffer != NULL, "null sde buffer");
3157 
3158   // Don't bother storing it if there is no way to retrieve it
3159   if (JvmtiExport::can_get_source_debug_extension()) {
3160     assert((length+1) > length, "Overflow checking");
3161     u1* const sde = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, u1, length+1);
3162     for (int i = 0; i < length; i++) {
3163       sde[i] = sde_buffer[i];
3164     }
3165     sde[length] = '\0';
3166     set_class_sde_buffer((const char*)sde, length);
3167   }
3168   // Got utf8 string, set stream position forward
3169   cfs->skip_u1(length, CHECK);
3170 }
3171 
3172 
3173 // Inner classes can be static, private or protected (classic VM does this)
3174 #define RECOGNIZED_INNER_CLASS_MODIFIERS ( JVM_RECOGNIZED_CLASS_MODIFIERS | \
3175                                            JVM_ACC_PRIVATE |                \
3176                                            JVM_ACC_PROTECTED |              \
3177                                            JVM_ACC_STATIC                   \
3178                                          )
3179 
3180 // Find index of the InnerClasses entry for the specified inner_class_info_index.
3181 // Return -1 if none is found.
3182 static int inner_classes_find_index(const Array<u2>* inner_classes, int inner, const ConstantPool* cp, int length) {
3183   Symbol* cp_klass_name =  cp->klass_name_at(inner);
3184   for (int idx = 0; idx < length; idx += InstanceKlass::inner_class_next_offset) {
3185     int idx_inner = inner_classes->at(idx + InstanceKlass::inner_class_inner_class_info_offset);
3186     if (cp->klass_name_at(idx_inner) == cp_klass_name) {
3187       return idx;
3188     }
3189   }
3190   return -1;
3191 }
3192 
3193 // Return the outer_class_info_index for the InnerClasses entry containing the
3194 // specified inner_class_info_index.  Return -1 if no InnerClasses entry is found.
3195 static int inner_classes_jump_to_outer(const Array<u2>* inner_classes, int inner, const ConstantPool* cp, int length) {
3196   if (inner == 0) return -1;
3197   int idx = inner_classes_find_index(inner_classes, inner, cp, length);
3198   if (idx == -1) return -1;
3199   int result = inner_classes->at(idx + InstanceKlass::inner_class_outer_class_info_offset);
3200   return result;
3201 }
3202 
3203 // Return true if circularity is found, false if no circularity is found.
3204 // Use Floyd's cycle finding algorithm.
3205 static bool inner_classes_check_loop_through_outer(const Array<u2>* inner_classes, int idx, const ConstantPool* cp, int length) {
3206   int slow = inner_classes->at(idx + InstanceKlass::inner_class_inner_class_info_offset);
3207   int fast = inner_classes->at(idx + InstanceKlass::inner_class_outer_class_info_offset);
3208   while (fast != -1 && fast != 0) {
3209     if (slow != 0 && (cp->klass_name_at(slow) == cp->klass_name_at(fast))) {
3210       return true;  // found a circularity
3211     }
3212     fast = inner_classes_jump_to_outer(inner_classes, fast, cp, length);
3213     if (fast == -1) return false;
3214     fast = inner_classes_jump_to_outer(inner_classes, fast, cp, length);
3215     if (fast == -1) return false;
3216     slow = inner_classes_jump_to_outer(inner_classes, slow, cp, length);
3217     assert(slow != -1, "sanity check");
3218   }
3219   return false;
3220 }
3221 
3222 // Loop through each InnerClasses entry checking for circularities and duplications
3223 // with other entries.  If duplicate entries are found then throw CFE.  Otherwise,
3224 // return true if a circularity or entries with duplicate inner_class_info_indexes
3225 // are found.
3226 bool ClassFileParser::check_inner_classes_circularity(const ConstantPool* cp, int length, TRAPS) {
3227   // Loop through each InnerClasses entry.
3228   for (int idx = 0; idx < length; idx += InstanceKlass::inner_class_next_offset) {
3229     // Return true if there are circular entries.
3230     if (inner_classes_check_loop_through_outer(_inner_classes, idx, cp, length)) {
3231       return true;
3232     }
3233     // Check if there are duplicate entries or entries with the same inner_class_info_index.
3234     for (int y = idx + InstanceKlass::inner_class_next_offset; y < length;
3235          y += InstanceKlass::inner_class_next_offset) {
3236 
3237       // To maintain compatibility, throw an exception if duplicate inner classes
3238       // entries are found.
3239       guarantee_property((_inner_classes->at(idx) != _inner_classes->at(y) ||
3240                           _inner_classes->at(idx+1) != _inner_classes->at(y+1) ||
3241                           _inner_classes->at(idx+2) != _inner_classes->at(y+2) ||
3242                           _inner_classes->at(idx+3) != _inner_classes->at(y+3)),
3243                          "Duplicate entry in InnerClasses attribute in class file %s",
3244                          CHECK_(true));
3245       // Return true if there are two entries with the same inner_class_info_index.
3246       if (_inner_classes->at(y) == _inner_classes->at(idx)) {
3247         return true;
3248       }
3249     }
3250   }
3251   return false;
3252 }
3253 
3254 // Return number of classes in the inner classes attribute table
3255 u2 ClassFileParser::parse_classfile_inner_classes_attribute(const ClassFileStream* const cfs,
3256                                                             const ConstantPool* cp,
3257                                                             const u1* const inner_classes_attribute_start,
3258                                                             bool parsed_enclosingmethod_attribute,
3259                                                             u2 enclosing_method_class_index,
3260                                                             u2 enclosing_method_method_index,
3261                                                             TRAPS) {
3262   const u1* const current_mark = cfs->current();
3263   u2 length = 0;
3264   if (inner_classes_attribute_start != NULL) {
3265     cfs->set_current(inner_classes_attribute_start);
3266     cfs->guarantee_more(2, CHECK_0);  // length
3267     length = cfs->get_u2_fast();
3268   }
3269 
3270   // 4-tuples of shorts of inner classes data and 2 shorts of enclosing
3271   // method data:
3272   //   [inner_class_info_index,
3273   //    outer_class_info_index,
3274   //    inner_name_index,
3275   //    inner_class_access_flags,
3276   //    ...
3277   //    enclosing_method_class_index,
3278   //    enclosing_method_method_index]
3279   const int size = length * 4 + (parsed_enclosingmethod_attribute ? 2 : 0);
3280   Array<u2>* inner_classes = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
3281   _inner_classes = inner_classes;
3282 
3283   int index = 0;
3284   cfs->guarantee_more(8 * length, CHECK_0);  // 4-tuples of u2
3285   for (int n = 0; n < length; n++) {
3286     // Inner class index
3287     const u2 inner_class_info_index = cfs->get_u2_fast();
3288     check_property(
3289       valid_klass_reference_at(inner_class_info_index),
3290       "inner_class_info_index %u has bad constant type in class file %s",
3291       inner_class_info_index, CHECK_0);
3292     // Outer class index
3293     const u2 outer_class_info_index = cfs->get_u2_fast();
3294     check_property(
3295       outer_class_info_index == 0 ||
3296         valid_klass_reference_at(outer_class_info_index),
3297       "outer_class_info_index %u has bad constant type in class file %s",
3298       outer_class_info_index, CHECK_0);
3299     // Inner class name
3300     const u2 inner_name_index = cfs->get_u2_fast();
3301     check_property(
3302       inner_name_index == 0 || valid_symbol_at(inner_name_index),
3303       "inner_name_index %u has bad constant type in class file %s",
3304       inner_name_index, CHECK_0);
3305     if (_need_verify) {
3306       guarantee_property(inner_class_info_index != outer_class_info_index,
3307                          "Class is both outer and inner class in class file %s", CHECK_0);
3308     }
3309 
3310     jint recognized_modifiers = RECOGNIZED_INNER_CLASS_MODIFIERS;
3311     // JVM_ACC_MODULE is defined in JDK-9 and later.
3312     if (_major_version >= JAVA_9_VERSION) {
3313       recognized_modifiers |= JVM_ACC_MODULE;
3314     }
3315     // JVM_ACC_INLINE is defined for class file version 55 and later
3316     if (supports_inline_types()) {
3317       recognized_modifiers |= JVM_ACC_INLINE;
3318     }
3319 
3320     // Access flags
3321     jint flags = cfs->get_u2_fast() & recognized_modifiers;
3322 
3323     if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
3324       // Set abstract bit for old class files for backward compatibility
3325       flags |= JVM_ACC_ABSTRACT;
3326     }
3327     verify_legal_class_modifiers(flags, CHECK_0);
3328     AccessFlags inner_access_flags(flags);
3329 
3330     inner_classes->at_put(index++, inner_class_info_index);
3331     inner_classes->at_put(index++, outer_class_info_index);
3332     inner_classes->at_put(index++, inner_name_index);
3333     inner_classes->at_put(index++, inner_access_flags.as_short());
3334   }
3335 
3336   // 4347400: make sure there's no duplicate entry in the classes array
3337   // Also, check for circular entries.
3338   bool has_circularity = false;
3339   if (_need_verify && _major_version >= JAVA_1_5_VERSION) {
3340     has_circularity = check_inner_classes_circularity(cp, length * 4, CHECK_0);
3341     if (has_circularity) {
3342       // If circularity check failed then ignore InnerClasses attribute.
3343       MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
3344       index = 0;
3345       if (parsed_enclosingmethod_attribute) {
3346         inner_classes = MetadataFactory::new_array<u2>(_loader_data, 2, CHECK_0);
3347         _inner_classes = inner_classes;
3348       } else {
3349         _inner_classes = Universe::the_empty_short_array();
3350       }
3351     }
3352   }
3353   // Set EnclosingMethod class and method indexes.
3354   if (parsed_enclosingmethod_attribute) {
3355     inner_classes->at_put(index++, enclosing_method_class_index);
3356     inner_classes->at_put(index++, enclosing_method_method_index);
3357   }
3358   assert(index == size || has_circularity, "wrong size");
3359 
3360   // Restore buffer's current position.
3361   cfs->set_current(current_mark);
3362 
3363   return length;
3364 }
3365 
3366 u2 ClassFileParser::parse_classfile_nest_members_attribute(const ClassFileStream* const cfs,
3367                                                            const u1* const nest_members_attribute_start,
3368                                                            TRAPS) {
3369   const u1* const current_mark = cfs->current();
3370   u2 length = 0;
3371   if (nest_members_attribute_start != NULL) {
3372     cfs->set_current(nest_members_attribute_start);
3373     cfs->guarantee_more(2, CHECK_0);  // length
3374     length = cfs->get_u2_fast();
3375   }
3376   const int size = length;
3377   Array<u2>* const nest_members = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
3378   _nest_members = nest_members;
3379 
3380   int index = 0;
3381   cfs->guarantee_more(2 * length, CHECK_0);
3382   for (int n = 0; n < length; n++) {
3383     const u2 class_info_index = cfs->get_u2_fast();
3384     check_property(
3385       valid_klass_reference_at(class_info_index),
3386       "Nest member class_info_index %u has bad constant type in class file %s",
3387       class_info_index, CHECK_0);
3388     nest_members->at_put(index++, class_info_index);
3389   }
3390   assert(index == size, "wrong size");
3391 
3392   // Restore buffer's current position.
3393   cfs->set_current(current_mark);
3394 
3395   return length;
3396 }
3397 
3398 u2 ClassFileParser::parse_classfile_permitted_subclasses_attribute(const ClassFileStream* const cfs,
3399                                                                    const u1* const permitted_subclasses_attribute_start,
3400                                                                    TRAPS) {
3401   const u1* const current_mark = cfs->current();
3402   u2 length = 0;
3403   if (permitted_subclasses_attribute_start != NULL) {
3404     cfs->set_current(permitted_subclasses_attribute_start);
3405     cfs->guarantee_more(2, CHECK_0);  // length
3406     length = cfs->get_u2_fast();
3407   }
3408   const int size = length;
3409   Array<u2>* const permitted_subclasses = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
3410   _permitted_subclasses = permitted_subclasses;
3411 
3412   if (length > 0) {
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         "Permitted subclass class_info_index %u has bad constant type in class file %s",
3420         class_info_index, CHECK_0);
3421       permitted_subclasses->at_put(index++, class_info_index);
3422     }
3423     assert(index == size, "wrong size");
3424   }
3425 
3426   // Restore buffer's current position.
3427   cfs->set_current(current_mark);
3428 
3429   return length;
3430 }
3431 
3432 //  Record {
3433 //    u2 attribute_name_index;
3434 //    u4 attribute_length;
3435 //    u2 components_count;
3436 //    component_info components[components_count];
3437 //  }
3438 //  component_info {
3439 //    u2 name_index;
3440 //    u2 descriptor_index
3441 //    u2 attributes_count;
3442 //    attribute_info_attributes[attributes_count];
3443 //  }
3444 u2 ClassFileParser::parse_classfile_record_attribute(const ClassFileStream* const cfs,
3445                                                      const ConstantPool* cp,
3446                                                      const u1* const record_attribute_start,
3447                                                      TRAPS) {
3448   const u1* const current_mark = cfs->current();
3449   int components_count = 0;
3450   unsigned int calculate_attr_size = 0;
3451   if (record_attribute_start != NULL) {
3452     cfs->set_current(record_attribute_start);
3453     cfs->guarantee_more(2, CHECK_0);  // num of components
3454     components_count = (int)cfs->get_u2_fast();
3455     calculate_attr_size = 2;
3456   }
3457 
3458   Array<RecordComponent*>* const record_components =
3459     MetadataFactory::new_array<RecordComponent*>(_loader_data, components_count, NULL, CHECK_0);
3460   _record_components = record_components;
3461 
3462   for (int x = 0; x < components_count; x++) {
3463     cfs->guarantee_more(6, CHECK_0); // name_index, descriptor_index, attributes_count
3464 
3465     const u2 name_index = cfs->get_u2_fast();
3466     check_property(valid_symbol_at(name_index),
3467       "Invalid constant pool index %u for name in Record attribute in class file %s",
3468       name_index, CHECK_0);
3469     const Symbol* const name = cp->symbol_at(name_index);
3470     verify_legal_field_name(name, CHECK_0);
3471 
3472     const u2 descriptor_index = cfs->get_u2_fast();
3473     check_property(valid_symbol_at(descriptor_index),
3474       "Invalid constant pool index %u for descriptor in Record attribute in class file %s",
3475       descriptor_index, CHECK_0);
3476     const Symbol* const descr = cp->symbol_at(descriptor_index);
3477     verify_legal_field_signature(name, descr, CHECK_0);
3478 
3479     const u2 attributes_count = cfs->get_u2_fast();
3480     calculate_attr_size += 6;
3481     u2 generic_sig_index = 0;
3482     const u1* runtime_visible_annotations = NULL;
3483     int runtime_visible_annotations_length = 0;
3484     const u1* runtime_invisible_annotations = NULL;
3485     int runtime_invisible_annotations_length = 0;
3486     bool runtime_invisible_annotations_exists = false;
3487     const u1* runtime_visible_type_annotations = NULL;
3488     int runtime_visible_type_annotations_length = 0;
3489     const u1* runtime_invisible_type_annotations = NULL;
3490     int runtime_invisible_type_annotations_length = 0;
3491     bool runtime_invisible_type_annotations_exists = false;
3492 
3493     // Expected attributes for record components are Signature, Runtime(In)VisibleAnnotations,
3494     // and Runtime(In)VisibleTypeAnnotations.  Other attributes are ignored.
3495     for (int y = 0; y < attributes_count; y++) {
3496       cfs->guarantee_more(6, CHECK_0);  // attribute_name_index, attribute_length
3497       const u2 attribute_name_index = cfs->get_u2_fast();
3498       const u4 attribute_length = cfs->get_u4_fast();
3499       calculate_attr_size += 6;
3500       check_property(
3501         valid_symbol_at(attribute_name_index),
3502         "Invalid Record attribute name index %u in class file %s",
3503         attribute_name_index, CHECK_0);
3504 
3505       const Symbol* const attribute_name = cp->symbol_at(attribute_name_index);
3506       if (attribute_name == vmSymbols::tag_signature()) {
3507         if (generic_sig_index != 0) {
3508           classfile_parse_error(
3509             "Multiple Signature attributes for Record component in class file %s",
3510             THREAD);
3511           return 0;
3512         }
3513         if (attribute_length != 2) {
3514           classfile_parse_error(
3515             "Invalid Signature attribute length %u in Record component in class file %s",
3516             attribute_length, THREAD);
3517           return 0;
3518         }
3519         generic_sig_index = parse_generic_signature_attribute(cfs, CHECK_0);
3520 
3521       } else if (attribute_name == vmSymbols::tag_runtime_visible_annotations()) {
3522         if (runtime_visible_annotations != NULL) {
3523           classfile_parse_error(
3524             "Multiple RuntimeVisibleAnnotations attributes for Record component in class file %s", THREAD);
3525           return 0;
3526         }
3527         runtime_visible_annotations_length = attribute_length;
3528         runtime_visible_annotations = cfs->current();
3529 
3530         assert(runtime_visible_annotations != NULL, "null record component visible annotation");
3531         cfs->guarantee_more(runtime_visible_annotations_length, CHECK_0);
3532         cfs->skip_u1_fast(runtime_visible_annotations_length);
3533 
3534       } else if (attribute_name == vmSymbols::tag_runtime_invisible_annotations()) {
3535         if (runtime_invisible_annotations_exists) {
3536           classfile_parse_error(
3537             "Multiple RuntimeInvisibleAnnotations attributes for Record component in class file %s", THREAD);
3538           return 0;
3539         }
3540         runtime_invisible_annotations_exists = true;
3541         if (PreserveAllAnnotations) {
3542           runtime_invisible_annotations_length = attribute_length;
3543           runtime_invisible_annotations = cfs->current();
3544           assert(runtime_invisible_annotations != NULL, "null record component invisible annotation");
3545         }
3546         cfs->skip_u1(attribute_length, CHECK_0);
3547 
3548       } else if (attribute_name == vmSymbols::tag_runtime_visible_type_annotations()) {
3549         if (runtime_visible_type_annotations != NULL) {
3550           classfile_parse_error(
3551             "Multiple RuntimeVisibleTypeAnnotations attributes for Record component in class file %s", THREAD);
3552           return 0;
3553         }
3554         runtime_visible_type_annotations_length = attribute_length;
3555         runtime_visible_type_annotations = cfs->current();
3556 
3557         assert(runtime_visible_type_annotations != NULL, "null record component visible type annotation");
3558         cfs->guarantee_more(runtime_visible_type_annotations_length, CHECK_0);
3559         cfs->skip_u1_fast(runtime_visible_type_annotations_length);
3560 
3561       } else if (attribute_name == vmSymbols::tag_runtime_invisible_type_annotations()) {
3562         if (runtime_invisible_type_annotations_exists) {
3563           classfile_parse_error(
3564             "Multiple RuntimeInvisibleTypeAnnotations attributes for Record component in class file %s", THREAD);
3565           return 0;
3566         }
3567         runtime_invisible_type_annotations_exists = true;
3568         if (PreserveAllAnnotations) {
3569           runtime_invisible_type_annotations_length = attribute_length;
3570           runtime_invisible_type_annotations = cfs->current();
3571           assert(runtime_invisible_type_annotations != NULL, "null record component invisible type annotation");
3572         }
3573         cfs->skip_u1(attribute_length, CHECK_0);
3574 
3575       } else {
3576         // Skip unknown attributes
3577         cfs->skip_u1(attribute_length, CHECK_0);
3578       }
3579       calculate_attr_size += attribute_length;
3580     } // End of attributes For loop
3581 
3582     AnnotationArray* annotations = assemble_annotations(runtime_visible_annotations,
3583                                                         runtime_visible_annotations_length,
3584                                                         runtime_invisible_annotations,
3585                                                         runtime_invisible_annotations_length,
3586                                                         CHECK_0);
3587     AnnotationArray* type_annotations = assemble_annotations(runtime_visible_type_annotations,
3588                                                              runtime_visible_type_annotations_length,
3589                                                              runtime_invisible_type_annotations,
3590                                                              runtime_invisible_type_annotations_length,
3591                                                              CHECK_0);
3592 
3593     RecordComponent* record_component =
3594       RecordComponent::allocate(_loader_data, name_index, descriptor_index,
3595                                 attributes_count, generic_sig_index,
3596                                 annotations, type_annotations, CHECK_0);
3597     record_components->at_put(x, record_component);
3598   }  // End of component processing loop
3599 
3600   // Restore buffer's current position.
3601   cfs->set_current(current_mark);
3602   return calculate_attr_size;
3603 }
3604 
3605 void ClassFileParser::parse_classfile_synthetic_attribute() {
3606   set_class_synthetic_flag(true);
3607 }
3608 
3609 void ClassFileParser::parse_classfile_signature_attribute(const ClassFileStream* const cfs, TRAPS) {
3610   assert(cfs != NULL, "invariant");
3611 
3612   const u2 signature_index = cfs->get_u2(CHECK);
3613   check_property(
3614     valid_symbol_at(signature_index),
3615     "Invalid constant pool index %u in Signature attribute in class file %s",
3616     signature_index, CHECK);
3617   set_class_generic_signature_index(signature_index);
3618 }
3619 
3620 void ClassFileParser::parse_classfile_bootstrap_methods_attribute(const ClassFileStream* const cfs,
3621                                                                   ConstantPool* cp,
3622                                                                   u4 attribute_byte_length,
3623                                                                   TRAPS) {
3624   assert(cfs != NULL, "invariant");
3625   assert(cp != NULL, "invariant");
3626 
3627   const u1* const current_start = cfs->current();
3628 
3629   guarantee_property(attribute_byte_length >= sizeof(u2),
3630                      "Invalid BootstrapMethods attribute length %u in class file %s",
3631                      attribute_byte_length,
3632                      CHECK);
3633 
3634   cfs->guarantee_more(attribute_byte_length, CHECK);
3635 
3636   const int attribute_array_length = cfs->get_u2_fast();
3637 
3638   guarantee_property(_max_bootstrap_specifier_index < attribute_array_length,
3639                      "Short length on BootstrapMethods in class file %s",
3640                      CHECK);
3641 
3642 
3643   // The attribute contains a counted array of counted tuples of shorts,
3644   // represending bootstrap specifiers:
3645   //    length*{bootstrap_method_index, argument_count*{argument_index}}
3646   const int operand_count = (attribute_byte_length - sizeof(u2)) / sizeof(u2);
3647   // operand_count = number of shorts in attr, except for leading length
3648 
3649   // The attribute is copied into a short[] array.
3650   // The array begins with a series of short[2] pairs, one for each tuple.
3651   const int index_size = (attribute_array_length * 2);
3652 
3653   Array<u2>* const operands =
3654     MetadataFactory::new_array<u2>(_loader_data, index_size + operand_count, CHECK);
3655 
3656   // Eagerly assign operands so they will be deallocated with the constant
3657   // pool if there is an error.
3658   cp->set_operands(operands);
3659 
3660   int operand_fill_index = index_size;
3661   const int cp_size = cp->length();
3662 
3663   for (int n = 0; n < attribute_array_length; n++) {
3664     // Store a 32-bit offset into the header of the operand array.
3665     ConstantPool::operand_offset_at_put(operands, n, operand_fill_index);
3666 
3667     // Read a bootstrap specifier.
3668     cfs->guarantee_more(sizeof(u2) * 2, CHECK);  // bsm, argc
3669     const u2 bootstrap_method_index = cfs->get_u2_fast();
3670     const u2 argument_count = cfs->get_u2_fast();
3671     check_property(
3672       valid_cp_range(bootstrap_method_index, cp_size) &&
3673       cp->tag_at(bootstrap_method_index).is_method_handle(),
3674       "bootstrap_method_index %u has bad constant type in class file %s",
3675       bootstrap_method_index,
3676       CHECK);
3677 
3678     guarantee_property((operand_fill_index + 1 + argument_count) < operands->length(),
3679       "Invalid BootstrapMethods num_bootstrap_methods or num_bootstrap_arguments value in class file %s",
3680       CHECK);
3681 
3682     operands->at_put(operand_fill_index++, bootstrap_method_index);
3683     operands->at_put(operand_fill_index++, argument_count);
3684 
3685     cfs->guarantee_more(sizeof(u2) * argument_count, CHECK);  // argv[argc]
3686     for (int j = 0; j < argument_count; j++) {
3687       const u2 argument_index = cfs->get_u2_fast();
3688       check_property(
3689         valid_cp_range(argument_index, cp_size) &&
3690         cp->tag_at(argument_index).is_loadable_constant(),
3691         "argument_index %u has bad constant type in class file %s",
3692         argument_index,
3693         CHECK);
3694       operands->at_put(operand_fill_index++, argument_index);
3695     }
3696   }
3697   guarantee_property(current_start + attribute_byte_length == cfs->current(),
3698                      "Bad length on BootstrapMethods in class file %s",
3699                      CHECK);
3700 }
3701 
3702 void ClassFileParser::parse_classfile_attributes(const ClassFileStream* const cfs,
3703                                                  ConstantPool* cp,
3704                  ClassFileParser::ClassAnnotationCollector* parsed_annotations,
3705                                                  TRAPS) {
3706   assert(cfs != NULL, "invariant");
3707   assert(cp != NULL, "invariant");
3708   assert(parsed_annotations != NULL, "invariant");
3709 
3710   // Set inner classes attribute to default sentinel
3711   _inner_classes = Universe::the_empty_short_array();
3712   // Set nest members attribute to default sentinel
3713   _nest_members = Universe::the_empty_short_array();
3714   // Set _permitted_subclasses attribute to default sentinel
3715   _permitted_subclasses = Universe::the_empty_short_array();
3716   cfs->guarantee_more(2, CHECK);  // attributes_count
3717   u2 attributes_count = cfs->get_u2_fast();
3718   bool parsed_sourcefile_attribute = false;
3719   bool parsed_innerclasses_attribute = false;
3720   bool parsed_nest_members_attribute = false;
3721   bool parsed_permitted_subclasses_attribute = false;
3722   bool parsed_nest_host_attribute = false;
3723   bool parsed_record_attribute = false;
3724   bool parsed_enclosingmethod_attribute = false;
3725   bool parsed_bootstrap_methods_attribute = false;
3726   const u1* runtime_visible_annotations = NULL;
3727   int runtime_visible_annotations_length = 0;
3728   const u1* runtime_invisible_annotations = NULL;
3729   int runtime_invisible_annotations_length = 0;
3730   const u1* runtime_visible_type_annotations = NULL;
3731   int runtime_visible_type_annotations_length = 0;
3732   const u1* runtime_invisible_type_annotations = NULL;
3733   int runtime_invisible_type_annotations_length = 0;
3734   bool runtime_invisible_type_annotations_exists = false;
3735   bool runtime_invisible_annotations_exists = false;
3736   bool parsed_source_debug_ext_annotations_exist = false;
3737   const u1* inner_classes_attribute_start = NULL;
3738   u4  inner_classes_attribute_length = 0;
3739   u2  enclosing_method_class_index = 0;
3740   u2  enclosing_method_method_index = 0;
3741   const u1* nest_members_attribute_start = NULL;
3742   u4  nest_members_attribute_length = 0;
3743   const u1* record_attribute_start = NULL;
3744   u4  record_attribute_length = 0;
3745   const u1* permitted_subclasses_attribute_start = NULL;
3746   u4  permitted_subclasses_attribute_length = 0;
3747 
3748   // Iterate over attributes
3749   while (attributes_count--) {
3750     cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
3751     const u2 attribute_name_index = cfs->get_u2_fast();
3752     const u4 attribute_length = cfs->get_u4_fast();
3753     check_property(
3754       valid_symbol_at(attribute_name_index),
3755       "Attribute name has bad constant pool index %u in class file %s",
3756       attribute_name_index, CHECK);
3757     const Symbol* const tag = cp->symbol_at(attribute_name_index);
3758     if (tag == vmSymbols::tag_source_file()) {
3759       // Check for SourceFile tag
3760       if (_need_verify) {
3761         guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
3762       }
3763       if (parsed_sourcefile_attribute) {
3764         classfile_parse_error("Multiple SourceFile attributes in class file %s", THREAD);
3765         return;
3766       } else {
3767         parsed_sourcefile_attribute = true;
3768       }
3769       parse_classfile_sourcefile_attribute(cfs, CHECK);
3770     } else if (tag == vmSymbols::tag_source_debug_extension()) {
3771       // Check for SourceDebugExtension tag
3772       if (parsed_source_debug_ext_annotations_exist) {
3773         classfile_parse_error(
3774           "Multiple SourceDebugExtension attributes in class file %s", THREAD);
3775         return;
3776       }
3777       parsed_source_debug_ext_annotations_exist = true;
3778       parse_classfile_source_debug_extension_attribute(cfs, (int)attribute_length, CHECK);
3779     } else if (tag == vmSymbols::tag_inner_classes()) {
3780       // Check for InnerClasses tag
3781       if (parsed_innerclasses_attribute) {
3782         classfile_parse_error("Multiple InnerClasses attributes in class file %s", THREAD);
3783         return;
3784       } else {
3785         parsed_innerclasses_attribute = true;
3786       }
3787       inner_classes_attribute_start = cfs->current();
3788       inner_classes_attribute_length = attribute_length;
3789       cfs->skip_u1(inner_classes_attribute_length, CHECK);
3790     } else if (tag == vmSymbols::tag_synthetic()) {
3791       // Check for Synthetic tag
3792       // Shouldn't we check that the synthetic flags wasn't already set? - not required in spec
3793       if (attribute_length != 0) {
3794         classfile_parse_error(
3795           "Invalid Synthetic classfile attribute length %u in class file %s",
3796           attribute_length, THREAD);
3797         return;
3798       }
3799       parse_classfile_synthetic_attribute();
3800     } else if (tag == vmSymbols::tag_deprecated()) {
3801       // Check for Deprecated tag - 4276120
3802       if (attribute_length != 0) {
3803         classfile_parse_error(
3804           "Invalid Deprecated classfile attribute length %u in class file %s",
3805           attribute_length, THREAD);
3806         return;
3807       }
3808     } else if (_major_version >= JAVA_1_5_VERSION) {
3809       if (tag == vmSymbols::tag_signature()) {
3810         if (_generic_signature_index != 0) {
3811           classfile_parse_error(
3812             "Multiple Signature attributes in class file %s", THREAD);
3813           return;
3814         }
3815         if (attribute_length != 2) {
3816           classfile_parse_error(
3817             "Wrong Signature attribute length %u in class file %s",
3818             attribute_length, THREAD);
3819           return;
3820         }
3821         parse_classfile_signature_attribute(cfs, CHECK);
3822       } else if (tag == vmSymbols::tag_runtime_visible_annotations()) {
3823         if (runtime_visible_annotations != NULL) {
3824           classfile_parse_error(
3825             "Multiple RuntimeVisibleAnnotations attributes in class file %s", THREAD);
3826           return;
3827         }
3828         runtime_visible_annotations_length = attribute_length;
3829         runtime_visible_annotations = cfs->current();
3830         assert(runtime_visible_annotations != NULL, "null visible annotations");
3831         cfs->guarantee_more(runtime_visible_annotations_length, CHECK);
3832         parse_annotations(cp,
3833                           runtime_visible_annotations,
3834                           runtime_visible_annotations_length,
3835                           parsed_annotations,
3836                           _loader_data,
3837                           _can_access_vm_annotations);
3838         cfs->skip_u1_fast(runtime_visible_annotations_length);
3839       } else if (tag == vmSymbols::tag_runtime_invisible_annotations()) {
3840         if (runtime_invisible_annotations_exists) {
3841           classfile_parse_error(
3842             "Multiple RuntimeInvisibleAnnotations attributes in class file %s", THREAD);
3843           return;
3844         }
3845         runtime_invisible_annotations_exists = true;
3846         if (PreserveAllAnnotations) {
3847           runtime_invisible_annotations_length = attribute_length;
3848           runtime_invisible_annotations = cfs->current();
3849           assert(runtime_invisible_annotations != NULL, "null invisible annotations");
3850         }
3851         cfs->skip_u1(attribute_length, CHECK);
3852       } else if (tag == vmSymbols::tag_enclosing_method()) {
3853         if (parsed_enclosingmethod_attribute) {
3854           classfile_parse_error("Multiple EnclosingMethod attributes in class file %s", THREAD);
3855           return;
3856         } else {
3857           parsed_enclosingmethod_attribute = true;
3858         }
3859         guarantee_property(attribute_length == 4,
3860           "Wrong EnclosingMethod attribute length %u in class file %s",
3861           attribute_length, CHECK);
3862         cfs->guarantee_more(4, CHECK);  // class_index, method_index
3863         enclosing_method_class_index  = cfs->get_u2_fast();
3864         enclosing_method_method_index = cfs->get_u2_fast();
3865         if (enclosing_method_class_index == 0) {
3866           classfile_parse_error("Invalid class index in EnclosingMethod attribute in class file %s", THREAD);
3867           return;
3868         }
3869         // Validate the constant pool indices and types
3870         check_property(valid_klass_reference_at(enclosing_method_class_index),
3871           "Invalid or out-of-bounds class index in EnclosingMethod attribute in class file %s", CHECK);
3872         if (enclosing_method_method_index != 0 &&
3873             (!cp->is_within_bounds(enclosing_method_method_index) ||
3874              !cp->tag_at(enclosing_method_method_index).is_name_and_type())) {
3875           classfile_parse_error("Invalid or out-of-bounds method index in EnclosingMethod attribute in class file %s", THREAD);
3876           return;
3877         }
3878       } else if (tag == vmSymbols::tag_bootstrap_methods() &&
3879                  _major_version >= Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {
3880         if (parsed_bootstrap_methods_attribute) {
3881           classfile_parse_error("Multiple BootstrapMethods attributes in class file %s", THREAD);
3882           return;
3883         }
3884         parsed_bootstrap_methods_attribute = true;
3885         parse_classfile_bootstrap_methods_attribute(cfs, cp, attribute_length, CHECK);
3886       } else if (tag == vmSymbols::tag_runtime_visible_type_annotations()) {
3887         if (runtime_visible_type_annotations != NULL) {
3888           classfile_parse_error(
3889             "Multiple RuntimeVisibleTypeAnnotations attributes in class file %s", THREAD);
3890           return;
3891         }
3892         runtime_visible_type_annotations_length = attribute_length;
3893         runtime_visible_type_annotations = cfs->current();
3894         assert(runtime_visible_type_annotations != NULL, "null visible type annotations");
3895         // No need for the VM to parse Type annotations
3896         cfs->skip_u1(runtime_visible_type_annotations_length, CHECK);
3897       } else if (tag == vmSymbols::tag_runtime_invisible_type_annotations()) {
3898         if (runtime_invisible_type_annotations_exists) {
3899           classfile_parse_error(
3900             "Multiple RuntimeInvisibleTypeAnnotations attributes in class file %s", THREAD);
3901           return;
3902         } else {
3903           runtime_invisible_type_annotations_exists = true;
3904         }
3905         if (PreserveAllAnnotations) {
3906           runtime_invisible_type_annotations_length = attribute_length;
3907           runtime_invisible_type_annotations = cfs->current();
3908           assert(runtime_invisible_type_annotations != NULL, "null invisible type annotations");
3909         }
3910         cfs->skip_u1(attribute_length, CHECK);
3911       } else if (_major_version >= JAVA_11_VERSION) {
3912         if (tag == vmSymbols::tag_nest_members()) {
3913           // Check for NestMembers tag
3914           if (parsed_nest_members_attribute) {
3915             classfile_parse_error("Multiple NestMembers attributes in class file %s", THREAD);
3916             return;
3917           } else {
3918             parsed_nest_members_attribute = true;
3919           }
3920           if (parsed_nest_host_attribute) {
3921             classfile_parse_error("Conflicting NestHost and NestMembers attributes in class file %s", THREAD);
3922             return;
3923           }
3924           nest_members_attribute_start = cfs->current();
3925           nest_members_attribute_length = attribute_length;
3926           cfs->skip_u1(nest_members_attribute_length, CHECK);
3927         } else if (tag == vmSymbols::tag_nest_host()) {
3928           if (parsed_nest_host_attribute) {
3929             classfile_parse_error("Multiple NestHost attributes in class file %s", THREAD);
3930             return;
3931           } else {
3932             parsed_nest_host_attribute = true;
3933           }
3934           if (parsed_nest_members_attribute) {
3935             classfile_parse_error("Conflicting NestMembers and NestHost attributes in class file %s", THREAD);
3936             return;
3937           }
3938           if (_need_verify) {
3939             guarantee_property(attribute_length == 2, "Wrong NestHost attribute length in class file %s", CHECK);
3940           }
3941           cfs->guarantee_more(2, CHECK);
3942           u2 class_info_index = cfs->get_u2_fast();
3943           check_property(
3944                          valid_klass_reference_at(class_info_index),
3945                          "Nest-host class_info_index %u has bad constant type in class file %s",
3946                          class_info_index, CHECK);
3947           _nest_host = class_info_index;
3948 
3949         } else if (_major_version >= JAVA_16_VERSION) {
3950           if (tag == vmSymbols::tag_record()) {
3951             if (parsed_record_attribute) {
3952               classfile_parse_error("Multiple Record attributes in class file %s", THREAD);
3953               return;
3954             }
3955             parsed_record_attribute = true;
3956             record_attribute_start = cfs->current();
3957             record_attribute_length = attribute_length;
3958           } else if (_major_version >= JAVA_17_VERSION) {
3959             if (tag == vmSymbols::tag_permitted_subclasses()) {
3960               if (parsed_permitted_subclasses_attribute) {
3961                 classfile_parse_error("Multiple PermittedSubclasses attributes in class file %s", CHECK);
3962                 return;
3963               }
3964               // Classes marked ACC_FINAL cannot have a PermittedSubclasses attribute.
3965               if (_access_flags.is_final()) {
3966                 classfile_parse_error("PermittedSubclasses attribute in final class file %s", CHECK);
3967                 return;
3968               }
3969               parsed_permitted_subclasses_attribute = true;
3970               permitted_subclasses_attribute_start = cfs->current();
3971               permitted_subclasses_attribute_length = attribute_length;
3972             }
3973           }
3974           // Skip attribute_length for any attribute where major_verson >= JAVA_17_VERSION
3975           cfs->skip_u1(attribute_length, CHECK);
3976         } else {
3977           // Unknown attribute
3978           cfs->skip_u1(attribute_length, CHECK);
3979         }
3980       } else {
3981         // Unknown attribute
3982         cfs->skip_u1(attribute_length, CHECK);
3983       }
3984     } else {
3985       // Unknown attribute
3986       cfs->skip_u1(attribute_length, CHECK);
3987     }
3988   }
3989   _class_annotations = assemble_annotations(runtime_visible_annotations,
3990                                             runtime_visible_annotations_length,
3991                                             runtime_invisible_annotations,
3992                                             runtime_invisible_annotations_length,
3993                                             CHECK);
3994   _class_type_annotations = assemble_annotations(runtime_visible_type_annotations,
3995                                                  runtime_visible_type_annotations_length,
3996                                                  runtime_invisible_type_annotations,
3997                                                  runtime_invisible_type_annotations_length,
3998                                                  CHECK);
3999 
4000   if (parsed_innerclasses_attribute || parsed_enclosingmethod_attribute) {
4001     const u2 num_of_classes = parse_classfile_inner_classes_attribute(
4002                             cfs,
4003                             cp,
4004                             inner_classes_attribute_start,
4005                             parsed_innerclasses_attribute,
4006                             enclosing_method_class_index,
4007                             enclosing_method_method_index,
4008                             CHECK);
4009     if (parsed_innerclasses_attribute && _need_verify && _major_version >= JAVA_1_5_VERSION) {
4010       guarantee_property(
4011         inner_classes_attribute_length == sizeof(num_of_classes) + 4 * sizeof(u2) * num_of_classes,
4012         "Wrong InnerClasses attribute length in class file %s", CHECK);
4013     }
4014   }
4015 
4016   if (parsed_nest_members_attribute) {
4017     const u2 num_of_classes = parse_classfile_nest_members_attribute(
4018                             cfs,
4019                             nest_members_attribute_start,
4020                             CHECK);
4021     if (_need_verify) {
4022       guarantee_property(
4023         nest_members_attribute_length == sizeof(num_of_classes) + sizeof(u2) * num_of_classes,
4024         "Wrong NestMembers attribute length in class file %s", CHECK);
4025     }
4026   }
4027 
4028   if (parsed_record_attribute) {
4029     const unsigned int calculated_attr_length = parse_classfile_record_attribute(
4030                             cfs,
4031                             cp,
4032                             record_attribute_start,
4033                             CHECK);
4034     if (_need_verify) {
4035       guarantee_property(record_attribute_length == calculated_attr_length,
4036                          "Record attribute has wrong length in class file %s",
4037                          CHECK);
4038     }
4039   }
4040 
4041   if (parsed_permitted_subclasses_attribute) {
4042     const u2 num_subclasses = parse_classfile_permitted_subclasses_attribute(
4043                             cfs,
4044                             permitted_subclasses_attribute_start,
4045                             CHECK);
4046     if (_need_verify) {
4047       guarantee_property(
4048         permitted_subclasses_attribute_length == sizeof(num_subclasses) + sizeof(u2) * num_subclasses,
4049         "Wrong PermittedSubclasses attribute length in class file %s", CHECK);
4050     }
4051   }
4052 
4053   if (_max_bootstrap_specifier_index >= 0) {
4054     guarantee_property(parsed_bootstrap_methods_attribute,
4055                        "Missing BootstrapMethods attribute in class file %s", CHECK);
4056   }
4057 }
4058 
4059 void ClassFileParser::apply_parsed_class_attributes(InstanceKlass* k) {
4060   assert(k != NULL, "invariant");
4061 
4062   if (_synthetic_flag)
4063     k->set_is_synthetic();
4064   if (_sourcefile_index != 0) {
4065     k->set_source_file_name_index(_sourcefile_index);
4066   }
4067   if (_generic_signature_index != 0) {
4068     k->set_generic_signature_index(_generic_signature_index);
4069   }
4070   if (_sde_buffer != NULL) {
4071     k->set_source_debug_extension(_sde_buffer, _sde_length);
4072   }
4073 }
4074 
4075 // Create the Annotations object that will
4076 // hold the annotations array for the Klass.
4077 void ClassFileParser::create_combined_annotations(TRAPS) {
4078     if (_class_annotations == NULL &&
4079         _class_type_annotations == NULL &&
4080         _fields_annotations == NULL &&
4081         _fields_type_annotations == NULL) {
4082       // Don't create the Annotations object unnecessarily.
4083       return;
4084     }
4085 
4086     Annotations* const annotations = Annotations::allocate(_loader_data, CHECK);
4087     annotations->set_class_annotations(_class_annotations);
4088     annotations->set_class_type_annotations(_class_type_annotations);
4089     annotations->set_fields_annotations(_fields_annotations);
4090     annotations->set_fields_type_annotations(_fields_type_annotations);
4091 
4092     // This is the Annotations object that will be
4093     // assigned to InstanceKlass being constructed.
4094     _combined_annotations = annotations;
4095 
4096     // The annotations arrays below has been transfered the
4097     // _combined_annotations so these fields can now be cleared.
4098     _class_annotations       = NULL;
4099     _class_type_annotations  = NULL;
4100     _fields_annotations      = NULL;
4101     _fields_type_annotations = NULL;
4102 }
4103 
4104 // Transfer ownership of metadata allocated to the InstanceKlass.
4105 void ClassFileParser::apply_parsed_class_metadata(
4106                                             InstanceKlass* this_klass,
4107                                             int java_fields_count) {
4108   assert(this_klass != NULL, "invariant");
4109 
4110   _cp->set_pool_holder(this_klass);
4111   this_klass->set_constants(_cp);
4112   this_klass->set_fields(_fields, java_fields_count);
4113   this_klass->set_methods(_methods);
4114   this_klass->set_inner_classes(_inner_classes);
4115   this_klass->set_nest_members(_nest_members);
4116   this_klass->set_nest_host_index(_nest_host);
4117   this_klass->set_annotations(_combined_annotations);
4118   this_klass->set_permitted_subclasses(_permitted_subclasses);
4119   this_klass->set_record_components(_record_components);
4120   // Delay the setting of _local_interfaces and _transitive_interfaces until after
4121   // initialize_supers() in fill_instance_klass(). It is because the _local_interfaces could
4122   // be shared with _transitive_interfaces and _transitive_interfaces may be shared with
4123   // its _super. If an OOM occurs while loading the current klass, its _super field
4124   // may not have been set. When GC tries to free the klass, the _transitive_interfaces
4125   // may be deallocated mistakenly in InstanceKlass::deallocate_interfaces(). Subsequent
4126   // dereferences to the deallocated _transitive_interfaces will result in a crash.
4127 
4128   // Clear out these fields so they don't get deallocated by the destructor
4129   clear_class_metadata();
4130 }
4131 
4132 AnnotationArray* ClassFileParser::assemble_annotations(const u1* const runtime_visible_annotations,
4133                                                        int runtime_visible_annotations_length,
4134                                                        const u1* const runtime_invisible_annotations,
4135                                                        int runtime_invisible_annotations_length,
4136                                                        TRAPS) {
4137   AnnotationArray* annotations = NULL;
4138   if (runtime_visible_annotations != NULL ||
4139       runtime_invisible_annotations != NULL) {
4140     annotations = MetadataFactory::new_array<u1>(_loader_data,
4141                                           runtime_visible_annotations_length +
4142                                           runtime_invisible_annotations_length,
4143                                           CHECK_(annotations));
4144     if (runtime_visible_annotations != NULL) {
4145       for (int i = 0; i < runtime_visible_annotations_length; i++) {
4146         annotations->at_put(i, runtime_visible_annotations[i]);
4147       }
4148     }
4149     if (runtime_invisible_annotations != NULL) {
4150       for (int i = 0; i < runtime_invisible_annotations_length; i++) {
4151         int append = runtime_visible_annotations_length+i;
4152         annotations->at_put(append, runtime_invisible_annotations[i]);
4153       }
4154     }
4155   }
4156   return annotations;
4157 }
4158 
4159 const InstanceKlass* ClassFileParser::parse_super_class(ConstantPool* const cp,
4160                                                         const int super_class_index,
4161                                                         const bool need_verify,
4162                                                         TRAPS) {
4163   assert(cp != NULL, "invariant");
4164   const InstanceKlass* super_klass = NULL;
4165 
4166   if (super_class_index == 0) {
4167     check_property(_class_name == vmSymbols::java_lang_Object(),
4168                    "Invalid superclass index 0 in class file %s",

4169                    CHECK_NULL);
4170   } else {
4171     check_property(valid_klass_reference_at(super_class_index),
4172                    "Invalid superclass index %u in class file %s",
4173                    super_class_index,
4174                    CHECK_NULL);
4175     // The class name should be legal because it is checked when parsing constant pool.
4176     // However, make sure it is not an array type.
4177     bool is_array = false;
4178     if (cp->tag_at(super_class_index).is_klass()) {
4179       super_klass = InstanceKlass::cast(cp->resolved_klass_at(super_class_index));
4180       if (need_verify)
4181         is_array = super_klass->is_array_klass();
4182     } else if (need_verify) {
4183       is_array = (cp->klass_name_at(super_class_index)->char_at(0) == JVM_SIGNATURE_ARRAY);
4184     }
4185     if (need_verify) {
4186       guarantee_property(!is_array,
4187                         "Bad superclass name in class file %s", CHECK_NULL);
4188     }
4189   }
4190   return super_klass;
4191 }
4192 
4193 OopMapBlocksBuilder::OopMapBlocksBuilder(unsigned int max_blocks) {
4194   _max_nonstatic_oop_maps = max_blocks;
4195   _nonstatic_oop_map_count = 0;
4196   if (max_blocks == 0) {
4197     _nonstatic_oop_maps = NULL;
4198   } else {
4199     _nonstatic_oop_maps =
4200         NEW_RESOURCE_ARRAY(OopMapBlock, _max_nonstatic_oop_maps);
4201     memset(_nonstatic_oop_maps, 0, sizeof(OopMapBlock) * max_blocks);
4202   }
4203 }
4204 
4205 OopMapBlock* OopMapBlocksBuilder::last_oop_map() const {
4206   assert(_nonstatic_oop_map_count > 0, "Has no oop maps");
4207   return _nonstatic_oop_maps + (_nonstatic_oop_map_count - 1);
4208 }
4209 
4210 // addition of super oop maps
4211 void OopMapBlocksBuilder::initialize_inherited_blocks(OopMapBlock* blocks, unsigned int nof_blocks) {
4212   assert(nof_blocks && _nonstatic_oop_map_count == 0 &&
4213          nof_blocks <= _max_nonstatic_oop_maps, "invariant");
4214 
4215   memcpy(_nonstatic_oop_maps, blocks, sizeof(OopMapBlock) * nof_blocks);
4216   _nonstatic_oop_map_count += nof_blocks;
4217 }
4218 
4219 // collection of oops
4220 void OopMapBlocksBuilder::add(int offset, int count) {
4221   if (_nonstatic_oop_map_count == 0) {
4222     _nonstatic_oop_map_count++;
4223   }
4224   OopMapBlock* nonstatic_oop_map = last_oop_map();
4225   if (nonstatic_oop_map->count() == 0) {  // Unused map, set it up
4226     nonstatic_oop_map->set_offset(offset);
4227     nonstatic_oop_map->set_count(count);
4228   } else if (nonstatic_oop_map->is_contiguous(offset)) { // contiguous, add
4229     nonstatic_oop_map->increment_count(count);
4230   } else { // Need a new one...
4231     _nonstatic_oop_map_count++;
4232     assert(_nonstatic_oop_map_count <= _max_nonstatic_oop_maps, "range check");
4233     nonstatic_oop_map = last_oop_map();
4234     nonstatic_oop_map->set_offset(offset);
4235     nonstatic_oop_map->set_count(count);
4236   }
4237 }
4238 
4239 // general purpose copy, e.g. into allocated instanceKlass
4240 void OopMapBlocksBuilder::copy(OopMapBlock* dst) {
4241   if (_nonstatic_oop_map_count != 0) {
4242     memcpy(dst, _nonstatic_oop_maps, sizeof(OopMapBlock) * _nonstatic_oop_map_count);
4243   }
4244 }
4245 
4246 // Sort and compact adjacent blocks
4247 void OopMapBlocksBuilder::compact() {
4248   if (_nonstatic_oop_map_count <= 1) {
4249     return;
4250   }
4251   /*
4252    * Since field layout sneeks in oops before values, we will be able to condense
4253    * blocks. There is potential to compact between super, own refs and values
4254    * containing refs.
4255    *
4256    * Currently compaction is slightly limited due to values being 8 byte aligned.
4257    * This may well change: FixMe if it doesn't, the code below is fairly general purpose
4258    * and maybe it doesn't need to be.
4259    */
4260   qsort(_nonstatic_oop_maps, _nonstatic_oop_map_count, sizeof(OopMapBlock),
4261         (_sort_Fn)OopMapBlock::compare_offset);
4262   if (_nonstatic_oop_map_count < 2) {
4263     return;
4264   }
4265 
4266   // Make a temp copy, and iterate through and copy back into the original
4267   ResourceMark rm;
4268   OopMapBlock* oop_maps_copy =
4269       NEW_RESOURCE_ARRAY(OopMapBlock, _nonstatic_oop_map_count);
4270   OopMapBlock* oop_maps_copy_end = oop_maps_copy + _nonstatic_oop_map_count;
4271   copy(oop_maps_copy);
4272   OopMapBlock* nonstatic_oop_map = _nonstatic_oop_maps;
4273   unsigned int new_count = 1;
4274   oop_maps_copy++;
4275   while(oop_maps_copy < oop_maps_copy_end) {
4276     assert(nonstatic_oop_map->offset() < oop_maps_copy->offset(), "invariant");
4277     if (nonstatic_oop_map->is_contiguous(oop_maps_copy->offset())) {
4278       nonstatic_oop_map->increment_count(oop_maps_copy->count());
4279     } else {
4280       nonstatic_oop_map++;
4281       new_count++;
4282       nonstatic_oop_map->set_offset(oop_maps_copy->offset());
4283       nonstatic_oop_map->set_count(oop_maps_copy->count());
4284     }
4285     oop_maps_copy++;
4286   }
4287   assert(new_count <= _nonstatic_oop_map_count, "end up with more maps after compact() ?");
4288   _nonstatic_oop_map_count = new_count;
4289 }
4290 
4291 void OopMapBlocksBuilder::print_on(outputStream* st) const {
4292   st->print_cr("  OopMapBlocks: %3d  /%3d", _nonstatic_oop_map_count, _max_nonstatic_oop_maps);
4293   if (_nonstatic_oop_map_count > 0) {
4294     OopMapBlock* map = _nonstatic_oop_maps;
4295     OopMapBlock* last_map = last_oop_map();
4296     assert(map <= last_map, "Last less than first");
4297     while (map <= last_map) {
4298       st->print_cr("    Offset: %3d  -%3d Count: %3d", map->offset(),
4299                    map->offset() + map->offset_span() - heapOopSize, map->count());
4300       map++;
4301     }
4302   }
4303 }
4304 
4305 void OopMapBlocksBuilder::print_value_on(outputStream* st) const {
4306   print_on(st);
4307 }
4308 
4309 void ClassFileParser::throwInlineTypeLimitation(THREAD_AND_LOCATION_DECL,
4310                                                 const char* msg,
4311                                                 const Symbol* name,
4312                                                 const Symbol* sig) const {
4313 
4314   ResourceMark rm(THREAD);
4315   if (name == NULL || sig == NULL) {
4316     Exceptions::fthrow(THREAD_AND_LOCATION_ARGS,
4317         vmSymbols::java_lang_ClassFormatError(),
4318         "class: %s - %s", _class_name->as_C_string(), msg);
4319   }
4320   else {
4321     Exceptions::fthrow(THREAD_AND_LOCATION_ARGS,
4322         vmSymbols::java_lang_ClassFormatError(),
4323         "\"%s\" sig: \"%s\" class: %s - %s", name->as_C_string(), sig->as_C_string(),
4324         _class_name->as_C_string(), msg);
4325   }
4326 }
4327 
4328 void ClassFileParser::set_precomputed_flags(InstanceKlass* ik) {
4329   assert(ik != NULL, "invariant");
4330 
4331   const Klass* const super = ik->super();
4332 
4333   // Check if this klass has an empty finalize method (i.e. one with return bytecode only),
4334   // in which case we don't have to register objects as finalizable
4335   if (!_has_empty_finalizer) {
4336     if (_has_finalizer ||
4337         (super != NULL && super->has_finalizer())) {
4338       ik->set_has_finalizer();
4339     }
4340   }
4341 
4342 #ifdef ASSERT
4343   bool f = false;
4344   const Method* const m = ik->lookup_method(vmSymbols::finalize_method_name(),
4345                                            vmSymbols::void_method_signature());
4346   if (m != NULL && !m->is_empty_method()) {
4347       f = true;
4348   }
4349 
4350   // Spec doesn't prevent agent from redefinition of empty finalizer.
4351   // Despite the fact that it's generally bad idea and redefined finalizer
4352   // will not work as expected we shouldn't abort vm in this case
4353   if (!ik->has_redefined_this_or_super()) {
4354     assert(ik->has_finalizer() == f, "inconsistent has_finalizer");
4355   }
4356 #endif
4357 
4358   // Check if this klass supports the java.lang.Cloneable interface
4359   if (vmClasses::Cloneable_klass_loaded()) {
4360     if (ik->is_subtype_of(vmClasses::Cloneable_klass())) {
4361       if (ik->is_inline_klass()) {
4362         JavaThread *THREAD = JavaThread::current();
4363         throwInlineTypeLimitation(THREAD_AND_LOCATION, "Inline Types do not support Cloneable");
4364         return;
4365       }
4366       ik->set_is_cloneable();
4367     }
4368   }
4369 
4370   // Check if this klass has a vanilla default constructor
4371   if (super == NULL) {
4372     // java.lang.Object has empty default constructor
4373     ik->set_has_vanilla_constructor();
4374   } else {
4375     if (super->has_vanilla_constructor() &&
4376         _has_vanilla_constructor) {
4377       ik->set_has_vanilla_constructor();
4378     }
4379 #ifdef ASSERT
4380     bool v = false;
4381     if (super->has_vanilla_constructor()) {
4382       const Method* const constructor =
4383         ik->find_method(vmSymbols::object_initializer_name(),
4384                        vmSymbols::void_method_signature());
4385       if (constructor != NULL && constructor->is_vanilla_constructor()) {
4386         v = true;
4387       }
4388     }
4389     assert(v == ik->has_vanilla_constructor(), "inconsistent has_vanilla_constructor");
4390 #endif
4391   }
4392 
4393   // If it cannot be fast-path allocated, set a bit in the layout helper.
4394   // See documentation of InstanceKlass::can_be_fastpath_allocated().
4395   assert(ik->size_helper() > 0, "layout_helper is initialized");
4396   if ((!RegisterFinalizersAtInit && ik->has_finalizer())
4397       || ik->is_abstract() || ik->is_interface()
4398       || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == NULL)
4399       || ik->size_helper() >= FastAllocateSizeLimit) {
4400     // Forbid fast-path allocation.
4401     const jint lh = Klass::instance_layout_helper(ik->size_helper(), true);
4402     ik->set_layout_helper(lh);
4403   }
4404 }
4405 
4406 bool ClassFileParser::supports_inline_types() const {
4407   // Inline types are only supported by class file version 55 and later
4408   return _major_version >= JAVA_11_VERSION;
4409 }
4410 
4411 // utility methods for appending an array with check for duplicates
4412 
4413 static void append_interfaces(GrowableArray<InstanceKlass*>* result,
4414                               const Array<InstanceKlass*>* const ifs) {
4415   // iterate over new interfaces
4416   for (int i = 0; i < ifs->length(); i++) {
4417     InstanceKlass* const e = ifs->at(i);
4418     assert(e->is_klass() && e->is_interface(), "just checking");
4419     // add new interface
4420     result->append_if_missing(e);
4421   }
4422 }
4423 
4424 static Array<InstanceKlass*>* compute_transitive_interfaces(const InstanceKlass* super,
4425                                                             Array<InstanceKlass*>* local_ifs,
4426                                                             ClassLoaderData* loader_data,
4427                                                             TRAPS) {
4428   assert(local_ifs != NULL, "invariant");
4429   assert(loader_data != NULL, "invariant");
4430 
4431   // Compute maximum size for transitive interfaces
4432   int max_transitive_size = 0;
4433   int super_size = 0;
4434   // Add superclass transitive interfaces size
4435   if (super != NULL) {
4436     super_size = super->transitive_interfaces()->length();
4437     max_transitive_size += super_size;
4438   }
4439   // Add local interfaces' super interfaces
4440   const int local_size = local_ifs->length();
4441   for (int i = 0; i < local_size; i++) {
4442     InstanceKlass* const l = local_ifs->at(i);
4443     max_transitive_size += l->transitive_interfaces()->length();
4444   }
4445   // Finally add local interfaces
4446   max_transitive_size += local_size;
4447   // Construct array
4448   if (max_transitive_size == 0) {
4449     // no interfaces, use canonicalized array
4450     return Universe::the_empty_instance_klass_array();
4451   } else if (max_transitive_size == super_size) {
4452     // no new local interfaces added, share superklass' transitive interface array
4453     return super->transitive_interfaces();
4454     // The three lines below are commented to work around bug JDK-8245487
4455 //  } else if (max_transitive_size == local_size) {
4456 //    // only local interfaces added, share local interface array
4457 //    return local_ifs;
4458   } else {
4459     ResourceMark rm;
4460     GrowableArray<InstanceKlass*>* const result = new GrowableArray<InstanceKlass*>(max_transitive_size);
4461 
4462     // Copy down from superclass
4463     if (super != NULL) {
4464       append_interfaces(result, super->transitive_interfaces());
4465     }
4466 
4467     // Copy down from local interfaces' superinterfaces
4468     for (int i = 0; i < local_size; i++) {
4469       InstanceKlass* const l = local_ifs->at(i);
4470       append_interfaces(result, l->transitive_interfaces());
4471     }
4472     // Finally add local interfaces
4473     append_interfaces(result, local_ifs);
4474 
4475     // length will be less than the max_transitive_size if duplicates were removed
4476     const int length = result->length();
4477     assert(length <= max_transitive_size, "just checking");
4478 
4479     if (length == 1 && result->at(0) == vmClasses::IdentityObject_klass()) {
4480       return Universe::the_single_IdentityObject_klass_array();
4481     }
4482     if (length == 1 && result->at(0) == vmClasses::PrimitiveObject_klass()) {
4483       return Universe::the_single_PrimitiveObject_klass_array();
4484     }
4485 
4486     Array<InstanceKlass*>* const new_result =
4487       MetadataFactory::new_array<InstanceKlass*>(loader_data, length, CHECK_NULL);
4488     for (int i = 0; i < length; i++) {
4489       InstanceKlass* const e = result->at(i);
4490       assert(e != NULL, "just checking");
4491       new_result->at_put(i, e);
4492     }
4493     return new_result;
4494   }
4495 }
4496 
4497 void ClassFileParser::check_super_class_access(const InstanceKlass* this_klass, TRAPS) {
4498   assert(this_klass != NULL, "invariant");
4499   const Klass* const super = this_klass->super();
4500 
4501   if (super != NULL) {
4502     const InstanceKlass* super_ik = InstanceKlass::cast(super);
4503 
4504     if (super->is_final()) {
4505       classfile_icce_error("class %s cannot inherit from final class %s", super_ik, THREAD);
4506       return;
4507     }
4508 
4509     if (super_ik->is_sealed() && !super_ik->has_as_permitted_subclass(this_klass)) {
4510       classfile_icce_error("class %s cannot inherit from sealed class %s", super_ik, THREAD);
4511       return;
4512     }
4513 
4514     // If the loader is not the boot loader then throw an exception if its
4515     // superclass is in package jdk.internal.reflect and its loader is not a
4516     // special reflection class loader
4517     if (!this_klass->class_loader_data()->is_the_null_class_loader_data()) {
4518       PackageEntry* super_package = super->package();
4519       if (super_package != NULL &&
4520           super_package->name()->fast_compare(vmSymbols::jdk_internal_reflect()) == 0 &&
4521           !java_lang_ClassLoader::is_reflection_class_loader(this_klass->class_loader())) {
4522         ResourceMark rm(THREAD);
4523         Exceptions::fthrow(
4524           THREAD_AND_LOCATION,
4525           vmSymbols::java_lang_IllegalAccessError(),
4526           "class %s loaded by %s cannot access jdk/internal/reflect superclass %s",
4527           this_klass->external_name(),
4528           this_klass->class_loader_data()->loader_name_and_id(),
4529           super->external_name());
4530         return;
4531       }
4532     }
4533 
4534     Reflection::VerifyClassAccessResults vca_result =
4535       Reflection::verify_class_access(this_klass, InstanceKlass::cast(super), false);
4536     if (vca_result != Reflection::ACCESS_OK) {
4537       ResourceMark rm(THREAD);
4538       char* msg = Reflection::verify_class_access_msg(this_klass,
4539                                                       InstanceKlass::cast(super),
4540                                                       vca_result);
4541       if (msg == NULL) {
4542         bool same_module = (this_klass->module() == super->module());
4543         Exceptions::fthrow(
4544           THREAD_AND_LOCATION,
4545           vmSymbols::java_lang_IllegalAccessError(),
4546           "class %s cannot access its %ssuperclass %s (%s%s%s)",
4547           this_klass->external_name(),
4548           super->is_abstract() ? "abstract " : "",
4549           super->external_name(),
4550           (same_module) ? this_klass->joint_in_module_of_loader(super) : this_klass->class_in_module_of_loader(),
4551           (same_module) ? "" : "; ",
4552           (same_module) ? "" : super->class_in_module_of_loader());
4553       } else {
4554         // Add additional message content.
4555         Exceptions::fthrow(
4556           THREAD_AND_LOCATION,
4557           vmSymbols::java_lang_IllegalAccessError(),
4558           "superclass access check failed: %s",
4559           msg);
4560       }
4561     }
4562   }
4563 }
4564 
4565 
4566 void ClassFileParser::check_super_interface_access(const InstanceKlass* this_klass, TRAPS) {
4567   assert(this_klass != NULL, "invariant");
4568   const Array<InstanceKlass*>* const local_interfaces = this_klass->local_interfaces();
4569   const int lng = local_interfaces->length();
4570   for (int i = lng - 1; i >= 0; i--) {
4571     InstanceKlass* const k = local_interfaces->at(i);
4572     assert (k != NULL && k->is_interface(), "invalid interface");
4573 
4574     if (k->is_sealed() && !k->has_as_permitted_subclass(this_klass)) {
4575       classfile_icce_error(this_klass->is_interface() ?
4576                              "class %s cannot extend sealed interface %s" :
4577                              "class %s cannot implement sealed interface %s",
4578                            k, THREAD);
4579       return;
4580     }
4581 
4582     Reflection::VerifyClassAccessResults vca_result =
4583       Reflection::verify_class_access(this_klass, k, false);
4584     if (vca_result != Reflection::ACCESS_OK) {
4585       ResourceMark rm(THREAD);
4586       char* msg = Reflection::verify_class_access_msg(this_klass,
4587                                                       k,
4588                                                       vca_result);
4589       if (msg == NULL) {
4590         bool same_module = (this_klass->module() == k->module());
4591         Exceptions::fthrow(
4592           THREAD_AND_LOCATION,
4593           vmSymbols::java_lang_IllegalAccessError(),
4594           "class %s cannot access its superinterface %s (%s%s%s)",
4595           this_klass->external_name(),
4596           k->external_name(),
4597           (same_module) ? this_klass->joint_in_module_of_loader(k) : this_klass->class_in_module_of_loader(),
4598           (same_module) ? "" : "; ",
4599           (same_module) ? "" : k->class_in_module_of_loader());
4600       } else {
4601         // Add additional message content.
4602         Exceptions::fthrow(
4603           THREAD_AND_LOCATION,
4604           vmSymbols::java_lang_IllegalAccessError(),
4605           "superinterface check failed: %s",
4606           msg);
4607       }
4608     }
4609   }
4610 }
4611 
4612 
4613 static void check_final_method_override(const InstanceKlass* this_klass, TRAPS) {
4614   assert(this_klass != NULL, "invariant");
4615   const Array<Method*>* const methods = this_klass->methods();
4616   const int num_methods = methods->length();
4617 
4618   // go thru each method and check if it overrides a final method
4619   for (int index = 0; index < num_methods; index++) {
4620     const Method* const m = methods->at(index);
4621 
4622     // skip private, static, and <init> methods
4623     if ((!m->is_private() && !m->is_static()) &&
4624         (m->name() != vmSymbols::object_initializer_name())) {
4625 
4626       const Symbol* const name = m->name();
4627       const Symbol* const signature = m->signature();
4628       const Klass* k = this_klass->super();
4629       const Method* super_m = NULL;
4630       while (k != NULL) {
4631         // skip supers that don't have final methods.
4632         if (k->has_final_method()) {
4633           // lookup a matching method in the super class hierarchy
4634           super_m = InstanceKlass::cast(k)->lookup_method(name, signature);
4635           if (super_m == NULL) {
4636             break; // didn't find any match; get out
4637           }
4638 
4639           if (super_m->is_final() && !super_m->is_static() &&
4640               !super_m->access_flags().is_private()) {
4641             // matching method in super is final, and not static or private
4642             bool can_access = Reflection::verify_member_access(this_klass,
4643                                                                super_m->method_holder(),
4644                                                                super_m->method_holder(),
4645                                                                super_m->access_flags(),
4646                                                               false, false, CHECK);
4647             if (can_access) {
4648               // this class can access super final method and therefore override
4649               ResourceMark rm(THREAD);
4650               THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
4651                         err_msg("class %s overrides final method %s.%s%s",
4652                                 this_klass->external_name(),
4653                                 super_m->method_holder()->external_name(),
4654                                 name->as_C_string(),
4655                                 signature->as_C_string()));
4656             }
4657           }
4658 
4659           // continue to look from super_m's holder's super.
4660           k = super_m->method_holder()->super();
4661           continue;
4662         }
4663 
4664         k = k->super();
4665       }
4666     }
4667   }
4668 }
4669 
4670 
4671 // assumes that this_klass is an interface
4672 static void check_illegal_static_method(const InstanceKlass* this_klass, TRAPS) {
4673   assert(this_klass != NULL, "invariant");
4674   assert(this_klass->is_interface(), "not an interface");
4675   const Array<Method*>* methods = this_klass->methods();
4676   const int num_methods = methods->length();
4677 
4678   for (int index = 0; index < num_methods; index++) {
4679     const Method* const m = methods->at(index);
4680     // if m is static and not the init method, throw a verify error
4681     if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) {
4682       ResourceMark rm(THREAD);
4683       Exceptions::fthrow(
4684         THREAD_AND_LOCATION,
4685         vmSymbols::java_lang_VerifyError(),
4686         "Illegal static method %s in interface %s",
4687         m->name()->as_C_string(),
4688         this_klass->external_name()
4689       );
4690       return;
4691     }
4692   }
4693 }
4694 
4695 // utility methods for format checking
4696 
4697 void ClassFileParser::verify_legal_class_modifiers(jint flags, TRAPS) const {
4698   const bool is_module = (flags & JVM_ACC_MODULE) != 0;
4699   const bool is_inline_type = (flags & JVM_ACC_INLINE) != 0;
4700   assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");
4701   assert(supports_inline_types() || !is_inline_type, "JVM_ACC_INLINE should not be set");
4702   if (is_module) {
4703     ResourceMark rm(THREAD);
4704     Exceptions::fthrow(
4705       THREAD_AND_LOCATION,
4706       vmSymbols::java_lang_NoClassDefFoundError(),
4707       "%s is not a class because access_flag ACC_MODULE is set",
4708       _class_name->as_C_string());
4709     return;
4710   }
4711 
4712   if (is_inline_type && !EnableValhalla) {
4713     ResourceMark rm(THREAD);
4714     Exceptions::fthrow(
4715       THREAD_AND_LOCATION,
4716       vmSymbols::java_lang_ClassFormatError(),
4717       "Class modifier ACC_INLINE in class %s requires option -XX:+EnableValhalla",
4718       _class_name->as_C_string()
4719     );
4720     return;
4721   }
4722 
4723   if (!_need_verify) { return; }
4724 
4725   const bool is_interface  = (flags & JVM_ACC_INTERFACE)  != 0;
4726   const bool is_abstract   = (flags & JVM_ACC_ABSTRACT)   != 0;
4727   const bool is_final      = (flags & JVM_ACC_FINAL)      != 0;
4728   const bool is_super      = (flags & JVM_ACC_SUPER)      != 0;
4729   const bool is_enum       = (flags & JVM_ACC_ENUM)       != 0;
4730   const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4731   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4732   const bool major_gte_14  = _major_version >= JAVA_14_VERSION;
4733 
4734   if ((is_abstract && is_final) ||
4735       (is_interface && !is_abstract) ||
4736       (is_interface && major_gte_1_5 && (is_super || is_enum)) ||
4737       (!is_interface && major_gte_1_5 && is_annotation) ||
4738       (is_inline_type && (is_interface || is_abstract || is_enum || !is_final))) {
4739     ResourceMark rm(THREAD);
4740     const char* class_note = "";
4741     if (is_inline_type)  class_note = " (an inline class)";
4742     Exceptions::fthrow(
4743       THREAD_AND_LOCATION,
4744       vmSymbols::java_lang_ClassFormatError(),
4745       "Illegal class modifiers in class %s%s: 0x%X",
4746       _class_name->as_C_string(), class_note, flags
4747     );
4748     return;
4749   }
4750 }
4751 
4752 static bool has_illegal_visibility(jint flags) {
4753   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4754   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4755   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4756 
4757   return ((is_public && is_protected) ||
4758           (is_public && is_private) ||
4759           (is_protected && is_private));
4760 }
4761 
4762 // A legal major_version.minor_version must be one of the following:
4763 //
4764 //  Major_version >= 45 and major_version < 56, any minor_version.
4765 //  Major_version >= 56 and major_version <= JVM_CLASSFILE_MAJOR_VERSION and minor_version = 0.
4766 //  Major_version = JVM_CLASSFILE_MAJOR_VERSION and minor_version = 65535 and --enable-preview is present.
4767 //
4768 void ClassFileParser::verify_class_version(u2 major, u2 minor, Symbol* class_name, TRAPS){
4769   ResourceMark rm(THREAD);
4770   const u2 max_version = JVM_CLASSFILE_MAJOR_VERSION;
4771   if (major < JAVA_MIN_SUPPORTED_VERSION) {
4772     classfile_ucve_error("%s (class file version %u.%u) was compiled with an invalid major version",
4773                          class_name, major, minor, THREAD);
4774     return;
4775   }
4776 
4777   if (major > max_version) {
4778     Exceptions::fthrow(
4779       THREAD_AND_LOCATION,
4780       vmSymbols::java_lang_UnsupportedClassVersionError(),
4781       "%s has been compiled by a more recent version of the Java Runtime (class file version %u.%u), "
4782       "this version of the Java Runtime only recognizes class file versions up to %u.0",
4783       class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION);
4784     return;
4785   }
4786 
4787   if (major < JAVA_12_VERSION || minor == 0) {
4788     return;
4789   }
4790 
4791   if (minor == JAVA_PREVIEW_MINOR_VERSION) {
4792     if (major != max_version) {
4793       Exceptions::fthrow(
4794         THREAD_AND_LOCATION,
4795         vmSymbols::java_lang_UnsupportedClassVersionError(),
4796         "%s (class file version %u.%u) was compiled with preview features that are unsupported. "
4797         "This version of the Java Runtime only recognizes preview features for class file version %u.%u",
4798         class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION, JAVA_PREVIEW_MINOR_VERSION);
4799       return;
4800     }
4801 
4802     if (!Arguments::enable_preview()) {
4803       classfile_ucve_error("Preview features are not enabled for %s (class file version %u.%u). Try running with '--enable-preview'",
4804                            class_name, major, minor, THREAD);
4805       return;
4806     }
4807 
4808   } else { // minor != JAVA_PREVIEW_MINOR_VERSION
4809     classfile_ucve_error("%s (class file version %u.%u) was compiled with an invalid non-zero minor version",
4810                          class_name, major, minor, THREAD);
4811   }
4812 }
4813 
4814 void ClassFileParser::verify_legal_field_modifiers(jint flags,
4815                                                    bool is_interface,
4816                                                    bool is_inline_type,
4817                                                    TRAPS) const {
4818   if (!_need_verify) { return; }
4819 
4820   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4821   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4822   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4823   const bool is_static    = (flags & JVM_ACC_STATIC)    != 0;
4824   const bool is_final     = (flags & JVM_ACC_FINAL)     != 0;
4825   const bool is_volatile  = (flags & JVM_ACC_VOLATILE)  != 0;
4826   const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
4827   const bool is_enum      = (flags & JVM_ACC_ENUM)      != 0;
4828   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4829 
4830   bool is_illegal = false;
4831 
4832   if (is_interface) {
4833     if (!is_public || !is_static || !is_final || is_private ||
4834         is_protected || is_volatile || is_transient ||
4835         (major_gte_1_5 && is_enum)) {
4836       is_illegal = true;
4837     }
4838   } else { // not interface
4839     if (has_illegal_visibility(flags) || (is_final && is_volatile)) {
4840       is_illegal = true;
4841     } else {
4842       if (is_inline_type && !is_static && !is_final) {
4843         is_illegal = true;
4844       }
4845     }
4846   }
4847 
4848   if (is_illegal) {
4849     ResourceMark rm(THREAD);
4850     Exceptions::fthrow(
4851       THREAD_AND_LOCATION,
4852       vmSymbols::java_lang_ClassFormatError(),
4853       "Illegal field modifiers in class %s: 0x%X",
4854       _class_name->as_C_string(), flags);
4855     return;
4856   }
4857 }
4858 
4859 void ClassFileParser::verify_legal_method_modifiers(jint flags,
4860                                                     bool is_interface,
4861                                                     bool is_inline_type,
4862                                                     const Symbol* name,
4863                                                     TRAPS) const {
4864   if (!_need_verify) { return; }
4865 
4866   const bool is_public       = (flags & JVM_ACC_PUBLIC)       != 0;
4867   const bool is_private      = (flags & JVM_ACC_PRIVATE)      != 0;
4868   const bool is_static       = (flags & JVM_ACC_STATIC)       != 0;
4869   const bool is_final        = (flags & JVM_ACC_FINAL)        != 0;
4870   const bool is_native       = (flags & JVM_ACC_NATIVE)       != 0;
4871   const bool is_abstract     = (flags & JVM_ACC_ABSTRACT)     != 0;
4872   const bool is_bridge       = (flags & JVM_ACC_BRIDGE)       != 0;
4873   const bool is_strict       = (flags & JVM_ACC_STRICT)       != 0;
4874   const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
4875   const bool is_protected    = (flags & JVM_ACC_PROTECTED)    != 0;
4876   const bool major_gte_1_5   = _major_version >= JAVA_1_5_VERSION;
4877   const bool major_gte_8     = _major_version >= JAVA_8_VERSION;
4878   const bool major_gte_17    = _major_version >= JAVA_17_VERSION;
4879   const bool is_initializer  = (name == vmSymbols::object_initializer_name());
4880 
4881   bool is_illegal = false;
4882 
4883   const char* class_note = "";
4884   if (is_interface) {
4885     if (major_gte_8) {
4886       // Class file version is JAVA_8_VERSION or later Methods of
4887       // interfaces may set any of the flags except ACC_PROTECTED,
4888       // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must
4889       // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.
4890       if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
4891           (is_native || is_protected || is_final || is_synchronized) ||
4892           // If a specific method of a class or interface has its
4893           // ACC_ABSTRACT flag set, it must not have any of its
4894           // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,
4895           // ACC_STRICT, or ACC_SYNCHRONIZED flags set.  No need to
4896           // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as
4897           // those flags are illegal irrespective of ACC_ABSTRACT being set or not.
4898           (is_abstract && (is_private || is_static || (!major_gte_17 && is_strict)))) {
4899         is_illegal = true;
4900       }
4901     } else if (major_gte_1_5) {
4902       // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)
4903       if (!is_public || is_private || is_protected || is_static || is_final ||
4904           is_synchronized || is_native || !is_abstract || is_strict) {
4905         is_illegal = true;
4906       }
4907     } else {
4908       // Class file version is pre-JAVA_1_5_VERSION
4909       if (!is_public || is_static || is_final || is_native || !is_abstract) {
4910         is_illegal = true;
4911       }
4912     }
4913   } else { // not interface
4914     if (has_illegal_visibility(flags)) {
4915       is_illegal = true;
4916     } else {
4917       if (is_initializer) {
4918         if (is_final || is_synchronized || is_native ||
4919             is_abstract || (major_gte_1_5 && is_bridge)) {
4920           is_illegal = true;
4921         }
4922         if (!is_static && !is_inline_type) {
4923           // OK, an object constructor in a regular class
4924         } else if (is_static && is_inline_type) {
4925           // OK, a static init factory in an inline class
4926         } else {
4927           // but no other combinations are allowed
4928           is_illegal = true;
4929           class_note = (is_inline_type ? " (an inline class)" : " (not an inline class)");
4930         }
4931       } else { // not initializer
4932         if (is_inline_type && is_synchronized && !is_static) {
4933           is_illegal = true;
4934           class_note = " (an inline class)";
4935         } else {
4936           if (is_abstract) {
4937             if ((is_final || is_native || is_private || is_static ||
4938                 (major_gte_1_5 && (is_synchronized || (!major_gte_17 && is_strict))))) {
4939               is_illegal = true;
4940             }
4941           }
4942         }
4943       }
4944     }
4945   }
4946 
4947   if (is_illegal) {
4948     ResourceMark rm(THREAD);
4949     Exceptions::fthrow(
4950       THREAD_AND_LOCATION,
4951       vmSymbols::java_lang_ClassFormatError(),
4952       "Method %s in class %s%s has illegal modifiers: 0x%X",
4953       name->as_C_string(), _class_name->as_C_string(), class_note, flags);
4954     return;
4955   }
4956 }
4957 
4958 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer,
4959                                         int length,
4960                                         TRAPS) const {
4961   assert(_need_verify, "only called when _need_verify is true");
4962   if (!UTF8::is_legal_utf8(buffer, length, _major_version <= 47)) {
4963     classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", THREAD);
4964   }
4965 }
4966 
4967 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
4968 // In class names, '/' separates unqualified names.  This is verified in this function also.
4969 // Method names also may not contain the characters '<' or '>', unless <init>
4970 // or <clinit>.  Note that method names may not be <init> or <clinit> in this
4971 // method.  Because these names have been checked as special cases before
4972 // calling this method in verify_legal_method_name.
4973 //
4974 // This method is also called from the modular system APIs in modules.cpp
4975 // to verify the validity of module and package names.
4976 bool ClassFileParser::verify_unqualified_name(const char* name,
4977                                               unsigned int length,
4978                                               int type) {
4979   if (length == 0) return false;  // Must have at least one char.
4980   for (const char* p = name; p != name + length; p++) {
4981     switch(*p) {
4982       case JVM_SIGNATURE_DOT:
4983       case JVM_SIGNATURE_ENDCLASS:
4984       case JVM_SIGNATURE_ARRAY:
4985         // do not permit '.', ';', or '['
4986         return false;
4987       case JVM_SIGNATURE_SLASH:
4988         // check for '//' or leading or trailing '/' which are not legal
4989         // unqualified name must not be empty
4990         if (type == ClassFileParser::LegalClass) {
4991           if (p == name || p+1 >= name+length ||
4992               *(p+1) == JVM_SIGNATURE_SLASH) {
4993             return false;
4994           }
4995         } else {
4996           return false;   // do not permit '/' unless it's class name
4997         }
4998         break;
4999       case JVM_SIGNATURE_SPECIAL:
5000       case JVM_SIGNATURE_ENDSPECIAL:
5001         // do not permit '<' or '>' in method names
5002         if (type == ClassFileParser::LegalMethod) {
5003           return false;
5004         }
5005     }
5006   }
5007   return true;
5008 }
5009 
5010 // Take pointer to a UTF8 byte string (not NUL-terminated).
5011 // Skip over the longest part of the string that could
5012 // be taken as a fieldname. Allow '/' if slash_ok is true.
5013 // Return a pointer to just past the fieldname.
5014 // Return NULL if no fieldname at all was found, or in the case of slash_ok
5015 // being true, we saw consecutive slashes (meaning we were looking for a
5016 // qualified path but found something that was badly-formed).
5017 static const char* skip_over_field_name(const char* const name,
5018                                         bool slash_ok,
5019                                         unsigned int length) {
5020   const char* p;
5021   jboolean last_is_slash = false;
5022   jboolean not_first_ch = false;
5023 
5024   for (p = name; p != name + length; not_first_ch = true) {
5025     const char* old_p = p;
5026     jchar ch = *p;
5027     if (ch < 128) {
5028       p++;
5029       // quick check for ascii
5030       if ((ch >= 'a' && ch <= 'z') ||
5031         (ch >= 'A' && ch <= 'Z') ||
5032         (ch == '_' || ch == '$') ||
5033         (not_first_ch && ch >= '0' && ch <= '9')) {
5034         last_is_slash = false;
5035         continue;
5036       }
5037       if (slash_ok && ch == JVM_SIGNATURE_SLASH) {
5038         if (last_is_slash) {
5039           return NULL;  // Don't permit consecutive slashes
5040         }
5041         last_is_slash = true;
5042         continue;
5043       }
5044     }
5045     else {
5046       jint unicode_ch;
5047       char* tmp_p = UTF8::next_character(p, &unicode_ch);
5048       p = tmp_p;
5049       last_is_slash = false;
5050       // Check if ch is Java identifier start or is Java identifier part
5051       // 4672820: call java.lang.Character methods directly without generating separate tables.
5052       EXCEPTION_MARK;
5053       // return value
5054       JavaValue result(T_BOOLEAN);
5055       // Set up the arguments to isJavaIdentifierStart or isJavaIdentifierPart
5056       JavaCallArguments args;
5057       args.push_int(unicode_ch);
5058 
5059       if (not_first_ch) {
5060         // public static boolean isJavaIdentifierPart(char ch);
5061         JavaCalls::call_static(&result,
5062           vmClasses::Character_klass(),
5063           vmSymbols::isJavaIdentifierPart_name(),
5064           vmSymbols::int_bool_signature(),
5065           &args,
5066           THREAD);
5067       } else {
5068         // public static boolean isJavaIdentifierStart(char ch);
5069         JavaCalls::call_static(&result,
5070           vmClasses::Character_klass(),
5071           vmSymbols::isJavaIdentifierStart_name(),
5072           vmSymbols::int_bool_signature(),
5073           &args,
5074           THREAD);
5075       }
5076       if (HAS_PENDING_EXCEPTION) {
5077         CLEAR_PENDING_EXCEPTION;
5078         return NULL;
5079       }
5080       if(result.get_jboolean()) {
5081         continue;
5082       }
5083     }
5084     return (not_first_ch) ? old_p : NULL;
5085   }
5086   return (not_first_ch) ? p : NULL;
5087 }
5088 
5089 // Take pointer to a UTF8 byte string (not NUL-terminated).
5090 // Skip over the longest part of the string that could
5091 // be taken as a field signature. Allow "void" if void_ok.
5092 // Return a pointer to just past the signature.
5093 // Return NULL if no legal signature is found.
5094 const char* ClassFileParser::skip_over_field_signature(const char* signature,
5095                                                        bool void_ok,
5096                                                        unsigned int length,
5097                                                        TRAPS) const {
5098   unsigned int array_dim = 0;
5099   while (length > 0) {
5100     switch (signature[0]) {
5101     case JVM_SIGNATURE_VOID: if (!void_ok) { return NULL; }
5102     case JVM_SIGNATURE_BOOLEAN:
5103     case JVM_SIGNATURE_BYTE:
5104     case JVM_SIGNATURE_CHAR:
5105     case JVM_SIGNATURE_SHORT:
5106     case JVM_SIGNATURE_INT:
5107     case JVM_SIGNATURE_FLOAT:
5108     case JVM_SIGNATURE_LONG:
5109     case JVM_SIGNATURE_DOUBLE:
5110       return signature + 1;
5111     case JVM_SIGNATURE_INLINE_TYPE:
5112       // Can't enable this check until JDK upgrades the bytecode generators
5113       // if (_major_version < CONSTANT_CLASS_DESCRIPTORS ) {
5114       //   classfile_parse_error("Class name contains illegal Q-signature "
5115       //                                    "in descriptor in class file %s",
5116       //                                    CHECK_0);
5117       // }
5118       // fall through
5119     case JVM_SIGNATURE_CLASS:
5120     {
5121       if (_major_version < JAVA_1_5_VERSION) {
5122         // Skip over the class name if one is there
5123         const char* const p = skip_over_field_name(signature + 1, true, --length);
5124 
5125         // The next character better be a semicolon
5126         if (p && (p - signature) > 1 && p[0] == JVM_SIGNATURE_ENDCLASS) {
5127           return p + 1;
5128         }
5129       }
5130       else {
5131         // Skip leading 'L' or 'Q' and ignore first appearance of ';'
5132         signature++;
5133         const char* c = (const char*) memchr(signature, JVM_SIGNATURE_ENDCLASS, length - 1);
5134         // Format check signature
5135         if (c != NULL) {
5136           int newlen = c - (char*) signature;
5137           bool legal = verify_unqualified_name(signature, newlen, LegalClass);
5138           if (!legal) {
5139             classfile_parse_error("Class name is empty or contains illegal character "
5140                                   "in descriptor in class file %s",
5141                                   THREAD);
5142             return NULL;
5143           }
5144           return signature + newlen + 1;
5145         }
5146       }
5147       return NULL;
5148     }
5149     case JVM_SIGNATURE_ARRAY:
5150       array_dim++;
5151       if (array_dim > 255) {
5152         // 4277370: array descriptor is valid only if it represents 255 or fewer dimensions.
5153         classfile_parse_error("Array type descriptor has more than 255 dimensions in class file %s", THREAD);
5154         return NULL;
5155       }
5156       // The rest of what's there better be a legal signature
5157       signature++;
5158       length--;
5159       void_ok = false;
5160       break;
5161     default:
5162       return NULL;
5163     }
5164   }
5165   return NULL;
5166 }
5167 
5168 // Checks if name is a legal class name.
5169 void ClassFileParser::verify_legal_class_name(const Symbol* name, TRAPS) const {
5170   if (!_need_verify || _relax_verify) { return; }
5171 
5172   assert(name->refcount() > 0, "symbol must be kept alive");
5173   char* bytes = (char*)name->bytes();
5174   unsigned int length = name->utf8_length();
5175   bool legal = false;
5176 
5177   if (length > 0) {
5178     const char* p;
5179     if (bytes[0] == JVM_SIGNATURE_ARRAY) {
5180       p = skip_over_field_signature(bytes, false, length, CHECK);
5181       legal = (p != NULL) && ((p - bytes) == (int)length);
5182     } else if (_major_version < JAVA_1_5_VERSION) {
5183       if (bytes[0] != JVM_SIGNATURE_SPECIAL) {
5184         p = skip_over_field_name(bytes, true, length);
5185         legal = (p != NULL) && ((p - bytes) == (int)length);
5186       }
5187     } else if ((_major_version >= CONSTANT_CLASS_DESCRIPTORS || _class_name->starts_with("jdk/internal/reflect/"))
5188                    && bytes[length - 1] == ';' ) {
5189       // Support for L...; and Q...; descriptors
5190       legal = verify_unqualified_name(bytes + 1, length - 2, LegalClass);
5191     } else {
5192       // 4900761: relax the constraints based on JSR202 spec
5193       // Class names may be drawn from the entire Unicode character set.
5194       // Identifiers between '/' must be unqualified names.
5195       // The utf8 string has been verified when parsing cpool entries.
5196       legal = verify_unqualified_name(bytes, length, LegalClass);
5197     }
5198   }
5199   if (!legal) {
5200     ResourceMark rm(THREAD);
5201     assert(_class_name != NULL, "invariant");
5202     Exceptions::fthrow(
5203       THREAD_AND_LOCATION,
5204       vmSymbols::java_lang_ClassFormatError(),
5205       "Illegal class name \"%.*s\" in class file %s", length, bytes,
5206       _class_name->as_C_string()
5207     );
5208     return;
5209   }
5210 }
5211 
5212 // Checks if name is a legal field name.
5213 void ClassFileParser::verify_legal_field_name(const Symbol* name, TRAPS) const {
5214   if (!_need_verify || _relax_verify) { return; }
5215 
5216   char* bytes = (char*)name->bytes();
5217   unsigned int length = name->utf8_length();
5218   bool legal = false;
5219 
5220   if (length > 0) {
5221     if (_major_version < JAVA_1_5_VERSION) {
5222       if (bytes[0] != JVM_SIGNATURE_SPECIAL) {
5223         const char* p = skip_over_field_name(bytes, false, length);
5224         legal = (p != NULL) && ((p - bytes) == (int)length);
5225       }
5226     } else {
5227       // 4881221: relax the constraints based on JSR202 spec
5228       legal = verify_unqualified_name(bytes, length, LegalField);
5229     }
5230   }
5231 
5232   if (!legal) {
5233     ResourceMark rm(THREAD);
5234     assert(_class_name != NULL, "invariant");
5235     Exceptions::fthrow(
5236       THREAD_AND_LOCATION,
5237       vmSymbols::java_lang_ClassFormatError(),
5238       "Illegal field name \"%.*s\" in class %s", length, bytes,
5239       _class_name->as_C_string()
5240     );
5241     return;
5242   }
5243 }
5244 
5245 // Checks if name is a legal method name.
5246 void ClassFileParser::verify_legal_method_name(const Symbol* name, TRAPS) const {
5247   if (!_need_verify || _relax_verify) { return; }
5248 
5249   assert(name != NULL, "method name is null");
5250   char* bytes = (char*)name->bytes();
5251   unsigned int length = name->utf8_length();
5252   bool legal = false;
5253 
5254   if (length > 0) {
5255     if (bytes[0] == JVM_SIGNATURE_SPECIAL) {
5256       if (name == vmSymbols::object_initializer_name() || name == vmSymbols::class_initializer_name()) {
5257         legal = true;
5258       }
5259     } else if (_major_version < JAVA_1_5_VERSION) {
5260       const char* p;
5261       p = skip_over_field_name(bytes, false, length);
5262       legal = (p != NULL) && ((p - bytes) == (int)length);
5263     } else {
5264       // 4881221: relax the constraints based on JSR202 spec
5265       legal = verify_unqualified_name(bytes, length, LegalMethod);
5266     }
5267   }
5268 
5269   if (!legal) {
5270     ResourceMark rm(THREAD);
5271     assert(_class_name != NULL, "invariant");
5272     Exceptions::fthrow(
5273       THREAD_AND_LOCATION,
5274       vmSymbols::java_lang_ClassFormatError(),
5275       "Illegal method name \"%.*s\" in class %s", length, bytes,
5276       _class_name->as_C_string()
5277     );
5278     return;
5279   }
5280 }
5281 
5282 
5283 // Checks if signature is a legal field signature.
5284 void ClassFileParser::verify_legal_field_signature(const Symbol* name,
5285                                                    const Symbol* signature,
5286                                                    TRAPS) const {
5287   if (!_need_verify) { return; }
5288   if (!supports_inline_types() && (signature->is_Q_signature() || signature->is_Q_array_signature())) {
5289     throwIllegalSignature("Field", name, signature, CHECK);
5290   }
5291 
5292   const char* const bytes = (const char* const)signature->bytes();
5293   const unsigned int length = signature->utf8_length();
5294   const char* const p = skip_over_field_signature(bytes, false, length, CHECK);
5295 
5296   if (p == NULL || (p - bytes) != (int)length) {
5297     throwIllegalSignature("Field", name, signature, CHECK);
5298   }
5299 }
5300 
5301 // Check that the signature is compatible with the method name.  For example,
5302 // check that <init> has a void signature.
5303 void ClassFileParser::verify_legal_name_with_signature(const Symbol* name,
5304                                                        const Symbol* signature,
5305                                                        TRAPS) const {
5306   if (!_need_verify) {
5307     return;
5308   }
5309 
5310   // Class initializers cannot have args for class format version >= 51.
5311   if (name == vmSymbols::class_initializer_name() &&
5312       signature != vmSymbols::void_method_signature() &&
5313       _major_version >= JAVA_7_VERSION) {
5314     throwIllegalSignature("Method", name, signature, THREAD);
5315     return;
5316   }
5317 
5318   if (!is_inline_type()) {
5319     int sig_length = signature->utf8_length();
5320     if (name->utf8_length() > 0 &&
5321       name->char_at(0) == JVM_SIGNATURE_SPECIAL &&
5322       sig_length > 0 &&
5323       signature->char_at(sig_length - 1) != JVM_SIGNATURE_VOID) {
5324       throwIllegalSignature("Method", name, signature, THREAD);
5325     }
5326   }
5327 }
5328 
5329 // Checks if signature is a legal method signature.
5330 // Returns number of parameters
5331 int ClassFileParser::verify_legal_method_signature(const Symbol* name,
5332                                                    const Symbol* signature,
5333                                                    TRAPS) const {
5334   if (!_need_verify) {
5335     // make sure caller's args_size will be less than 0 even for non-static
5336     // method so it will be recomputed in compute_size_of_parameters().
5337     return -2;
5338   }
5339 
5340   unsigned int args_size = 0;
5341   const char* p = (const char*)signature->bytes();
5342   unsigned int length = signature->utf8_length();
5343   const char* nextp;
5344 
5345   // The first character must be a '('
5346   if ((length > 0) && (*p++ == JVM_SIGNATURE_FUNC)) {
5347     length--;
5348     // Skip over legal field signatures
5349     nextp = skip_over_field_signature(p, false, length, CHECK_0);
5350     while ((length > 0) && (nextp != NULL)) {
5351       args_size++;
5352       if (p[0] == 'J' || p[0] == 'D') {
5353         args_size++;
5354       }
5355       length -= nextp - p;
5356       p = nextp;
5357       nextp = skip_over_field_signature(p, false, length, CHECK_0);
5358     }
5359     // The first non-signature thing better be a ')'
5360     if ((length > 0) && (*p++ == JVM_SIGNATURE_ENDFUNC)) {
5361       length--;
5362       // Now we better just have a return value
5363       nextp = skip_over_field_signature(p, true, length, CHECK_0);
5364       if (nextp && ((int)length == (nextp - p))) {
5365         return args_size;
5366       }
5367     }
5368   }
5369   // Report error
5370   throwIllegalSignature("Method", name, signature, THREAD);
5371   return 0;
5372 }
5373 
5374 int ClassFileParser::static_field_size() const {
5375   assert(_field_info != NULL, "invariant");
5376   return _field_info->_static_field_size;
5377 }
5378 
5379 int ClassFileParser::total_oop_map_count() const {
5380   assert(_field_info != NULL, "invariant");
5381   return _field_info->oop_map_blocks->_nonstatic_oop_map_count;
5382 }
5383 
5384 jint ClassFileParser::layout_size() const {
5385   assert(_field_info != NULL, "invariant");
5386   return _field_info->_instance_size;
5387 }
5388 
5389 static void check_methods_for_intrinsics(const InstanceKlass* ik,
5390                                          const Array<Method*>* methods) {
5391   assert(ik != NULL, "invariant");
5392   assert(methods != NULL, "invariant");
5393 
5394   // Set up Method*::intrinsic_id as soon as we know the names of methods.
5395   // (We used to do this lazily, but now we query it in Rewriter,
5396   // which is eagerly done for every method, so we might as well do it now,
5397   // when everything is fresh in memory.)
5398   const vmSymbolID klass_id = Method::klass_id_for_intrinsics(ik);
5399 
5400   if (klass_id != vmSymbolID::NO_SID) {
5401     for (int j = 0; j < methods->length(); ++j) {
5402       Method* method = methods->at(j);
5403       method->init_intrinsic_id(klass_id);
5404 
5405       if (CheckIntrinsics) {
5406         // Check if an intrinsic is defined for method 'method',
5407         // but the method is not annotated with @IntrinsicCandidate.
5408         if (method->intrinsic_id() != vmIntrinsics::_none &&
5409             !method->intrinsic_candidate()) {
5410               tty->print("Compiler intrinsic is defined for method [%s], "
5411               "but the method is not annotated with @IntrinsicCandidate.%s",
5412               method->name_and_sig_as_C_string(),
5413               NOT_DEBUG(" Method will not be inlined.") DEBUG_ONLY(" Exiting.")
5414             );
5415           tty->cr();
5416           DEBUG_ONLY(vm_exit(1));
5417         }
5418         // Check is the method 'method' is annotated with @IntrinsicCandidate,
5419         // but there is no intrinsic available for it.
5420         if (method->intrinsic_candidate() &&
5421           method->intrinsic_id() == vmIntrinsics::_none) {
5422             tty->print("Method [%s] is annotated with @IntrinsicCandidate, "
5423               "but no compiler intrinsic is defined for the method.%s",
5424               method->name_and_sig_as_C_string(),
5425               NOT_DEBUG("") DEBUG_ONLY(" Exiting.")
5426             );
5427           tty->cr();
5428           DEBUG_ONLY(vm_exit(1));
5429         }
5430       }
5431     } // end for
5432 
5433 #ifdef ASSERT
5434     if (CheckIntrinsics) {
5435       // Check for orphan methods in the current class. A method m
5436       // of a class C is orphan if an intrinsic is defined for method m,
5437       // but class C does not declare m.
5438       // The check is potentially expensive, therefore it is available
5439       // only in debug builds.
5440 
5441       for (auto id : EnumRange<vmIntrinsicID>{}) {
5442         if (vmIntrinsics::_compiledLambdaForm == id) {
5443           // The _compiledLamdbdaForm intrinsic is a special marker for bytecode
5444           // generated for the JVM from a LambdaForm and therefore no method
5445           // is defined for it.
5446           continue;
5447         }
5448         if (vmIntrinsics::_blackhole == id) {
5449           // The _blackhole intrinsic is a special marker. No explicit method
5450           // is defined for it.
5451           continue;
5452         }
5453 
5454         if (vmIntrinsics::class_for(id) == klass_id) {
5455           // Check if the current class contains a method with the same
5456           // name, flags, signature.
5457           bool match = false;
5458           for (int j = 0; j < methods->length(); ++j) {
5459             const Method* method = methods->at(j);
5460             if (method->intrinsic_id() == id) {
5461               match = true;
5462               break;
5463             }
5464           }
5465 
5466           if (!match) {
5467             char buf[1000];
5468             tty->print("Compiler intrinsic is defined for method [%s], "
5469                        "but the method is not available in class [%s].%s",
5470                         vmIntrinsics::short_name_as_C_string(id, buf, sizeof(buf)),
5471                         ik->name()->as_C_string(),
5472                         NOT_DEBUG("") DEBUG_ONLY(" Exiting.")
5473             );
5474             tty->cr();
5475             DEBUG_ONLY(vm_exit(1));
5476           }
5477         }
5478       } // end for
5479     } // CheckIntrinsics
5480 #endif // ASSERT
5481   }
5482 }
5483 
5484 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook,
5485                                                       const ClassInstanceInfo& cl_inst_info,
5486                                                       TRAPS) {
5487   if (_klass != NULL) {
5488     return _klass;
5489   }
5490 
5491   InstanceKlass* const ik =
5492     InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
5493 
5494   if (is_hidden()) {
5495     mangle_hidden_class_name(ik);
5496   }
5497 
5498   fill_instance_klass(ik, changed_by_loadhook, cl_inst_info, CHECK_NULL);
5499 
5500   assert(_klass == ik, "invariant");

5501   return ik;
5502 }
5503 
5504 // Return true if the specified class is not a valid super class for an inline type.
5505 // A valid super class for an inline type is abstract, has no instance fields,
5506 // does not implement interface java.lang.IdentityObject (checked elsewhere), has
5507 // an empty body-less no-arg constructor, and no synchronized instance methods.
5508 // This function doesn't check if the class's super types are invalid.  Those checks
5509 // are done elsewhere.  The final determination of whether or not a class is an
5510 // invalid super type for an inline class is done in fill_instance_klass().
5511 bool ClassFileParser::is_invalid_super_for_inline_type() {
5512   if (class_name() == vmSymbols::java_lang_IdentityObject()) {
5513     return true;
5514   }
5515   if (is_interface() || class_name() == vmSymbols::java_lang_Object()) {
5516     return false;
5517   }
5518   if (!access_flags().is_abstract() || _has_nonstatic_fields) {
5519     return true;
5520   } else {
5521     // Look at each method
5522     for (int x = 0; x < _methods->length(); x++) {
5523       const Method* const method = _methods->at(x);
5524       if (method->is_synchronized() && !method->is_static()) {
5525         return true;
5526 
5527       } else if (method->name() == vmSymbols::object_initializer_name()) {
5528         if (method->signature() != vmSymbols::void_method_signature() ||
5529             !method->is_vanilla_constructor()) {
5530           return true;
5531         }
5532       }
5533     }
5534   }
5535   return false;
5536 }
5537 
5538 void ClassFileParser::fill_instance_klass(InstanceKlass* ik,
5539                                           bool changed_by_loadhook,
5540                                           const ClassInstanceInfo& cl_inst_info,
5541                                           TRAPS) {
5542   assert(ik != NULL, "invariant");
5543 
5544   // Set name and CLD before adding to CLD
5545   ik->set_class_loader_data(_loader_data);
5546   ik->set_name(_class_name);
5547 
5548   // Add all classes to our internal class loader list here,
5549   // including classes in the bootstrap (NULL) class loader.
5550   const bool publicize = !is_internal();
5551 
5552   _loader_data->add_class(ik, publicize);
5553 
5554   set_klass_to_deallocate(ik);
5555 
5556   assert(_field_info != NULL, "invariant");
5557   assert(ik->static_field_size() == _field_info->_static_field_size, "sanity");
5558   assert(ik->nonstatic_oop_map_count() == _field_info->oop_map_blocks->_nonstatic_oop_map_count,
5559          "sanity");
5560 
5561   assert(ik->is_instance_klass(), "sanity");
5562   assert(ik->size_helper() == _field_info->_instance_size, "sanity");
5563 
5564   // Fill in information already parsed
5565   ik->set_should_verify_class(_need_verify);
5566 
5567   // Not yet: supers are done below to support the new subtype-checking fields
5568   ik->set_nonstatic_field_size(_field_info->_nonstatic_field_size);
5569   ik->set_has_nonstatic_fields(_field_info->_has_nonstatic_fields);
5570   if (_field_info->_is_naturally_atomic && ik->is_inline_klass()) {
5571     ik->set_is_naturally_atomic();
5572   }
5573 
5574   if (this->_invalid_inline_super) {
5575     ik->set_invalid_inline_super();
5576   }
5577 
5578   if (_has_injected_identityObject) {
5579     ik->set_has_injected_identityObject();
5580   }
5581   if (_has_injected_primitiveObject) {
5582     ik->set_has_injected_primitiveObject();
5583   }
5584 
5585   assert(_fac != NULL, "invariant");
5586   ik->set_static_oop_field_count(_fac->count[STATIC_OOP] + _fac->count[STATIC_INLINE]);
5587 
5588   // this transfers ownership of a lot of arrays from
5589   // the parser onto the InstanceKlass*
5590   apply_parsed_class_metadata(ik, _java_fields_count);
5591 
5592   // can only set dynamic nest-host after static nest information is set
5593   if (cl_inst_info.dynamic_nest_host() != NULL) {
5594     ik->set_nest_host(cl_inst_info.dynamic_nest_host());
5595   }
5596 
5597   // note that is not safe to use the fields in the parser from this point on
5598   assert(NULL == _cp, "invariant");
5599   assert(NULL == _fields, "invariant");
5600   assert(NULL == _methods, "invariant");
5601   assert(NULL == _inner_classes, "invariant");
5602   assert(NULL == _nest_members, "invariant");
5603   assert(NULL == _combined_annotations, "invariant");
5604   assert(NULL == _record_components, "invariant");
5605   assert(NULL == _permitted_subclasses, "invariant");
5606 
5607   if (_has_final_method) {
5608     ik->set_has_final_method();
5609   }
5610 
5611   ik->copy_method_ordering(_method_ordering, CHECK);
5612   // The InstanceKlass::_methods_jmethod_ids cache
5613   // is managed on the assumption that the initial cache
5614   // size is equal to the number of methods in the class. If
5615   // that changes, then InstanceKlass::idnum_can_increment()
5616   // has to be changed accordingly.
5617   ik->set_initial_method_idnum(ik->methods()->length());
5618 
5619   ik->set_this_class_index(_this_class_index);
5620 
5621   if (_is_hidden) {
5622     // _this_class_index is a CONSTANT_Class entry that refers to this
5623     // hidden class itself. If this class needs to refer to its own methods
5624     // or fields, it would use a CONSTANT_MethodRef, etc, which would reference
5625     // _this_class_index. However, because this class is hidden (it's
5626     // not stored in SystemDictionary), _this_class_index cannot be resolved
5627     // with ConstantPool::klass_at_impl, which does a SystemDictionary lookup.
5628     // Therefore, we must eagerly resolve _this_class_index now.
5629     ik->constants()->klass_at_put(_this_class_index, ik);
5630   }
5631 
5632   ik->set_minor_version(_minor_version);
5633   ik->set_major_version(_major_version);
5634   ik->set_has_nonstatic_concrete_methods(_has_nonstatic_concrete_methods);
5635   ik->set_declares_nonstatic_concrete_methods(_declares_nonstatic_concrete_methods);
5636   if (_is_declared_atomic) {
5637     ik->set_is_declared_atomic();
5638   }
5639 
5640   if (_is_hidden) {
5641     ik->set_is_hidden();
5642   }
5643 
5644   // Set PackageEntry for this_klass
5645   oop cl = ik->class_loader();
5646   Handle clh = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(cl));
5647   ClassLoaderData* cld = ClassLoaderData::class_loader_data_or_null(clh());
5648   ik->set_package(cld, NULL, CHECK);
5649 
5650   const Array<Method*>* const methods = ik->methods();
5651   assert(methods != NULL, "invariant");
5652   const int methods_len = methods->length();
5653 
5654   check_methods_for_intrinsics(ik, methods);
5655 
5656   // Fill in field values obtained by parse_classfile_attributes
5657   if (_parsed_annotations->has_any_annotations()) {
5658     _parsed_annotations->apply_to(ik);
5659   }
5660 
5661   apply_parsed_class_attributes(ik);
5662 
5663   // Miranda methods
5664   if ((_num_miranda_methods > 0) ||
5665       // if this class introduced new miranda methods or
5666       (_super_klass != NULL && _super_klass->has_miranda_methods())
5667         // super class exists and this class inherited miranda methods
5668      ) {
5669        ik->set_has_miranda_methods(); // then set a flag
5670   }
5671 
5672   // Fill in information needed to compute superclasses.
5673   ik->initialize_supers(const_cast<InstanceKlass*>(_super_klass), _transitive_interfaces, CHECK);
5674   ik->set_transitive_interfaces(_transitive_interfaces);
5675   ik->set_local_interfaces(_local_interfaces);
5676   _transitive_interfaces = NULL;
5677   _local_interfaces = NULL;
5678 
5679   // Initialize itable offset tables
5680   klassItable::setup_itable_offset_table(ik);
5681 
5682   // Compute transitive closure of interfaces this class implements
5683   // Do final class setup
5684   OopMapBlocksBuilder* oop_map_blocks = _field_info->oop_map_blocks;
5685   if (oop_map_blocks->_nonstatic_oop_map_count > 0) {
5686     oop_map_blocks->copy(ik->start_of_nonstatic_oop_maps());
5687   }
5688 
5689   if (_has_contended_fields || _parsed_annotations->is_contended() ||
5690       ( _super_klass != NULL && _super_klass->has_contended_annotations())) {
5691     ik->set_has_contended_annotations(true);
5692   }
5693 
5694   // Fill in has_finalizer, has_vanilla_constructor, and layout_helper
5695   set_precomputed_flags(ik);
5696 
5697   // check if this class can access its super class
5698   check_super_class_access(ik, CHECK);
5699 
5700   // check if this class can access its superinterfaces
5701   check_super_interface_access(ik, CHECK);
5702 
5703   // check if this class overrides any final method
5704   check_final_method_override(ik, CHECK);
5705 
5706   // reject static interface methods prior to Java 8
5707   if (ik->is_interface() && _major_version < JAVA_8_VERSION) {
5708     check_illegal_static_method(ik, CHECK);
5709   }
5710 
5711   // Obtain this_klass' module entry
5712   ModuleEntry* module_entry = ik->module();
5713   assert(module_entry != NULL, "module_entry should always be set");
5714 
5715   // Obtain java.lang.Module
5716   Handle module_handle(THREAD, module_entry->module());
5717 
5718   // Allocate mirror and initialize static fields
5719   // The create_mirror() call will also call compute_modifiers()
5720   java_lang_Class::create_mirror(ik,
5721                                  Handle(THREAD, _loader_data->class_loader()),
5722                                  module_handle,
5723                                  _protection_domain,
5724                                  cl_inst_info.class_data(),
5725                                  CHECK);
5726 
5727   assert(_all_mirandas != NULL, "invariant");
5728 
5729   // Generate any default methods - default methods are public interface methods
5730   // that have a default implementation.  This is new with Java 8.
5731   if (_has_nonstatic_concrete_methods) {
5732     DefaultMethods::generate_default_methods(ik,
5733                                              _all_mirandas,
5734                                              CHECK);
5735   }
5736 
5737   // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5738   if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5739       !module_entry->has_default_read_edges()) {
5740     if (!module_entry->set_has_default_read_edges()) {
5741       // We won a potential race
5742       JvmtiExport::add_default_read_edges(module_handle, THREAD);
5743     }
5744   }
5745 
5746   bool all_fields_empty = true;
5747   for (AllFieldStream fs(ik->fields(), ik->constants()); !fs.done(); fs.next()) {
5748     if (!fs.access_flags().is_static()) {
5749       if (fs.field_descriptor().is_inline_type()) {
5750         Klass* k = _inline_type_field_klasses->at(fs.index());
5751         ik->set_inline_type_field_klass(fs.index(), k);
5752         if (!InlineKlass::cast(k)->is_empty_inline_type()) { all_fields_empty = false; }
5753       } else {
5754         all_fields_empty = false;
5755       }
5756     } else if (is_inline_type() && (fs.name() == vmSymbols::default_value_name())) {
5757       InlineKlass::cast(ik)->set_default_value_offset(ik->field_offset(fs.index()));
5758     }
5759   }
5760 
5761   if (_is_empty_inline_type || (is_inline_type() && all_fields_empty)) {
5762     ik->set_is_empty_inline_type();
5763   }
5764 
5765   if (is_inline_type()) {
5766     InlineKlass* vk = InlineKlass::cast(ik);
5767     vk->set_alignment(_alignment);
5768     vk->set_first_field_offset(_first_field_offset);
5769     vk->set_exact_size_in_bytes(_exact_size_in_bytes);
5770     InlineKlass::cast(ik)->initialize_calling_convention(CHECK);
5771   }
5772 
5773   ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5774 
5775   if (!is_internal()) {
5776     ik->print_class_load_logging(_loader_data, module_entry, _stream);
5777 
5778     if (ik->minor_version() == JAVA_PREVIEW_MINOR_VERSION &&
5779         ik->major_version() == JVM_CLASSFILE_MAJOR_VERSION &&
5780         log_is_enabled(Info, class, preview)) {
5781       ResourceMark rm;
5782       log_info(class, preview)("Loading class %s that depends on preview features (class file version %d.65535)",
5783                                ik->external_name(), JVM_CLASSFILE_MAJOR_VERSION);
5784     }
5785 
5786     if (log_is_enabled(Debug, class, resolve))  {
5787       ResourceMark rm;
5788       // print out the superclass.
5789       const char * from = ik->external_name();
5790       if (ik->java_super() != NULL) {
5791         log_debug(class, resolve)("%s %s (super)",
5792                    from,
5793                    ik->java_super()->external_name());
5794       }
5795       // print out each of the interface classes referred to by this class.
5796       const Array<InstanceKlass*>* const local_interfaces = ik->local_interfaces();
5797       if (local_interfaces != NULL) {
5798         const int length = local_interfaces->length();
5799         for (int i = 0; i < length; i++) {
5800           const InstanceKlass* const k = local_interfaces->at(i);
5801           const char * to = k->external_name();
5802           log_debug(class, resolve)("%s %s (interface)", from, to);
5803         }
5804       }
5805     }
5806   }
5807 
5808   JFR_ONLY(INIT_ID(ik);)
5809 
5810   // If we reach here, all is well.
5811   // Now remove the InstanceKlass* from the _klass_to_deallocate field
5812   // in order for it to not be destroyed in the ClassFileParser destructor.
5813   set_klass_to_deallocate(NULL);
5814 
5815   // it's official
5816   set_klass(ik);
5817 
5818   // the common single interface arrays need setup here to provide the
5819   // correct answer to "compute_transitive_interfaces()", during
5820   // "SystemDictionary::initialize()"
5821   if (ik->name() == vmSymbols::java_lang_IdentityObject()) {
5822     Universe::initialize_the_single_IdentityObject_klass_array(ik, CHECK);
5823   }
5824   if (ik->name() == vmSymbols::java_lang_PrimitiveObject()) {
5825     Universe::initialize_the_single_PrimitiveObject_klass_array(ik, CHECK);
5826   }
5827 
5828   debug_only(ik->verify();)
5829 }
5830 
5831 void ClassFileParser::update_class_name(Symbol* new_class_name) {
5832   // Decrement the refcount in the old name, since we're clobbering it.
5833   _class_name->decrement_refcount();
5834 
5835   _class_name = new_class_name;
5836   // Increment the refcount of the new name.
5837   // Now the ClassFileParser owns this name and will decrement in
5838   // the destructor.
5839   _class_name->increment_refcount();
5840 }
5841 
5842 static bool relax_format_check_for(ClassLoaderData* loader_data) {
5843   bool trusted = loader_data->is_boot_class_loader_data() ||
5844                  loader_data->is_platform_class_loader_data();
5845   bool need_verify =
5846     // verifyAll
5847     (BytecodeVerificationLocal && BytecodeVerificationRemote) ||
5848     // verifyRemote
5849     (!BytecodeVerificationLocal && BytecodeVerificationRemote && !trusted);
5850   return !need_verify;
5851 }
5852 
5853 ClassFileParser::ClassFileParser(ClassFileStream* stream,
5854                                  Symbol* name,
5855                                  ClassLoaderData* loader_data,
5856                                  const ClassLoadInfo* cl_info,
5857                                  Publicity pub_level,
5858                                  TRAPS) :
5859   _stream(stream),
5860   _class_name(NULL),
5861   _loader_data(loader_data),
5862   _is_hidden(cl_info->is_hidden()),
5863   _can_access_vm_annotations(cl_info->can_access_vm_annotations()),
5864   _orig_cp_size(0),
5865   _super_klass(),
5866   _cp(NULL),
5867   _fields(NULL),
5868   _methods(NULL),
5869   _inner_classes(NULL),
5870   _nest_members(NULL),
5871   _nest_host(0),
5872   _permitted_subclasses(NULL),
5873   _record_components(NULL),
5874   _temp_local_interfaces(NULL),
5875   _local_interfaces(NULL),
5876   _transitive_interfaces(NULL),
5877   _combined_annotations(NULL),
5878   _class_annotations(NULL),
5879   _class_type_annotations(NULL),
5880   _fields_annotations(NULL),
5881   _fields_type_annotations(NULL),
5882   _klass(NULL),
5883   _klass_to_deallocate(NULL),
5884   _parsed_annotations(NULL),
5885   _fac(NULL),
5886   _field_info(NULL),
5887   _inline_type_field_klasses(NULL),
5888   _method_ordering(NULL),
5889   _all_mirandas(NULL),
5890   _vtable_size(0),
5891   _itable_size(0),
5892   _num_miranda_methods(0),
5893   _rt(REF_NONE),
5894   _protection_domain(cl_info->protection_domain()),
5895   _access_flags(),
5896   _pub_level(pub_level),
5897   _bad_constant_seen(0),
5898   _synthetic_flag(false),
5899   _sde_length(false),
5900   _sde_buffer(NULL),
5901   _sourcefile_index(0),
5902   _generic_signature_index(0),
5903   _major_version(0),
5904   _minor_version(0),
5905   _this_class_index(0),
5906   _super_class_index(0),
5907   _itfs_len(0),
5908   _java_fields_count(0),
5909   _need_verify(false),
5910   _relax_verify(false),
5911   _has_nonstatic_concrete_methods(false),
5912   _declares_nonstatic_concrete_methods(false),
5913   _has_final_method(false),
5914   _has_contended_fields(false),
5915   _has_inline_type_fields(false),
5916   _has_nonstatic_fields(false),
5917   _is_empty_inline_type(false),
5918   _is_naturally_atomic(false),
5919   _is_declared_atomic(false),
5920   _invalid_inline_super(false),
5921   _invalid_identity_super(false),
5922   _implements_identityObject(false),
5923   _has_injected_identityObject(false),
5924   _implements_primitiveObject(false),
5925   _has_injected_primitiveObject(false),
5926   _has_finalizer(false),
5927   _has_empty_finalizer(false),
5928   _has_vanilla_constructor(false),
5929   _max_bootstrap_specifier_index(-1) {
5930 
5931   _class_name = name != NULL ? name : vmSymbols::unknown_class_name();
5932   _class_name->increment_refcount();
5933 
5934   assert(_loader_data != NULL, "invariant");
5935   assert(stream != NULL, "invariant");
5936   assert(_stream != NULL, "invariant");
5937   assert(_stream->buffer() == _stream->current(), "invariant");
5938   assert(_class_name != NULL, "invariant");
5939   assert(0 == _access_flags.as_int(), "invariant");
5940 
5941   // Figure out whether we can skip format checking (matching classic VM behavior)
5942   if (DumpSharedSpaces) {
5943     // verify == true means it's a 'remote' class (i.e., non-boot class)
5944     // Verification decision is based on BytecodeVerificationRemote flag
5945     // for those classes.
5946     _need_verify = (stream->need_verify()) ? BytecodeVerificationRemote :
5947                                               BytecodeVerificationLocal;
5948   }
5949   else {
5950     _need_verify = Verifier::should_verify_for(_loader_data->class_loader(),
5951                                                stream->need_verify());
5952   }
5953 
5954   // synch back verification state to stream
5955   stream->set_verify(_need_verify);
5956 
5957   // Check if verification needs to be relaxed for this class file
5958   // Do not restrict it to jdk1.0 or jdk1.1 to maintain backward compatibility (4982376)
5959   _relax_verify = relax_format_check_for(_loader_data);
5960 
5961   parse_stream(stream, CHECK);
5962 
5963   post_process_parsed_stream(stream, _cp, CHECK);
5964 }
5965 
5966 void ClassFileParser::clear_class_metadata() {
5967   // metadata created before the instance klass is created.  Must be
5968   // deallocated if classfile parsing returns an error.
5969   _cp = NULL;
5970   _fields = NULL;
5971   _methods = NULL;
5972   _inner_classes = NULL;
5973   _nest_members = NULL;
5974   _permitted_subclasses = NULL;
5975   _combined_annotations = NULL;
5976   _class_annotations = _class_type_annotations = NULL;
5977   _fields_annotations = _fields_type_annotations = NULL;
5978   _record_components = NULL;
5979 }
5980 
5981 // Destructor to clean up
5982 ClassFileParser::~ClassFileParser() {
5983   _class_name->decrement_refcount();
5984 
5985   if (_cp != NULL) {
5986     MetadataFactory::free_metadata(_loader_data, _cp);
5987   }
5988   if (_fields != NULL) {
5989     MetadataFactory::free_array<u2>(_loader_data, _fields);
5990   }
5991 
5992   if (_inline_type_field_klasses != NULL) {
5993      MetadataFactory::free_array<InlineKlass*>(_loader_data, _inline_type_field_klasses);
5994   }
5995 
5996   if (_methods != NULL) {
5997     // Free methods
5998     InstanceKlass::deallocate_methods(_loader_data, _methods);
5999   }
6000 
6001   // beware of the Universe::empty_blah_array!!
6002   if (_inner_classes != NULL && _inner_classes != Universe::the_empty_short_array()) {
6003     MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
6004   }
6005 
6006   if (_nest_members != NULL && _nest_members != Universe::the_empty_short_array()) {
6007     MetadataFactory::free_array<u2>(_loader_data, _nest_members);
6008   }
6009 
6010   if (_record_components != NULL) {
6011     InstanceKlass::deallocate_record_components(_loader_data, _record_components);
6012   }
6013 
6014   if (_permitted_subclasses != NULL && _permitted_subclasses != Universe::the_empty_short_array()) {
6015     MetadataFactory::free_array<u2>(_loader_data, _permitted_subclasses);
6016   }
6017 
6018   // Free interfaces
6019   InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
6020                                        _local_interfaces, _transitive_interfaces);
6021 
6022   if (_combined_annotations != NULL) {
6023     // After all annotations arrays have been created, they are installed into the
6024     // Annotations object that will be assigned to the InstanceKlass being created.
6025 
6026     // Deallocate the Annotations object and the installed annotations arrays.
6027     _combined_annotations->deallocate_contents(_loader_data);
6028 
6029     // If the _combined_annotations pointer is non-NULL,
6030     // then the other annotations fields should have been cleared.
6031     assert(_class_annotations       == NULL, "Should have been cleared");
6032     assert(_class_type_annotations  == NULL, "Should have been cleared");
6033     assert(_fields_annotations      == NULL, "Should have been cleared");
6034     assert(_fields_type_annotations == NULL, "Should have been cleared");
6035   } else {
6036     // If the annotations arrays were not installed into the Annotations object,
6037     // then they have to be deallocated explicitly.
6038     MetadataFactory::free_array<u1>(_loader_data, _class_annotations);
6039     MetadataFactory::free_array<u1>(_loader_data, _class_type_annotations);
6040     Annotations::free_contents(_loader_data, _fields_annotations);
6041     Annotations::free_contents(_loader_data, _fields_type_annotations);
6042   }
6043 
6044   clear_class_metadata();
6045   _transitive_interfaces = NULL;
6046   _local_interfaces = NULL;
6047 
6048   // deallocate the klass if already created.  Don't directly deallocate, but add
6049   // to the deallocate list so that the klass is removed from the CLD::_klasses list
6050   // at a safepoint.
6051   if (_klass_to_deallocate != NULL) {
6052     _loader_data->add_to_deallocate_list(_klass_to_deallocate);
6053   }
6054 }
6055 
6056 void ClassFileParser::parse_stream(const ClassFileStream* const stream,
6057                                    TRAPS) {
6058 
6059   assert(stream != NULL, "invariant");
6060   assert(_class_name != NULL, "invariant");
6061 
6062   // BEGIN STREAM PARSING
6063   stream->guarantee_more(8, CHECK);  // magic, major, minor
6064   // Magic value
6065   const u4 magic = stream->get_u4_fast();
6066   guarantee_property(magic == JAVA_CLASSFILE_MAGIC,
6067                      "Incompatible magic value %u in class file %s",
6068                      magic, CHECK);
6069 
6070   // Version numbers
6071   _minor_version = stream->get_u2_fast();
6072   _major_version = stream->get_u2_fast();
6073 
6074   // Check version numbers - we check this even with verifier off
6075   verify_class_version(_major_version, _minor_version, _class_name, CHECK);
6076 
6077   stream->guarantee_more(3, CHECK); // length, first cp tag
6078   u2 cp_size = stream->get_u2_fast();
6079 
6080   guarantee_property(
6081     cp_size >= 1, "Illegal constant pool size %u in class file %s",
6082     cp_size, CHECK);
6083 
6084   _orig_cp_size = cp_size;
6085   if (is_hidden()) { // Add a slot for hidden class name.
6086     cp_size++;
6087   }
6088 
6089   _cp = ConstantPool::allocate(_loader_data,
6090                                cp_size,
6091                                CHECK);
6092 
6093   ConstantPool* const cp = _cp;
6094 
6095   parse_constant_pool(stream, cp, _orig_cp_size, CHECK);
6096 
6097   assert(cp_size == (const u2)cp->length(), "invariant");
6098 
6099   // ACCESS FLAGS
6100   stream->guarantee_more(8, CHECK);  // flags, this_class, super_class, infs_len
6101 
6102   jint recognized_modifiers = JVM_RECOGNIZED_CLASS_MODIFIERS;

6103   // JVM_ACC_MODULE is defined in JDK-9 and later.
6104   if (_major_version >= JAVA_9_VERSION) {
6105     recognized_modifiers |= JVM_ACC_MODULE;
6106   }
6107   // JVM_ACC_INLINE is defined for class file version 55 and later
6108   if (supports_inline_types()) {
6109     recognized_modifiers |= JVM_ACC_INLINE;
6110   }
6111 
6112   // Access flags
6113   jint flags = stream->get_u2_fast() & recognized_modifiers;
6114 
6115   if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
6116     // Set abstract bit for old class files for backward compatibility
6117     flags |= JVM_ACC_ABSTRACT;
6118   }
6119 
6120   verify_legal_class_modifiers(flags, CHECK);
6121 
6122   short bad_constant = class_bad_constant_seen();
6123   if (bad_constant != 0) {
6124     // Do not throw CFE until after the access_flags are checked because if
6125     // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
6126     classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, THREAD);
6127     return;
6128   }
6129 
6130   _access_flags.set_flags(flags);
6131 
6132   // This class and superclass
6133   _this_class_index = stream->get_u2_fast();
6134   check_property(
6135     valid_cp_range(_this_class_index, cp_size) &&
6136       cp->tag_at(_this_class_index).is_unresolved_klass(),
6137     "Invalid this class index %u in constant pool in class file %s",
6138     _this_class_index, CHECK);
6139 
6140   Symbol* const class_name_in_cp = cp->klass_name_at(_this_class_index);
6141   assert(class_name_in_cp != NULL, "class_name can't be null");
6142 
6143   // Don't need to check whether this class name is legal or not.
6144   // It has been checked when constant pool is parsed.
6145   // However, make sure it is not an array type.
6146   if (_need_verify) {
6147     guarantee_property(class_name_in_cp->char_at(0) != JVM_SIGNATURE_ARRAY,
6148                        "Bad class name in class file %s",
6149                        CHECK);
6150   }
6151 
6152 #ifdef ASSERT
6153   // Basic sanity checks
6154   if (_is_hidden) {
6155     assert(_class_name != vmSymbols::unknown_class_name(), "hidden classes should have a special name");
6156   }
6157 #endif
6158 
6159   // Update the _class_name as needed depending on whether this is a named, un-named, or hidden class.
6160 
6161   if (_is_hidden) {
6162     assert(_class_name != NULL, "Unexpected null _class_name");
6163 #ifdef ASSERT
6164     if (_need_verify) {
6165       verify_legal_class_name(_class_name, CHECK);
6166     }
6167 #endif
6168 
6169   } else {
6170     // Check if name in class file matches given name
6171     if (_class_name != class_name_in_cp) {
6172       if (_class_name != vmSymbols::unknown_class_name()) {
6173         ResourceMark rm(THREAD);
6174         Exceptions::fthrow(THREAD_AND_LOCATION,
6175                            vmSymbols::java_lang_NoClassDefFoundError(),
6176                            "%s (wrong name: %s)",
6177                            class_name_in_cp->as_C_string(),
6178                            _class_name->as_C_string()
6179                            );
6180         return;
6181       } else {
6182         // The class name was not known by the caller so we set it from
6183         // the value in the CP.
6184         update_class_name(class_name_in_cp);
6185       }
6186       // else nothing to do: the expected class name matches what is in the CP
6187     }
6188   }
6189 
6190   // Verification prevents us from creating names with dots in them, this
6191   // asserts that that's the case.
6192   assert(is_internal_format(_class_name), "external class name format used internally");
6193 
6194   if (!is_internal()) {
6195     LogTarget(Debug, class, preorder) lt;
6196     if (lt.is_enabled()){
6197       ResourceMark rm(THREAD);
6198       LogStream ls(lt);
6199       ls.print("%s", _class_name->as_klass_external_name());
6200       if (stream->source() != NULL) {
6201         ls.print(" source: %s", stream->source());
6202       }
6203       ls.cr();
6204     }
6205   }
6206 
6207   // SUPERKLASS
6208   _super_class_index = stream->get_u2_fast();
6209   _super_klass = parse_super_class(cp,
6210                                    _super_class_index,
6211                                    _need_verify,
6212                                    CHECK);
6213 
6214   // Interfaces
6215   _itfs_len = stream->get_u2_fast();
6216   parse_interfaces(stream,
6217                    _itfs_len,
6218                    cp,
6219                    &_has_nonstatic_concrete_methods,
6220                    &_is_declared_atomic,
6221                    CHECK);
6222 
6223   assert(_temp_local_interfaces != NULL, "invariant");
6224 
6225   // Fields (offsets are filled in later)
6226   _fac = new FieldAllocationCount();
6227   parse_fields(stream,
6228                is_interface(),
6229                is_inline_type(),
6230                _fac,
6231                cp,
6232                cp_size,
6233                &_java_fields_count,
6234                CHECK);
6235 
6236   assert(_fields != NULL, "invariant");
6237 
6238   // Methods
6239   AccessFlags promoted_flags;
6240   parse_methods(stream,
6241                 is_interface(),
6242                 is_inline_type(),
6243                 &promoted_flags,
6244                 &_has_final_method,
6245                 &_declares_nonstatic_concrete_methods,
6246                 CHECK);
6247 
6248   assert(_methods != NULL, "invariant");
6249 
6250   // promote flags from parse_methods() to the klass' flags
6251   _access_flags.add_promoted_flags(promoted_flags.as_int());
6252 
6253   if (_declares_nonstatic_concrete_methods) {
6254     _has_nonstatic_concrete_methods = true;
6255   }
6256 
6257   // Additional attributes/annotations
6258   _parsed_annotations = new ClassAnnotationCollector();
6259   parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK);
6260 
6261   assert(_inner_classes != NULL, "invariant");
6262 
6263   // Finalize the Annotations metadata object,
6264   // now that all annotation arrays have been created.
6265   create_combined_annotations(CHECK);
6266 
6267   // Make sure this is the end of class file stream
6268   guarantee_property(stream->at_eos(),
6269                      "Extra bytes at the end of class file %s",
6270                      CHECK);
6271 
6272   // all bytes in stream read and parsed
6273 }
6274 
6275 void ClassFileParser::mangle_hidden_class_name(InstanceKlass* const ik) {
6276   ResourceMark rm;
6277   // Construct hidden name from _class_name, "+", and &ik. Note that we can't
6278   // use a '/' because that confuses finding the class's package.  Also, can't
6279   // use an illegal char such as ';' because that causes serialization issues
6280   // and issues with hidden classes that create their own hidden classes.
6281   char addr_buf[20];
6282   if (DumpSharedSpaces) {
6283     // We want stable names for the archived hidden classes (only for static
6284     // archive for now). Spaces under default_SharedBaseAddress() will be
6285     // occupied by the archive at run time, so we know that no dynamically
6286     // loaded InstanceKlass will be placed under there.
6287     static volatile size_t counter = 0;
6288     Atomic::cmpxchg(&counter, (size_t)0, Arguments::default_SharedBaseAddress()); // initialize it
6289     size_t new_id = Atomic::add(&counter, (size_t)1);
6290     jio_snprintf(addr_buf, 20, SIZE_FORMAT_HEX, new_id);
6291   } else {
6292     jio_snprintf(addr_buf, 20, INTPTR_FORMAT, p2i(ik));
6293   }
6294   size_t new_name_len = _class_name->utf8_length() + 2 + strlen(addr_buf);
6295   char* new_name = NEW_RESOURCE_ARRAY(char, new_name_len);
6296   jio_snprintf(new_name, new_name_len, "%s+%s",
6297                _class_name->as_C_string(), addr_buf);
6298   update_class_name(SymbolTable::new_symbol(new_name));
6299 
6300   // Add a Utf8 entry containing the hidden name.
6301   assert(_class_name != NULL, "Unexpected null _class_name");
6302   int hidden_index = _orig_cp_size; // this is an extra slot we added
6303   _cp->symbol_at_put(hidden_index, _class_name);
6304 
6305   // Update this_class_index's slot in the constant pool with the new Utf8 entry.
6306   // We have to update the resolved_klass_index and the name_index together
6307   // so extract the existing resolved_klass_index first.
6308   CPKlassSlot cp_klass_slot = _cp->klass_slot_at(_this_class_index);
6309   int resolved_klass_index = cp_klass_slot.resolved_klass_index();
6310   _cp->unresolved_klass_at_put(_this_class_index, hidden_index, resolved_klass_index);
6311   assert(_cp->klass_slot_at(_this_class_index).name_index() == _orig_cp_size,
6312          "Bad name_index");
6313 }
6314 
6315 void ClassFileParser::post_process_parsed_stream(const ClassFileStream* const stream,
6316                                                  ConstantPool* cp,
6317                                                  TRAPS) {
6318   assert(stream != NULL, "invariant");
6319   assert(stream->at_eos(), "invariant");
6320   assert(cp != NULL, "invariant");
6321   assert(_loader_data != NULL, "invariant");
6322 
6323   if (_class_name == vmSymbols::java_lang_Object()) {
6324     check_property(_temp_local_interfaces->length() == 0,
6325         "java.lang.Object cannot implement an interface in class file %s",
6326         CHECK);
6327   }
6328   // We check super class after class file is parsed and format is checked
6329   if (_super_class_index > 0 && NULL == _super_klass) {
6330     Symbol* const super_class_name = cp->klass_name_at(_super_class_index);
6331     if (is_interface()) {
6332       // Before attempting to resolve the superclass, check for class format
6333       // errors not checked yet.
6334       guarantee_property(super_class_name == vmSymbols::java_lang_Object(),
6335         "Interfaces must have java.lang.Object as superclass in class file %s",
6336         CHECK);
6337     }
6338     Handle loader(THREAD, _loader_data->class_loader());
6339     _super_klass = (const InstanceKlass*)
6340                        SystemDictionary::resolve_super_or_fail(_class_name,
6341                                                                super_class_name,
6342                                                                loader,
6343                                                                _protection_domain,
6344                                                                true,
6345                                                                CHECK);
6346   }
6347 
6348   if (_super_klass != NULL) {
6349     if (_super_klass->has_nonstatic_concrete_methods()) {
6350       _has_nonstatic_concrete_methods = true;
6351     }
6352     if (_super_klass->is_declared_atomic()) {
6353       _is_declared_atomic = true;
6354     }
6355 
6356     if (_super_klass->is_interface()) {
6357       classfile_icce_error("class %s has interface %s as super class", _super_klass, THREAD);
6358       return;
6359     }
6360 
6361     // For an inline class, only java/lang/Object or special abstract classes
6362     // are acceptable super classes.
6363     if (is_inline_type()) {
6364       const InstanceKlass* super_ik = _super_klass;
6365       if (super_ik->invalid_inline_super()) {
6366         classfile_icce_error("inline class %s has an invalid super class %s", _super_klass, THREAD);
6367         return;
6368       }
6369     }
6370   }
6371 
6372   if (_class_name == vmSymbols::java_lang_NonTearable() && _loader_data->class_loader() == NULL) {
6373     // This is the original source of this condition.
6374     // It propagates by inheritance, as if testing "instanceof NonTearable".
6375     _is_declared_atomic = true;
6376   } else if (*ForceNonTearable != '\0') {
6377     // Allow a command line switch to force the same atomicity property:
6378     const char* class_name_str = _class_name->as_C_string();
6379     if (StringUtils::class_list_match(ForceNonTearable, class_name_str)) {
6380       _is_declared_atomic = true;
6381     }
6382   }
6383 
6384   // Set ik->invalid_inline_super field to TRUE if already marked as invalid,
6385   // if super is marked invalid, or if is_invalid_super_for_inline_type()
6386   // returns true
6387   if (invalid_inline_super() ||
6388       (_super_klass != NULL && _super_klass->invalid_inline_super()) ||
6389       is_invalid_super_for_inline_type()) {
6390     set_invalid_inline_super();
6391   }
6392 
6393   if (EnableValhalla && !is_inline_type() && invalid_inline_super() && (_super_klass == NULL || !_super_klass->invalid_inline_super())
6394       && !_implements_identityObject && class_name() != vmSymbols::java_lang_IdentityObject()) {
6395     _temp_local_interfaces->append(vmClasses::IdentityObject_klass());
6396     _has_injected_identityObject = true;
6397   }
6398   // Check if declared as PrimitiveObject...else add if needed
6399   if (_implements_primitiveObject) {
6400     if (!is_inline_type() && invalid_inline_super()) {
6401       classfile_icce_error("class %s can not implement %s, neither valid inline classes or valid supertype",
6402                             vmClasses::PrimitiveObject_klass(), THREAD);
6403       return;
6404     }
6405   } else if (is_inline_type()) {
6406     _temp_local_interfaces->append(vmClasses::PrimitiveObject_klass());
6407     _has_injected_primitiveObject = true;
6408   }
6409 
6410   int itfs_len = _temp_local_interfaces->length();
6411   if (itfs_len == 0) {
6412     _local_interfaces = Universe::the_empty_instance_klass_array();
6413   } else if (itfs_len == 1 && _temp_local_interfaces->at(0) == vmClasses::IdentityObject_klass()) {
6414     _local_interfaces = Universe::the_single_IdentityObject_klass_array();
6415   } else if (itfs_len == 1 && _temp_local_interfaces->at(0) == vmClasses::PrimitiveObject_klass()) {
6416     _local_interfaces = Universe::the_single_PrimitiveObject_klass_array();
6417   } else {
6418     _local_interfaces = MetadataFactory::new_array<InstanceKlass*>(_loader_data, itfs_len, NULL, CHECK);
6419     for (int i = 0; i < itfs_len; i++) {
6420       _local_interfaces->at_put(i, _temp_local_interfaces->at(i));
6421     }
6422   }
6423   _temp_local_interfaces = NULL;
6424   assert(_local_interfaces != NULL, "invariant");
6425 
6426   // Compute the transitive list of all unique interfaces implemented by this class
6427   _transitive_interfaces =
6428     compute_transitive_interfaces(_super_klass,
6429                                   _local_interfaces,
6430                                   _loader_data,
6431                                   CHECK);
6432 
6433   assert(_transitive_interfaces != NULL, "invariant");
6434 
6435   // sort methods
6436   _method_ordering = sort_methods(_methods);
6437 
6438   _all_mirandas = new GrowableArray<Method*>(20);
6439 
6440   Handle loader(THREAD, _loader_data->class_loader());
6441   klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
6442                                                     &_num_miranda_methods,
6443                                                     _all_mirandas,
6444                                                     _super_klass,
6445                                                     _methods,
6446                                                     _access_flags,
6447                                                     _major_version,
6448                                                     loader,
6449                                                     _class_name,
6450                                                     _local_interfaces);
6451 
6452   // Size of Java itable (in words)
6453   _itable_size = is_interface() ? 0 :
6454     klassItable::compute_itable_size(_transitive_interfaces);
6455 
6456   assert(_fac != NULL, "invariant");
6457   assert(_parsed_annotations != NULL, "invariant");
6458 
6459 
6460   if (EnableValhalla) {
6461     _inline_type_field_klasses = MetadataFactory::new_array<InlineKlass*>(_loader_data,
6462                                                    java_fields_count(),
6463                                                    NULL,
6464                                                    CHECK);
6465     for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
6466       if (Signature::basic_type(fs.signature()) == T_INLINE_TYPE && !fs.access_flags().is_static()) {
6467         // Pre-load inline class
6468         Klass* klass = SystemDictionary::resolve_inline_type_field_or_fail(&fs,
6469             Handle(THREAD, _loader_data->class_loader()),
6470             _protection_domain, true, CHECK);
6471         assert(klass != NULL, "Sanity check");
6472         if (!klass->access_flags().is_inline_type()) {
6473           assert(klass->is_instance_klass(), "Sanity check");
6474           ResourceMark rm(THREAD);
6475             THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
6476                       err_msg("Class %s expects class %s to be an inline type, but it is not",
6477                       _class_name->as_C_string(),
6478                       InstanceKlass::cast(klass)->external_name()));
6479         }
6480         _inline_type_field_klasses->at_put(fs.index(), InlineKlass::cast(klass));
6481       }
6482     }
6483   }
6484 
6485   _field_info = new FieldLayoutInfo();
6486   FieldLayoutBuilder lb(class_name(), super_klass(), _cp, _fields,
6487       _parsed_annotations->is_contended(), is_inline_type(),
6488       _field_info, _inline_type_field_klasses);
6489   lb.build_layout(CHECK);
6490   if (is_inline_type()) {
6491     _alignment = lb.get_alignment();
6492     _first_field_offset = lb.get_first_field_offset();
6493     _exact_size_in_bytes = lb.get_exact_size_in_byte();
6494   }
6495   _has_inline_type_fields = _field_info->_has_inline_fields;
6496 
6497   // Compute reference type
6498   _rt = (NULL ==_super_klass) ? REF_NONE : _super_klass->reference_type();

6499 }
6500 
6501 void ClassFileParser::set_klass(InstanceKlass* klass) {
6502 
6503 #ifdef ASSERT
6504   if (klass != NULL) {
6505     assert(NULL == _klass, "leaking?");
6506   }
6507 #endif
6508 
6509   _klass = klass;
6510 }
6511 
6512 void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) {
6513 
6514 #ifdef ASSERT
6515   if (klass != NULL) {
6516     assert(NULL == _klass_to_deallocate, "leaking?");
6517   }
6518 #endif
6519 
6520   _klass_to_deallocate = klass;
6521 }
6522 
6523 // Caller responsible for ResourceMark
6524 // clone stream with rewound position
6525 const ClassFileStream* ClassFileParser::clone_stream() const {
6526   assert(_stream != NULL, "invariant");
6527 
6528   return _stream->clone();
6529 }
6530 
6531 // ----------------------------------------------------------------------------
6532 // debugging
6533 
6534 #ifdef ASSERT
6535 
6536 // return true if class_name contains no '.' (internal format is '/')
6537 bool ClassFileParser::is_internal_format(Symbol* class_name) {
6538   if (class_name != NULL) {
6539     ResourceMark rm;
6540     char* name = class_name->as_C_string();
6541     return strchr(name, JVM_SIGNATURE_DOT) == NULL;
6542   } else {
6543     return true;
6544   }
6545 }
6546 
6547 #endif
--- EOF ---