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