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