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