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