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