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