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