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