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