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