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