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