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 ? 2 : 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   int instance_fields_count = 0;
1580   for (int n = 0; n < length; n++) {
1581     // access_flags, name_index, descriptor_index, attributes_count
1582     cfs->guarantee_more(8, CHECK);
1583 
1584     jint recognized_modifiers = JVM_RECOGNIZED_FIELD_MODIFIERS;
1585 
1586     const jint flags = cfs->get_u2_fast() & recognized_modifiers;
1587     verify_legal_field_modifiers(flags, is_interface, is_value_type, CHECK);
1588     AccessFlags access_flags;
1589     access_flags.set_flags(flags);
1590 
1591     const u2 name_index = cfs->get_u2_fast();
1592     check_property(valid_symbol_at(name_index),
1593       "Invalid constant pool index %u for field name in class file %s",
1594       name_index, CHECK);
1595     const Symbol* const name = cp->symbol_at(name_index);
1596     verify_legal_field_name(name, CHECK);
1597 
1598     const u2 signature_index = cfs->get_u2_fast();
1599     check_property(valid_symbol_at(signature_index),
1600       "Invalid constant pool index %u for field signature in class file %s",
1601       signature_index, CHECK);
1602     const Symbol* const sig = cp->symbol_at(signature_index);
1603     verify_legal_field_signature(name, sig, CHECK);
1604     assert(!access_flags.is_flattenable(), "ACC_FLATTENABLE should have been filtered out");
1605     if (sig->is_Q_signature()) {
1606       // assert(_major_version >= CONSTANT_CLASS_DESCRIPTORS, "Q-descriptors are only supported in recent classfiles");
1607       access_flags.set_is_flattenable();
1608     }
1609     if (access_flags.is_flattenable()) {
1610       // Array flattenability cannot be specified.  Arrays of value classes are
1611       // are always flattenable.  Arrays of other classes are not flattenable.
1612       if (sig->utf8_length() > 1 && sig->char_at(0) == '[') {
1613         classfile_parse_error(
1614             "Field \"%s\" with signature \"%s\" in class file %s is invalid."
1615             " ACC_FLATTENABLE cannot be specified for an array",
1616             name->as_C_string(), sig->as_klass_external_name(), CHECK);
1617       }
1618       _has_flattenable_fields = true;
1619     }
1620     if (!access_flags.is_static()) instance_fields_count++;
1621 
1622     u2 constantvalue_index = 0;
1623     bool is_synthetic = false;
1624     u2 generic_signature_index = 0;
1625     const bool is_static = access_flags.is_static();
1626     FieldAnnotationCollector parsed_annotations(_loader_data);
1627 
1628     const u2 attributes_count = cfs->get_u2_fast();
1629     if (attributes_count > 0) {
1630       parse_field_attributes(cfs,
1631                              attributes_count,
1632                              is_static,
1633                              signature_index,
1634                              &constantvalue_index,
1635                              &is_synthetic,
1636                              &generic_signature_index,
1637                              &parsed_annotations,
1638                              CHECK);
1639 
1640       if (parsed_annotations.field_annotations() != NULL) {
1641         if (_fields_annotations == NULL) {
1642           _fields_annotations = MetadataFactory::new_array<AnnotationArray*>(
1643                                              _loader_data, length, NULL,
1644                                              CHECK);
1645         }
1646         _fields_annotations->at_put(n, parsed_annotations.field_annotations());
1647         parsed_annotations.set_field_annotations(NULL);
1648       }
1649       if (parsed_annotations.field_type_annotations() != NULL) {
1650         if (_fields_type_annotations == NULL) {
1651           _fields_type_annotations =
1652             MetadataFactory::new_array<AnnotationArray*>(_loader_data,
1653                                                          length,
1654                                                          NULL,
1655                                                          CHECK);
1656         }
1657         _fields_type_annotations->at_put(n, parsed_annotations.field_type_annotations());
1658         parsed_annotations.set_field_type_annotations(NULL);
1659       }
1660 
1661       if (is_synthetic) {
1662         access_flags.set_is_synthetic();
1663       }
1664       if (generic_signature_index != 0) {
1665         access_flags.set_field_has_generic_signature();
1666         fa[generic_signature_slot] = generic_signature_index;
1667         generic_signature_slot ++;
1668         num_generic_signature ++;
1669       }
1670     }
1671 
1672     FieldInfo* const field = FieldInfo::from_field_array(fa, n);
1673     field->initialize(access_flags.as_short(),
1674                       name_index,
1675                       signature_index,
1676                       constantvalue_index);
1677     const BasicType type = cp->basic_type_for_signature_at(signature_index);
1678 
1679     // Remember how many oops we encountered and compute allocation type
1680     const FieldAllocationType atype = fac->update(is_static, type, access_flags.is_flattenable());
1681     field->set_allocation_type(atype);
1682 
1683     // After field is initialized with type, we can augment it with aux info
1684     if (parsed_annotations.has_any_annotations())
1685       parsed_annotations.apply_to(field);
1686   }
1687 
1688   int index = length;
1689   if (num_injected != 0) {
1690     for (int n = 0; n < num_injected; n++) {
1691       // Check for duplicates
1692       if (injected[n].may_be_java) {
1693         const Symbol* const name      = injected[n].name();
1694         const Symbol* const signature = injected[n].signature();
1695         bool duplicate = false;
1696         for (int i = 0; i < length; i++) {
1697           const FieldInfo* const f = FieldInfo::from_field_array(fa, i);
1698           if (name      == cp->symbol_at(f->name_index()) &&
1699               signature == cp->symbol_at(f->signature_index())) {
1700             // Symbol is desclared in Java so skip this one
1701             duplicate = true;
1702             break;
1703           }
1704         }
1705         if (duplicate) {
1706           // These will be removed from the field array at the end
1707           continue;
1708         }
1709       }
1710 
1711       // Injected field
1712       FieldInfo* const field = FieldInfo::from_field_array(fa, index);
1713       field->initialize(JVM_ACC_FIELD_INTERNAL,
1714                         injected[n].name_index,
1715                         injected[n].signature_index,
1716                         0);
1717 
1718       const BasicType type = FieldType::basic_type(injected[n].signature());
1719 
1720       // Remember how many oops we encountered and compute allocation type
1721       const FieldAllocationType atype = fac->update(false, type, false);
1722       field->set_allocation_type(atype);
1723       index++;
1724     }
1725   }
1726 
1727   if (is_value_type) {
1728     FieldInfo* const field = FieldInfo::from_field_array(fa, index);
1729     field->initialize(JVM_ACC_FIELD_INTERNAL | JVM_ACC_STATIC,
1730                       vmSymbols::default_value_name_enum,
1731                       vmSymbols::java_lang_Object_enum,
1732                       0);
1733     const BasicType type = FieldType::basic_type(vmSymbols::object_signature());
1734     const FieldAllocationType atype = fac->update(true, type, false);
1735     field->set_allocation_type(atype);
1736     index++;
1737   }
1738 
1739   if (is_value_type && instance_fields_count == 0) {
1740     _is_empty_value = true;
1741     FieldInfo* const field = FieldInfo::from_field_array(fa, index);
1742     field->initialize(JVM_ACC_FIELD_INTERNAL,
1743         vmSymbols::empty_marker_name_enum,
1744         vmSymbols::byte_signature_enum,
1745         0);
1746     const BasicType type = FieldType::basic_type(vmSymbols::byte_signature());
1747     const FieldAllocationType atype = fac->update(false, type, false);
1748     field->set_allocation_type(atype);
1749     index++;
1750   }
1751 
1752   assert(NULL == _fields, "invariant");
1753 
1754   _fields =
1755     MetadataFactory::new_array<u2>(_loader_data,
1756                                    index * FieldInfo::field_slots + num_generic_signature,
1757                                    CHECK);
1758   // Sometimes injected fields already exist in the Java source so
1759   // the fields array could be too long.  In that case the
1760   // fields array is trimed. Also unused slots that were reserved
1761   // for generic signature indexes are discarded.
1762   {
1763     int i = 0;
1764     for (; i < index * FieldInfo::field_slots; i++) {
1765       _fields->at_put(i, fa[i]);
1766     }
1767     for (int j = total_fields * FieldInfo::field_slots;
1768          j < generic_signature_slot; j++) {
1769       _fields->at_put(i++, fa[j]);
1770     }
1771     assert(_fields->length() == i, "");
1772   }
1773 
1774   if (_need_verify && length > 1) {
1775     // Check duplicated fields
1776     ResourceMark rm(THREAD);
1777     NameSigHash** names_and_sigs = NEW_RESOURCE_ARRAY_IN_THREAD(
1778       THREAD, NameSigHash*, HASH_ROW_SIZE);
1779     initialize_hashtable(names_and_sigs);
1780     bool dup = false;
1781     const Symbol* name = NULL;
1782     const Symbol* sig = NULL;
1783     {
1784       debug_only(NoSafepointVerifier nsv;)
1785       for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
1786         name = fs.name();
1787         sig = fs.signature();
1788         // If no duplicates, add name/signature in hashtable names_and_sigs.
1789         if (!put_after_lookup(name, sig, names_and_sigs)) {
1790           dup = true;
1791           break;
1792         }
1793       }
1794     }
1795     if (dup) {
1796       classfile_parse_error("Duplicate field name \"%s\" with signature \"%s\" in class file %s",
1797                              name->as_C_string(), sig->as_klass_external_name(), CHECK);
1798     }
1799   }
1800 }
1801 
1802 
1803 const ClassFileParser::unsafe_u2* ClassFileParser::parse_exception_table(const ClassFileStream* const cfs,
1804                                                                          u4 code_length,
1805                                                                          u4 exception_table_length,
1806                                                                          TRAPS) {
1807   assert(cfs != NULL, "invariant");
1808 
1809   const unsafe_u2* const exception_table_start = cfs->current();
1810   assert(exception_table_start != NULL, "null exception table");
1811 
1812   cfs->guarantee_more(8 * exception_table_length, CHECK_NULL); // start_pc,
1813                                                                // end_pc,
1814                                                                // handler_pc,
1815                                                                // catch_type_index
1816 
1817   // Will check legal target after parsing code array in verifier.
1818   if (_need_verify) {
1819     for (unsigned int i = 0; i < exception_table_length; i++) {
1820       const u2 start_pc = cfs->get_u2_fast();
1821       const u2 end_pc = cfs->get_u2_fast();
1822       const u2 handler_pc = cfs->get_u2_fast();
1823       const u2 catch_type_index = cfs->get_u2_fast();
1824       guarantee_property((start_pc < end_pc) && (end_pc <= code_length),
1825                          "Illegal exception table range in class file %s",
1826                          CHECK_NULL);
1827       guarantee_property(handler_pc < code_length,
1828                          "Illegal exception table handler in class file %s",
1829                          CHECK_NULL);
1830       if (catch_type_index != 0) {
1831         guarantee_property(valid_klass_reference_at(catch_type_index),
1832                            "Catch type in exception table has bad constant type in class file %s", CHECK_NULL);
1833       }
1834     }
1835   } else {
1836     cfs->skip_u2_fast(exception_table_length * 4);
1837   }
1838   return exception_table_start;
1839 }
1840 
1841 void ClassFileParser::parse_linenumber_table(u4 code_attribute_length,
1842                                              u4 code_length,
1843                                              CompressedLineNumberWriteStream**const write_stream,
1844                                              TRAPS) {
1845 
1846   const ClassFileStream* const cfs = _stream;
1847   unsigned int num_entries = cfs->get_u2(CHECK);
1848 
1849   // Each entry is a u2 start_pc, and a u2 line_number
1850   const unsigned int length_in_bytes = num_entries * (sizeof(u2) * 2);
1851 
1852   // Verify line number attribute and table length
1853   check_property(
1854     code_attribute_length == sizeof(u2) + length_in_bytes,
1855     "LineNumberTable attribute has wrong length in class file %s", CHECK);
1856 
1857   cfs->guarantee_more(length_in_bytes, CHECK);
1858 
1859   if ((*write_stream) == NULL) {
1860     if (length_in_bytes > fixed_buffer_size) {
1861       (*write_stream) = new CompressedLineNumberWriteStream(length_in_bytes);
1862     } else {
1863       (*write_stream) = new CompressedLineNumberWriteStream(
1864         _linenumbertable_buffer, fixed_buffer_size);
1865     }
1866   }
1867 
1868   while (num_entries-- > 0) {
1869     const u2 bci  = cfs->get_u2_fast(); // start_pc
1870     const u2 line = cfs->get_u2_fast(); // line_number
1871     guarantee_property(bci < code_length,
1872         "Invalid pc in LineNumberTable in class file %s", CHECK);
1873     (*write_stream)->write_pair(bci, line);
1874   }
1875 }
1876 
1877 
1878 class LVT_Hash : public AllStatic {
1879  public:
1880 
1881   static bool equals(LocalVariableTableElement const& e0, LocalVariableTableElement const& e1) {
1882   /*
1883    * 3-tuple start_bci/length/slot has to be unique key,
1884    * so the following comparison seems to be redundant:
1885    *       && elem->name_cp_index == entry->_elem->name_cp_index
1886    */
1887     return (e0.start_bci     == e1.start_bci &&
1888             e0.length        == e1.length &&
1889             e0.name_cp_index == e1.name_cp_index &&
1890             e0.slot          == e1.slot);
1891   }
1892 
1893   static unsigned int hash(LocalVariableTableElement const& e0) {
1894     unsigned int raw_hash = e0.start_bci;
1895 
1896     raw_hash = e0.length        + raw_hash * 37;
1897     raw_hash = e0.name_cp_index + raw_hash * 37;
1898     raw_hash = e0.slot          + raw_hash * 37;
1899 
1900     return raw_hash;
1901   }
1902 };
1903 
1904 
1905 // Class file LocalVariableTable elements.
1906 class Classfile_LVT_Element {
1907  public:
1908   u2 start_bci;
1909   u2 length;
1910   u2 name_cp_index;
1911   u2 descriptor_cp_index;
1912   u2 slot;
1913 };
1914 
1915 static void copy_lvt_element(const Classfile_LVT_Element* const src,
1916                              LocalVariableTableElement* const lvt) {
1917   lvt->start_bci           = Bytes::get_Java_u2((u1*) &src->start_bci);
1918   lvt->length              = Bytes::get_Java_u2((u1*) &src->length);
1919   lvt->name_cp_index       = Bytes::get_Java_u2((u1*) &src->name_cp_index);
1920   lvt->descriptor_cp_index = Bytes::get_Java_u2((u1*) &src->descriptor_cp_index);
1921   lvt->signature_cp_index  = 0;
1922   lvt->slot                = Bytes::get_Java_u2((u1*) &src->slot);
1923 }
1924 
1925 // Function is used to parse both attributes:
1926 // LocalVariableTable (LVT) and LocalVariableTypeTable (LVTT)
1927 const ClassFileParser::unsafe_u2* ClassFileParser::parse_localvariable_table(const ClassFileStream* cfs,
1928                                                                              u4 code_length,
1929                                                                              u2 max_locals,
1930                                                                              u4 code_attribute_length,
1931                                                                              u2* const localvariable_table_length,
1932                                                                              bool isLVTT,
1933                                                                              TRAPS) {
1934   const char* const tbl_name = (isLVTT) ? "LocalVariableTypeTable" : "LocalVariableTable";
1935   *localvariable_table_length = cfs->get_u2(CHECK_NULL);
1936   const unsigned int size =
1937     (*localvariable_table_length) * sizeof(Classfile_LVT_Element) / sizeof(u2);
1938 
1939   const ConstantPool* const cp = _cp;
1940 
1941   // Verify local variable table attribute has right length
1942   if (_need_verify) {
1943     guarantee_property(code_attribute_length == (sizeof(*localvariable_table_length) + size * sizeof(u2)),
1944                        "%s has wrong length in class file %s", tbl_name, CHECK_NULL);
1945   }
1946 
1947   const unsafe_u2* const localvariable_table_start = cfs->current();
1948   assert(localvariable_table_start != NULL, "null local variable table");
1949   if (!_need_verify) {
1950     cfs->skip_u2_fast(size);
1951   } else {
1952     cfs->guarantee_more(size * 2, CHECK_NULL);
1953     for(int i = 0; i < (*localvariable_table_length); i++) {
1954       const u2 start_pc = cfs->get_u2_fast();
1955       const u2 length = cfs->get_u2_fast();
1956       const u2 name_index = cfs->get_u2_fast();
1957       const u2 descriptor_index = cfs->get_u2_fast();
1958       const u2 index = cfs->get_u2_fast();
1959       // Assign to a u4 to avoid overflow
1960       const u4 end_pc = (u4)start_pc + (u4)length;
1961 
1962       if (start_pc >= code_length) {
1963         classfile_parse_error(
1964           "Invalid start_pc %u in %s in class file %s",
1965           start_pc, tbl_name, CHECK_NULL);
1966       }
1967       if (end_pc > code_length) {
1968         classfile_parse_error(
1969           "Invalid length %u in %s in class file %s",
1970           length, tbl_name, CHECK_NULL);
1971       }
1972       const int cp_size = cp->length();
1973       guarantee_property(valid_symbol_at(name_index),
1974         "Name index %u in %s has bad constant type in class file %s",
1975         name_index, tbl_name, CHECK_NULL);
1976       guarantee_property(valid_symbol_at(descriptor_index),
1977         "Signature index %u in %s has bad constant type in class file %s",
1978         descriptor_index, tbl_name, CHECK_NULL);
1979 
1980       const Symbol* const name = cp->symbol_at(name_index);
1981       const Symbol* const sig = cp->symbol_at(descriptor_index);
1982       verify_legal_field_name(name, CHECK_NULL);
1983       u2 extra_slot = 0;
1984       if (!isLVTT) {
1985         verify_legal_field_signature(name, sig, CHECK_NULL);
1986 
1987         // 4894874: check special cases for double and long local variables
1988         if (sig == vmSymbols::type_signature(T_DOUBLE) ||
1989             sig == vmSymbols::type_signature(T_LONG)) {
1990           extra_slot = 1;
1991         }
1992       }
1993       guarantee_property((index + extra_slot) < max_locals,
1994                           "Invalid index %u in %s in class file %s",
1995                           index, tbl_name, CHECK_NULL);
1996     }
1997   }
1998   return localvariable_table_start;
1999 }
2000 
2001 static const u1* parse_stackmap_table(const ClassFileStream* const cfs,
2002                                       u4 code_attribute_length,
2003                                       bool need_verify,
2004                                       TRAPS) {
2005   assert(cfs != NULL, "invariant");
2006 
2007   if (0 == code_attribute_length) {
2008     return NULL;
2009   }
2010 
2011   const u1* const stackmap_table_start = cfs->current();
2012   assert(stackmap_table_start != NULL, "null stackmap table");
2013 
2014   // check code_attribute_length first
2015   cfs->skip_u1(code_attribute_length, CHECK_NULL);
2016 
2017   if (!need_verify && !DumpSharedSpaces) {
2018     return NULL;
2019   }
2020   return stackmap_table_start;
2021 }
2022 
2023 const ClassFileParser::unsafe_u2* ClassFileParser::parse_checked_exceptions(const ClassFileStream* const cfs,
2024                                                                             u2* const checked_exceptions_length,
2025                                                                             u4 method_attribute_length,
2026                                                                             TRAPS) {
2027   assert(cfs != NULL, "invariant");
2028   assert(checked_exceptions_length != NULL, "invariant");
2029 
2030   cfs->guarantee_more(2, CHECK_NULL);  // checked_exceptions_length
2031   *checked_exceptions_length = cfs->get_u2_fast();
2032   const unsigned int size =
2033     (*checked_exceptions_length) * sizeof(CheckedExceptionElement) / sizeof(u2);
2034   const unsafe_u2* const checked_exceptions_start = cfs->current();
2035   assert(checked_exceptions_start != NULL, "null checked exceptions");
2036   if (!_need_verify) {
2037     cfs->skip_u2_fast(size);
2038   } else {
2039     // Verify each value in the checked exception table
2040     u2 checked_exception;
2041     const u2 len = *checked_exceptions_length;
2042     cfs->guarantee_more(2 * len, CHECK_NULL);
2043     for (int i = 0; i < len; i++) {
2044       checked_exception = cfs->get_u2_fast();
2045       check_property(
2046         valid_klass_reference_at(checked_exception),
2047         "Exception name has bad type at constant pool %u in class file %s",
2048         checked_exception, CHECK_NULL);
2049     }
2050   }
2051   // check exceptions attribute length
2052   if (_need_verify) {
2053     guarantee_property(method_attribute_length == (sizeof(*checked_exceptions_length) +
2054                                                    sizeof(u2) * size),
2055                       "Exceptions attribute has wrong length in class file %s", CHECK_NULL);
2056   }
2057   return checked_exceptions_start;
2058 }
2059 
2060 void ClassFileParser::throwIllegalSignature(const char* type,
2061                                             const Symbol* name,
2062                                             const Symbol* sig,
2063                                             TRAPS) const {
2064   assert(name != NULL, "invariant");
2065   assert(sig != NULL, "invariant");
2066 
2067   const char* class_note = "";
2068   if (is_value_type() && name == vmSymbols::object_initializer_name()) {
2069     class_note = " (an inline class)";
2070   }
2071 
2072   ResourceMark rm(THREAD);
2073   Exceptions::fthrow(THREAD_AND_LOCATION,
2074       vmSymbols::java_lang_ClassFormatError(),
2075       "%s \"%s\" in class %s%s has illegal signature \"%s\"", type,
2076       name->as_C_string(), _class_name->as_C_string(), class_note, sig->as_C_string());
2077 }
2078 
2079 AnnotationCollector::ID
2080 AnnotationCollector::annotation_index(const ClassLoaderData* loader_data,
2081                                       const Symbol* name) {
2082   const vmSymbols::SID sid = vmSymbols::find_sid(name);
2083   // Privileged code can use all annotations.  Other code silently drops some.
2084   const bool privileged = loader_data->is_the_null_class_loader_data() ||
2085                           loader_data->is_platform_class_loader_data() ||
2086                           loader_data->is_unsafe_anonymous();
2087   switch (sid) {
2088     case vmSymbols::VM_SYMBOL_ENUM_NAME(reflect_CallerSensitive_signature): {
2089       if (_location != _in_method)  break;  // only allow for methods
2090       if (!privileged)              break;  // only allow in privileged code
2091       return _method_CallerSensitive;
2092     }
2093     case vmSymbols::VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ForceInline_signature): {
2094       if (_location != _in_method)  break;  // only allow for methods
2095       if (!privileged)              break;  // only allow in privileged code
2096       return _method_ForceInline;
2097     }
2098     case vmSymbols::VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_DontInline_signature): {
2099       if (_location != _in_method)  break;  // only allow for methods
2100       if (!privileged)              break;  // only allow in privileged code
2101       return _method_DontInline;
2102     }
2103     case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_InjectedProfile_signature): {
2104       if (_location != _in_method)  break;  // only allow for methods
2105       if (!privileged)              break;  // only allow in privileged code
2106       return _method_InjectedProfile;
2107     }
2108     case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_LambdaForm_Compiled_signature): {
2109       if (_location != _in_method)  break;  // only allow for methods
2110       if (!privileged)              break;  // only allow in privileged code
2111       return _method_LambdaForm_Compiled;
2112     }
2113     case vmSymbols::VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Hidden_signature): {
2114       if (_location != _in_method)  break;  // only allow for methods
2115       if (!privileged)              break;  // only allow in privileged code
2116       return _method_Hidden;
2117     }
2118     case vmSymbols::VM_SYMBOL_ENUM_NAME(jdk_internal_HotSpotIntrinsicCandidate_signature): {
2119       if (_location != _in_method)  break;  // only allow for methods
2120       if (!privileged)              break;  // only allow in privileged code
2121       return _method_HotSpotIntrinsicCandidate;
2122     }
2123     case vmSymbols::VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Stable_signature): {
2124       if (_location != _in_field)   break;  // only allow for fields
2125       if (!privileged)              break;  // only allow in privileged code
2126       return _field_Stable;
2127     }
2128     case vmSymbols::VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Contended_signature): {
2129       if (_location != _in_field && _location != _in_class) {
2130         break;  // only allow for fields and classes
2131       }
2132       if (!EnableContended || (RestrictContended && !privileged)) {
2133         break;  // honor privileges
2134       }
2135       return _jdk_internal_vm_annotation_Contended;
2136     }
2137     case vmSymbols::VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ReservedStackAccess_signature): {
2138       if (_location != _in_method)  break;  // only allow for methods
2139       if (RestrictReservedStack && !privileged) break; // honor privileges
2140       return _jdk_internal_vm_annotation_ReservedStackAccess;
2141     }
2142     default: {
2143       break;
2144     }
2145   }
2146   return AnnotationCollector::_unknown;
2147 }
2148 
2149 void ClassFileParser::FieldAnnotationCollector::apply_to(FieldInfo* f) {
2150   if (is_contended())
2151     f->set_contended_group(contended_group());
2152   if (is_stable())
2153     f->set_stable(true);
2154 }
2155 
2156 ClassFileParser::FieldAnnotationCollector::~FieldAnnotationCollector() {
2157   // If there's an error deallocate metadata for field annotations
2158   MetadataFactory::free_array<u1>(_loader_data, _field_annotations);
2159   MetadataFactory::free_array<u1>(_loader_data, _field_type_annotations);
2160 }
2161 
2162 void MethodAnnotationCollector::apply_to(const methodHandle& m) {
2163   if (has_annotation(_method_CallerSensitive))
2164     m->set_caller_sensitive(true);
2165   if (has_annotation(_method_ForceInline))
2166     m->set_force_inline(true);
2167   if (has_annotation(_method_DontInline))
2168     m->set_dont_inline(true);
2169   if (has_annotation(_method_InjectedProfile))
2170     m->set_has_injected_profile(true);
2171   if (has_annotation(_method_LambdaForm_Compiled) && m->intrinsic_id() == vmIntrinsics::_none)
2172     m->set_intrinsic_id(vmIntrinsics::_compiledLambdaForm);
2173   if (has_annotation(_method_Hidden))
2174     m->set_hidden(true);
2175   if (has_annotation(_method_HotSpotIntrinsicCandidate) && !m->is_synthetic())
2176     m->set_intrinsic_candidate(true);
2177   if (has_annotation(_jdk_internal_vm_annotation_ReservedStackAccess))
2178     m->set_has_reserved_stack_access(true);
2179 }
2180 
2181 void ClassFileParser::ClassAnnotationCollector::apply_to(InstanceKlass* ik) {
2182   assert(ik != NULL, "invariant");
2183   ik->set_is_contended(is_contended());
2184 }
2185 
2186 #define MAX_ARGS_SIZE 255
2187 #define MAX_CODE_SIZE 65535
2188 #define INITIAL_MAX_LVT_NUMBER 256
2189 
2190 /* Copy class file LVT's/LVTT's into the HotSpot internal LVT.
2191  *
2192  * Rules for LVT's and LVTT's are:
2193  *   - There can be any number of LVT's and LVTT's.
2194  *   - If there are n LVT's, it is the same as if there was just
2195  *     one LVT containing all the entries from the n LVT's.
2196  *   - There may be no more than one LVT entry per local variable.
2197  *     Two LVT entries are 'equal' if these fields are the same:
2198  *        start_pc, length, name, slot
2199  *   - There may be no more than one LVTT entry per each LVT entry.
2200  *     Each LVTT entry has to match some LVT entry.
2201  *   - HotSpot internal LVT keeps natural ordering of class file LVT entries.
2202  */
2203 void ClassFileParser::copy_localvariable_table(const ConstMethod* cm,
2204                                                int lvt_cnt,
2205                                                u2* const localvariable_table_length,
2206                                                const unsafe_u2** const localvariable_table_start,
2207                                                int lvtt_cnt,
2208                                                u2* const localvariable_type_table_length,
2209                                                const unsafe_u2** const localvariable_type_table_start,
2210                                                TRAPS) {
2211 
2212   ResourceMark rm(THREAD);
2213 
2214   typedef ResourceHashtable<LocalVariableTableElement, LocalVariableTableElement*,
2215                             &LVT_Hash::hash, &LVT_Hash::equals> LVT_HashTable;
2216 
2217   LVT_HashTable* const table = new LVT_HashTable();
2218 
2219   // To fill LocalVariableTable in
2220   const Classfile_LVT_Element* cf_lvt;
2221   LocalVariableTableElement* lvt = cm->localvariable_table_start();
2222 
2223   for (int tbl_no = 0; tbl_no < lvt_cnt; tbl_no++) {
2224     cf_lvt = (Classfile_LVT_Element *) localvariable_table_start[tbl_no];
2225     for (int idx = 0; idx < localvariable_table_length[tbl_no]; idx++, lvt++) {
2226       copy_lvt_element(&cf_lvt[idx], lvt);
2227       // If no duplicates, add LVT elem in hashtable.
2228       if (table->put(*lvt, lvt) == false
2229           && _need_verify
2230           && _major_version >= JAVA_1_5_VERSION) {
2231         classfile_parse_error("Duplicated LocalVariableTable attribute "
2232                               "entry for '%s' in class file %s",
2233                                _cp->symbol_at(lvt->name_cp_index)->as_utf8(),
2234                                CHECK);
2235       }
2236     }
2237   }
2238 
2239   // To merge LocalVariableTable and LocalVariableTypeTable
2240   const Classfile_LVT_Element* cf_lvtt;
2241   LocalVariableTableElement lvtt_elem;
2242 
2243   for (int tbl_no = 0; tbl_no < lvtt_cnt; tbl_no++) {
2244     cf_lvtt = (Classfile_LVT_Element *) localvariable_type_table_start[tbl_no];
2245     for (int idx = 0; idx < localvariable_type_table_length[tbl_no]; idx++) {
2246       copy_lvt_element(&cf_lvtt[idx], &lvtt_elem);
2247       LocalVariableTableElement** entry = table->get(lvtt_elem);
2248       if (entry == NULL) {
2249         if (_need_verify) {
2250           classfile_parse_error("LVTT entry for '%s' in class file %s "
2251                                 "does not match any LVT entry",
2252                                  _cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(),
2253                                  CHECK);
2254         }
2255       } else if ((*entry)->signature_cp_index != 0 && _need_verify) {
2256         classfile_parse_error("Duplicated LocalVariableTypeTable attribute "
2257                               "entry for '%s' in class file %s",
2258                                _cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(),
2259                                CHECK);
2260       } else {
2261         // to add generic signatures into LocalVariableTable
2262         (*entry)->signature_cp_index = lvtt_elem.descriptor_cp_index;
2263       }
2264     }
2265   }
2266 }
2267 
2268 
2269 void ClassFileParser::copy_method_annotations(ConstMethod* cm,
2270                                        const u1* runtime_visible_annotations,
2271                                        int runtime_visible_annotations_length,
2272                                        const u1* runtime_invisible_annotations,
2273                                        int runtime_invisible_annotations_length,
2274                                        const u1* runtime_visible_parameter_annotations,
2275                                        int runtime_visible_parameter_annotations_length,
2276                                        const u1* runtime_invisible_parameter_annotations,
2277                                        int runtime_invisible_parameter_annotations_length,
2278                                        const u1* runtime_visible_type_annotations,
2279                                        int runtime_visible_type_annotations_length,
2280                                        const u1* runtime_invisible_type_annotations,
2281                                        int runtime_invisible_type_annotations_length,
2282                                        const u1* annotation_default,
2283                                        int annotation_default_length,
2284                                        TRAPS) {
2285 
2286   AnnotationArray* a;
2287 
2288   if (runtime_visible_annotations_length +
2289       runtime_invisible_annotations_length > 0) {
2290      a = assemble_annotations(runtime_visible_annotations,
2291                               runtime_visible_annotations_length,
2292                               runtime_invisible_annotations,
2293                               runtime_invisible_annotations_length,
2294                               CHECK);
2295      cm->set_method_annotations(a);
2296   }
2297 
2298   if (runtime_visible_parameter_annotations_length +
2299       runtime_invisible_parameter_annotations_length > 0) {
2300     a = assemble_annotations(runtime_visible_parameter_annotations,
2301                              runtime_visible_parameter_annotations_length,
2302                              runtime_invisible_parameter_annotations,
2303                              runtime_invisible_parameter_annotations_length,
2304                              CHECK);
2305     cm->set_parameter_annotations(a);
2306   }
2307 
2308   if (annotation_default_length > 0) {
2309     a = assemble_annotations(annotation_default,
2310                              annotation_default_length,
2311                              NULL,
2312                              0,
2313                              CHECK);
2314     cm->set_default_annotations(a);
2315   }
2316 
2317   if (runtime_visible_type_annotations_length +
2318       runtime_invisible_type_annotations_length > 0) {
2319     a = assemble_annotations(runtime_visible_type_annotations,
2320                              runtime_visible_type_annotations_length,
2321                              runtime_invisible_type_annotations,
2322                              runtime_invisible_type_annotations_length,
2323                              CHECK);
2324     cm->set_type_annotations(a);
2325   }
2326 }
2327 
2328 
2329 // Note: the parse_method below is big and clunky because all parsing of the code and exceptions
2330 // attribute is inlined. This is cumbersome to avoid since we inline most of the parts in the
2331 // Method* to save footprint, so we only know the size of the resulting Method* when the
2332 // entire method attribute is parsed.
2333 //
2334 // The promoted_flags parameter is used to pass relevant access_flags
2335 // from the method back up to the containing klass. These flag values
2336 // are added to klass's access_flags.
2337 
2338 Method* ClassFileParser::parse_method(const ClassFileStream* const cfs,
2339                                       bool is_interface,
2340                                       bool is_value_type,
2341                                       const ConstantPool* cp,
2342                                       AccessFlags* const promoted_flags,
2343                                       TRAPS) {
2344   assert(cfs != NULL, "invariant");
2345   assert(cp != NULL, "invariant");
2346   assert(promoted_flags != NULL, "invariant");
2347 
2348   ResourceMark rm(THREAD);
2349   // Parse fixed parts:
2350   // access_flags, name_index, descriptor_index, attributes_count
2351   cfs->guarantee_more(8, CHECK_NULL);
2352 
2353   int flags = cfs->get_u2_fast();
2354   const u2 name_index = cfs->get_u2_fast();
2355   const int cp_size = cp->length();
2356   check_property(
2357     valid_symbol_at(name_index),
2358     "Illegal constant pool index %u for method name in class file %s",
2359     name_index, CHECK_NULL);
2360   const Symbol* const name = cp->symbol_at(name_index);
2361   verify_legal_method_name(name, CHECK_NULL);
2362 
2363   const u2 signature_index = cfs->get_u2_fast();
2364   guarantee_property(
2365     valid_symbol_at(signature_index),
2366     "Illegal constant pool index %u for method signature in class file %s",
2367     signature_index, CHECK_NULL);
2368   const Symbol* const signature = cp->symbol_at(signature_index);
2369 
2370   if (name == vmSymbols::class_initializer_name()) {
2371     // We ignore the other access flags for a valid class initializer.
2372     // (JVM Spec 2nd ed., chapter 4.6)
2373     if (_major_version < 51) { // backward compatibility
2374       flags = JVM_ACC_STATIC;
2375     } else if ((flags & JVM_ACC_STATIC) == JVM_ACC_STATIC) {
2376       flags &= JVM_ACC_STATIC | JVM_ACC_STRICT;
2377     } else {
2378       classfile_parse_error("Method <clinit> is not static in class file %s", CHECK_NULL);
2379     }
2380   } else {
2381     verify_legal_method_modifiers(flags, is_interface, is_value_type, name, CHECK_NULL);
2382   }
2383 
2384   if (name == vmSymbols::object_initializer_name()) {
2385     if (is_interface) {
2386       classfile_parse_error("Interface cannot have a method named <init>, class file %s", CHECK_NULL);
2387     } else if (!is_value_type && signature->is_void_method_signature()) {
2388       // OK, a constructor
2389     } else if (is_value_type && !signature->is_void_method_signature()) {
2390       // also OK, a static factory, as long as the return value is good
2391       bool ok = false;
2392       SignatureStream ss((Symbol*) signature, true);
2393       while (!ss.at_return_type())  ss.next();
2394       if (ss.is_object()) {
2395         TempNewSymbol ret = ss.as_symbol_or_null();
2396         const Symbol* required = class_name();
2397         if (is_unsafe_anonymous()) {
2398           // The original class name in the UAC byte stream gets changed.  So
2399           // using the original name in the return type is no longer valid.
2400           required = vmSymbols::java_lang_Object();
2401         }
2402         ok = (ret == required);
2403       }
2404       if (!ok) {
2405         throwIllegalSignature("Method", name, signature, CHECK_0);
2406       }
2407     } else {
2408       // not OK, so throw the same error as in verify_legal_method_signature.
2409       throwIllegalSignature("Method", name, signature, CHECK_0);
2410     }
2411     // A declared <init> method must always be either a non-static
2412     // object constructor, with a void return, or else it must be a
2413     // static factory method, with a non-void return.  No other
2414     // definition of <init> is possible.
2415     //
2416     // The verifier (in verify_invoke_instructions) will inspect the
2417     // signature of any attempt to invoke <init>, and ensures that it
2418     // returns non-void if and only if it is being invoked by
2419     // invokestatic, and void if and only if it is being invoked by
2420     // invokespecial.
2421     //
2422     // When a symbolic reference to <init> is resolved for a
2423     // particular invocation mode (special or static), the mode is
2424     // matched to the JVM_ACC_STATIC modifier of the <init> method.
2425     // Thus, it is impossible to statically invoke a constructor, and
2426     // impossible to "new + invokespecial" a static factory, either
2427     // through bytecode or through reflection.
2428   }
2429 
2430   int args_size = -1;  // only used when _need_verify is true
2431   if (_need_verify) {
2432     args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) +
2433                  verify_legal_method_signature(name, signature, CHECK_NULL);
2434     if (args_size > MAX_ARGS_SIZE) {
2435       classfile_parse_error("Too many arguments in method signature in class file %s", CHECK_NULL);
2436     }
2437   }
2438 
2439   AccessFlags access_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS);
2440 
2441   // Default values for code and exceptions attribute elements
2442   u2 max_stack = 0;
2443   u2 max_locals = 0;
2444   u4 code_length = 0;
2445   const u1* code_start = 0;
2446   u2 exception_table_length = 0;
2447   const unsafe_u2* exception_table_start = NULL; // (potentially unaligned) pointer to array of u2 elements
2448   Array<int>* exception_handlers = Universe::the_empty_int_array();
2449   u2 checked_exceptions_length = 0;
2450   const unsafe_u2* checked_exceptions_start = NULL; // (potentially unaligned) pointer to array of u2 elements
2451   CompressedLineNumberWriteStream* linenumber_table = NULL;
2452   int linenumber_table_length = 0;
2453   int total_lvt_length = 0;
2454   u2 lvt_cnt = 0;
2455   u2 lvtt_cnt = 0;
2456   bool lvt_allocated = false;
2457   u2 max_lvt_cnt = INITIAL_MAX_LVT_NUMBER;
2458   u2 max_lvtt_cnt = INITIAL_MAX_LVT_NUMBER;
2459   u2* localvariable_table_length = NULL;
2460   const unsafe_u2** localvariable_table_start = NULL; // (potentially unaligned) pointer to array of LVT attributes
2461   u2* localvariable_type_table_length = NULL;
2462   const unsafe_u2** localvariable_type_table_start = NULL; // (potentially unaligned) pointer to LVTT attributes
2463   int method_parameters_length = -1;
2464   const u1* method_parameters_data = NULL;
2465   bool method_parameters_seen = false;
2466   bool parsed_code_attribute = false;
2467   bool parsed_checked_exceptions_attribute = false;
2468   bool parsed_stackmap_attribute = false;
2469   // stackmap attribute - JDK1.5
2470   const u1* stackmap_data = NULL;
2471   int stackmap_data_length = 0;
2472   u2 generic_signature_index = 0;
2473   MethodAnnotationCollector parsed_annotations;
2474   const u1* runtime_visible_annotations = NULL;
2475   int runtime_visible_annotations_length = 0;
2476   const u1* runtime_invisible_annotations = NULL;
2477   int runtime_invisible_annotations_length = 0;
2478   const u1* runtime_visible_parameter_annotations = NULL;
2479   int runtime_visible_parameter_annotations_length = 0;
2480   const u1* runtime_invisible_parameter_annotations = NULL;
2481   int runtime_invisible_parameter_annotations_length = 0;
2482   const u1* runtime_visible_type_annotations = NULL;
2483   int runtime_visible_type_annotations_length = 0;
2484   const u1* runtime_invisible_type_annotations = NULL;
2485   int runtime_invisible_type_annotations_length = 0;
2486   bool runtime_invisible_annotations_exists = false;
2487   bool runtime_invisible_type_annotations_exists = false;
2488   bool runtime_invisible_parameter_annotations_exists = false;
2489   const u1* annotation_default = NULL;
2490   int annotation_default_length = 0;
2491 
2492   // Parse code and exceptions attribute
2493   u2 method_attributes_count = cfs->get_u2_fast();
2494   while (method_attributes_count--) {
2495     cfs->guarantee_more(6, CHECK_NULL);  // method_attribute_name_index, method_attribute_length
2496     const u2 method_attribute_name_index = cfs->get_u2_fast();
2497     const u4 method_attribute_length = cfs->get_u4_fast();
2498     check_property(
2499       valid_symbol_at(method_attribute_name_index),
2500       "Invalid method attribute name index %u in class file %s",
2501       method_attribute_name_index, CHECK_NULL);
2502 
2503     const Symbol* const method_attribute_name = cp->symbol_at(method_attribute_name_index);
2504     if (method_attribute_name == vmSymbols::tag_code()) {
2505       // Parse Code attribute
2506       if (_need_verify) {
2507         guarantee_property(
2508             !access_flags.is_native() && !access_flags.is_abstract(),
2509                         "Code attribute in native or abstract methods in class file %s",
2510                          CHECK_NULL);
2511       }
2512       if (parsed_code_attribute) {
2513         classfile_parse_error("Multiple Code attributes in class file %s",
2514                               CHECK_NULL);
2515       }
2516       parsed_code_attribute = true;
2517 
2518       // Stack size, locals size, and code size
2519       if (_major_version == 45 && _minor_version <= 2) {
2520         cfs->guarantee_more(4, CHECK_NULL);
2521         max_stack = cfs->get_u1_fast();
2522         max_locals = cfs->get_u1_fast();
2523         code_length = cfs->get_u2_fast();
2524       } else {
2525         cfs->guarantee_more(8, CHECK_NULL);
2526         max_stack = cfs->get_u2_fast();
2527         max_locals = cfs->get_u2_fast();
2528         code_length = cfs->get_u4_fast();
2529       }
2530       if (_need_verify) {
2531         guarantee_property(args_size <= max_locals,
2532                            "Arguments can't fit into locals in class file %s",
2533                            CHECK_NULL);
2534         guarantee_property(code_length > 0 && code_length <= MAX_CODE_SIZE,
2535                            "Invalid method Code length %u in class file %s",
2536                            code_length, CHECK_NULL);
2537       }
2538       // Code pointer
2539       code_start = cfs->current();
2540       assert(code_start != NULL, "null code start");
2541       cfs->guarantee_more(code_length, CHECK_NULL);
2542       cfs->skip_u1_fast(code_length);
2543 
2544       // Exception handler table
2545       cfs->guarantee_more(2, CHECK_NULL);  // exception_table_length
2546       exception_table_length = cfs->get_u2_fast();
2547       if (exception_table_length > 0) {
2548         exception_table_start = parse_exception_table(cfs,
2549                                                       code_length,
2550                                                       exception_table_length,
2551                                                       CHECK_NULL);
2552       }
2553 
2554       // Parse additional attributes in code attribute
2555       cfs->guarantee_more(2, CHECK_NULL);  // code_attributes_count
2556       u2 code_attributes_count = cfs->get_u2_fast();
2557 
2558       unsigned int calculated_attribute_length = 0;
2559 
2560       if (_major_version > 45 || (_major_version == 45 && _minor_version > 2)) {
2561         calculated_attribute_length =
2562             sizeof(max_stack) + sizeof(max_locals) + sizeof(code_length);
2563       } else {
2564         // max_stack, locals and length are smaller in pre-version 45.2 classes
2565         calculated_attribute_length = sizeof(u1) + sizeof(u1) + sizeof(u2);
2566       }
2567       calculated_attribute_length +=
2568         code_length +
2569         sizeof(exception_table_length) +
2570         sizeof(code_attributes_count) +
2571         exception_table_length *
2572             ( sizeof(u2) +   // start_pc
2573               sizeof(u2) +   // end_pc
2574               sizeof(u2) +   // handler_pc
2575               sizeof(u2) );  // catch_type_index
2576 
2577       while (code_attributes_count--) {
2578         cfs->guarantee_more(6, CHECK_NULL);  // code_attribute_name_index, code_attribute_length
2579         const u2 code_attribute_name_index = cfs->get_u2_fast();
2580         const u4 code_attribute_length = cfs->get_u4_fast();
2581         calculated_attribute_length += code_attribute_length +
2582                                        sizeof(code_attribute_name_index) +
2583                                        sizeof(code_attribute_length);
2584         check_property(valid_symbol_at(code_attribute_name_index),
2585                        "Invalid code attribute name index %u in class file %s",
2586                        code_attribute_name_index,
2587                        CHECK_NULL);
2588         if (LoadLineNumberTables &&
2589             cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_line_number_table()) {
2590           // Parse and compress line number table
2591           parse_linenumber_table(code_attribute_length,
2592                                  code_length,
2593                                  &linenumber_table,
2594                                  CHECK_NULL);
2595 
2596         } else if (LoadLocalVariableTables &&
2597                    cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_table()) {
2598           // Parse local variable table
2599           if (!lvt_allocated) {
2600             localvariable_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2601               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
2602             localvariable_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2603               THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER);
2604             localvariable_type_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2605               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
2606             localvariable_type_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2607               THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER);
2608             lvt_allocated = true;
2609           }
2610           if (lvt_cnt == max_lvt_cnt) {
2611             max_lvt_cnt <<= 1;
2612             localvariable_table_length = REALLOC_RESOURCE_ARRAY(u2, localvariable_table_length, lvt_cnt, max_lvt_cnt);
2613             localvariable_table_start  = REALLOC_RESOURCE_ARRAY(const unsafe_u2*, localvariable_table_start, lvt_cnt, max_lvt_cnt);
2614           }
2615           localvariable_table_start[lvt_cnt] =
2616             parse_localvariable_table(cfs,
2617                                       code_length,
2618                                       max_locals,
2619                                       code_attribute_length,
2620                                       &localvariable_table_length[lvt_cnt],
2621                                       false,    // is not LVTT
2622                                       CHECK_NULL);
2623           total_lvt_length += localvariable_table_length[lvt_cnt];
2624           lvt_cnt++;
2625         } else if (LoadLocalVariableTypeTables &&
2626                    _major_version >= JAVA_1_5_VERSION &&
2627                    cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_type_table()) {
2628           if (!lvt_allocated) {
2629             localvariable_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2630               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
2631             localvariable_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2632               THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER);
2633             localvariable_type_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2634               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
2635             localvariable_type_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2636               THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER);
2637             lvt_allocated = true;
2638           }
2639           // Parse local variable type table
2640           if (lvtt_cnt == max_lvtt_cnt) {
2641             max_lvtt_cnt <<= 1;
2642             localvariable_type_table_length = REALLOC_RESOURCE_ARRAY(u2, localvariable_type_table_length, lvtt_cnt, max_lvtt_cnt);
2643             localvariable_type_table_start  = REALLOC_RESOURCE_ARRAY(const unsafe_u2*, localvariable_type_table_start, lvtt_cnt, max_lvtt_cnt);
2644           }
2645           localvariable_type_table_start[lvtt_cnt] =
2646             parse_localvariable_table(cfs,
2647                                       code_length,
2648                                       max_locals,
2649                                       code_attribute_length,
2650                                       &localvariable_type_table_length[lvtt_cnt],
2651                                       true,     // is LVTT
2652                                       CHECK_NULL);
2653           lvtt_cnt++;
2654         } else if (_major_version >= Verifier::STACKMAP_ATTRIBUTE_MAJOR_VERSION &&
2655                    cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_stack_map_table()) {
2656           // Stack map is only needed by the new verifier in JDK1.5.
2657           if (parsed_stackmap_attribute) {
2658             classfile_parse_error("Multiple StackMapTable attributes in class file %s", CHECK_NULL);
2659           }
2660           stackmap_data = parse_stackmap_table(cfs, code_attribute_length, _need_verify, CHECK_NULL);
2661           stackmap_data_length = code_attribute_length;
2662           parsed_stackmap_attribute = true;
2663         } else {
2664           // Skip unknown attributes
2665           cfs->skip_u1(code_attribute_length, CHECK_NULL);
2666         }
2667       }
2668       // check method attribute length
2669       if (_need_verify) {
2670         guarantee_property(method_attribute_length == calculated_attribute_length,
2671                            "Code segment has wrong length in class file %s",
2672                            CHECK_NULL);
2673       }
2674     } else if (method_attribute_name == vmSymbols::tag_exceptions()) {
2675       // Parse Exceptions attribute
2676       if (parsed_checked_exceptions_attribute) {
2677         classfile_parse_error("Multiple Exceptions attributes in class file %s",
2678                               CHECK_NULL);
2679       }
2680       parsed_checked_exceptions_attribute = true;
2681       checked_exceptions_start =
2682             parse_checked_exceptions(cfs,
2683                                      &checked_exceptions_length,
2684                                      method_attribute_length,
2685                                      CHECK_NULL);
2686     } else if (method_attribute_name == vmSymbols::tag_method_parameters()) {
2687       // reject multiple method parameters
2688       if (method_parameters_seen) {
2689         classfile_parse_error("Multiple MethodParameters attributes in class file %s",
2690                               CHECK_NULL);
2691       }
2692       method_parameters_seen = true;
2693       method_parameters_length = cfs->get_u1_fast();
2694       const u2 real_length = (method_parameters_length * 4u) + 1u;
2695       if (method_attribute_length != real_length) {
2696         classfile_parse_error(
2697           "Invalid MethodParameters method attribute length %u in class file",
2698           method_attribute_length, CHECK_NULL);
2699       }
2700       method_parameters_data = cfs->current();
2701       cfs->skip_u2_fast(method_parameters_length);
2702       cfs->skip_u2_fast(method_parameters_length);
2703       // ignore this attribute if it cannot be reflected
2704       if (!SystemDictionary::Parameter_klass_loaded())
2705         method_parameters_length = -1;
2706     } else if (method_attribute_name == vmSymbols::tag_synthetic()) {
2707       if (method_attribute_length != 0) {
2708         classfile_parse_error(
2709           "Invalid Synthetic method attribute length %u in class file %s",
2710           method_attribute_length, CHECK_NULL);
2711       }
2712       // Should we check that there hasn't already been a synthetic attribute?
2713       access_flags.set_is_synthetic();
2714     } else if (method_attribute_name == vmSymbols::tag_deprecated()) { // 4276120
2715       if (method_attribute_length != 0) {
2716         classfile_parse_error(
2717           "Invalid Deprecated method attribute length %u in class file %s",
2718           method_attribute_length, CHECK_NULL);
2719       }
2720     } else if (_major_version >= JAVA_1_5_VERSION) {
2721       if (method_attribute_name == vmSymbols::tag_signature()) {
2722         if (generic_signature_index != 0) {
2723           classfile_parse_error(
2724             "Multiple Signature attributes for method in class file %s",
2725             CHECK_NULL);
2726         }
2727         if (method_attribute_length != 2) {
2728           classfile_parse_error(
2729             "Invalid Signature attribute length %u in class file %s",
2730             method_attribute_length, CHECK_NULL);
2731         }
2732         generic_signature_index = parse_generic_signature_attribute(cfs, CHECK_NULL);
2733       } else if (method_attribute_name == vmSymbols::tag_runtime_visible_annotations()) {
2734         if (runtime_visible_annotations != NULL) {
2735           classfile_parse_error(
2736             "Multiple RuntimeVisibleAnnotations attributes for method in class file %s",
2737             CHECK_NULL);
2738         }
2739         runtime_visible_annotations_length = method_attribute_length;
2740         runtime_visible_annotations = cfs->current();
2741         assert(runtime_visible_annotations != NULL, "null visible annotations");
2742         cfs->guarantee_more(runtime_visible_annotations_length, CHECK_NULL);
2743         parse_annotations(cp,
2744                           runtime_visible_annotations,
2745                           runtime_visible_annotations_length,
2746                           &parsed_annotations,
2747                           _loader_data,
2748                           CHECK_NULL);
2749         cfs->skip_u1_fast(runtime_visible_annotations_length);
2750       } else if (method_attribute_name == vmSymbols::tag_runtime_invisible_annotations()) {
2751         if (runtime_invisible_annotations_exists) {
2752           classfile_parse_error(
2753             "Multiple RuntimeInvisibleAnnotations attributes for method in class file %s",
2754             CHECK_NULL);
2755         }
2756         runtime_invisible_annotations_exists = true;
2757         if (PreserveAllAnnotations) {
2758           runtime_invisible_annotations_length = method_attribute_length;
2759           runtime_invisible_annotations = cfs->current();
2760           assert(runtime_invisible_annotations != NULL, "null invisible annotations");
2761         }
2762         cfs->skip_u1(method_attribute_length, CHECK_NULL);
2763       } else if (method_attribute_name == vmSymbols::tag_runtime_visible_parameter_annotations()) {
2764         if (runtime_visible_parameter_annotations != NULL) {
2765           classfile_parse_error(
2766             "Multiple RuntimeVisibleParameterAnnotations attributes for method in class file %s",
2767             CHECK_NULL);
2768         }
2769         runtime_visible_parameter_annotations_length = method_attribute_length;
2770         runtime_visible_parameter_annotations = cfs->current();
2771         assert(runtime_visible_parameter_annotations != NULL, "null visible parameter annotations");
2772         cfs->skip_u1(runtime_visible_parameter_annotations_length, CHECK_NULL);
2773       } else if (method_attribute_name == vmSymbols::tag_runtime_invisible_parameter_annotations()) {
2774         if (runtime_invisible_parameter_annotations_exists) {
2775           classfile_parse_error(
2776             "Multiple RuntimeInvisibleParameterAnnotations attributes for method in class file %s",
2777             CHECK_NULL);
2778         }
2779         runtime_invisible_parameter_annotations_exists = true;
2780         if (PreserveAllAnnotations) {
2781           runtime_invisible_parameter_annotations_length = method_attribute_length;
2782           runtime_invisible_parameter_annotations = cfs->current();
2783           assert(runtime_invisible_parameter_annotations != NULL,
2784             "null invisible parameter annotations");
2785         }
2786         cfs->skip_u1(method_attribute_length, CHECK_NULL);
2787       } else if (method_attribute_name == vmSymbols::tag_annotation_default()) {
2788         if (annotation_default != NULL) {
2789           classfile_parse_error(
2790             "Multiple AnnotationDefault attributes for method in class file %s",
2791             CHECK_NULL);
2792         }
2793         annotation_default_length = method_attribute_length;
2794         annotation_default = cfs->current();
2795         assert(annotation_default != NULL, "null annotation default");
2796         cfs->skip_u1(annotation_default_length, CHECK_NULL);
2797       } else if (method_attribute_name == vmSymbols::tag_runtime_visible_type_annotations()) {
2798         if (runtime_visible_type_annotations != NULL) {
2799           classfile_parse_error(
2800             "Multiple RuntimeVisibleTypeAnnotations attributes for method in class file %s",
2801             CHECK_NULL);
2802         }
2803         runtime_visible_type_annotations_length = method_attribute_length;
2804         runtime_visible_type_annotations = cfs->current();
2805         assert(runtime_visible_type_annotations != NULL, "null visible type annotations");
2806         // No need for the VM to parse Type annotations
2807         cfs->skip_u1(runtime_visible_type_annotations_length, CHECK_NULL);
2808       } else if (method_attribute_name == vmSymbols::tag_runtime_invisible_type_annotations()) {
2809         if (runtime_invisible_type_annotations_exists) {
2810           classfile_parse_error(
2811             "Multiple RuntimeInvisibleTypeAnnotations attributes for method in class file %s",
2812             CHECK_NULL);
2813         } else {
2814           runtime_invisible_type_annotations_exists = true;
2815         }
2816         if (PreserveAllAnnotations) {
2817           runtime_invisible_type_annotations_length = method_attribute_length;
2818           runtime_invisible_type_annotations = cfs->current();
2819           assert(runtime_invisible_type_annotations != NULL, "null invisible type annotations");
2820         }
2821         cfs->skip_u1(method_attribute_length, CHECK_NULL);
2822       } else {
2823         // Skip unknown attributes
2824         cfs->skip_u1(method_attribute_length, CHECK_NULL);
2825       }
2826     } else {
2827       // Skip unknown attributes
2828       cfs->skip_u1(method_attribute_length, CHECK_NULL);
2829     }
2830   }
2831 
2832   if (linenumber_table != NULL) {
2833     linenumber_table->write_terminator();
2834     linenumber_table_length = linenumber_table->position();
2835   }
2836 
2837   // Make sure there's at least one Code attribute in non-native/non-abstract method
2838   if (_need_verify) {
2839     guarantee_property(access_flags.is_native() ||
2840                        access_flags.is_abstract() ||
2841                        parsed_code_attribute,
2842                        "Absent Code attribute in method that is not native or abstract in class file %s",
2843                        CHECK_NULL);
2844   }
2845 
2846   // All sizing information for a Method* is finally available, now create it
2847   InlineTableSizes sizes(
2848       total_lvt_length,
2849       linenumber_table_length,
2850       exception_table_length,
2851       checked_exceptions_length,
2852       method_parameters_length,
2853       generic_signature_index,
2854       runtime_visible_annotations_length +
2855            runtime_invisible_annotations_length,
2856       runtime_visible_parameter_annotations_length +
2857            runtime_invisible_parameter_annotations_length,
2858       runtime_visible_type_annotations_length +
2859            runtime_invisible_type_annotations_length,
2860       annotation_default_length,
2861       0);
2862 
2863   Method* const m = Method::allocate(_loader_data,
2864                                      code_length,
2865                                      access_flags,
2866                                      &sizes,
2867                                      ConstMethod::NORMAL,
2868                                      CHECK_NULL);
2869 
2870   ClassLoadingService::add_class_method_size(m->size()*wordSize);
2871 
2872   // Fill in information from fixed part (access_flags already set)
2873   m->set_constants(_cp);
2874   m->set_name_index(name_index);
2875   m->set_signature_index(signature_index);
2876 
2877   ResultTypeFinder rtf(cp->symbol_at(signature_index));
2878   m->constMethod()->set_result_type(rtf.type());
2879 
2880   if (args_size >= 0) {
2881     m->set_size_of_parameters(args_size);
2882   } else {
2883     m->compute_size_of_parameters(THREAD);
2884   }
2885 #ifdef ASSERT
2886   if (args_size >= 0) {
2887     m->compute_size_of_parameters(THREAD);
2888     assert(args_size == m->size_of_parameters(), "");
2889   }
2890 #endif
2891 
2892   // Fill in code attribute information
2893   m->set_max_stack(max_stack);
2894   m->set_max_locals(max_locals);
2895   if (stackmap_data != NULL) {
2896     m->constMethod()->copy_stackmap_data(_loader_data,
2897                                          (u1*)stackmap_data,
2898                                          stackmap_data_length,
2899                                          CHECK_NULL);
2900   }
2901 
2902   // Copy byte codes
2903   m->set_code((u1*)code_start);
2904 
2905   // Copy line number table
2906   if (linenumber_table != NULL) {
2907     memcpy(m->compressed_linenumber_table(),
2908            linenumber_table->buffer(),
2909            linenumber_table_length);
2910   }
2911 
2912   // Copy exception table
2913   if (exception_table_length > 0) {
2914     Copy::conjoint_swap_if_needed<Endian::JAVA>(exception_table_start,
2915                                                 m->exception_table_start(),
2916                                                 exception_table_length * sizeof(ExceptionTableElement),
2917                                                 sizeof(u2));
2918   }
2919 
2920   // Copy method parameters
2921   if (method_parameters_length > 0) {
2922     MethodParametersElement* elem = m->constMethod()->method_parameters_start();
2923     for (int i = 0; i < method_parameters_length; i++) {
2924       elem[i].name_cp_index = Bytes::get_Java_u2((address)method_parameters_data);
2925       method_parameters_data += 2;
2926       elem[i].flags = Bytes::get_Java_u2((address)method_parameters_data);
2927       method_parameters_data += 2;
2928     }
2929   }
2930 
2931   // Copy checked exceptions
2932   if (checked_exceptions_length > 0) {
2933     Copy::conjoint_swap_if_needed<Endian::JAVA>(checked_exceptions_start,
2934                                                 m->checked_exceptions_start(),
2935                                                 checked_exceptions_length * sizeof(CheckedExceptionElement),
2936                                                 sizeof(u2));
2937   }
2938 
2939   // Copy class file LVT's/LVTT's into the HotSpot internal LVT.
2940   if (total_lvt_length > 0) {
2941     promoted_flags->set_has_localvariable_table();
2942     copy_localvariable_table(m->constMethod(),
2943                              lvt_cnt,
2944                              localvariable_table_length,
2945                              localvariable_table_start,
2946                              lvtt_cnt,
2947                              localvariable_type_table_length,
2948                              localvariable_type_table_start,
2949                              CHECK_NULL);
2950   }
2951 
2952   if (parsed_annotations.has_any_annotations())
2953     parsed_annotations.apply_to(m);
2954 
2955   // Copy annotations
2956   copy_method_annotations(m->constMethod(),
2957                           runtime_visible_annotations,
2958                           runtime_visible_annotations_length,
2959                           runtime_invisible_annotations,
2960                           runtime_invisible_annotations_length,
2961                           runtime_visible_parameter_annotations,
2962                           runtime_visible_parameter_annotations_length,
2963                           runtime_invisible_parameter_annotations,
2964                           runtime_invisible_parameter_annotations_length,
2965                           runtime_visible_type_annotations,
2966                           runtime_visible_type_annotations_length,
2967                           runtime_invisible_type_annotations,
2968                           runtime_invisible_type_annotations_length,
2969                           annotation_default,
2970                           annotation_default_length,
2971                           CHECK_NULL);
2972 
2973   if (name == vmSymbols::finalize_method_name() &&
2974       signature == vmSymbols::void_method_signature()) {
2975     if (m->is_empty_method()) {
2976       _has_empty_finalizer = true;
2977     } else {
2978       _has_finalizer = true;
2979     }
2980   }
2981   if (name == vmSymbols::object_initializer_name() &&
2982       signature == vmSymbols::void_method_signature() &&
2983       m->is_vanilla_constructor()) {
2984     _has_vanilla_constructor = true;
2985   }
2986 
2987   NOT_PRODUCT(m->verify());
2988   return m;
2989 }
2990 
2991 
2992 // The promoted_flags parameter is used to pass relevant access_flags
2993 // from the methods back up to the containing klass. These flag values
2994 // are added to klass's access_flags.
2995 // Side-effects: populates the _methods field in the parser
2996 void ClassFileParser::parse_methods(const ClassFileStream* const cfs,
2997                                     bool is_interface,
2998                                     bool is_value_type,
2999                                     AccessFlags* promoted_flags,
3000                                     bool* has_final_method,
3001                                     bool* declares_nonstatic_concrete_methods,
3002                                     TRAPS) {
3003   assert(cfs != NULL, "invariant");
3004   assert(promoted_flags != NULL, "invariant");
3005   assert(has_final_method != NULL, "invariant");
3006   assert(declares_nonstatic_concrete_methods != NULL, "invariant");
3007 
3008   assert(NULL == _methods, "invariant");
3009 
3010   cfs->guarantee_more(2, CHECK);  // length
3011   const u2 length = cfs->get_u2_fast();
3012   if (length == 0) {
3013     _methods = Universe::the_empty_method_array();
3014   } else {
3015     _methods = MetadataFactory::new_array<Method*>(_loader_data,
3016                                                    length,
3017                                                    NULL,
3018                                                    CHECK);
3019 
3020     for (int index = 0; index < length; index++) {
3021       Method* method = parse_method(cfs,
3022                                     is_interface,
3023                                     is_value_type,
3024                                     _cp,
3025                                     promoted_flags,
3026                                     CHECK);
3027 
3028       if (method->is_final()) {
3029         *has_final_method = true;
3030       }
3031       // declares_nonstatic_concrete_methods: declares concrete instance methods, any access flags
3032       // used for interface initialization, and default method inheritance analysis
3033       if (is_interface && !(*declares_nonstatic_concrete_methods)
3034         && !method->is_abstract() && !method->is_static()) {
3035         *declares_nonstatic_concrete_methods = true;
3036       }
3037       _methods->at_put(index, method);
3038     }
3039 
3040     if (_need_verify && length > 1) {
3041       // Check duplicated methods
3042       ResourceMark rm(THREAD);
3043       NameSigHash** names_and_sigs = NEW_RESOURCE_ARRAY_IN_THREAD(
3044         THREAD, NameSigHash*, HASH_ROW_SIZE);
3045       initialize_hashtable(names_and_sigs);
3046       bool dup = false;
3047       const Symbol* name = NULL;
3048       const Symbol* sig = NULL;
3049       {
3050         debug_only(NoSafepointVerifier nsv;)
3051         for (int i = 0; i < length; i++) {
3052           const Method* const m = _methods->at(i);
3053           name = m->name();
3054           sig = m->signature();
3055           // If no duplicates, add name/signature in hashtable names_and_sigs.
3056           if (!put_after_lookup(name, sig, names_and_sigs)) {
3057             dup = true;
3058             break;
3059           }
3060         }
3061       }
3062       if (dup) {
3063         classfile_parse_error("Duplicate method name \"%s\" with signature \"%s\" in class file %s",
3064                                name->as_C_string(), sig->as_klass_external_name(), CHECK);
3065       }
3066     }
3067   }
3068 }
3069 
3070 static const intArray* sort_methods(Array<Method*>* methods) {
3071   const int length = methods->length();
3072   // If JVMTI original method ordering or sharing is enabled we have to
3073   // remember the original class file ordering.
3074   // We temporarily use the vtable_index field in the Method* to store the
3075   // class file index, so we can read in after calling qsort.
3076   // Put the method ordering in the shared archive.
3077   if (JvmtiExport::can_maintain_original_method_order() || DumpSharedSpaces) {
3078     for (int index = 0; index < length; index++) {
3079       Method* const m = methods->at(index);
3080       assert(!m->valid_vtable_index(), "vtable index should not be set");
3081       m->set_vtable_index(index);
3082     }
3083   }
3084   // Sort method array by ascending method name (for faster lookups & vtable construction)
3085   // Note that the ordering is not alphabetical, see Symbol::fast_compare
3086   Method::sort_methods(methods);
3087 
3088   intArray* method_ordering = NULL;
3089   // If JVMTI original method ordering or sharing is enabled construct int
3090   // array remembering the original ordering
3091   if (JvmtiExport::can_maintain_original_method_order() || DumpSharedSpaces) {
3092     method_ordering = new intArray(length, length, -1);
3093     for (int index = 0; index < length; index++) {
3094       Method* const m = methods->at(index);
3095       const int old_index = m->vtable_index();
3096       assert(old_index >= 0 && old_index < length, "invalid method index");
3097       method_ordering->at_put(index, old_index);
3098       m->set_vtable_index(Method::invalid_vtable_index);
3099     }
3100   }
3101   return method_ordering;
3102 }
3103 
3104 // Parse generic_signature attribute for methods and fields
3105 u2 ClassFileParser::parse_generic_signature_attribute(const ClassFileStream* const cfs,
3106                                                       TRAPS) {
3107   assert(cfs != NULL, "invariant");
3108 
3109   cfs->guarantee_more(2, CHECK_0);  // generic_signature_index
3110   const u2 generic_signature_index = cfs->get_u2_fast();
3111   check_property(
3112     valid_symbol_at(generic_signature_index),
3113     "Invalid Signature attribute at constant pool index %u in class file %s",
3114     generic_signature_index, CHECK_0);
3115   return generic_signature_index;
3116 }
3117 
3118 void ClassFileParser::parse_classfile_sourcefile_attribute(const ClassFileStream* const cfs,
3119                                                            TRAPS) {
3120 
3121   assert(cfs != NULL, "invariant");
3122 
3123   cfs->guarantee_more(2, CHECK);  // sourcefile_index
3124   const u2 sourcefile_index = cfs->get_u2_fast();
3125   check_property(
3126     valid_symbol_at(sourcefile_index),
3127     "Invalid SourceFile attribute at constant pool index %u in class file %s",
3128     sourcefile_index, CHECK);
3129   set_class_sourcefile_index(sourcefile_index);
3130 }
3131 
3132 void ClassFileParser::parse_classfile_source_debug_extension_attribute(const ClassFileStream* const cfs,
3133                                                                        int length,
3134                                                                        TRAPS) {
3135   assert(cfs != NULL, "invariant");
3136 
3137   const u1* const sde_buffer = cfs->current();
3138   assert(sde_buffer != NULL, "null sde buffer");
3139 
3140   // Don't bother storing it if there is no way to retrieve it
3141   if (JvmtiExport::can_get_source_debug_extension()) {
3142     assert((length+1) > length, "Overflow checking");
3143     u1* const sde = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, u1, length+1);
3144     for (int i = 0; i < length; i++) {
3145       sde[i] = sde_buffer[i];
3146     }
3147     sde[length] = '\0';
3148     set_class_sde_buffer((const char*)sde, length);
3149   }
3150   // Got utf8 string, set stream position forward
3151   cfs->skip_u1(length, CHECK);
3152 }
3153 
3154 
3155 // Inner classes can be static, private or protected (classic VM does this)
3156 #define RECOGNIZED_INNER_CLASS_MODIFIERS ( JVM_RECOGNIZED_CLASS_MODIFIERS | \
3157                                            JVM_ACC_PRIVATE |                \
3158                                            JVM_ACC_PROTECTED |              \
3159                                            JVM_ACC_STATIC                   \
3160                                          )
3161 
3162 // Return number of classes in the inner classes attribute table
3163 u2 ClassFileParser::parse_classfile_inner_classes_attribute(const ClassFileStream* const cfs,
3164                                                             const u1* const inner_classes_attribute_start,
3165                                                             bool parsed_enclosingmethod_attribute,
3166                                                             u2 enclosing_method_class_index,
3167                                                             u2 enclosing_method_method_index,
3168                                                             TRAPS) {
3169   const u1* const current_mark = cfs->current();
3170   u2 length = 0;
3171   if (inner_classes_attribute_start != NULL) {
3172     cfs->set_current(inner_classes_attribute_start);
3173     cfs->guarantee_more(2, CHECK_0);  // length
3174     length = cfs->get_u2_fast();
3175   }
3176 
3177   // 4-tuples of shorts of inner classes data and 2 shorts of enclosing
3178   // method data:
3179   //   [inner_class_info_index,
3180   //    outer_class_info_index,
3181   //    inner_name_index,
3182   //    inner_class_access_flags,
3183   //    ...
3184   //    enclosing_method_class_index,
3185   //    enclosing_method_method_index]
3186   const int size = length * 4 + (parsed_enclosingmethod_attribute ? 2 : 0);
3187   Array<u2>* const inner_classes = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
3188   _inner_classes = inner_classes;
3189 
3190   int index = 0;
3191   cfs->guarantee_more(8 * length, CHECK_0);  // 4-tuples of u2
3192   for (int n = 0; n < length; n++) {
3193     // Inner class index
3194     const u2 inner_class_info_index = cfs->get_u2_fast();
3195     check_property(
3196       valid_klass_reference_at(inner_class_info_index),
3197       "inner_class_info_index %u has bad constant type in class file %s",
3198       inner_class_info_index, CHECK_0);
3199     // Outer class index
3200     const u2 outer_class_info_index = cfs->get_u2_fast();
3201     check_property(
3202       outer_class_info_index == 0 ||
3203         valid_klass_reference_at(outer_class_info_index),
3204       "outer_class_info_index %u has bad constant type in class file %s",
3205       outer_class_info_index, CHECK_0);
3206     // Inner class name
3207     const u2 inner_name_index = cfs->get_u2_fast();
3208     check_property(
3209       inner_name_index == 0 || valid_symbol_at(inner_name_index),
3210       "inner_name_index %u has bad constant type in class file %s",
3211       inner_name_index, CHECK_0);
3212     if (_need_verify) {
3213       guarantee_property(inner_class_info_index != outer_class_info_index,
3214                          "Class is both outer and inner class in class file %s", CHECK_0);
3215     }
3216 
3217     jint recognized_modifiers = RECOGNIZED_INNER_CLASS_MODIFIERS;
3218     // JVM_ACC_MODULE is defined in JDK-9 and later.
3219     if (_major_version >= JAVA_9_VERSION) {
3220       recognized_modifiers |= JVM_ACC_MODULE;
3221     }
3222     // JVM_ACC_VALUE is defined for class file version 55 and later
3223     if (supports_value_types()) {
3224       recognized_modifiers |= JVM_ACC_VALUE;
3225     }
3226 
3227     // Access flags
3228     jint flags = cfs->get_u2_fast() & recognized_modifiers;
3229 
3230     if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
3231       // Set abstract bit for old class files for backward compatibility
3232       flags |= JVM_ACC_ABSTRACT;
3233     }
3234     verify_legal_class_modifiers(flags, CHECK_0);
3235     AccessFlags inner_access_flags(flags);
3236 
3237     inner_classes->at_put(index++, inner_class_info_index);
3238     inner_classes->at_put(index++, outer_class_info_index);
3239     inner_classes->at_put(index++, inner_name_index);
3240     inner_classes->at_put(index++, inner_access_flags.as_short());
3241   }
3242 
3243   // 4347400: make sure there's no duplicate entry in the classes array
3244   if (_need_verify && _major_version >= JAVA_1_5_VERSION) {
3245     for(int i = 0; i < length * 4; i += 4) {
3246       for(int j = i + 4; j < length * 4; j += 4) {
3247         guarantee_property((inner_classes->at(i)   != inner_classes->at(j) ||
3248                             inner_classes->at(i+1) != inner_classes->at(j+1) ||
3249                             inner_classes->at(i+2) != inner_classes->at(j+2) ||
3250                             inner_classes->at(i+3) != inner_classes->at(j+3)),
3251                             "Duplicate entry in InnerClasses in class file %s",
3252                             CHECK_0);
3253       }
3254     }
3255   }
3256 
3257   // Set EnclosingMethod class and method indexes.
3258   if (parsed_enclosingmethod_attribute) {
3259     inner_classes->at_put(index++, enclosing_method_class_index);
3260     inner_classes->at_put(index++, enclosing_method_method_index);
3261   }
3262   assert(index == size, "wrong size");
3263 
3264   // Restore buffer's current position.
3265   cfs->set_current(current_mark);
3266 
3267   return length;
3268 }
3269 
3270 u2 ClassFileParser::parse_classfile_nest_members_attribute(const ClassFileStream* const cfs,
3271                                                            const u1* const nest_members_attribute_start,
3272                                                            TRAPS) {
3273   const u1* const current_mark = cfs->current();
3274   u2 length = 0;
3275   if (nest_members_attribute_start != NULL) {
3276     cfs->set_current(nest_members_attribute_start);
3277     cfs->guarantee_more(2, CHECK_0);  // length
3278     length = cfs->get_u2_fast();
3279   }
3280   const int size = length;
3281   Array<u2>* const nest_members = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
3282   _nest_members = nest_members;
3283 
3284   int index = 0;
3285   cfs->guarantee_more(2 * length, CHECK_0);
3286   for (int n = 0; n < length; n++) {
3287     const u2 class_info_index = cfs->get_u2_fast();
3288     check_property(
3289       valid_klass_reference_at(class_info_index),
3290       "Nest member class_info_index %u has bad constant type in class file %s",
3291       class_info_index, CHECK_0);
3292     nest_members->at_put(index++, class_info_index);
3293   }
3294   assert(index == size, "wrong size");
3295 
3296   // Restore buffer's current position.
3297   cfs->set_current(current_mark);
3298 
3299   return length;
3300 }
3301 
3302 void ClassFileParser::parse_classfile_synthetic_attribute(TRAPS) {
3303   set_class_synthetic_flag(true);
3304 }
3305 
3306 void ClassFileParser::parse_classfile_signature_attribute(const ClassFileStream* const cfs, TRAPS) {
3307   assert(cfs != NULL, "invariant");
3308 
3309   const u2 signature_index = cfs->get_u2(CHECK);
3310   check_property(
3311     valid_symbol_at(signature_index),
3312     "Invalid constant pool index %u in Signature attribute in class file %s",
3313     signature_index, CHECK);
3314   set_class_generic_signature_index(signature_index);
3315 }
3316 
3317 void ClassFileParser::parse_classfile_bootstrap_methods_attribute(const ClassFileStream* const cfs,
3318                                                                   ConstantPool* cp,
3319                                                                   u4 attribute_byte_length,
3320                                                                   TRAPS) {
3321   assert(cfs != NULL, "invariant");
3322   assert(cp != NULL, "invariant");
3323 
3324   const u1* const current_start = cfs->current();
3325 
3326   guarantee_property(attribute_byte_length >= sizeof(u2),
3327                      "Invalid BootstrapMethods attribute length %u in class file %s",
3328                      attribute_byte_length,
3329                      CHECK);
3330 
3331   cfs->guarantee_more(attribute_byte_length, CHECK);
3332 
3333   const int attribute_array_length = cfs->get_u2_fast();
3334 
3335   guarantee_property(_max_bootstrap_specifier_index < attribute_array_length,
3336                      "Short length on BootstrapMethods in class file %s",
3337                      CHECK);
3338 
3339 
3340   // The attribute contains a counted array of counted tuples of shorts,
3341   // represending bootstrap specifiers:
3342   //    length*{bootstrap_method_index, argument_count*{argument_index}}
3343   const int operand_count = (attribute_byte_length - sizeof(u2)) / sizeof(u2);
3344   // operand_count = number of shorts in attr, except for leading length
3345 
3346   // The attribute is copied into a short[] array.
3347   // The array begins with a series of short[2] pairs, one for each tuple.
3348   const int index_size = (attribute_array_length * 2);
3349 
3350   Array<u2>* const operands =
3351     MetadataFactory::new_array<u2>(_loader_data, index_size + operand_count, CHECK);
3352 
3353   // Eagerly assign operands so they will be deallocated with the constant
3354   // pool if there is an error.
3355   cp->set_operands(operands);
3356 
3357   int operand_fill_index = index_size;
3358   const int cp_size = cp->length();
3359 
3360   for (int n = 0; n < attribute_array_length; n++) {
3361     // Store a 32-bit offset into the header of the operand array.
3362     ConstantPool::operand_offset_at_put(operands, n, operand_fill_index);
3363 
3364     // Read a bootstrap specifier.
3365     cfs->guarantee_more(sizeof(u2) * 2, CHECK);  // bsm, argc
3366     const u2 bootstrap_method_index = cfs->get_u2_fast();
3367     const u2 argument_count = cfs->get_u2_fast();
3368     check_property(
3369       valid_cp_range(bootstrap_method_index, cp_size) &&
3370       cp->tag_at(bootstrap_method_index).is_method_handle(),
3371       "bootstrap_method_index %u has bad constant type in class file %s",
3372       bootstrap_method_index,
3373       CHECK);
3374 
3375     guarantee_property((operand_fill_index + 1 + argument_count) < operands->length(),
3376       "Invalid BootstrapMethods num_bootstrap_methods or num_bootstrap_arguments value in class file %s",
3377       CHECK);
3378 
3379     operands->at_put(operand_fill_index++, bootstrap_method_index);
3380     operands->at_put(operand_fill_index++, argument_count);
3381 
3382     cfs->guarantee_more(sizeof(u2) * argument_count, CHECK);  // argv[argc]
3383     for (int j = 0; j < argument_count; j++) {
3384       const u2 argument_index = cfs->get_u2_fast();
3385       check_property(
3386         valid_cp_range(argument_index, cp_size) &&
3387         cp->tag_at(argument_index).is_loadable_constant(),
3388         "argument_index %u has bad constant type in class file %s",
3389         argument_index,
3390         CHECK);
3391       operands->at_put(operand_fill_index++, argument_index);
3392     }
3393   }
3394   guarantee_property(current_start + attribute_byte_length == cfs->current(),
3395                      "Bad length on BootstrapMethods in class file %s",
3396                      CHECK);
3397 }
3398 
3399 void ClassFileParser::parse_classfile_attributes(const ClassFileStream* const cfs,
3400                                                  ConstantPool* cp,
3401                  ClassFileParser::ClassAnnotationCollector* parsed_annotations,
3402                                                  TRAPS) {
3403   assert(cfs != NULL, "invariant");
3404   assert(cp != NULL, "invariant");
3405   assert(parsed_annotations != NULL, "invariant");
3406 
3407   // Set inner classes attribute to default sentinel
3408   _inner_classes = Universe::the_empty_short_array();
3409   // Set nest members attribute to default sentinel
3410   _nest_members = Universe::the_empty_short_array();
3411   cfs->guarantee_more(2, CHECK);  // attributes_count
3412   u2 attributes_count = cfs->get_u2_fast();
3413   bool parsed_sourcefile_attribute = false;
3414   bool parsed_innerclasses_attribute = false;
3415   bool parsed_nest_members_attribute = false;
3416   bool parsed_nest_host_attribute = false;
3417   bool parsed_enclosingmethod_attribute = false;
3418   bool parsed_bootstrap_methods_attribute = false;
3419   const u1* runtime_visible_annotations = NULL;
3420   int runtime_visible_annotations_length = 0;
3421   const u1* runtime_invisible_annotations = NULL;
3422   int runtime_invisible_annotations_length = 0;
3423   const u1* runtime_visible_type_annotations = NULL;
3424   int runtime_visible_type_annotations_length = 0;
3425   const u1* runtime_invisible_type_annotations = NULL;
3426   int runtime_invisible_type_annotations_length = 0;
3427   bool runtime_invisible_type_annotations_exists = false;
3428   bool runtime_invisible_annotations_exists = false;
3429   bool parsed_source_debug_ext_annotations_exist = false;
3430   const u1* inner_classes_attribute_start = NULL;
3431   u4  inner_classes_attribute_length = 0;
3432   const u1* value_types_attribute_start = NULL;
3433   u4 value_types_attribute_length = 0;
3434   u2  enclosing_method_class_index = 0;
3435   u2  enclosing_method_method_index = 0;
3436   const u1* nest_members_attribute_start = NULL;
3437   u4  nest_members_attribute_length = 0;
3438 
3439   // Iterate over attributes
3440   while (attributes_count--) {
3441     cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
3442     const u2 attribute_name_index = cfs->get_u2_fast();
3443     const u4 attribute_length = cfs->get_u4_fast();
3444     check_property(
3445       valid_symbol_at(attribute_name_index),
3446       "Attribute name has bad constant pool index %u in class file %s",
3447       attribute_name_index, CHECK);
3448     const Symbol* const tag = cp->symbol_at(attribute_name_index);
3449     if (tag == vmSymbols::tag_source_file()) {
3450       // Check for SourceFile tag
3451       if (_need_verify) {
3452         guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
3453       }
3454       if (parsed_sourcefile_attribute) {
3455         classfile_parse_error("Multiple SourceFile attributes in class file %s", CHECK);
3456       } else {
3457         parsed_sourcefile_attribute = true;
3458       }
3459       parse_classfile_sourcefile_attribute(cfs, CHECK);
3460     } else if (tag == vmSymbols::tag_source_debug_extension()) {
3461       // Check for SourceDebugExtension tag
3462       if (parsed_source_debug_ext_annotations_exist) {
3463           classfile_parse_error(
3464             "Multiple SourceDebugExtension attributes in class file %s", CHECK);
3465       }
3466       parsed_source_debug_ext_annotations_exist = true;
3467       parse_classfile_source_debug_extension_attribute(cfs, (int)attribute_length, CHECK);
3468     } else if (tag == vmSymbols::tag_inner_classes()) {
3469       // Check for InnerClasses tag
3470       if (parsed_innerclasses_attribute) {
3471         classfile_parse_error("Multiple InnerClasses attributes in class file %s", CHECK);
3472       } else {
3473         parsed_innerclasses_attribute = true;
3474       }
3475       inner_classes_attribute_start = cfs->current();
3476       inner_classes_attribute_length = attribute_length;
3477       cfs->skip_u1(inner_classes_attribute_length, CHECK);
3478     } else if (tag == vmSymbols::tag_synthetic()) {
3479       // Check for Synthetic tag
3480       // Shouldn't we check that the synthetic flags wasn't already set? - not required in spec
3481       if (attribute_length != 0) {
3482         classfile_parse_error(
3483           "Invalid Synthetic classfile attribute length %u in class file %s",
3484           attribute_length, CHECK);
3485       }
3486       parse_classfile_synthetic_attribute(CHECK);
3487     } else if (tag == vmSymbols::tag_deprecated()) {
3488       // Check for Deprecatd tag - 4276120
3489       if (attribute_length != 0) {
3490         classfile_parse_error(
3491           "Invalid Deprecated classfile attribute length %u in class file %s",
3492           attribute_length, CHECK);
3493       }
3494     } else if (_major_version >= JAVA_1_5_VERSION) {
3495       if (tag == vmSymbols::tag_signature()) {
3496         if (_generic_signature_index != 0) {
3497           classfile_parse_error(
3498             "Multiple Signature attributes in class file %s", CHECK);
3499         }
3500         if (attribute_length != 2) {
3501           classfile_parse_error(
3502             "Wrong Signature attribute length %u in class file %s",
3503             attribute_length, CHECK);
3504         }
3505         parse_classfile_signature_attribute(cfs, CHECK);
3506       } else if (tag == vmSymbols::tag_runtime_visible_annotations()) {
3507         if (runtime_visible_annotations != NULL) {
3508           classfile_parse_error(
3509             "Multiple RuntimeVisibleAnnotations attributes in class file %s", CHECK);
3510         }
3511         runtime_visible_annotations_length = attribute_length;
3512         runtime_visible_annotations = cfs->current();
3513         assert(runtime_visible_annotations != NULL, "null visible annotations");
3514         cfs->guarantee_more(runtime_visible_annotations_length, CHECK);
3515         parse_annotations(cp,
3516                           runtime_visible_annotations,
3517                           runtime_visible_annotations_length,
3518                           parsed_annotations,
3519                           _loader_data,
3520                           CHECK);
3521         cfs->skip_u1_fast(runtime_visible_annotations_length);
3522       } else if (tag == vmSymbols::tag_runtime_invisible_annotations()) {
3523         if (runtime_invisible_annotations_exists) {
3524           classfile_parse_error(
3525             "Multiple RuntimeInvisibleAnnotations attributes in class file %s", CHECK);
3526         }
3527         runtime_invisible_annotations_exists = true;
3528         if (PreserveAllAnnotations) {
3529           runtime_invisible_annotations_length = attribute_length;
3530           runtime_invisible_annotations = cfs->current();
3531           assert(runtime_invisible_annotations != NULL, "null invisible annotations");
3532         }
3533         cfs->skip_u1(attribute_length, CHECK);
3534       } else if (tag == vmSymbols::tag_enclosing_method()) {
3535         if (parsed_enclosingmethod_attribute) {
3536           classfile_parse_error("Multiple EnclosingMethod attributes in class file %s", CHECK);
3537         } else {
3538           parsed_enclosingmethod_attribute = true;
3539         }
3540         guarantee_property(attribute_length == 4,
3541           "Wrong EnclosingMethod attribute length %u in class file %s",
3542           attribute_length, CHECK);
3543         cfs->guarantee_more(4, CHECK);  // class_index, method_index
3544         enclosing_method_class_index  = cfs->get_u2_fast();
3545         enclosing_method_method_index = cfs->get_u2_fast();
3546         if (enclosing_method_class_index == 0) {
3547           classfile_parse_error("Invalid class index in EnclosingMethod attribute in class file %s", CHECK);
3548         }
3549         // Validate the constant pool indices and types
3550         check_property(valid_klass_reference_at(enclosing_method_class_index),
3551           "Invalid or out-of-bounds class index in EnclosingMethod attribute in class file %s", CHECK);
3552         if (enclosing_method_method_index != 0 &&
3553             (!cp->is_within_bounds(enclosing_method_method_index) ||
3554              !cp->tag_at(enclosing_method_method_index).is_name_and_type())) {
3555           classfile_parse_error("Invalid or out-of-bounds method index in EnclosingMethod attribute in class file %s", CHECK);
3556         }
3557       } else if (tag == vmSymbols::tag_bootstrap_methods() &&
3558                  _major_version >= Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {
3559         if (parsed_bootstrap_methods_attribute) {
3560           classfile_parse_error("Multiple BootstrapMethods attributes in class file %s", CHECK);
3561         }
3562         parsed_bootstrap_methods_attribute = true;
3563         parse_classfile_bootstrap_methods_attribute(cfs, cp, attribute_length, CHECK);
3564       } else if (tag == vmSymbols::tag_runtime_visible_type_annotations()) {
3565         if (runtime_visible_type_annotations != NULL) {
3566           classfile_parse_error(
3567             "Multiple RuntimeVisibleTypeAnnotations attributes in class file %s", CHECK);
3568         }
3569         runtime_visible_type_annotations_length = attribute_length;
3570         runtime_visible_type_annotations = cfs->current();
3571         assert(runtime_visible_type_annotations != NULL, "null visible type annotations");
3572         // No need for the VM to parse Type annotations
3573         cfs->skip_u1(runtime_visible_type_annotations_length, CHECK);
3574       } else if (tag == vmSymbols::tag_runtime_invisible_type_annotations()) {
3575         if (runtime_invisible_type_annotations_exists) {
3576           classfile_parse_error(
3577             "Multiple RuntimeInvisibleTypeAnnotations attributes in class file %s", CHECK);
3578         } else {
3579           runtime_invisible_type_annotations_exists = true;
3580         }
3581         if (PreserveAllAnnotations) {
3582           runtime_invisible_type_annotations_length = attribute_length;
3583           runtime_invisible_type_annotations = cfs->current();
3584           assert(runtime_invisible_type_annotations != NULL, "null invisible type annotations");
3585         }
3586         cfs->skip_u1(attribute_length, CHECK);
3587       } else if (_major_version >= JAVA_11_VERSION) {
3588         if (tag == vmSymbols::tag_nest_members()) {
3589           // Check for NestMembers tag
3590           if (parsed_nest_members_attribute) {
3591             classfile_parse_error("Multiple NestMembers attributes in class file %s", CHECK);
3592           } else {
3593             parsed_nest_members_attribute = true;
3594           }
3595           if (parsed_nest_host_attribute) {
3596             classfile_parse_error("Conflicting NestHost and NestMembers attributes in class file %s", CHECK);
3597           }
3598           nest_members_attribute_start = cfs->current();
3599           nest_members_attribute_length = attribute_length;
3600           cfs->skip_u1(nest_members_attribute_length, CHECK);
3601         } else if (tag == vmSymbols::tag_nest_host()) {
3602           if (parsed_nest_host_attribute) {
3603             classfile_parse_error("Multiple NestHost attributes in class file %s", CHECK);
3604           } else {
3605             parsed_nest_host_attribute = true;
3606           }
3607           if (parsed_nest_members_attribute) {
3608             classfile_parse_error("Conflicting NestMembers and NestHost attributes in class file %s", CHECK);
3609           }
3610           if (_need_verify) {
3611             guarantee_property(attribute_length == 2, "Wrong NestHost attribute length in class file %s", CHECK);
3612           }
3613           cfs->guarantee_more(2, CHECK);
3614           u2 class_info_index = cfs->get_u2_fast();
3615           check_property(
3616                          valid_klass_reference_at(class_info_index),
3617                          "Nest-host class_info_index %u has bad constant type in class file %s",
3618                          class_info_index, CHECK);
3619           _nest_host = class_info_index;
3620         } else {
3621           // Unknown attribute
3622           cfs->skip_u1(attribute_length, CHECK);
3623         }
3624       } else {
3625         // Unknown attribute
3626         cfs->skip_u1(attribute_length, CHECK);
3627       }
3628     } else {
3629       // Unknown attribute
3630       cfs->skip_u1(attribute_length, CHECK);
3631     }
3632   }
3633   _annotations = assemble_annotations(runtime_visible_annotations,
3634                                       runtime_visible_annotations_length,
3635                                       runtime_invisible_annotations,
3636                                       runtime_invisible_annotations_length,
3637                                       CHECK);
3638   _type_annotations = assemble_annotations(runtime_visible_type_annotations,
3639                                            runtime_visible_type_annotations_length,
3640                                            runtime_invisible_type_annotations,
3641                                            runtime_invisible_type_annotations_length,
3642                                            CHECK);
3643 
3644   if (parsed_innerclasses_attribute || parsed_enclosingmethod_attribute) {
3645     const u2 num_of_classes = parse_classfile_inner_classes_attribute(
3646                             cfs,
3647                             inner_classes_attribute_start,
3648                             parsed_innerclasses_attribute,
3649                             enclosing_method_class_index,
3650                             enclosing_method_method_index,
3651                             CHECK);
3652     if (parsed_innerclasses_attribute && _need_verify && _major_version >= JAVA_1_5_VERSION) {
3653       guarantee_property(
3654         inner_classes_attribute_length == sizeof(num_of_classes) + 4 * sizeof(u2) * num_of_classes,
3655         "Wrong InnerClasses attribute length in class file %s", CHECK);
3656     }
3657   }
3658 
3659   if (parsed_nest_members_attribute) {
3660     const u2 num_of_classes = parse_classfile_nest_members_attribute(
3661                             cfs,
3662                             nest_members_attribute_start,
3663                             CHECK);
3664     if (_need_verify) {
3665       guarantee_property(
3666         nest_members_attribute_length == sizeof(num_of_classes) + sizeof(u2) * num_of_classes,
3667         "Wrong NestMembers attribute length in class file %s", CHECK);
3668     }
3669   }
3670 
3671   if (_max_bootstrap_specifier_index >= 0) {
3672     guarantee_property(parsed_bootstrap_methods_attribute,
3673                        "Missing BootstrapMethods attribute in class file %s", CHECK);
3674   }
3675 }
3676 
3677 void ClassFileParser::apply_parsed_class_attributes(InstanceKlass* k) {
3678   assert(k != NULL, "invariant");
3679 
3680   if (_synthetic_flag)
3681     k->set_is_synthetic();
3682   if (_sourcefile_index != 0) {
3683     k->set_source_file_name_index(_sourcefile_index);
3684   }
3685   if (_generic_signature_index != 0) {
3686     k->set_generic_signature_index(_generic_signature_index);
3687   }
3688   if (_sde_buffer != NULL) {
3689     k->set_source_debug_extension(_sde_buffer, _sde_length);
3690   }
3691 }
3692 
3693 // Create the Annotations object that will
3694 // hold the annotations array for the Klass.
3695 void ClassFileParser::create_combined_annotations(TRAPS) {
3696     if (_annotations == NULL &&
3697         _type_annotations == NULL &&
3698         _fields_annotations == NULL &&
3699         _fields_type_annotations == NULL) {
3700       // Don't create the Annotations object unnecessarily.
3701       return;
3702     }
3703 
3704     Annotations* const annotations = Annotations::allocate(_loader_data, CHECK);
3705     annotations->set_class_annotations(_annotations);
3706     annotations->set_class_type_annotations(_type_annotations);
3707     annotations->set_fields_annotations(_fields_annotations);
3708     annotations->set_fields_type_annotations(_fields_type_annotations);
3709 
3710     // This is the Annotations object that will be
3711     // assigned to InstanceKlass being constructed.
3712     _combined_annotations = annotations;
3713 
3714     // The annotations arrays below has been transfered the
3715     // _combined_annotations so these fields can now be cleared.
3716     _annotations             = NULL;
3717     _type_annotations        = NULL;
3718     _fields_annotations      = NULL;
3719     _fields_type_annotations = NULL;
3720 }
3721 
3722 // Transfer ownership of metadata allocated to the InstanceKlass.
3723 void ClassFileParser::apply_parsed_class_metadata(
3724                                             InstanceKlass* this_klass,
3725                                             int java_fields_count, TRAPS) {
3726   assert(this_klass != NULL, "invariant");
3727 
3728   _cp->set_pool_holder(this_klass);
3729   this_klass->set_constants(_cp);
3730   this_klass->set_fields(_fields, java_fields_count);
3731   this_klass->set_methods(_methods);
3732   this_klass->set_inner_classes(_inner_classes);
3733   this_klass->set_nest_members(_nest_members);
3734   this_klass->set_nest_host_index(_nest_host);
3735   this_klass->set_local_interfaces(_local_interfaces);
3736   this_klass->set_annotations(_combined_annotations);
3737   // Delay the setting of _transitive_interfaces until after initialize_supers() in
3738   // fill_instance_klass(). It is because the _transitive_interfaces may be shared with
3739   // its _super. If an OOM occurs while loading the current klass, its _super field
3740   // may not have been set. When GC tries to free the klass, the _transitive_interfaces
3741   // may be deallocated mistakenly in InstanceKlass::deallocate_interfaces(). Subsequent
3742   // dereferences to the deallocated _transitive_interfaces will result in a crash.
3743 
3744   // Clear out these fields so they don't get deallocated by the destructor
3745   clear_class_metadata();
3746 }
3747 
3748 AnnotationArray* ClassFileParser::assemble_annotations(const u1* const runtime_visible_annotations,
3749                                                        int runtime_visible_annotations_length,
3750                                                        const u1* const runtime_invisible_annotations,
3751                                                        int runtime_invisible_annotations_length,
3752                                                        TRAPS) {
3753   AnnotationArray* annotations = NULL;
3754   if (runtime_visible_annotations != NULL ||
3755       runtime_invisible_annotations != NULL) {
3756     annotations = MetadataFactory::new_array<u1>(_loader_data,
3757                                           runtime_visible_annotations_length +
3758                                           runtime_invisible_annotations_length,
3759                                           CHECK_(annotations));
3760     if (runtime_visible_annotations != NULL) {
3761       for (int i = 0; i < runtime_visible_annotations_length; i++) {
3762         annotations->at_put(i, runtime_visible_annotations[i]);
3763       }
3764     }
3765     if (runtime_invisible_annotations != NULL) {
3766       for (int i = 0; i < runtime_invisible_annotations_length; i++) {
3767         int append = runtime_visible_annotations_length+i;
3768         annotations->at_put(append, runtime_invisible_annotations[i]);
3769       }
3770     }
3771   }
3772   return annotations;
3773 }
3774 
3775 const InstanceKlass* ClassFileParser::parse_super_class(ConstantPool* const cp,
3776                                                         const int super_class_index,
3777                                                         const bool need_verify,
3778                                                         TRAPS) {
3779   assert(cp != NULL, "invariant");
3780   const InstanceKlass* super_klass = NULL;
3781 
3782   if (super_class_index == 0) {
3783     check_property(_class_name == vmSymbols::java_lang_Object()
3784                    || (_access_flags.get_flags() & JVM_ACC_VALUE),
3785                    "Invalid superclass index %u in class file %s",
3786                    super_class_index,
3787                    CHECK_NULL);
3788   } else {
3789     check_property(valid_klass_reference_at(super_class_index),
3790                    "Invalid superclass index %u in class file %s",
3791                    super_class_index,
3792                    CHECK_NULL);
3793     // The class name should be legal because it is checked when parsing constant pool.
3794     // However, make sure it is not an array type.
3795     bool is_array = false;
3796     if (cp->tag_at(super_class_index).is_klass()) {
3797       super_klass = InstanceKlass::cast(cp->resolved_klass_at(super_class_index));
3798       if (need_verify)
3799         is_array = super_klass->is_array_klass();
3800     } else if (need_verify) {
3801       is_array = (cp->klass_name_at(super_class_index)->char_at(0) == JVM_SIGNATURE_ARRAY);
3802     }
3803     if (need_verify) {
3804       guarantee_property(!is_array,
3805                         "Bad superclass name in class file %s", CHECK_NULL);
3806     }
3807   }
3808   return super_klass;
3809 }
3810 
3811 #ifndef PRODUCT
3812 static void print_field_layout(const Symbol* name,
3813                                Array<u2>* fields,
3814                                const constantPoolHandle& cp,
3815                                int instance_size,
3816                                int instance_fields_start,
3817                                int instance_fields_end,
3818                                int static_fields_end) {
3819 
3820   assert(name != NULL, "invariant");
3821 
3822   tty->print("%s: field layout\n", name->as_klass_external_name());
3823   tty->print("  @%3d %s\n", instance_fields_start, "--- instance fields start ---");
3824   for (AllFieldStream fs(fields, cp); !fs.done(); fs.next()) {
3825     if (!fs.access_flags().is_static()) {
3826       tty->print("  @%3d \"%s\" %s\n",
3827         fs.offset(),
3828         fs.name()->as_klass_external_name(),
3829         fs.signature()->as_klass_external_name());
3830     }
3831   }
3832   tty->print("  @%3d %s\n", instance_fields_end, "--- instance fields end ---");
3833   tty->print("  @%3d %s\n", instance_size * wordSize, "--- instance ends ---");
3834   tty->print("  @%3d %s\n", InstanceMirrorKlass::offset_of_static_fields(), "--- static fields start ---");
3835   for (AllFieldStream fs(fields, cp); !fs.done(); fs.next()) {
3836     if (fs.access_flags().is_static()) {
3837       tty->print("  @%3d \"%s\" %s\n",
3838         fs.offset(),
3839         fs.name()->as_klass_external_name(),
3840         fs.signature()->as_klass_external_name());
3841     }
3842   }
3843   tty->print("  @%3d %s\n", static_fields_end, "--- static fields end ---");
3844   tty->print("\n");
3845 }
3846 #endif
3847 
3848 OopMapBlocksBuilder::OopMapBlocksBuilder(unsigned int  max_blocks, TRAPS) {
3849   max_nonstatic_oop_maps = max_blocks;
3850   nonstatic_oop_map_count = 0;
3851   if (max_blocks == 0) {
3852     nonstatic_oop_maps = NULL;
3853   } else {
3854     nonstatic_oop_maps = NEW_RESOURCE_ARRAY_IN_THREAD(
3855         THREAD, OopMapBlock, max_nonstatic_oop_maps);
3856     memset(nonstatic_oop_maps, 0, sizeof(OopMapBlock) * max_blocks);
3857   }
3858 }
3859 
3860 OopMapBlock* OopMapBlocksBuilder::last_oop_map() const {
3861   assert(nonstatic_oop_map_count > 0, "Has no oop maps");
3862   return nonstatic_oop_maps + (nonstatic_oop_map_count - 1);
3863 }
3864 
3865 // addition of super oop maps
3866 void OopMapBlocksBuilder::initialize_inherited_blocks(OopMapBlock* blocks, unsigned int nof_blocks) {
3867   assert(nof_blocks && nonstatic_oop_map_count == 0 &&
3868       nof_blocks <= max_nonstatic_oop_maps, "invariant");
3869 
3870   memcpy(nonstatic_oop_maps, blocks, sizeof(OopMapBlock) * nof_blocks);
3871   nonstatic_oop_map_count += nof_blocks;
3872 }
3873 
3874 // collection of oops
3875 void OopMapBlocksBuilder::add(int offset, int count) {
3876   if (nonstatic_oop_map_count == 0) {
3877     nonstatic_oop_map_count++;
3878   }
3879   OopMapBlock*  nonstatic_oop_map = last_oop_map();
3880   if (nonstatic_oop_map->count() == 0) {  // Unused map, set it up
3881     nonstatic_oop_map->set_offset(offset);
3882     nonstatic_oop_map->set_count(count);
3883   } else if (nonstatic_oop_map->is_contiguous(offset)) { // contiguous, add
3884     nonstatic_oop_map->increment_count(count);
3885   } else { // Need a new one...
3886     nonstatic_oop_map_count++;
3887     assert(nonstatic_oop_map_count <= max_nonstatic_oop_maps, "range check");
3888     nonstatic_oop_map = last_oop_map();
3889     nonstatic_oop_map->set_offset(offset);
3890     nonstatic_oop_map->set_count(count);
3891   }
3892 }
3893 
3894 // general purpose copy, e.g. into allocated instanceKlass
3895 void OopMapBlocksBuilder::copy(OopMapBlock* dst) {
3896   if (nonstatic_oop_map_count != 0) {
3897     memcpy(dst, nonstatic_oop_maps, sizeof(OopMapBlock) * nonstatic_oop_map_count);
3898   }
3899 }
3900 
3901 // Sort and compact adjacent blocks
3902 void OopMapBlocksBuilder::compact(TRAPS) {
3903   if (nonstatic_oop_map_count <= 1) {
3904     return;
3905   }
3906   /*
3907    * Since field layout sneeks in oops before values, we will be able to condense
3908    * blocks. There is potential to compact between super, own refs and values
3909    * containing refs.
3910    *
3911    * Currently compaction is slightly limited due to values being 8 byte aligned.
3912    * This may well change: FixMe if doesn't, the code below is fairly general purpose
3913    * and maybe it doesn't need to be.
3914    */
3915   qsort(nonstatic_oop_maps, nonstatic_oop_map_count, sizeof(OopMapBlock),
3916       (_sort_Fn)OopMapBlock::compare_offset);
3917   if (nonstatic_oop_map_count < 2) {
3918     return;
3919   }
3920 
3921   //Make a temp copy, and iterate through and copy back into the orig
3922   ResourceMark rm(THREAD);
3923   OopMapBlock* oop_maps_copy = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, OopMapBlock,
3924       nonstatic_oop_map_count);
3925   OopMapBlock* oop_maps_copy_end = oop_maps_copy + nonstatic_oop_map_count;
3926   copy(oop_maps_copy);
3927   OopMapBlock*  nonstatic_oop_map = nonstatic_oop_maps;
3928   unsigned int new_count = 1;
3929   oop_maps_copy++;
3930   while(oop_maps_copy < oop_maps_copy_end) {
3931     assert(nonstatic_oop_map->offset() < oop_maps_copy->offset(), "invariant");
3932     if (nonstatic_oop_map->is_contiguous(oop_maps_copy->offset())) {
3933       nonstatic_oop_map->increment_count(oop_maps_copy->count());
3934     } else {
3935       nonstatic_oop_map++;
3936       new_count++;
3937       nonstatic_oop_map->set_offset(oop_maps_copy->offset());
3938       nonstatic_oop_map->set_count(oop_maps_copy->count());
3939     }
3940     oop_maps_copy++;
3941   }
3942   assert(new_count <= nonstatic_oop_map_count, "end up with more maps after compact() ?");
3943   nonstatic_oop_map_count = new_count;
3944 }
3945 
3946 void OopMapBlocksBuilder::print_on(outputStream* st) const {
3947   st->print_cr("  OopMapBlocks: %3d  /%3d", nonstatic_oop_map_count, max_nonstatic_oop_maps);
3948   if (nonstatic_oop_map_count > 0) {
3949     OopMapBlock* map = nonstatic_oop_maps;
3950     OopMapBlock* last_map = last_oop_map();
3951     assert(map <= last_map, "Last less than first");
3952     while (map <= last_map) {
3953       st->print_cr("    Offset: %3d  -%3d Count: %3d", map->offset(),
3954           map->offset() + map->offset_span() - heapOopSize, map->count());
3955       map++;
3956     }
3957   }
3958 }
3959 
3960 void OopMapBlocksBuilder::print_value_on(outputStream* st) const {
3961   print_on(st);
3962 }
3963 
3964 void ClassFileParser::throwValueTypeLimitation(THREAD_AND_LOCATION_DECL,
3965                                                const char* msg,
3966                                                const Symbol* name,
3967                                                const Symbol* sig) const {
3968 
3969   ResourceMark rm(THREAD);
3970   if (name == NULL || sig == NULL) {
3971     Exceptions::fthrow(THREAD_AND_LOCATION_ARGS,
3972         vmSymbols::java_lang_ClassFormatError(),
3973         "class: %s - %s", _class_name->as_C_string(), msg);
3974   }
3975   else {
3976     Exceptions::fthrow(THREAD_AND_LOCATION_ARGS,
3977         vmSymbols::java_lang_ClassFormatError(),
3978         "\"%s\" sig: \"%s\" class: %s - %s", name->as_C_string(), sig->as_C_string(),
3979         _class_name->as_C_string(), msg);
3980   }
3981 }
3982 
3983 // Layout fields and fill in FieldLayoutInfo.  Could use more refactoring!
3984 void ClassFileParser::layout_fields(ConstantPool* cp,
3985                                     const FieldAllocationCount* fac,
3986                                     const ClassAnnotationCollector* parsed_annotations,
3987                                     FieldLayoutInfo* info,
3988                                     TRAPS) {
3989 
3990   assert(cp != NULL, "invariant");
3991 
3992   // Field size and offset computation
3993   int nonstatic_field_size = _super_klass == NULL ? 0 :
3994                                _super_klass->nonstatic_field_size();
3995   int next_nonstatic_valuetype_offset = 0;
3996   int first_nonstatic_valuetype_offset = 0;
3997 
3998   // Fields that are value types are handled differently depending if they are static or not:
3999   // - static fields are oops
4000   // - non-static fields are embedded
4001 
4002   // Count the contended fields by type.
4003   //
4004   // We ignore static fields, because @Contended is not supported for them.
4005   // The layout code below will also ignore the static fields.
4006   int nonstatic_contended_count = 0;
4007   FieldAllocationCount fac_contended;
4008   for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
4009     FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();
4010     if (fs.is_contended()) {
4011       fac_contended.count[atype]++;
4012       if (!fs.access_flags().is_static()) {
4013         nonstatic_contended_count++;
4014       }
4015     }
4016   }
4017 
4018 
4019   // Calculate the starting byte offsets
4020   int next_static_oop_offset    = InstanceMirrorKlass::offset_of_static_fields();
4021   // Value types in static fields are not embedded, they are handled with oops
4022   int next_static_double_offset = next_static_oop_offset +
4023                                   ((fac->count[STATIC_OOP] + fac->count[STATIC_FLATTENABLE]) * heapOopSize);
4024   if (fac->count[STATIC_DOUBLE]) {
4025     next_static_double_offset = align_up(next_static_double_offset, BytesPerLong);
4026   }
4027 
4028   int next_static_word_offset   = next_static_double_offset +
4029                                     ((fac->count[STATIC_DOUBLE]) * BytesPerLong);
4030   int next_static_short_offset  = next_static_word_offset +
4031                                     ((fac->count[STATIC_WORD]) * BytesPerInt);
4032   int next_static_byte_offset   = next_static_short_offset +
4033                                   ((fac->count[STATIC_SHORT]) * BytesPerShort);
4034 
4035   int nonstatic_fields_start  = instanceOopDesc::base_offset_in_bytes() +
4036                                 nonstatic_field_size * heapOopSize;
4037 
4038   // First field of value types is aligned on a long boundary in order to ease
4039   // in-lining of value types (with header removal) in packed arrays and
4040   // flatten value types
4041   int initial_value_type_padding = 0;
4042   if (is_value_type()) {
4043     int old = nonstatic_fields_start;
4044     nonstatic_fields_start = align_up(nonstatic_fields_start, BytesPerLong);
4045     initial_value_type_padding = nonstatic_fields_start - old;
4046   }
4047 
4048   int next_nonstatic_field_offset = nonstatic_fields_start;
4049 
4050   const bool is_contended_class     = parsed_annotations->is_contended();
4051 
4052   // Class is contended, pad before all the fields
4053   if (is_contended_class) {
4054     next_nonstatic_field_offset += ContendedPaddingWidth;
4055   }
4056 
4057   // Temporary value types restrictions
4058   if (is_value_type()) {
4059     if (is_contended_class) {
4060       throwValueTypeLimitation(THREAD_AND_LOCATION, "Value Types do not support @Contended annotation yet");
4061       return;
4062     }
4063   }
4064 
4065   // Compute the non-contended fields count.
4066   // The packing code below relies on these counts to determine if some field
4067   // can be squeezed into the alignment gap. Contended fields are obviously
4068   // exempt from that.
4069   unsigned int nonstatic_double_count = fac->count[NONSTATIC_DOUBLE] - fac_contended.count[NONSTATIC_DOUBLE];
4070   unsigned int nonstatic_word_count   = fac->count[NONSTATIC_WORD]   - fac_contended.count[NONSTATIC_WORD];
4071   unsigned int nonstatic_short_count  = fac->count[NONSTATIC_SHORT]  - fac_contended.count[NONSTATIC_SHORT];
4072   unsigned int nonstatic_byte_count   = fac->count[NONSTATIC_BYTE]   - fac_contended.count[NONSTATIC_BYTE];
4073   unsigned int nonstatic_oop_count    = fac->count[NONSTATIC_OOP]    - fac_contended.count[NONSTATIC_OOP];
4074 
4075   int static_value_type_count = 0;
4076   int nonstatic_value_type_count = 0;
4077   int* nonstatic_value_type_indexes = NULL;
4078   Klass** nonstatic_value_type_klasses = NULL;
4079   unsigned int value_type_oop_map_count = 0;
4080   int not_flattened_value_types = 0;
4081 
4082   int max_nonstatic_value_type = fac->count[NONSTATIC_FLATTENABLE] + 1;
4083 
4084   nonstatic_value_type_indexes = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, int,
4085                                                               max_nonstatic_value_type);
4086   for (int i = 0; i < max_nonstatic_value_type; i++) {
4087     nonstatic_value_type_indexes[i] = -1;
4088   }
4089   nonstatic_value_type_klasses = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, Klass*,
4090                                                               max_nonstatic_value_type);
4091 
4092   for (AllFieldStream fs(_fields, _cp); !fs.done(); fs.next()) {
4093     if (fs.allocation_type() == STATIC_FLATTENABLE) {
4094       ResourceMark rm;
4095       if (!fs.signature()->is_Q_signature()) {
4096         THROW(vmSymbols::java_lang_ClassFormatError());
4097       }
4098       static_value_type_count++;
4099     } else if (fs.allocation_type() == NONSTATIC_FLATTENABLE) {
4100       // Pre-resolve the flattenable field and check for value type circularity issues.
4101       ResourceMark rm;
4102       if (!fs.signature()->is_Q_signature()) {
4103         THROW(vmSymbols::java_lang_ClassFormatError());
4104       }
4105       Klass* klass =
4106         SystemDictionary::resolve_flattenable_field_or_fail(&fs,
4107                                                             Handle(THREAD, _loader_data->class_loader()),
4108                                                             _protection_domain, true, CHECK);
4109       assert(klass != NULL, "Sanity check");
4110       if (!klass->access_flags().is_value_type()) {
4111         THROW(vmSymbols::java_lang_IncompatibleClassChangeError());
4112       }
4113       ValueKlass* vk = ValueKlass::cast(klass);
4114       // Conditions to apply flattening or not should be defined in a single place
4115       if ((ValueFieldMaxFlatSize < 0) || (vk->size_helper() * HeapWordSize) <= ValueFieldMaxFlatSize) {
4116         nonstatic_value_type_indexes[nonstatic_value_type_count] = fs.index();
4117         nonstatic_value_type_klasses[nonstatic_value_type_count] = klass;
4118         nonstatic_value_type_count++;
4119 
4120         ValueKlass* vklass = ValueKlass::cast(klass);
4121         if (vklass->contains_oops()) {
4122           value_type_oop_map_count += vklass->nonstatic_oop_map_count();
4123         }
4124         fs.set_flattened(true);
4125       } else {
4126         not_flattened_value_types++;
4127         fs.set_flattened(false);
4128       }
4129     }
4130   }
4131 
4132   // Adjusting non_static_oop_count to take into account not flattened value types;
4133   nonstatic_oop_count += not_flattened_value_types;
4134 
4135   // Total non-static fields count, including every contended field
4136   unsigned int nonstatic_fields_count = fac->count[NONSTATIC_DOUBLE] + fac->count[NONSTATIC_WORD] +
4137                                         fac->count[NONSTATIC_SHORT] + fac->count[NONSTATIC_BYTE] +
4138                                         fac->count[NONSTATIC_OOP] + fac->count[NONSTATIC_FLATTENABLE];
4139 
4140   const bool super_has_nonstatic_fields =
4141           (_super_klass != NULL && _super_klass->has_nonstatic_fields());
4142   const bool has_nonstatic_fields =
4143     super_has_nonstatic_fields || (nonstatic_fields_count != 0);
4144   const bool has_nonstatic_value_fields = nonstatic_value_type_count > 0;
4145 
4146   if (is_value_type() && (!has_nonstatic_fields)) {
4147     // There are a number of fixes required throughout the type system and JIT
4148     throwValueTypeLimitation(THREAD_AND_LOCATION, "Value Types do not support zero instance size yet");
4149     return;
4150   }
4151 
4152   // Prepare list of oops for oop map generation.
4153   //
4154   // "offset" and "count" lists are describing the set of contiguous oop
4155   // regions. offset[i] is the start of the i-th region, which then has
4156   // count[i] oops following. Before we know how many regions are required,
4157   // we pessimistically allocate the maps to fit all the oops into the
4158   // distinct regions.
4159   //
4160   int super_oop_map_count = (_super_klass == NULL) ? 0 :_super_klass->nonstatic_oop_map_count();
4161   int max_oop_map_count =
4162       super_oop_map_count +
4163       fac->count[NONSTATIC_OOP] +
4164       value_type_oop_map_count +
4165       not_flattened_value_types;
4166 
4167   OopMapBlocksBuilder* nonstatic_oop_maps = new OopMapBlocksBuilder(max_oop_map_count, THREAD);
4168   if (super_oop_map_count > 0) {
4169     nonstatic_oop_maps->initialize_inherited_blocks(_super_klass->start_of_nonstatic_oop_maps(),
4170                                                     _super_klass->nonstatic_oop_map_count());
4171   }
4172 
4173   int first_nonstatic_oop_offset = 0; // will be set for first oop field
4174 
4175   bool compact_fields   = CompactFields;
4176   int allocation_style = FieldsAllocationStyle;
4177   if( allocation_style < 0 || allocation_style > 2 ) { // Out of range?
4178     assert(false, "0 <= FieldsAllocationStyle <= 2");
4179     allocation_style = 1; // Optimistic
4180   }
4181 
4182   // The next classes have predefined hard-coded fields offsets
4183   // (see in JavaClasses::compute_hard_coded_offsets()).
4184   // Use default fields allocation order for them.
4185   if( (allocation_style != 0 || compact_fields ) && _loader_data->class_loader() == NULL &&
4186       (_class_name == vmSymbols::java_lang_AssertionStatusDirectives() ||
4187        _class_name == vmSymbols::java_lang_Class() ||
4188        _class_name == vmSymbols::java_lang_ClassLoader() ||
4189        _class_name == vmSymbols::java_lang_ref_Reference() ||
4190        _class_name == vmSymbols::java_lang_ref_SoftReference() ||
4191        _class_name == vmSymbols::java_lang_StackTraceElement() ||
4192        _class_name == vmSymbols::java_lang_String() ||
4193        _class_name == vmSymbols::java_lang_Throwable() ||
4194        _class_name == vmSymbols::java_lang_Boolean() ||
4195        _class_name == vmSymbols::java_lang_Character() ||
4196        _class_name == vmSymbols::java_lang_Float() ||
4197        _class_name == vmSymbols::java_lang_Double() ||
4198        _class_name == vmSymbols::java_lang_Byte() ||
4199        _class_name == vmSymbols::java_lang_Short() ||
4200        _class_name == vmSymbols::java_lang_Integer() ||
4201        _class_name == vmSymbols::java_lang_Long())) {
4202     allocation_style = 0;     // Allocate oops first
4203     compact_fields   = false; // Don't compact fields
4204   }
4205 
4206   int next_nonstatic_oop_offset = 0;
4207   int next_nonstatic_double_offset = 0;
4208 
4209   // Rearrange fields for a given allocation style
4210   if( allocation_style == 0 ) {
4211     // Fields order: oops, longs/doubles, ints, shorts/chars, bytes, padded fields
4212     next_nonstatic_oop_offset    = next_nonstatic_field_offset;
4213     next_nonstatic_double_offset = next_nonstatic_oop_offset +
4214                                     (nonstatic_oop_count * heapOopSize);
4215   } else if( allocation_style == 1 ) {
4216     // Fields order: longs/doubles, ints, shorts/chars, bytes, oops, padded fields
4217     next_nonstatic_double_offset = next_nonstatic_field_offset;
4218   } else if( allocation_style == 2 ) {
4219     // Fields allocation: oops fields in super and sub classes are together.
4220     if( nonstatic_field_size > 0 && super_oop_map_count > 0 ) {
4221       if (next_nonstatic_field_offset == nonstatic_oop_maps->last_oop_map()->end_offset()) {
4222         allocation_style = 0;   // allocate oops first
4223         next_nonstatic_oop_offset    = next_nonstatic_field_offset;
4224         next_nonstatic_double_offset = next_nonstatic_oop_offset +
4225                                        (nonstatic_oop_count * heapOopSize);
4226       }
4227     }
4228     if( allocation_style == 2 ) {
4229       allocation_style = 1;     // allocate oops last
4230       next_nonstatic_double_offset = next_nonstatic_field_offset;
4231     }
4232   } else {
4233     ShouldNotReachHere();
4234   }
4235 
4236   int nonstatic_oop_space_count   = 0;
4237   int nonstatic_word_space_count  = 0;
4238   int nonstatic_short_space_count = 0;
4239   int nonstatic_byte_space_count  = 0;
4240   int nonstatic_oop_space_offset = 0;
4241   int nonstatic_word_space_offset = 0;
4242   int nonstatic_short_space_offset = 0;
4243   int nonstatic_byte_space_offset = 0;
4244 
4245   // Try to squeeze some of the fields into the gaps due to
4246   // long/double alignment.
4247   if (nonstatic_double_count > 0) {
4248     int offset = next_nonstatic_double_offset;
4249     next_nonstatic_double_offset = align_up(offset, BytesPerLong);
4250     if (compact_fields && offset != next_nonstatic_double_offset) {
4251       // Allocate available fields into the gap before double field.
4252       int length = next_nonstatic_double_offset - offset;
4253       assert(length == BytesPerInt, "");
4254       nonstatic_word_space_offset = offset;
4255       if (nonstatic_word_count > 0) {
4256         nonstatic_word_count      -= 1;
4257         nonstatic_word_space_count = 1; // Only one will fit
4258         length -= BytesPerInt;
4259         offset += BytesPerInt;
4260       }
4261       nonstatic_short_space_offset = offset;
4262       while (length >= BytesPerShort && nonstatic_short_count > 0) {
4263         nonstatic_short_count       -= 1;
4264         nonstatic_short_space_count += 1;
4265         length -= BytesPerShort;
4266         offset += BytesPerShort;
4267       }
4268       nonstatic_byte_space_offset = offset;
4269       while (length > 0 && nonstatic_byte_count > 0) {
4270         nonstatic_byte_count       -= 1;
4271         nonstatic_byte_space_count += 1;
4272         length -= 1;
4273       }
4274       // Allocate oop field in the gap if there are no other fields for that.
4275       nonstatic_oop_space_offset = offset;
4276       if (length >= heapOopSize && nonstatic_oop_count > 0 &&
4277           allocation_style != 0) { // when oop fields not first
4278         nonstatic_oop_count      -= 1;
4279         nonstatic_oop_space_count = 1; // Only one will fit
4280         length -= heapOopSize;
4281         offset += heapOopSize;
4282       }
4283     }
4284   }
4285 
4286   int next_nonstatic_word_offset = next_nonstatic_double_offset +
4287                                      (nonstatic_double_count * BytesPerLong);
4288   int next_nonstatic_short_offset = next_nonstatic_word_offset +
4289                                       (nonstatic_word_count * BytesPerInt);
4290   int next_nonstatic_byte_offset = next_nonstatic_short_offset +
4291                                      (nonstatic_short_count * BytesPerShort);
4292   int next_nonstatic_padded_offset = next_nonstatic_byte_offset +
4293                                        nonstatic_byte_count;
4294 
4295   // let oops jump before padding with this allocation style
4296   if( allocation_style == 1 ) {
4297     next_nonstatic_oop_offset = next_nonstatic_padded_offset;
4298     if( nonstatic_oop_count > 0 ) {
4299       next_nonstatic_oop_offset = align_up(next_nonstatic_oop_offset, heapOopSize);
4300     }
4301     next_nonstatic_padded_offset = next_nonstatic_oop_offset + (nonstatic_oop_count * heapOopSize);
4302   }
4303 
4304   // Aligning embedded value types
4305   // bug below, the current algorithm to layout embedded value types always put them at the
4306   // end of the layout, which doesn't match the different allocation policies the VM is
4307   // supposed to provide => FixMe
4308   // Note also that the current alignment policy is to make each value type starting on a
4309   // 64 bits boundary. This could be optimized later. For instance, it could be nice to
4310   // align value types according to their most constrained internal type.
4311   next_nonstatic_valuetype_offset = align_up(next_nonstatic_padded_offset, BytesPerLong);
4312   int next_value_type_index = 0;
4313 
4314   // Iterate over fields again and compute correct offsets.
4315   // The field allocation type was temporarily stored in the offset slot.
4316   // oop fields are located before non-oop fields (static and non-static).
4317   for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
4318 
4319     // skip already laid out fields
4320     if (fs.is_offset_set()) continue;
4321 
4322     // contended instance fields are handled below
4323     if (fs.is_contended() && !fs.access_flags().is_static()) continue;
4324 
4325     int real_offset = 0;
4326     const FieldAllocationType atype = (const FieldAllocationType) fs.allocation_type();
4327 
4328     // pack the rest of the fields
4329     switch (atype) {
4330       // Value types in static fields are handled with oops
4331       case STATIC_FLATTENABLE:   // Fallthrough
4332       case STATIC_OOP:
4333         real_offset = next_static_oop_offset;
4334         next_static_oop_offset += heapOopSize;
4335         break;
4336       case STATIC_BYTE:
4337         real_offset = next_static_byte_offset;
4338         next_static_byte_offset += 1;
4339         break;
4340       case STATIC_SHORT:
4341         real_offset = next_static_short_offset;
4342         next_static_short_offset += BytesPerShort;
4343         break;
4344       case STATIC_WORD:
4345         real_offset = next_static_word_offset;
4346         next_static_word_offset += BytesPerInt;
4347         break;
4348       case STATIC_DOUBLE:
4349         real_offset = next_static_double_offset;
4350         next_static_double_offset += BytesPerLong;
4351         break;
4352       case NONSTATIC_FLATTENABLE:
4353         if (fs.is_flattened()) {
4354           Klass* klass = nonstatic_value_type_klasses[next_value_type_index];
4355           assert(klass != NULL, "Klass should have been loaded and resolved earlier");
4356           assert(klass->access_flags().is_value_type(),"Must be a value type");
4357           ValueKlass* vklass = ValueKlass::cast(klass);
4358           real_offset = next_nonstatic_valuetype_offset;
4359           next_nonstatic_valuetype_offset += (vklass->size_helper()) * wordSize - vklass->first_field_offset();
4360           // aligning next value type on a 64 bits boundary
4361           next_nonstatic_valuetype_offset = align_up(next_nonstatic_valuetype_offset, BytesPerLong);
4362           next_value_type_index += 1;
4363 
4364           if (vklass->contains_oops()) { // add flatten oop maps
4365             int diff = real_offset - vklass->first_field_offset();
4366             const OopMapBlock* map = vklass->start_of_nonstatic_oop_maps();
4367             const OopMapBlock* const last_map = map + vklass->nonstatic_oop_map_count();
4368             while (map < last_map) {
4369               nonstatic_oop_maps->add(map->offset() + diff, map->count());
4370               map++;
4371             }
4372           }
4373           break;
4374         } else {
4375           // Fall through
4376         }
4377       case NONSTATIC_OOP:
4378         if( nonstatic_oop_space_count > 0 ) {
4379           real_offset = nonstatic_oop_space_offset;
4380           nonstatic_oop_space_offset += heapOopSize;
4381           nonstatic_oop_space_count  -= 1;
4382         } else {
4383           real_offset = next_nonstatic_oop_offset;
4384           next_nonstatic_oop_offset += heapOopSize;
4385         }
4386         nonstatic_oop_maps->add(real_offset, 1);
4387         break;
4388       case NONSTATIC_BYTE:
4389         if( nonstatic_byte_space_count > 0 ) {
4390           real_offset = nonstatic_byte_space_offset;
4391           nonstatic_byte_space_offset += 1;
4392           nonstatic_byte_space_count  -= 1;
4393         } else {
4394           real_offset = next_nonstatic_byte_offset;
4395           next_nonstatic_byte_offset += 1;
4396         }
4397         break;
4398       case NONSTATIC_SHORT:
4399         if( nonstatic_short_space_count > 0 ) {
4400           real_offset = nonstatic_short_space_offset;
4401           nonstatic_short_space_offset += BytesPerShort;
4402           nonstatic_short_space_count  -= 1;
4403         } else {
4404           real_offset = next_nonstatic_short_offset;
4405           next_nonstatic_short_offset += BytesPerShort;
4406         }
4407         break;
4408       case NONSTATIC_WORD:
4409         if( nonstatic_word_space_count > 0 ) {
4410           real_offset = nonstatic_word_space_offset;
4411           nonstatic_word_space_offset += BytesPerInt;
4412           nonstatic_word_space_count  -= 1;
4413         } else {
4414           real_offset = next_nonstatic_word_offset;
4415           next_nonstatic_word_offset += BytesPerInt;
4416         }
4417         break;
4418       case NONSTATIC_DOUBLE:
4419         real_offset = next_nonstatic_double_offset;
4420         next_nonstatic_double_offset += BytesPerLong;
4421         break;
4422       default:
4423         ShouldNotReachHere();
4424     }
4425     fs.set_offset(real_offset);
4426   }
4427 
4428 
4429   // Handle the contended cases.
4430   //
4431   // Each contended field should not intersect the cache line with another contended field.
4432   // In the absence of alignment information, we end up with pessimistically separating
4433   // the fields with full-width padding.
4434   //
4435   // Additionally, this should not break alignment for the fields, so we round the alignment up
4436   // for each field.
4437   if (nonstatic_contended_count > 0) {
4438 
4439     // if there is at least one contended field, we need to have pre-padding for them
4440     next_nonstatic_padded_offset += ContendedPaddingWidth;
4441 
4442     // collect all contended groups
4443     ResourceBitMap bm(cp->size());
4444     for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
4445       // skip already laid out fields
4446       if (fs.is_offset_set()) continue;
4447 
4448       if (fs.is_contended()) {
4449         bm.set_bit(fs.contended_group());
4450       }
4451     }
4452 
4453     int current_group = -1;
4454     while ((current_group = (int)bm.get_next_one_offset(current_group + 1)) != (int)bm.size()) {
4455 
4456       for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
4457 
4458         // skip already laid out fields
4459         if (fs.is_offset_set()) continue;
4460 
4461         // skip non-contended fields and fields from different group
4462         if (!fs.is_contended() || (fs.contended_group() != current_group)) continue;
4463 
4464         // handle statics below
4465         if (fs.access_flags().is_static()) continue;
4466 
4467         int real_offset = 0;
4468         FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();
4469 
4470         switch (atype) {
4471           case NONSTATIC_BYTE:
4472             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, 1);
4473             real_offset = next_nonstatic_padded_offset;
4474             next_nonstatic_padded_offset += 1;
4475             break;
4476 
4477           case NONSTATIC_SHORT:
4478             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, BytesPerShort);
4479             real_offset = next_nonstatic_padded_offset;
4480             next_nonstatic_padded_offset += BytesPerShort;
4481             break;
4482 
4483           case NONSTATIC_WORD:
4484             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, BytesPerInt);
4485             real_offset = next_nonstatic_padded_offset;
4486             next_nonstatic_padded_offset += BytesPerInt;
4487             break;
4488 
4489           case NONSTATIC_DOUBLE:
4490             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, BytesPerLong);
4491             real_offset = next_nonstatic_padded_offset;
4492             next_nonstatic_padded_offset += BytesPerLong;
4493             break;
4494 
4495             // Value types in static fields are handled with oops
4496           case NONSTATIC_FLATTENABLE:
4497             throwValueTypeLimitation(THREAD_AND_LOCATION,
4498                                      "@Contended annotation not supported for value types yet", fs.name(), fs.signature());
4499             return;
4500 
4501           case NONSTATIC_OOP:
4502             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, heapOopSize);
4503             real_offset = next_nonstatic_padded_offset;
4504             next_nonstatic_padded_offset += heapOopSize;
4505             nonstatic_oop_maps->add(real_offset, 1);
4506             break;
4507 
4508           default:
4509             ShouldNotReachHere();
4510         }
4511 
4512         if (fs.contended_group() == 0) {
4513           // Contended group defines the equivalence class over the fields:
4514           // the fields within the same contended group are not inter-padded.
4515           // The only exception is default group, which does not incur the
4516           // equivalence, and so requires intra-padding.
4517           next_nonstatic_padded_offset += ContendedPaddingWidth;
4518         }
4519 
4520         fs.set_offset(real_offset);
4521       } // for
4522 
4523       // Start laying out the next group.
4524       // Note that this will effectively pad the last group in the back;
4525       // this is expected to alleviate memory contention effects for
4526       // subclass fields and/or adjacent object.
4527       // If this was the default group, the padding is already in place.
4528       if (current_group != 0) {
4529         next_nonstatic_padded_offset += ContendedPaddingWidth;
4530       }
4531     }
4532 
4533     // handle static fields
4534   }
4535 
4536   // Entire class is contended, pad in the back.
4537   // This helps to alleviate memory contention effects for subclass fields
4538   // and/or adjacent object.
4539   if (is_contended_class) {
4540     assert(!is_value_type(), "@Contended not supported for value types yet");
4541     next_nonstatic_padded_offset += ContendedPaddingWidth;
4542   }
4543 
4544   int notaligned_nonstatic_fields_end;
4545   if (nonstatic_value_type_count != 0) {
4546     notaligned_nonstatic_fields_end = next_nonstatic_valuetype_offset;
4547   } else {
4548     notaligned_nonstatic_fields_end = next_nonstatic_padded_offset;
4549   }
4550 
4551   int nonstatic_field_sz_align = heapOopSize;
4552   if (is_value_type()) {
4553     if ((notaligned_nonstatic_fields_end - nonstatic_fields_start) > heapOopSize) {
4554       nonstatic_field_sz_align = BytesPerLong; // value copy of fields only uses jlong copy
4555     }
4556   }
4557   int nonstatic_fields_end      = align_up(notaligned_nonstatic_fields_end, nonstatic_field_sz_align);
4558   int instance_end              = align_up(notaligned_nonstatic_fields_end, wordSize);
4559   int static_fields_end         = align_up(next_static_byte_offset, wordSize);
4560 
4561   int static_field_size         = (static_fields_end -
4562                                    InstanceMirrorKlass::offset_of_static_fields()) / wordSize;
4563   nonstatic_field_size          = nonstatic_field_size +
4564                                   (nonstatic_fields_end - nonstatic_fields_start) / heapOopSize;
4565 
4566   int instance_size             = align_object_size(instance_end / wordSize);
4567 
4568   assert(instance_size == align_object_size(align_up(
4569          (instanceOopDesc::base_offset_in_bytes() + nonstatic_field_size*heapOopSize)
4570          + initial_value_type_padding, wordSize) / wordSize), "consistent layout helper value");
4571 
4572 
4573   // Invariant: nonstatic_field end/start should only change if there are
4574   // nonstatic fields in the class, or if the class is contended. We compare
4575   // against the non-aligned value, so that end alignment will not fail the
4576   // assert without actually having the fields.
4577   assert((notaligned_nonstatic_fields_end == nonstatic_fields_start) ||
4578          is_contended_class ||
4579          (nonstatic_fields_count > 0), "double-check nonstatic start/end");
4580 
4581   // Number of non-static oop map blocks allocated at end of klass.
4582   nonstatic_oop_maps->compact(THREAD);
4583 
4584 #ifndef PRODUCT
4585   if ((PrintFieldLayout && !is_value_type()) ||
4586       (PrintValueLayout && (is_value_type() || has_nonstatic_value_fields))) {
4587     print_field_layout(_class_name,
4588           _fields,
4589           cp,
4590           instance_size,
4591           nonstatic_fields_start,
4592           nonstatic_fields_end,
4593           static_fields_end);
4594     nonstatic_oop_maps->print_on(tty);
4595     tty->print("\n");
4596     tty->print_cr("Instance size = %d", instance_size);
4597     tty->print_cr("Nonstatic_field_size = %d", nonstatic_field_size);
4598     tty->print_cr("Static_field_size = %d", static_field_size);
4599     tty->print_cr("Has nonstatic fields = %d", has_nonstatic_fields);
4600     tty->print_cr("---");
4601   }
4602 
4603 #endif
4604   // Pass back information needed for InstanceKlass creation
4605   info->oop_map_blocks = nonstatic_oop_maps;
4606   info->instance_size = instance_size;
4607   info->static_field_size = static_field_size;
4608   info->nonstatic_field_size = nonstatic_field_size;
4609   info->has_nonstatic_fields = has_nonstatic_fields;
4610 }
4611 
4612 void ClassFileParser::set_precomputed_flags(InstanceKlass* ik, TRAPS) {
4613   assert(ik != NULL, "invariant");
4614 
4615   const Klass* const super = ik->super();
4616 
4617   // Check if this klass has an empty finalize method (i.e. one with return bytecode only),
4618   // in which case we don't have to register objects as finalizable
4619   if (!_has_empty_finalizer) {
4620     if (_has_finalizer ||
4621         (super != NULL && super->has_finalizer())) {
4622       ik->set_has_finalizer();
4623     }
4624   }
4625 
4626 #ifdef ASSERT
4627   bool f = false;
4628   const Method* const m = ik->lookup_method(vmSymbols::finalize_method_name(),
4629                                            vmSymbols::void_method_signature());
4630   if (m != NULL && !m->is_empty_method()) {
4631       f = true;
4632   }
4633 
4634   // Spec doesn't prevent agent from redefinition of empty finalizer.
4635   // Despite the fact that it's generally bad idea and redefined finalizer
4636   // will not work as expected we shouldn't abort vm in this case
4637   if (!ik->has_redefined_this_or_super()) {
4638     assert(ik->has_finalizer() == f, "inconsistent has_finalizer");
4639   }
4640 #endif
4641 
4642   // Check if this klass supports the java.lang.Cloneable interface
4643   if (SystemDictionary::Cloneable_klass_loaded()) {
4644     if (ik->is_subtype_of(SystemDictionary::Cloneable_klass())) {
4645       if (ik->is_value()) {
4646         throwValueTypeLimitation(THREAD_AND_LOCATION, "Value Types do not support Cloneable");
4647         return;
4648       }
4649       ik->set_is_cloneable();
4650     }
4651   }
4652 
4653   // Check if this klass has a vanilla default constructor
4654   if (super == NULL) {
4655     // java.lang.Object has empty default constructor
4656     ik->set_has_vanilla_constructor();
4657   } else {
4658     if (super->has_vanilla_constructor() &&
4659         _has_vanilla_constructor) {
4660       ik->set_has_vanilla_constructor();
4661     }
4662 #ifdef ASSERT
4663     bool v = false;
4664     if (super->has_vanilla_constructor()) {
4665       const Method* const constructor =
4666         ik->find_method(vmSymbols::object_initializer_name(),
4667                        vmSymbols::void_method_signature());
4668       if (constructor != NULL && constructor->is_vanilla_constructor()) {
4669         v = true;
4670       }
4671     }
4672     assert(v == ik->has_vanilla_constructor(), "inconsistent has_vanilla_constructor");
4673 #endif
4674   }
4675 
4676   // If it cannot be fast-path allocated, set a bit in the layout helper.
4677   // See documentation of InstanceKlass::can_be_fastpath_allocated().
4678   assert(ik->size_helper() > 0, "layout_helper is initialized");
4679   if ((!RegisterFinalizersAtInit && ik->has_finalizer())
4680       || ik->is_abstract() || ik->is_interface()
4681       || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == NULL)
4682       || ik->size_helper() >= FastAllocateSizeLimit) {
4683     // Forbid fast-path allocation.
4684     const jint lh = Klass::instance_layout_helper(ik->size_helper(), true);
4685     ik->set_layout_helper(lh);
4686   }
4687 }
4688 
4689 bool ClassFileParser::supports_value_types() const {
4690   // Value types are only supported by class file version 55 and later
4691   return _major_version >= JAVA_11_VERSION;
4692 }
4693 
4694 // utility methods for appending an array with check for duplicates
4695 
4696 static void append_interfaces(GrowableArray<InstanceKlass*>* result,
4697                               const Array<InstanceKlass*>* const ifs) {
4698   // iterate over new interfaces
4699   for (int i = 0; i < ifs->length(); i++) {
4700     InstanceKlass* const e = ifs->at(i);
4701     assert(e->is_klass() && e->is_interface(), "just checking");
4702     // add new interface
4703     result->append_if_missing(e);
4704   }
4705 }
4706 
4707 static Array<InstanceKlass*>* compute_transitive_interfaces(const InstanceKlass* super,
4708                                                             Array<InstanceKlass*>* local_ifs,
4709                                                             ClassLoaderData* loader_data,
4710                                                             TRAPS) {
4711   assert(local_ifs != NULL, "invariant");
4712   assert(loader_data != NULL, "invariant");
4713 
4714   // Compute maximum size for transitive interfaces
4715   int max_transitive_size = 0;
4716   int super_size = 0;
4717   // Add superclass transitive interfaces size
4718   if (super != NULL) {
4719     super_size = super->transitive_interfaces()->length();
4720     max_transitive_size += super_size;
4721   }
4722   // Add local interfaces' super interfaces
4723   const int local_size = local_ifs->length();
4724   for (int i = 0; i < local_size; i++) {
4725     InstanceKlass* const l = local_ifs->at(i);
4726     max_transitive_size += l->transitive_interfaces()->length();
4727   }
4728   // Finally add local interfaces
4729   max_transitive_size += local_size;
4730   // Construct array
4731   if (max_transitive_size == 0) {
4732     // no interfaces, use canonicalized array
4733     return Universe::the_empty_instance_klass_array();
4734   } else if (max_transitive_size == super_size) {
4735     // no new local interfaces added, share superklass' transitive interface array
4736     return super->transitive_interfaces();
4737   } else if (max_transitive_size == local_size) {
4738     // only local interfaces added, share local interface array
4739     return local_ifs;
4740   } else {
4741     ResourceMark rm;
4742     GrowableArray<InstanceKlass*>* const result = new GrowableArray<InstanceKlass*>(max_transitive_size);
4743 
4744     // Copy down from superclass
4745     if (super != NULL) {
4746       append_interfaces(result, super->transitive_interfaces());
4747     }
4748 
4749     // Copy down from local interfaces' superinterfaces
4750     for (int i = 0; i < local_size; i++) {
4751       InstanceKlass* const l = local_ifs->at(i);
4752       append_interfaces(result, l->transitive_interfaces());
4753     }
4754     // Finally add local interfaces
4755     append_interfaces(result, local_ifs);
4756 
4757     // length will be less than the max_transitive_size if duplicates were removed
4758     const int length = result->length();
4759     assert(length <= max_transitive_size, "just checking");
4760     Array<InstanceKlass*>* const new_result =
4761       MetadataFactory::new_array<InstanceKlass*>(loader_data, length, CHECK_NULL);
4762     for (int i = 0; i < length; i++) {
4763       InstanceKlass* const e = result->at(i);
4764       assert(e != NULL, "just checking");
4765       new_result->at_put(i, e);
4766     }
4767     return new_result;
4768   }
4769 }
4770 
4771 static void check_super_class_access(const InstanceKlass* this_klass, TRAPS) {
4772   assert(this_klass != NULL, "invariant");
4773   const Klass* const super = this_klass->super();
4774   if (super != NULL) {
4775 
4776     // If the loader is not the boot loader then throw an exception if its
4777     // superclass is in package jdk.internal.reflect and its loader is not a
4778     // special reflection class loader
4779     if (!this_klass->class_loader_data()->is_the_null_class_loader_data()) {
4780       assert(super->is_instance_klass(), "super is not instance klass");
4781       PackageEntry* super_package = super->package();
4782       if (super_package != NULL &&
4783           super_package->name()->fast_compare(vmSymbols::jdk_internal_reflect()) == 0 &&
4784           !java_lang_ClassLoader::is_reflection_class_loader(this_klass->class_loader())) {
4785         ResourceMark rm(THREAD);
4786         Exceptions::fthrow(
4787           THREAD_AND_LOCATION,
4788           vmSymbols::java_lang_IllegalAccessError(),
4789           "class %s loaded by %s cannot access jdk/internal/reflect superclass %s",
4790           this_klass->external_name(),
4791           this_klass->class_loader_data()->loader_name_and_id(),
4792           super->external_name());
4793         return;
4794       }
4795     }
4796 
4797     Reflection::VerifyClassAccessResults vca_result =
4798       Reflection::verify_class_access(this_klass, InstanceKlass::cast(super), false);
4799     if (vca_result != Reflection::ACCESS_OK) {
4800       ResourceMark rm(THREAD);
4801       char* msg = Reflection::verify_class_access_msg(this_klass,
4802                                                       InstanceKlass::cast(super),
4803                                                       vca_result);
4804       if (msg == NULL) {
4805         bool same_module = (this_klass->module() == super->module());
4806         Exceptions::fthrow(
4807           THREAD_AND_LOCATION,
4808           vmSymbols::java_lang_IllegalAccessError(),
4809           "class %s cannot access its %ssuperclass %s (%s%s%s)",
4810           this_klass->external_name(),
4811           super->is_abstract() ? "abstract " : "",
4812           super->external_name(),
4813           (same_module) ? this_klass->joint_in_module_of_loader(super) : this_klass->class_in_module_of_loader(),
4814           (same_module) ? "" : "; ",
4815           (same_module) ? "" : super->class_in_module_of_loader());
4816       } else {
4817         // Add additional message content.
4818         Exceptions::fthrow(
4819           THREAD_AND_LOCATION,
4820           vmSymbols::java_lang_IllegalAccessError(),
4821           "superclass access check failed: %s",
4822           msg);
4823       }
4824     }
4825   }
4826 }
4827 
4828 
4829 static void check_super_interface_access(const InstanceKlass* this_klass, TRAPS) {
4830   assert(this_klass != NULL, "invariant");
4831   const Array<InstanceKlass*>* const local_interfaces = this_klass->local_interfaces();
4832   const int lng = local_interfaces->length();
4833   for (int i = lng - 1; i >= 0; i--) {
4834     InstanceKlass* const k = local_interfaces->at(i);
4835     assert (k != NULL && k->is_interface(), "invalid interface");
4836     Reflection::VerifyClassAccessResults vca_result =
4837       Reflection::verify_class_access(this_klass, k, false);
4838     if (vca_result != Reflection::ACCESS_OK) {
4839       ResourceMark rm(THREAD);
4840       char* msg = Reflection::verify_class_access_msg(this_klass,
4841                                                       k,
4842                                                       vca_result);
4843       if (msg == NULL) {
4844         bool same_module = (this_klass->module() == k->module());
4845         Exceptions::fthrow(
4846           THREAD_AND_LOCATION,
4847           vmSymbols::java_lang_IllegalAccessError(),
4848           "class %s cannot access its superinterface %s (%s%s%s)",
4849           this_klass->external_name(),
4850           k->external_name(),
4851           (same_module) ? this_klass->joint_in_module_of_loader(k) : this_klass->class_in_module_of_loader(),
4852           (same_module) ? "" : "; ",
4853           (same_module) ? "" : k->class_in_module_of_loader());
4854       } else {
4855         // Add additional message content.
4856         Exceptions::fthrow(
4857           THREAD_AND_LOCATION,
4858           vmSymbols::java_lang_IllegalAccessError(),
4859           "superinterface check failed: %s",
4860           msg);
4861       }
4862     }
4863   }
4864 }
4865 
4866 
4867 static void check_final_method_override(const InstanceKlass* this_klass, TRAPS) {
4868   assert(this_klass != NULL, "invariant");
4869   const Array<Method*>* const methods = this_klass->methods();
4870   const int num_methods = methods->length();
4871 
4872   // go thru each method and check if it overrides a final method
4873   for (int index = 0; index < num_methods; index++) {
4874     const Method* const m = methods->at(index);
4875 
4876     // skip private, static, and <init> methods
4877     if ((!m->is_private() && !m->is_static()) &&
4878         (m->name() != vmSymbols::object_initializer_name())) {
4879 
4880       const Symbol* const name = m->name();
4881       const Symbol* const signature = m->signature();
4882       const Klass* k = this_klass->super();
4883       const Method* super_m = NULL;
4884       while (k != NULL) {
4885         // skip supers that don't have final methods.
4886         if (k->has_final_method()) {
4887           // lookup a matching method in the super class hierarchy
4888           super_m = InstanceKlass::cast(k)->lookup_method(name, signature);
4889           if (super_m == NULL) {
4890             break; // didn't find any match; get out
4891           }
4892 
4893           if (super_m->is_final() && !super_m->is_static() &&
4894               !super_m->access_flags().is_private()) {
4895             // matching method in super is final, and not static or private
4896             bool can_access = Reflection::verify_member_access(this_klass,
4897                                                                super_m->method_holder(),
4898                                                                super_m->method_holder(),
4899                                                                super_m->access_flags(),
4900                                                               false, false, CHECK);
4901             if (can_access) {
4902               // this class can access super final method and therefore override
4903               ResourceMark rm(THREAD);
4904               Exceptions::fthrow(THREAD_AND_LOCATION,
4905                                  vmSymbols::java_lang_VerifyError(),
4906                                  "class %s overrides final method %s.%s%s",
4907                                  this_klass->external_name(),
4908                                  super_m->method_holder()->external_name(),
4909                                  name->as_C_string(),
4910                                  signature->as_C_string()
4911                                  );
4912               return;
4913             }
4914           }
4915 
4916           // continue to look from super_m's holder's super.
4917           k = super_m->method_holder()->super();
4918           continue;
4919         }
4920 
4921         k = k->super();
4922       }
4923     }
4924   }
4925 }
4926 
4927 
4928 // assumes that this_klass is an interface
4929 static void check_illegal_static_method(const InstanceKlass* this_klass, TRAPS) {
4930   assert(this_klass != NULL, "invariant");
4931   assert(this_klass->is_interface(), "not an interface");
4932   const Array<Method*>* methods = this_klass->methods();
4933   const int num_methods = methods->length();
4934 
4935   for (int index = 0; index < num_methods; index++) {
4936     const Method* const m = methods->at(index);
4937     // if m is static and not the init method, throw a verify error
4938     if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) {
4939       ResourceMark rm(THREAD);
4940       Exceptions::fthrow(
4941         THREAD_AND_LOCATION,
4942         vmSymbols::java_lang_VerifyError(),
4943         "Illegal static method %s in interface %s",
4944         m->name()->as_C_string(),
4945         this_klass->external_name()
4946       );
4947       return;
4948     }
4949   }
4950 }
4951 
4952 // utility methods for format checking
4953 
4954 void ClassFileParser::verify_legal_class_modifiers(jint flags, TRAPS) const {
4955   const bool is_module = (flags & JVM_ACC_MODULE) != 0;
4956   const bool is_value_type = (flags & JVM_ACC_VALUE) != 0;
4957   assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");
4958   assert(supports_value_types() || !is_value_type, "JVM_ACC_VALUE should not be set");
4959   if (is_module) {
4960     ResourceMark rm(THREAD);
4961     Exceptions::fthrow(
4962       THREAD_AND_LOCATION,
4963       vmSymbols::java_lang_NoClassDefFoundError(),
4964       "%s is not a class because access_flag ACC_MODULE is set",
4965       _class_name->as_C_string());
4966     return;
4967   }
4968 
4969   if (is_value_type && !EnableValhalla) {
4970     ResourceMark rm(THREAD);
4971     Exceptions::fthrow(
4972       THREAD_AND_LOCATION,
4973       vmSymbols::java_lang_ClassFormatError(),
4974       "Class modifier ACC_VALUE in class %s requires option -XX:+EnableValhalla",
4975       _class_name->as_C_string()
4976     );
4977   }
4978 
4979   if (!_need_verify) { return; }
4980 
4981   const bool is_interface  = (flags & JVM_ACC_INTERFACE)  != 0;
4982   const bool is_abstract   = (flags & JVM_ACC_ABSTRACT)   != 0;
4983   const bool is_final      = (flags & JVM_ACC_FINAL)      != 0;
4984   const bool is_super      = (flags & JVM_ACC_SUPER)      != 0;
4985   const bool is_enum       = (flags & JVM_ACC_ENUM)       != 0;
4986   const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4987   const bool major_gte_15  = _major_version >= JAVA_1_5_VERSION;
4988 
4989   if ((is_abstract && is_final) ||
4990       (is_interface && !is_abstract) ||
4991       (is_interface && major_gte_15 && (is_super || is_enum)) ||
4992       (!is_interface && major_gte_15 && is_annotation) ||
4993       (is_value_type && (is_interface || is_abstract || is_enum || !is_final))) {
4994     ResourceMark rm(THREAD);
4995     const char* class_note = "";
4996     if (is_value_type)  class_note = " (an inline class)";
4997     Exceptions::fthrow(
4998       THREAD_AND_LOCATION,
4999       vmSymbols::java_lang_ClassFormatError(),
5000       "Illegal class modifiers in class %s%s: 0x%X",
5001       _class_name->as_C_string(), class_note, flags
5002     );
5003     return;
5004   }
5005 }
5006 
5007 static bool has_illegal_visibility(jint flags) {
5008   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
5009   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
5010   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
5011 
5012   return ((is_public && is_protected) ||
5013           (is_public && is_private) ||
5014           (is_protected && is_private));
5015 }
5016 
5017 // A legal major_version.minor_version must be one of the following:
5018 //
5019 //  Major_version >= 45 and major_version < 56, any minor_version.
5020 //  Major_version >= 56 and major_version <= JVM_CLASSFILE_MAJOR_VERSION and minor_version = 0.
5021 //  Major_version = JVM_CLASSFILE_MAJOR_VERSION and minor_version = 65535 and --enable-preview is present.
5022 //
5023 static void verify_class_version(u2 major, u2 minor, Symbol* class_name, TRAPS){
5024   ResourceMark rm(THREAD);
5025   const u2 max_version = JVM_CLASSFILE_MAJOR_VERSION;
5026   if (major < JAVA_MIN_SUPPORTED_VERSION) {
5027     Exceptions::fthrow(
5028       THREAD_AND_LOCATION,
5029       vmSymbols::java_lang_UnsupportedClassVersionError(),
5030       "%s (class file version %u.%u) was compiled with an invalid major version",
5031       class_name->as_C_string(), major, minor);
5032     return;
5033   }
5034 
5035   if (major > max_version) {
5036     Exceptions::fthrow(
5037       THREAD_AND_LOCATION,
5038       vmSymbols::java_lang_UnsupportedClassVersionError(),
5039       "%s has been compiled by a more recent version of the Java Runtime (class file version %u.%u), "
5040       "this version of the Java Runtime only recognizes class file versions up to %u.0",
5041       class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION);
5042     return;
5043   }
5044 
5045   if (major < JAVA_12_VERSION || minor == 0) {
5046     return;
5047   }
5048 
5049   if (minor == JAVA_PREVIEW_MINOR_VERSION) {
5050     if (major != max_version) {
5051       Exceptions::fthrow(
5052         THREAD_AND_LOCATION,
5053         vmSymbols::java_lang_UnsupportedClassVersionError(),
5054         "%s (class file version %u.%u) was compiled with preview features that are unsupported. "
5055         "This version of the Java Runtime only recognizes preview features for class file version %u.%u",
5056         class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION, JAVA_PREVIEW_MINOR_VERSION);
5057       return;
5058     }
5059 
5060     if (!Arguments::enable_preview()) {
5061       Exceptions::fthrow(
5062         THREAD_AND_LOCATION,
5063         vmSymbols::java_lang_UnsupportedClassVersionError(),
5064         "Preview features are not enabled for %s (class file version %u.%u). Try running with '--enable-preview'",
5065         class_name->as_C_string(), major, minor);
5066       return;
5067     }
5068 
5069   } else { // minor != JAVA_PREVIEW_MINOR_VERSION
5070     Exceptions::fthrow(
5071         THREAD_AND_LOCATION,
5072         vmSymbols::java_lang_UnsupportedClassVersionError(),
5073         "%s (class file version %u.%u) was compiled with an invalid non-zero minor version",
5074         class_name->as_C_string(), major, minor);
5075   }
5076 }
5077 
5078 void ClassFileParser::verify_legal_field_modifiers(jint flags,
5079                                                    bool is_interface,
5080                                                    bool is_value_type,
5081                                                    TRAPS) const {
5082   if (!_need_verify) { return; }
5083 
5084   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
5085   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
5086   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
5087   const bool is_static    = (flags & JVM_ACC_STATIC)    != 0;
5088   const bool is_final     = (flags & JVM_ACC_FINAL)     != 0;
5089   const bool is_volatile  = (flags & JVM_ACC_VOLATILE)  != 0;
5090   const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
5091   const bool is_enum      = (flags & JVM_ACC_ENUM)      != 0;
5092   const bool major_gte_15 = _major_version >= JAVA_1_5_VERSION;
5093 
5094   bool is_illegal = false;
5095 
5096   if (is_interface) {
5097     if (!is_public || !is_static || !is_final || is_private ||
5098         is_protected || is_volatile || is_transient ||
5099         (major_gte_15 && is_enum)) {
5100       is_illegal = true;
5101     }
5102   } else { // not interface
5103     if (has_illegal_visibility(flags) || (is_final && is_volatile)) {
5104       is_illegal = true;
5105     } else {
5106       if (is_value_type && !is_static && !is_final) {
5107         is_illegal = true;
5108       }
5109     }
5110   }
5111 
5112   if (is_illegal) {
5113     ResourceMark rm(THREAD);
5114     Exceptions::fthrow(
5115       THREAD_AND_LOCATION,
5116       vmSymbols::java_lang_ClassFormatError(),
5117       "Illegal field modifiers in class %s: 0x%X",
5118       _class_name->as_C_string(), flags);
5119     return;
5120   }
5121 }
5122 
5123 void ClassFileParser::verify_legal_method_modifiers(jint flags,
5124                                                     bool is_interface,
5125                                                     bool is_value_type,
5126                                                     const Symbol* name,
5127                                                     TRAPS) const {
5128   if (!_need_verify) { return; }
5129 
5130   const bool is_public       = (flags & JVM_ACC_PUBLIC)       != 0;
5131   const bool is_private      = (flags & JVM_ACC_PRIVATE)      != 0;
5132   const bool is_static       = (flags & JVM_ACC_STATIC)       != 0;
5133   const bool is_final        = (flags & JVM_ACC_FINAL)        != 0;
5134   const bool is_native       = (flags & JVM_ACC_NATIVE)       != 0;
5135   const bool is_abstract     = (flags & JVM_ACC_ABSTRACT)     != 0;
5136   const bool is_bridge       = (flags & JVM_ACC_BRIDGE)       != 0;
5137   const bool is_strict       = (flags & JVM_ACC_STRICT)       != 0;
5138   const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
5139   const bool is_protected    = (flags & JVM_ACC_PROTECTED)    != 0;
5140   const bool major_gte_15    = _major_version >= JAVA_1_5_VERSION;
5141   const bool major_gte_8     = _major_version >= JAVA_8_VERSION;
5142   const bool is_initializer  = (name == vmSymbols::object_initializer_name());
5143 
5144   bool is_illegal = false;
5145 
5146   const char* class_note = "";
5147 
5148   if (is_interface) {
5149     if (major_gte_8) {
5150       // Class file version is JAVA_8_VERSION or later Methods of
5151       // interfaces may set any of the flags except ACC_PROTECTED,
5152       // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must
5153       // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.
5154       if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
5155           (is_native || is_protected || is_final || is_synchronized) ||
5156           // If a specific method of a class or interface has its
5157           // ACC_ABSTRACT flag set, it must not have any of its
5158           // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,
5159           // ACC_STRICT, or ACC_SYNCHRONIZED flags set.  No need to
5160           // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as
5161           // those flags are illegal irrespective of ACC_ABSTRACT being set or not.
5162           (is_abstract && (is_private || is_static || is_strict))) {
5163         is_illegal = true;
5164       }
5165     } else if (major_gte_15) {
5166       // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)
5167       if (!is_public || is_private || is_protected || is_static || is_final ||
5168           is_synchronized || is_native || !is_abstract || is_strict) {
5169         is_illegal = true;
5170       }
5171     } else {
5172       // Class file version is pre-JAVA_1_5_VERSION
5173       if (!is_public || is_static || is_final || is_native || !is_abstract) {
5174         is_illegal = true;
5175       }
5176     }
5177   } else { // not interface
5178     if (has_illegal_visibility(flags)) {
5179       is_illegal = true;
5180     } else {
5181       if (is_initializer) {
5182         if (is_final || is_synchronized || is_native ||
5183             is_abstract || (major_gte_15 && is_bridge)) {
5184           is_illegal = true;
5185         }
5186         if (!is_static && !is_value_type) {
5187           // OK, an object constructor in a regular class
5188         } else if (is_static && is_value_type) {
5189           // OK, a static init factory in an inline class
5190         } else {
5191           // but no other combinations are allowed
5192           is_illegal = true;
5193           class_note = (is_value_type ? " (an inline class)" : " (not an inline class)");
5194         }
5195       } else { // not initializer
5196         if (is_value_type && is_synchronized && !is_static) {
5197           is_illegal = true;
5198           class_note = " (an inline class)";
5199         } else {
5200           if (is_abstract) {
5201             if ((is_final || is_native || is_private || is_static ||
5202                 (major_gte_15 && (is_synchronized || is_strict)))) {
5203               is_illegal = true;
5204             }
5205           }
5206         }
5207       }
5208     }
5209   }
5210 
5211   if (is_illegal) {
5212     ResourceMark rm(THREAD);
5213     Exceptions::fthrow(
5214       THREAD_AND_LOCATION,
5215       vmSymbols::java_lang_ClassFormatError(),
5216       "Method %s in class %s%s has illegal modifiers: 0x%X",
5217       name->as_C_string(), _class_name->as_C_string(), class_note, flags);
5218     return;
5219   }
5220 }
5221 
5222 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer,
5223                                         int length,
5224                                         TRAPS) const {
5225   assert(_need_verify, "only called when _need_verify is true");
5226   if (!UTF8::is_legal_utf8(buffer, length, _major_version <= 47)) {
5227     classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", CHECK);
5228   }
5229 }
5230 
5231 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
5232 // In class names, '/' separates unqualified names.  This is verified in this function also.
5233 // Method names also may not contain the characters '<' or '>', unless <init>
5234 // or <clinit>.  Note that method names may not be <init> or <clinit> in this
5235 // method.  Because these names have been checked as special cases before
5236 // calling this method in verify_legal_method_name.
5237 //
5238 // This method is also called from the modular system APIs in modules.cpp
5239 // to verify the validity of module and package names.
5240 bool ClassFileParser::verify_unqualified_name(const char* name,
5241                                               unsigned int length,
5242                                               int type) {
5243   if (length == 0) return false;  // Must have at least one char.
5244   for (const char* p = name; p != name + length; p++) {
5245     switch(*p) {
5246       case '.':
5247       case ';':
5248       case '[':
5249         // do not permit '.', ';', or '['
5250         return false;
5251       case '/':
5252         // check for '//' or leading or trailing '/' which are not legal
5253         // unqualified name must not be empty
5254         if (type == ClassFileParser::LegalClass) {
5255           if (p == name || p+1 >= name+length || *(p+1) == '/') {
5256             return false;
5257           }
5258         } else {
5259           return false;   // do not permit '/' unless it's class name
5260         }
5261         break;
5262       case '<':
5263       case '>':
5264         // do not permit '<' or '>' in method names
5265         if (type == ClassFileParser::LegalMethod) {
5266           return false;
5267         }
5268     }
5269   }
5270   return true;
5271 }
5272 
5273 // Take pointer to a UTF8 byte string (not NUL-terminated).
5274 // Skip over the longest part of the string that could
5275 // be taken as a fieldname. Allow '/' if slash_ok is true.
5276 // Return a pointer to just past the fieldname.
5277 // Return NULL if no fieldname at all was found, or in the case of slash_ok
5278 // being true, we saw consecutive slashes (meaning we were looking for a
5279 // qualified path but found something that was badly-formed).
5280 static const char* skip_over_field_name(const char* const name,
5281                                         bool slash_ok,
5282                                         unsigned int length) {
5283   const char* p;
5284   jboolean last_is_slash = false;
5285   jboolean not_first_ch = false;
5286 
5287   for (p = name; p != name + length; not_first_ch = true) {
5288     const char* old_p = p;
5289     jchar ch = *p;
5290     if (ch < 128) {
5291       p++;
5292       // quick check for ascii
5293       if ((ch >= 'a' && ch <= 'z') ||
5294         (ch >= 'A' && ch <= 'Z') ||
5295         (ch == '_' || ch == '$') ||
5296         (not_first_ch && ch >= '0' && ch <= '9')) {
5297         last_is_slash = false;
5298         continue;
5299       }
5300       if (slash_ok && ch == '/') {
5301         if (last_is_slash) {
5302           return NULL;  // Don't permit consecutive slashes
5303         }
5304         last_is_slash = true;
5305         continue;
5306       }
5307     }
5308     else {
5309       jint unicode_ch;
5310       char* tmp_p = UTF8::next_character(p, &unicode_ch);
5311       p = tmp_p;
5312       last_is_slash = false;
5313       // Check if ch is Java identifier start or is Java identifier part
5314       // 4672820: call java.lang.Character methods directly without generating separate tables.
5315       EXCEPTION_MARK;
5316       // return value
5317       JavaValue result(T_BOOLEAN);
5318       // Set up the arguments to isJavaIdentifierStart or isJavaIdentifierPart
5319       JavaCallArguments args;
5320       args.push_int(unicode_ch);
5321 
5322       if (not_first_ch) {
5323         // public static boolean isJavaIdentifierPart(char ch);
5324         JavaCalls::call_static(&result,
5325           SystemDictionary::Character_klass(),
5326           vmSymbols::isJavaIdentifierPart_name(),
5327           vmSymbols::int_bool_signature(),
5328           &args,
5329           THREAD);
5330       } else {
5331         // public static boolean isJavaIdentifierStart(char ch);
5332         JavaCalls::call_static(&result,
5333           SystemDictionary::Character_klass(),
5334           vmSymbols::isJavaIdentifierStart_name(),
5335           vmSymbols::int_bool_signature(),
5336           &args,
5337           THREAD);
5338       }
5339       if (HAS_PENDING_EXCEPTION) {
5340         CLEAR_PENDING_EXCEPTION;
5341         return NULL;
5342       }
5343       if(result.get_jboolean()) {
5344         continue;
5345       }
5346     }
5347     return (not_first_ch) ? old_p : NULL;
5348   }
5349   return (not_first_ch) ? p : NULL;
5350 }
5351 
5352 // Take pointer to a UTF8 byte string (not NUL-terminated).
5353 // Skip over the longest part of the string that could
5354 // be taken as a field signature. Allow "void" if void_ok.
5355 // Return a pointer to just past the signature.
5356 // Return NULL if no legal signature is found.
5357 const char* ClassFileParser::skip_over_field_signature(const char* signature,
5358                                                        bool void_ok,
5359                                                        unsigned int length,
5360                                                        TRAPS) const {
5361   unsigned int array_dim = 0;
5362   while (length > 0) {
5363     switch (signature[0]) {
5364     case JVM_SIGNATURE_VOID: if (!void_ok) { return NULL; }
5365     case JVM_SIGNATURE_BOOLEAN:
5366     case JVM_SIGNATURE_BYTE:
5367     case JVM_SIGNATURE_CHAR:
5368     case JVM_SIGNATURE_SHORT:
5369     case JVM_SIGNATURE_INT:
5370     case JVM_SIGNATURE_FLOAT:
5371     case JVM_SIGNATURE_LONG:
5372     case JVM_SIGNATURE_DOUBLE:
5373       return signature + 1;
5374     case JVM_SIGNATURE_VALUETYPE:
5375       // Can't enable this check until JDK upgrades the bytecode generators
5376       // if (_major_version < CONSTANT_CLASS_DESCRIPTORS ) {
5377       //   classfile_parse_error("Class name contains illegal Q-signature "
5378       //                                    "in descriptor in class file %s",
5379       //                                    CHECK_0);
5380       // }
5381       // fall through
5382     case JVM_SIGNATURE_CLASS:
5383     {
5384       if (_major_version < JAVA_1_5_VERSION) {
5385         // Skip over the class name if one is there
5386         const char* const p = skip_over_field_name(signature + 1, true, --length);
5387 
5388         // The next character better be a semicolon
5389         if (p && (p - signature) > 1 && p[0] == ';') {
5390           return p + 1;
5391         }
5392       }
5393       else {
5394         // Skip leading 'L' or 'Q' and ignore first appearance of ';'
5395         signature++;
5396         const char* c = (const char*) memchr(signature, ';', length - 1);
5397         // Format check signature
5398         if (c != NULL) {
5399           int newlen = c - (char*) signature;
5400           bool legal = verify_unqualified_name(signature, newlen, LegalClass);
5401           if (!legal) {
5402             classfile_parse_error("Class name is empty or contains illegal character "
5403                                   "in descriptor in class file %s",
5404                                   CHECK_0);
5405             return NULL;
5406           }
5407           return signature + newlen + 1;
5408         }
5409       }
5410       return NULL;
5411     }
5412     case JVM_SIGNATURE_ARRAY:
5413       array_dim++;
5414       if (array_dim > 255) {
5415         // 4277370: array descriptor is valid only if it represents 255 or fewer dimensions.
5416         classfile_parse_error("Array type descriptor has more than 255 dimensions in class file %s", CHECK_0);
5417       }
5418       // The rest of what's there better be a legal signature
5419       signature++;
5420       length--;
5421       void_ok = false;
5422       break;
5423     default:
5424       return NULL;
5425     }
5426   }
5427   return NULL;
5428 }
5429 
5430 // Checks if name is a legal class name.
5431 void ClassFileParser::verify_legal_class_name(const Symbol* name, TRAPS) const {
5432   if (!_need_verify || _relax_verify) { return; }
5433 
5434   assert(name->refcount() > 0, "symbol must be kept alive");
5435   char* bytes = (char*)name->bytes();
5436   unsigned int length = name->utf8_length();
5437   bool legal = false;
5438 
5439   if (length > 0) {
5440     const char* p;
5441     if (bytes[0] == JVM_SIGNATURE_ARRAY) {
5442       p = skip_over_field_signature(bytes, false, length, CHECK);
5443       legal = (p != NULL) && ((p - bytes) == (int)length);
5444     } else if (_major_version < JAVA_1_5_VERSION) {
5445       if (bytes[0] != '<') {
5446         p = skip_over_field_name(bytes, true, length);
5447         legal = (p != NULL) && ((p - bytes) == (int)length);
5448       }
5449     } else if (_major_version >= CONSTANT_CLASS_DESCRIPTORS && bytes[length - 1] == ';' ) {
5450       // Support for L...; and Q...; descriptors
5451       legal = verify_unqualified_name(bytes + 1, length - 2, LegalClass);
5452     } else {
5453       // 4900761: relax the constraints based on JSR202 spec
5454       // Class names may be drawn from the entire Unicode character set.
5455       // Identifiers between '/' must be unqualified names.
5456       // The utf8 string has been verified when parsing cpool entries.
5457       legal = verify_unqualified_name(bytes, length, LegalClass);
5458     }
5459   }
5460   if (!legal) {
5461     ResourceMark rm(THREAD);
5462     assert(_class_name != NULL, "invariant");
5463     Exceptions::fthrow(
5464       THREAD_AND_LOCATION,
5465       vmSymbols::java_lang_ClassFormatError(),
5466       "Illegal class name \"%.*s\" in class file %s", length, bytes,
5467       _class_name->as_C_string()
5468     );
5469     return;
5470   }
5471 }
5472 
5473 // Checks if name is a legal field name.
5474 void ClassFileParser::verify_legal_field_name(const Symbol* name, TRAPS) const {
5475   if (!_need_verify || _relax_verify) { return; }
5476 
5477   char* bytes = (char*)name->bytes();
5478   unsigned int length = name->utf8_length();
5479   bool legal = false;
5480 
5481   if (length > 0) {
5482     if (_major_version < JAVA_1_5_VERSION) {
5483       if (bytes[0] != '<') {
5484         const char* p = skip_over_field_name(bytes, false, length);
5485         legal = (p != NULL) && ((p - bytes) == (int)length);
5486       }
5487     } else {
5488       // 4881221: relax the constraints based on JSR202 spec
5489       legal = verify_unqualified_name(bytes, length, LegalField);
5490     }
5491   }
5492 
5493   if (!legal) {
5494     ResourceMark rm(THREAD);
5495     assert(_class_name != NULL, "invariant");
5496     Exceptions::fthrow(
5497       THREAD_AND_LOCATION,
5498       vmSymbols::java_lang_ClassFormatError(),
5499       "Illegal field name \"%.*s\" in class %s", length, bytes,
5500       _class_name->as_C_string()
5501     );
5502     return;
5503   }
5504 }
5505 
5506 // Checks if name is a legal method name.
5507 void ClassFileParser::verify_legal_method_name(const Symbol* name, TRAPS) const {
5508   if (!_need_verify || _relax_verify) { return; }
5509 
5510   assert(name != NULL, "method name is null");
5511   char* bytes = (char*)name->bytes();
5512   unsigned int length = name->utf8_length();
5513   bool legal = false;
5514 
5515   if (length > 0) {
5516     if (bytes[0] == '<') {
5517       if (name == vmSymbols::object_initializer_name() || name == vmSymbols::class_initializer_name()) {
5518         legal = true;
5519       }
5520     } else if (_major_version < JAVA_1_5_VERSION) {
5521       const char* p;
5522       p = skip_over_field_name(bytes, false, length);
5523       legal = (p != NULL) && ((p - bytes) == (int)length);
5524     } else {
5525       // 4881221: relax the constraints based on JSR202 spec
5526       legal = verify_unqualified_name(bytes, length, LegalMethod);
5527     }
5528   }
5529 
5530   if (!legal) {
5531     ResourceMark rm(THREAD);
5532     assert(_class_name != NULL, "invariant");
5533     Exceptions::fthrow(
5534       THREAD_AND_LOCATION,
5535       vmSymbols::java_lang_ClassFormatError(),
5536       "Illegal method name \"%.*s\" in class %s", length, bytes,
5537       _class_name->as_C_string()
5538     );
5539     return;
5540   }
5541 }
5542 
5543 
5544 // Checks if signature is a legal field signature.
5545 void ClassFileParser::verify_legal_field_signature(const Symbol* name,
5546                                                    const Symbol* signature,
5547                                                    TRAPS) const {
5548   if (!_need_verify) { return; }
5549 
5550   const char* const bytes = (const char* const)signature->bytes();
5551   const unsigned int length = signature->utf8_length();
5552   const char* const p = skip_over_field_signature(bytes, false, length, CHECK);
5553 
5554   if (p == NULL || (p - bytes) != (int)length) {
5555     throwIllegalSignature("Field", name, signature, CHECK);
5556   }
5557 }
5558 
5559 // Checks if signature is a legal method signature.
5560 // Returns number of parameters
5561 int ClassFileParser::verify_legal_method_signature(const Symbol* name,
5562                                                    const Symbol* signature,
5563                                                    TRAPS) const {
5564   if (!_need_verify) {
5565     // make sure caller's args_size will be less than 0 even for non-static
5566     // method so it will be recomputed in compute_size_of_parameters().
5567     return -2;
5568   }
5569 
5570   // Class initializers cannot have args for class format version >= 51.
5571   if (name == vmSymbols::class_initializer_name() &&
5572       signature != vmSymbols::void_method_signature() &&
5573       _major_version >= JAVA_7_VERSION) {
5574     throwIllegalSignature("Method", name, signature, CHECK_0);
5575     return 0;
5576   }
5577 
5578   unsigned int args_size = 0;
5579   const char* p = (const char*)signature->bytes();
5580   unsigned int length = signature->utf8_length();
5581   const char* nextp;
5582 
5583   // The first character must be a '('
5584   if ((length > 0) && (*p++ == JVM_SIGNATURE_FUNC)) {
5585     length--;
5586     // Skip over legal field signatures
5587     nextp = skip_over_field_signature(p, false, length, CHECK_0);
5588     while ((length > 0) && (nextp != NULL)) {
5589       args_size++;
5590       if (p[0] == 'J' || p[0] == 'D') {
5591         args_size++;
5592       }
5593       length -= nextp - p;
5594       p = nextp;
5595       nextp = skip_over_field_signature(p, false, length, CHECK_0);
5596     }
5597     // The first non-signature thing better be a ')'
5598     if ((length > 0) && (*p++ == JVM_SIGNATURE_ENDFUNC)) {
5599       length--;
5600       if (name->utf8_length() > 0 && name->char_at(0) == '<') {
5601         // All constructor methods must return void
5602         if ((length == 1) && (p[0] == JVM_SIGNATURE_VOID)) {
5603           return args_size;
5604         }
5605         // All static init methods must return the current class
5606         if ((length >= 3) && (p[length-1] == JVM_SIGNATURE_ENDCLASS)
5607             && name == vmSymbols::object_initializer_name()) {
5608           nextp = skip_over_field_signature(p, true, length, CHECK_0);
5609           if (nextp && ((int)length == (nextp - p))) {
5610             // The actual class will be checked against current class
5611             // when the method is defined (see parse_method).
5612             // A reference to a static init with a bad return type
5613             // will load and verify OK, but will fail to link.
5614             return args_size;
5615           }
5616         }
5617         // The distinction between static factory methods and
5618         // constructors depends on the JVM_ACC_STATIC modifier.
5619         // This distinction must be reflected in a void or non-void
5620         // return. For declared methods, the check is in parse_method.
5621       } else {
5622         // Now we better just have a return value
5623         nextp = skip_over_field_signature(p, true, length, CHECK_0);
5624         if (nextp && ((int)length == (nextp - p))) {
5625           return args_size;
5626         }
5627       }
5628     }
5629   }
5630   // Report error
5631   throwIllegalSignature("Method", name, signature, CHECK_0);
5632   return 0;
5633 }
5634 
5635 int ClassFileParser::static_field_size() const {
5636   assert(_field_info != NULL, "invariant");
5637   return _field_info->static_field_size;
5638 }
5639 
5640 int ClassFileParser::total_oop_map_count() const {
5641   assert(_field_info != NULL, "invariant");
5642   return _field_info->oop_map_blocks->nonstatic_oop_map_count;
5643 }
5644 
5645 jint ClassFileParser::layout_size() const {
5646   assert(_field_info != NULL, "invariant");
5647   return _field_info->instance_size;
5648 }
5649 
5650 static void check_methods_for_intrinsics(const InstanceKlass* ik,
5651                                          const Array<Method*>* methods) {
5652   assert(ik != NULL, "invariant");
5653   assert(methods != NULL, "invariant");
5654 
5655   // Set up Method*::intrinsic_id as soon as we know the names of methods.
5656   // (We used to do this lazily, but now we query it in Rewriter,
5657   // which is eagerly done for every method, so we might as well do it now,
5658   // when everything is fresh in memory.)
5659   const vmSymbols::SID klass_id = Method::klass_id_for_intrinsics(ik);
5660 
5661   if (klass_id != vmSymbols::NO_SID) {
5662     for (int j = 0; j < methods->length(); ++j) {
5663       Method* method = methods->at(j);
5664       method->init_intrinsic_id();
5665 
5666       if (CheckIntrinsics) {
5667         // Check if an intrinsic is defined for method 'method',
5668         // but the method is not annotated with @HotSpotIntrinsicCandidate.
5669         if (method->intrinsic_id() != vmIntrinsics::_none &&
5670             !method->intrinsic_candidate()) {
5671               tty->print("Compiler intrinsic is defined for method [%s], "
5672               "but the method is not annotated with @HotSpotIntrinsicCandidate.%s",
5673               method->name_and_sig_as_C_string(),
5674               NOT_DEBUG(" Method will not be inlined.") DEBUG_ONLY(" Exiting.")
5675             );
5676           tty->cr();
5677           DEBUG_ONLY(vm_exit(1));
5678         }
5679         // Check is the method 'method' is annotated with @HotSpotIntrinsicCandidate,
5680         // but there is no intrinsic available for it.
5681         if (method->intrinsic_candidate() &&
5682           method->intrinsic_id() == vmIntrinsics::_none) {
5683             tty->print("Method [%s] is annotated with @HotSpotIntrinsicCandidate, "
5684               "but no compiler intrinsic is defined for the method.%s",
5685               method->name_and_sig_as_C_string(),
5686               NOT_DEBUG("") DEBUG_ONLY(" Exiting.")
5687             );
5688           tty->cr();
5689           DEBUG_ONLY(vm_exit(1));
5690         }
5691       }
5692     } // end for
5693 
5694 #ifdef ASSERT
5695     if (CheckIntrinsics) {
5696       // Check for orphan methods in the current class. A method m
5697       // of a class C is orphan if an intrinsic is defined for method m,
5698       // but class C does not declare m.
5699       // The check is potentially expensive, therefore it is available
5700       // only in debug builds.
5701 
5702       for (int id = vmIntrinsics::FIRST_ID; id < (int)vmIntrinsics::ID_LIMIT; ++id) {
5703         if (vmIntrinsics::_compiledLambdaForm == id) {
5704           // The _compiledLamdbdaForm intrinsic is a special marker for bytecode
5705           // generated for the JVM from a LambdaForm and therefore no method
5706           // is defined for it.
5707           continue;
5708         }
5709 
5710         if (vmIntrinsics::class_for(vmIntrinsics::ID_from(id)) == klass_id) {
5711           // Check if the current class contains a method with the same
5712           // name, flags, signature.
5713           bool match = false;
5714           for (int j = 0; j < methods->length(); ++j) {
5715             const Method* method = methods->at(j);
5716             if (method->intrinsic_id() == id) {
5717               match = true;
5718               break;
5719             }
5720           }
5721 
5722           if (!match) {
5723             char buf[1000];
5724             tty->print("Compiler intrinsic is defined for method [%s], "
5725                        "but the method is not available in class [%s].%s",
5726                         vmIntrinsics::short_name_as_C_string(vmIntrinsics::ID_from(id),
5727                                                              buf, sizeof(buf)),
5728                         ik->name()->as_C_string(),
5729                         NOT_DEBUG("") DEBUG_ONLY(" Exiting.")
5730             );
5731             tty->cr();
5732             DEBUG_ONLY(vm_exit(1));
5733           }
5734         }
5735       } // end for
5736     } // CheckIntrinsics
5737 #endif // ASSERT
5738   }
5739 }
5740 
5741 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook, TRAPS) {
5742   if (_klass != NULL) {
5743     return _klass;
5744   }
5745 
5746   InstanceKlass* const ik =
5747     InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
5748 
5749   fill_instance_klass(ik, changed_by_loadhook, CHECK_NULL);
5750 
5751   assert(_klass == ik, "invariant");
5752 
5753 
5754   if (ik->should_store_fingerprint()) {
5755     ik->store_fingerprint(_stream->compute_fingerprint());
5756   }
5757 
5758   ik->set_has_passed_fingerprint_check(false);
5759   if (UseAOT && ik->supers_have_passed_fingerprint_checks()) {
5760     uint64_t aot_fp = AOTLoader::get_saved_fingerprint(ik);
5761     uint64_t fp = ik->has_stored_fingerprint() ? ik->get_stored_fingerprint() : _stream->compute_fingerprint();
5762     if (aot_fp != 0 && aot_fp == fp) {
5763       // This class matches with a class saved in an AOT library
5764       ik->set_has_passed_fingerprint_check(true);
5765     } else {
5766       ResourceMark rm;
5767       log_info(class, fingerprint)("%s :  expected = " PTR64_FORMAT " actual = " PTR64_FORMAT,
5768                                  ik->external_name(), aot_fp, _stream->compute_fingerprint());
5769     }
5770   }
5771 
5772   if (ik->is_value()) {
5773     ValueKlass* vk = ValueKlass::cast(ik);
5774     oop val = ik->allocate_instance(CHECK_NULL);
5775     vk->set_default_value(val);
5776   }
5777 
5778   return ik;
5779 }
5780 
5781 void ClassFileParser::fill_instance_klass(InstanceKlass* ik, bool changed_by_loadhook, TRAPS) {
5782   assert(ik != NULL, "invariant");
5783 
5784   // Set name and CLD before adding to CLD
5785   ik->set_class_loader_data(_loader_data);
5786   ik->set_name(_class_name);
5787 
5788   // Add all classes to our internal class loader list here,
5789   // including classes in the bootstrap (NULL) class loader.
5790   const bool publicize = !is_internal();
5791 
5792   _loader_data->add_class(ik, publicize);
5793 
5794   set_klass_to_deallocate(ik);
5795 
5796   assert(_field_info != NULL, "invariant");
5797   assert(ik->static_field_size() == _field_info->static_field_size, "sanity");
5798   assert(ik->nonstatic_oop_map_count() == _field_info->oop_map_blocks->nonstatic_oop_map_count,
5799     "sanity");
5800 
5801   assert(ik->is_instance_klass(), "sanity");
5802   assert(ik->size_helper() == _field_info->instance_size, "sanity");
5803 
5804   // Fill in information already parsed
5805   ik->set_should_verify_class(_need_verify);
5806 
5807   // Not yet: supers are done below to support the new subtype-checking fields
5808   ik->set_nonstatic_field_size(_field_info->nonstatic_field_size);
5809   ik->set_has_nonstatic_fields(_field_info->has_nonstatic_fields);
5810   if (_is_empty_value) {
5811     ik->set_is_empty_value();
5812   }
5813   assert(_fac != NULL, "invariant");
5814   ik->set_static_oop_field_count(_fac->count[STATIC_OOP] + _fac->count[STATIC_FLATTENABLE]);
5815 
5816   // this transfers ownership of a lot of arrays from
5817   // the parser onto the InstanceKlass*
5818   apply_parsed_class_metadata(ik, _java_fields_count, CHECK);
5819 
5820   // note that is not safe to use the fields in the parser from this point on
5821   assert(NULL == _cp, "invariant");
5822   assert(NULL == _fields, "invariant");
5823   assert(NULL == _methods, "invariant");
5824   assert(NULL == _inner_classes, "invariant");
5825   assert(NULL == _nest_members, "invariant");
5826   assert(NULL == _local_interfaces, "invariant");
5827   assert(NULL == _combined_annotations, "invariant");
5828 
5829   if (_has_final_method) {
5830     ik->set_has_final_method();
5831   }
5832 
5833   ik->copy_method_ordering(_method_ordering, CHECK);
5834   // The InstanceKlass::_methods_jmethod_ids cache
5835   // is managed on the assumption that the initial cache
5836   // size is equal to the number of methods in the class. If
5837   // that changes, then InstanceKlass::idnum_can_increment()
5838   // has to be changed accordingly.
5839   ik->set_initial_method_idnum(ik->methods()->length());
5840 
5841   ik->set_this_class_index(_this_class_index);
5842 
5843   if (is_unsafe_anonymous()) {
5844     // _this_class_index is a CONSTANT_Class entry that refers to this
5845     // anonymous class itself. If this class needs to refer to its own methods or
5846     // fields, it would use a CONSTANT_MethodRef, etc, which would reference
5847     // _this_class_index. However, because this class is anonymous (it's
5848     // not stored in SystemDictionary), _this_class_index cannot be resolved
5849     // with ConstantPool::klass_at_impl, which does a SystemDictionary lookup.
5850     // Therefore, we must eagerly resolve _this_class_index now.
5851     ik->constants()->klass_at_put(_this_class_index, ik);
5852   }
5853 
5854   ik->set_minor_version(_minor_version);
5855   ik->set_major_version(_major_version);
5856   ik->set_has_nonstatic_concrete_methods(_has_nonstatic_concrete_methods);
5857   ik->set_declares_nonstatic_concrete_methods(_declares_nonstatic_concrete_methods);
5858 
5859   if (_unsafe_anonymous_host != NULL) {
5860     assert (ik->is_unsafe_anonymous(), "should be the same");
5861     ik->set_unsafe_anonymous_host(_unsafe_anonymous_host);
5862   }
5863 
5864   // Set PackageEntry for this_klass
5865   oop cl = ik->class_loader();
5866   Handle clh = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(cl));
5867   ClassLoaderData* cld = ClassLoaderData::class_loader_data_or_null(clh());
5868   ik->set_package(cld, CHECK);
5869 
5870   const Array<Method*>* const methods = ik->methods();
5871   assert(methods != NULL, "invariant");
5872   const int methods_len = methods->length();
5873 
5874   check_methods_for_intrinsics(ik, methods);
5875 
5876   // Fill in field values obtained by parse_classfile_attributes
5877   if (_parsed_annotations->has_any_annotations()) {
5878     _parsed_annotations->apply_to(ik);
5879   }
5880 
5881   apply_parsed_class_attributes(ik);
5882 
5883   // Miranda methods
5884   if ((_num_miranda_methods > 0) ||
5885       // if this class introduced new miranda methods or
5886       (_super_klass != NULL && _super_klass->has_miranda_methods())
5887         // super class exists and this class inherited miranda methods
5888      ) {
5889        ik->set_has_miranda_methods(); // then set a flag
5890   }
5891 
5892   // Fill in information needed to compute superclasses.
5893   ik->initialize_supers(const_cast<InstanceKlass*>(_super_klass), _transitive_interfaces, CHECK);
5894   ik->set_transitive_interfaces(_transitive_interfaces);
5895   _transitive_interfaces = NULL;
5896 
5897   // Initialize itable offset tables
5898   klassItable::setup_itable_offset_table(ik);
5899 
5900   // Compute transitive closure of interfaces this class implements
5901   // Do final class setup
5902   OopMapBlocksBuilder* oop_map_blocks = _field_info->oop_map_blocks;
5903   if (oop_map_blocks->nonstatic_oop_map_count > 0) {
5904     oop_map_blocks->copy(ik->start_of_nonstatic_oop_maps());
5905   }
5906 
5907   // Fill in has_finalizer, has_vanilla_constructor, and layout_helper
5908   set_precomputed_flags(ik, CHECK);
5909 
5910   // check if this class can access its super class
5911   check_super_class_access(ik, CHECK);
5912 
5913   // check if this class can access its superinterfaces
5914   check_super_interface_access(ik, CHECK);
5915 
5916   // check if this class overrides any final method
5917   check_final_method_override(ik, CHECK);
5918 
5919   // reject static interface methods prior to Java 8
5920   if (ik->is_interface() && _major_version < JAVA_8_VERSION) {
5921     check_illegal_static_method(ik, CHECK);
5922   }
5923 
5924   // Obtain this_klass' module entry
5925   ModuleEntry* module_entry = ik->module();
5926   assert(module_entry != NULL, "module_entry should always be set");
5927 
5928   // Obtain java.lang.Module
5929   Handle module_handle(THREAD, module_entry->module());
5930 
5931   // Allocate mirror and initialize static fields
5932   // The create_mirror() call will also call compute_modifiers()
5933   java_lang_Class::create_mirror(ik,
5934                                  Handle(THREAD, _loader_data->class_loader()),
5935                                  module_handle,
5936                                  _protection_domain,
5937                                  CHECK);
5938 
5939   assert(_all_mirandas != NULL, "invariant");
5940 
5941   // Generate any default methods - default methods are public interface methods
5942   // that have a default implementation.  This is new with Java 8.
5943   if (_has_nonstatic_concrete_methods) {
5944     DefaultMethods::generate_default_methods(ik,
5945                                              _all_mirandas,
5946                                              CHECK);
5947   }
5948 
5949   // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5950   if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5951       !module_entry->has_default_read_edges()) {
5952     if (!module_entry->set_has_default_read_edges()) {
5953       // We won a potential race
5954       JvmtiExport::add_default_read_edges(module_handle, THREAD);
5955     }
5956   }
5957 
5958   int nfields = ik->java_fields_count();
5959   if (ik->is_value()) nfields++;
5960   for (int i = 0; i < nfields; i++) {
5961     if (ik->field_is_flattenable(i)) {
5962       Symbol* klass_name = ik->field_signature(i)->fundamental_name(CHECK);
5963       // Inline classes for instance fields must have been pre-loaded
5964       // Inline classes for static fields might not have been loaded yet
5965       Klass* klass = SystemDictionary::find(klass_name,
5966           Handle(THREAD, ik->class_loader()),
5967           Handle(THREAD, ik->protection_domain()), CHECK);
5968       if (klass != NULL) {
5969         assert(klass->access_flags().is_value_type(), "Value type expected");
5970         ik->set_value_field_klass(i, klass);
5971       }
5972       klass_name->decrement_refcount();
5973     } else
5974       if (is_value_type() && ((ik->field_access_flags(i) & JVM_ACC_FIELD_INTERNAL) != 0)
5975         && ((ik->field_access_flags(i) & JVM_ACC_STATIC) != 0)) {
5976       ValueKlass::cast(ik)->set_default_value_offset(ik->field_offset(i));
5977     }
5978   }
5979 
5980   if (is_value_type()) {
5981     ValueKlass* vk = ValueKlass::cast(ik);
5982     if (UseNewLayout) {
5983       vk->set_alignment(_alignment);
5984       vk->set_first_field_offset(_first_field_offset);
5985       vk->set_exact_size_in_bytes(_exact_size_in_bytes);
5986     } else {
5987       vk->set_first_field_offset(vk->first_field_offset_old());
5988     }
5989     ValueKlass::cast(ik)->initialize_calling_convention(CHECK);
5990   }
5991 
5992   ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5993 
5994   if (!is_internal()) {
5995     if (log_is_enabled(Info, class, load)) {
5996       ResourceMark rm;
5997       const char* module_name = (module_entry->name() == NULL) ? UNNAMED_MODULE : module_entry->name()->as_C_string();
5998       ik->print_class_load_logging(_loader_data, module_name, _stream);
5999     }
6000 
6001     if (ik->minor_version() == JAVA_PREVIEW_MINOR_VERSION &&
6002         ik->major_version() == JVM_CLASSFILE_MAJOR_VERSION &&
6003         log_is_enabled(Info, class, preview)) {
6004       ResourceMark rm;
6005       log_info(class, preview)("Loading class %s that depends on preview features (class file version %d.65535)",
6006                                ik->external_name(), JVM_CLASSFILE_MAJOR_VERSION);
6007     }
6008 
6009     if (log_is_enabled(Debug, class, resolve))  {
6010       ResourceMark rm;
6011       // print out the superclass.
6012       const char * from = ik->external_name();
6013       if (ik->java_super() != NULL) {
6014         log_debug(class, resolve)("%s %s (super)",
6015                    from,
6016                    ik->java_super()->external_name());
6017       }
6018       // print out each of the interface classes referred to by this class.
6019       const Array<InstanceKlass*>* const local_interfaces = ik->local_interfaces();
6020       if (local_interfaces != NULL) {
6021         const int length = local_interfaces->length();
6022         for (int i = 0; i < length; i++) {
6023           const InstanceKlass* const k = local_interfaces->at(i);
6024           const char * to = k->external_name();
6025           log_debug(class, resolve)("%s %s (interface)", from, to);
6026         }
6027       }
6028     }
6029   }
6030 
6031   JFR_ONLY(INIT_ID(ik);)
6032 
6033   // If we reach here, all is well.
6034   // Now remove the InstanceKlass* from the _klass_to_deallocate field
6035   // in order for it to not be destroyed in the ClassFileParser destructor.
6036   set_klass_to_deallocate(NULL);
6037 
6038   // it's official
6039   set_klass(ik);
6040 
6041   debug_only(ik->verify();)
6042 }
6043 
6044 void ClassFileParser::update_class_name(Symbol* new_class_name) {
6045   // Decrement the refcount in the old name, since we're clobbering it.
6046   _class_name->decrement_refcount();
6047 
6048   _class_name = new_class_name;
6049   // Increment the refcount of the new name.
6050   // Now the ClassFileParser owns this name and will decrement in
6051   // the destructor.
6052   _class_name->increment_refcount();
6053 }
6054 
6055 
6056 // For an unsafe anonymous class that is in the unnamed package, move it to its host class's
6057 // package by prepending its host class's package name to its class name and setting
6058 // its _class_name field.
6059 void ClassFileParser::prepend_host_package_name(const InstanceKlass* unsafe_anonymous_host, TRAPS) {
6060   ResourceMark rm(THREAD);
6061   assert(strrchr(_class_name->as_C_string(), '/') == NULL,
6062          "Unsafe anonymous class should not be in a package");
6063   const char* host_pkg_name =
6064     ClassLoader::package_from_name(unsafe_anonymous_host->name()->as_C_string(), NULL);
6065 
6066   if (host_pkg_name != NULL) {
6067     int host_pkg_len = (int)strlen(host_pkg_name);
6068     int class_name_len = _class_name->utf8_length();
6069     int symbol_len = host_pkg_len + 1 + class_name_len;
6070     char* new_anon_name = NEW_RESOURCE_ARRAY(char, symbol_len + 1);
6071     int n = os::snprintf(new_anon_name, symbol_len + 1, "%s/%.*s",
6072                          host_pkg_name, class_name_len, _class_name->base());
6073     assert(n == symbol_len, "Unexpected number of characters in string");
6074 
6075     // Decrement old _class_name to avoid leaking.
6076     _class_name->decrement_refcount();
6077 
6078     // Create a symbol and update the anonymous class name.
6079     // The new class name is created with a refcount of one. When installed into the InstanceKlass,
6080     // it'll be two and when the ClassFileParser destructor runs, it'll go back to one and get deleted
6081     // when the class is unloaded.
6082     _class_name = SymbolTable::new_symbol(new_anon_name, symbol_len);
6083   }
6084 }
6085 
6086 // If the host class and the anonymous class are in the same package then do
6087 // nothing.  If the anonymous class is in the unnamed package then move it to its
6088 // host's package.  If the classes are in different packages then throw an IAE
6089 // exception.
6090 void ClassFileParser::fix_unsafe_anonymous_class_name(TRAPS) {
6091   assert(_unsafe_anonymous_host != NULL, "Expected an unsafe anonymous class");
6092 
6093   const jbyte* anon_last_slash = UTF8::strrchr((const jbyte*)_class_name->base(),
6094                                                _class_name->utf8_length(), '/');
6095   if (anon_last_slash == NULL) {  // Unnamed package
6096     prepend_host_package_name(_unsafe_anonymous_host, CHECK);
6097   } else {
6098     if (!_unsafe_anonymous_host->is_same_class_package(_unsafe_anonymous_host->class_loader(), _class_name)) {
6099       ResourceMark rm(THREAD);
6100       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
6101         err_msg("Host class %s and anonymous class %s are in different packages",
6102         _unsafe_anonymous_host->name()->as_C_string(), _class_name->as_C_string()));
6103     }
6104   }
6105 }
6106 
6107 static bool relax_format_check_for(ClassLoaderData* loader_data) {
6108   bool trusted = (loader_data->is_the_null_class_loader_data() ||
6109                   SystemDictionary::is_platform_class_loader(loader_data->class_loader()));
6110   bool need_verify =
6111     // verifyAll
6112     (BytecodeVerificationLocal && BytecodeVerificationRemote) ||
6113     // verifyRemote
6114     (!BytecodeVerificationLocal && BytecodeVerificationRemote && !trusted);
6115   return !need_verify;
6116 }
6117 
6118 ClassFileParser::ClassFileParser(ClassFileStream* stream,
6119                                  Symbol* name,
6120                                  ClassLoaderData* loader_data,
6121                                  Handle protection_domain,
6122                                  const InstanceKlass* unsafe_anonymous_host,
6123                                  GrowableArray<Handle>* cp_patches,
6124                                  Publicity pub_level,
6125                                  TRAPS) :
6126   _stream(stream),
6127   _requested_name(name),
6128   _class_name(NULL),
6129   _loader_data(loader_data),
6130   _unsafe_anonymous_host(unsafe_anonymous_host),
6131   _cp_patches(cp_patches),
6132   _num_patched_klasses(0),
6133   _max_num_patched_klasses(0),
6134   _orig_cp_size(0),
6135   _first_patched_klass_resolved_index(0),
6136   _super_klass(),
6137   _cp(NULL),
6138   _fields(NULL),
6139   _methods(NULL),
6140   _inner_classes(NULL),
6141   _nest_members(NULL),
6142   _nest_host(0),
6143   _local_interfaces(NULL),
6144   _transitive_interfaces(NULL),
6145   _combined_annotations(NULL),
6146   _annotations(NULL),
6147   _type_annotations(NULL),
6148   _fields_annotations(NULL),
6149   _fields_type_annotations(NULL),
6150   _klass(NULL),
6151   _klass_to_deallocate(NULL),
6152   _parsed_annotations(NULL),
6153   _fac(NULL),
6154   _field_info(NULL),
6155   _method_ordering(NULL),
6156   _all_mirandas(NULL),
6157   _vtable_size(0),
6158   _itable_size(0),
6159   _num_miranda_methods(0),
6160   _rt(REF_NONE),
6161   _protection_domain(protection_domain),
6162   _access_flags(),
6163   _pub_level(pub_level),
6164   _bad_constant_seen(0),
6165   _synthetic_flag(false),
6166   _sde_length(false),
6167   _sde_buffer(NULL),
6168   _sourcefile_index(0),
6169   _generic_signature_index(0),
6170   _major_version(0),
6171   _minor_version(0),
6172   _this_class_index(0),
6173   _super_class_index(0),
6174   _itfs_len(0),
6175   _java_fields_count(0),
6176   _need_verify(false),
6177   _relax_verify(false),
6178   _has_nonstatic_concrete_methods(false),
6179   _declares_nonstatic_concrete_methods(false),
6180   _has_final_method(false),
6181   _has_flattenable_fields(false),
6182   _is_empty_value(false),
6183   _has_finalizer(false),
6184   _has_empty_finalizer(false),
6185   _has_vanilla_constructor(false),
6186   _max_bootstrap_specifier_index(-1) {
6187 
6188   _class_name = name != NULL ? name : vmSymbols::unknown_class_name();
6189   _class_name->increment_refcount();
6190 
6191   assert(THREAD->is_Java_thread(), "invariant");
6192   assert(_loader_data != NULL, "invariant");
6193   assert(stream != NULL, "invariant");
6194   assert(_stream != NULL, "invariant");
6195   assert(_stream->buffer() == _stream->current(), "invariant");
6196   assert(_class_name != NULL, "invariant");
6197   assert(0 == _access_flags.as_int(), "invariant");
6198 
6199   // Figure out whether we can skip format checking (matching classic VM behavior)
6200   if (DumpSharedSpaces) {
6201     // verify == true means it's a 'remote' class (i.e., non-boot class)
6202     // Verification decision is based on BytecodeVerificationRemote flag
6203     // for those classes.
6204     _need_verify = (stream->need_verify()) ? BytecodeVerificationRemote :
6205                                               BytecodeVerificationLocal;
6206   }
6207   else {
6208     _need_verify = Verifier::should_verify_for(_loader_data->class_loader(),
6209                                                stream->need_verify());
6210   }
6211   if (_cp_patches != NULL) {
6212     int len = _cp_patches->length();
6213     for (int i=0; i<len; i++) {
6214       if (has_cp_patch_at(i)) {
6215         Handle patch = cp_patch_at(i);
6216         if (java_lang_String::is_instance(patch()) || java_lang_Class::is_instance(patch())) {
6217           // We need to append the names of the patched classes to the end of the constant pool,
6218           // because a patched class may have a Utf8 name that's not already included in the
6219           // original constant pool. These class names are used when patch_constant_pool()
6220           // calls patch_class().
6221           //
6222           // Note that a String in cp_patch_at(i) may be used to patch a Utf8, a String, or a Class.
6223           // At this point, we don't know the tag for index i yet, because we haven't parsed the
6224           // constant pool. So we can only assume the worst -- every String is used to patch a Class.
6225           _max_num_patched_klasses++;
6226         }
6227       }
6228     }
6229   }
6230 
6231   // synch back verification state to stream
6232   stream->set_verify(_need_verify);
6233 
6234   // Check if verification needs to be relaxed for this class file
6235   // Do not restrict it to jdk1.0 or jdk1.1 to maintain backward compatibility (4982376)
6236   _relax_verify = relax_format_check_for(_loader_data);
6237 
6238   parse_stream(stream, CHECK);
6239 
6240   post_process_parsed_stream(stream, _cp, CHECK);
6241 }
6242 
6243 void ClassFileParser::clear_class_metadata() {
6244   // metadata created before the instance klass is created.  Must be
6245   // deallocated if classfile parsing returns an error.
6246   _cp = NULL;
6247   _fields = NULL;
6248   _methods = NULL;
6249   _inner_classes = NULL;
6250   _nest_members = NULL;
6251   _local_interfaces = NULL;
6252   _combined_annotations = NULL;
6253   _annotations = _type_annotations = NULL;
6254   _fields_annotations = _fields_type_annotations = NULL;
6255 }
6256 
6257 // Destructor to clean up
6258 ClassFileParser::~ClassFileParser() {
6259   _class_name->decrement_refcount();
6260 
6261   if (_cp != NULL) {
6262     MetadataFactory::free_metadata(_loader_data, _cp);
6263   }
6264   if (_fields != NULL) {
6265     MetadataFactory::free_array<u2>(_loader_data, _fields);
6266   }
6267 
6268   if (_methods != NULL) {
6269     // Free methods
6270     InstanceKlass::deallocate_methods(_loader_data, _methods);
6271   }
6272 
6273   // beware of the Universe::empty_blah_array!!
6274   if (_inner_classes != NULL && _inner_classes != Universe::the_empty_short_array()) {
6275     MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
6276   }
6277 
6278   if (_nest_members != NULL && _nest_members != Universe::the_empty_short_array()) {
6279     MetadataFactory::free_array<u2>(_loader_data, _nest_members);
6280   }
6281 
6282   // Free interfaces
6283   InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
6284                                        _local_interfaces, _transitive_interfaces);
6285 
6286   if (_combined_annotations != NULL) {
6287     // After all annotations arrays have been created, they are installed into the
6288     // Annotations object that will be assigned to the InstanceKlass being created.
6289 
6290     // Deallocate the Annotations object and the installed annotations arrays.
6291     _combined_annotations->deallocate_contents(_loader_data);
6292 
6293     // If the _combined_annotations pointer is non-NULL,
6294     // then the other annotations fields should have been cleared.
6295     assert(_annotations             == NULL, "Should have been cleared");
6296     assert(_type_annotations        == NULL, "Should have been cleared");
6297     assert(_fields_annotations      == NULL, "Should have been cleared");
6298     assert(_fields_type_annotations == NULL, "Should have been cleared");
6299   } else {
6300     // If the annotations arrays were not installed into the Annotations object,
6301     // then they have to be deallocated explicitly.
6302     MetadataFactory::free_array<u1>(_loader_data, _annotations);
6303     MetadataFactory::free_array<u1>(_loader_data, _type_annotations);
6304     Annotations::free_contents(_loader_data, _fields_annotations);
6305     Annotations::free_contents(_loader_data, _fields_type_annotations);
6306   }
6307 
6308   clear_class_metadata();
6309   _transitive_interfaces = NULL;
6310 
6311   // deallocate the klass if already created.  Don't directly deallocate, but add
6312   // to the deallocate list so that the klass is removed from the CLD::_klasses list
6313   // at a safepoint.
6314   if (_klass_to_deallocate != NULL) {
6315     _loader_data->add_to_deallocate_list(_klass_to_deallocate);
6316   }
6317 }
6318 
6319 void ClassFileParser::parse_stream(const ClassFileStream* const stream,
6320                                    TRAPS) {
6321 
6322   assert(stream != NULL, "invariant");
6323   assert(_class_name != NULL, "invariant");
6324 
6325   // BEGIN STREAM PARSING
6326   stream->guarantee_more(8, CHECK);  // magic, major, minor
6327   // Magic value
6328   const u4 magic = stream->get_u4_fast();
6329   guarantee_property(magic == JAVA_CLASSFILE_MAGIC,
6330                      "Incompatible magic value %u in class file %s",
6331                      magic, CHECK);
6332 
6333   // Version numbers
6334   _minor_version = stream->get_u2_fast();
6335   _major_version = stream->get_u2_fast();
6336 
6337   if (DumpSharedSpaces && _major_version < JAVA_6_VERSION) {
6338     ResourceMark rm;
6339     warning("Pre JDK 6 class not supported by CDS: %u.%u %s",
6340             _major_version,  _minor_version, _class_name->as_C_string());
6341     Exceptions::fthrow(
6342       THREAD_AND_LOCATION,
6343       vmSymbols::java_lang_UnsupportedClassVersionError(),
6344       "Unsupported major.minor version for dump time %u.%u",
6345       _major_version,
6346       _minor_version);
6347   }
6348 
6349   // Check version numbers - we check this even with verifier off
6350   verify_class_version(_major_version, _minor_version, _class_name, CHECK);
6351 
6352   stream->guarantee_more(3, CHECK); // length, first cp tag
6353   u2 cp_size = stream->get_u2_fast();
6354 
6355   guarantee_property(
6356     cp_size >= 1, "Illegal constant pool size %u in class file %s",
6357     cp_size, CHECK);
6358 
6359   _orig_cp_size = cp_size;
6360   if (int(cp_size) + _max_num_patched_klasses > 0xffff) {
6361     THROW_MSG(vmSymbols::java_lang_InternalError(), "not enough space for patched classes");
6362   }
6363   cp_size += _max_num_patched_klasses;
6364 
6365   _cp = ConstantPool::allocate(_loader_data,
6366                                cp_size,
6367                                CHECK);
6368 
6369   ConstantPool* const cp = _cp;
6370 
6371   parse_constant_pool(stream, cp, _orig_cp_size, CHECK);
6372 
6373   assert(cp_size == (const u2)cp->length(), "invariant");
6374 
6375   // ACCESS FLAGS
6376   stream->guarantee_more(8, CHECK);  // flags, this_class, super_class, infs_len
6377 
6378   jint recognized_modifiers = JVM_RECOGNIZED_CLASS_MODIFIERS;
6379   // JVM_ACC_MODULE is defined in JDK-9 and later.
6380   if (_major_version >= JAVA_9_VERSION) {
6381     recognized_modifiers |= JVM_ACC_MODULE;
6382   }
6383   // JVM_ACC_VALUE is defined for class file version 55 and later
6384   if (supports_value_types()) {
6385     recognized_modifiers |= JVM_ACC_VALUE;
6386   }
6387 
6388   // Access flags
6389   jint flags = stream->get_u2_fast() & recognized_modifiers;
6390 
6391   if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
6392     // Set abstract bit for old class files for backward compatibility
6393     flags |= JVM_ACC_ABSTRACT;
6394   }
6395 
6396   verify_legal_class_modifiers(flags, CHECK);
6397 
6398   short bad_constant = class_bad_constant_seen();
6399   if (bad_constant != 0) {
6400     // Do not throw CFE until after the access_flags are checked because if
6401     // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
6402     classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, CHECK);
6403   }
6404 
6405   _access_flags.set_flags(flags);
6406 
6407   // This class and superclass
6408   _this_class_index = stream->get_u2_fast();
6409   check_property(
6410     valid_cp_range(_this_class_index, cp_size) &&
6411       cp->tag_at(_this_class_index).is_unresolved_klass(),
6412     "Invalid this class index %u in constant pool in class file %s",
6413     _this_class_index, CHECK);
6414 
6415   Symbol* const class_name_in_cp = cp->klass_name_at(_this_class_index);
6416   assert(class_name_in_cp != NULL, "class_name can't be null");
6417 
6418   // Update _class_name to reflect the name in the constant pool
6419   update_class_name(class_name_in_cp);
6420 
6421   // Don't need to check whether this class name is legal or not.
6422   // It has been checked when constant pool is parsed.
6423   // However, make sure it is not an array type.
6424   if (_need_verify) {
6425     guarantee_property(_class_name->char_at(0) != JVM_SIGNATURE_ARRAY,
6426                        "Bad class name in class file %s",
6427                        CHECK);
6428   }
6429 
6430   // Checks if name in class file matches requested name
6431   if (_requested_name != NULL && _requested_name != _class_name) {
6432     ResourceMark rm(THREAD);
6433     Exceptions::fthrow(
6434       THREAD_AND_LOCATION,
6435       vmSymbols::java_lang_NoClassDefFoundError(),
6436       "%s (wrong name: %s)",
6437       _class_name->as_C_string(),
6438       _requested_name != NULL ? _requested_name->as_C_string() : "NoName"
6439     );
6440     return;
6441   }
6442 
6443   // if this is an anonymous class fix up its name if it's in the unnamed
6444   // package.  Otherwise, throw IAE if it is in a different package than
6445   // its host class.
6446   if (_unsafe_anonymous_host != NULL) {
6447     fix_unsafe_anonymous_class_name(CHECK);
6448   }
6449 
6450   // Verification prevents us from creating names with dots in them, this
6451   // asserts that that's the case.
6452   assert(is_internal_format(_class_name), "external class name format used internally");
6453 
6454   if (!is_internal()) {
6455     LogTarget(Debug, class, preorder) lt;
6456     if (lt.is_enabled()){
6457       ResourceMark rm(THREAD);
6458       LogStream ls(lt);
6459       ls.print("%s", _class_name->as_klass_external_name());
6460       if (stream->source() != NULL) {
6461         ls.print(" source: %s", stream->source());
6462       }
6463       ls.cr();
6464     }
6465 
6466 #if INCLUDE_CDS
6467     if (DumpLoadedClassList != NULL && stream->source() != NULL && classlist_file->is_open()) {
6468       if (!ClassLoader::has_jrt_entry()) {
6469         warning("DumpLoadedClassList and CDS are not supported in exploded build");
6470         DumpLoadedClassList = NULL;
6471       } else if (SystemDictionaryShared::is_sharing_possible(_loader_data) &&
6472                  _unsafe_anonymous_host == NULL) {
6473         // Only dump the classes that can be stored into CDS archive.
6474         // Unsafe anonymous classes such as generated LambdaForm classes are also not included.
6475         oop class_loader = _loader_data->class_loader();
6476         ResourceMark rm(THREAD);
6477         bool skip = false;
6478         if (class_loader == NULL || SystemDictionary::is_platform_class_loader(class_loader)) {
6479           // For the boot and platform class loaders, skip classes that are not found in the
6480           // java runtime image, such as those found in the --patch-module entries.
6481           // These classes can't be loaded from the archive during runtime.
6482           if (!stream->from_boot_loader_modules_image() && strncmp(stream->source(), "jrt:", 4) != 0) {
6483             skip = true;
6484           }
6485 
6486           if (class_loader == NULL && ClassLoader::contains_append_entry(stream->source())) {
6487             // .. but don't skip the boot classes that are loaded from -Xbootclasspath/a
6488             // as they can be loaded from the archive during runtime.
6489             skip = false;
6490           }
6491         }
6492         if (skip) {
6493           tty->print_cr("skip writing class %s from source %s to classlist file",
6494             _class_name->as_C_string(), stream->source());
6495         } else {
6496           classlist_file->print_cr("%s", _class_name->as_C_string());
6497           classlist_file->flush();
6498         }
6499       }
6500     }
6501 #endif
6502   }
6503 
6504   // SUPERKLASS
6505   _super_class_index = stream->get_u2_fast();
6506   _super_klass = parse_super_class(cp,
6507                                    _super_class_index,
6508                                    _need_verify,
6509                                    CHECK);
6510 
6511   // Interfaces
6512   _itfs_len = stream->get_u2_fast();
6513   parse_interfaces(stream,
6514                    _itfs_len,
6515                    cp,
6516                    &_has_nonstatic_concrete_methods,
6517                    CHECK);
6518 
6519   assert(_local_interfaces != NULL, "invariant");
6520 
6521   // Fields (offsets are filled in later)
6522   _fac = new FieldAllocationCount();
6523   parse_fields(stream,
6524                _access_flags.is_interface(),
6525                _access_flags.is_value_type(),
6526                _fac,
6527                cp,
6528                cp_size,
6529                &_java_fields_count,
6530                CHECK);
6531 
6532   assert(_fields != NULL, "invariant");
6533 
6534   // Methods
6535   AccessFlags promoted_flags;
6536   parse_methods(stream,
6537                 _access_flags.is_interface(),
6538                 _access_flags.is_value_type(),
6539                 &promoted_flags,
6540                 &_has_final_method,
6541                 &_declares_nonstatic_concrete_methods,
6542                 CHECK);
6543 
6544   assert(_methods != NULL, "invariant");
6545 
6546   // promote flags from parse_methods() to the klass' flags
6547   _access_flags.add_promoted_flags(promoted_flags.as_int());
6548 
6549   if (_declares_nonstatic_concrete_methods) {
6550     _has_nonstatic_concrete_methods = true;
6551   }
6552 
6553   // Additional attributes/annotations
6554   _parsed_annotations = new ClassAnnotationCollector();
6555   parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK);
6556 
6557   assert(_inner_classes != NULL, "invariant");
6558 
6559   // Finalize the Annotations metadata object,
6560   // now that all annotation arrays have been created.
6561   create_combined_annotations(CHECK);
6562 
6563   // Make sure this is the end of class file stream
6564   guarantee_property(stream->at_eos(),
6565                      "Extra bytes at the end of class file %s",
6566                      CHECK);
6567 
6568   // all bytes in stream read and parsed
6569 }
6570 
6571 void ClassFileParser::post_process_parsed_stream(const ClassFileStream* const stream,
6572                                                  ConstantPool* cp,
6573                                                  TRAPS) {
6574   assert(stream != NULL, "invariant");
6575   assert(stream->at_eos(), "invariant");
6576   assert(cp != NULL, "invariant");
6577   assert(_loader_data != NULL, "invariant");
6578 
6579   if (_class_name == vmSymbols::java_lang_Object()) {
6580     check_property(_local_interfaces == Universe::the_empty_instance_klass_array(),
6581                    "java.lang.Object cannot implement an interface in class file %s",
6582                    CHECK);
6583   }
6584   // We check super class after class file is parsed and format is checked
6585   if (_super_class_index > 0 && NULL ==_super_klass) {
6586     Symbol* const super_class_name = cp->klass_name_at(_super_class_index);
6587     if (_access_flags.is_interface()) {
6588       // Before attempting to resolve the superclass, check for class format
6589       // errors not checked yet.
6590       guarantee_property(super_class_name == vmSymbols::java_lang_Object(),
6591         "Interfaces must have java.lang.Object as superclass in class file %s",
6592         CHECK);
6593     }
6594     Handle loader(THREAD, _loader_data->class_loader());
6595     _super_klass = (const InstanceKlass*)
6596                        SystemDictionary::resolve_super_or_fail(_class_name,
6597                                                                super_class_name,
6598                                                                loader,
6599                                                                _protection_domain,
6600                                                                true,
6601                                                                CHECK);
6602   }
6603 
6604   if (_super_klass != NULL) {
6605     if (_super_klass->has_nonstatic_concrete_methods()) {
6606       _has_nonstatic_concrete_methods = true;
6607     }
6608 
6609     if (_super_klass->is_interface()) {
6610       ResourceMark rm(THREAD);
6611       Exceptions::fthrow(
6612         THREAD_AND_LOCATION,
6613         vmSymbols::java_lang_IncompatibleClassChangeError(),
6614         "class %s has interface %s as super class",
6615         _class_name->as_klass_external_name(),
6616         _super_klass->external_name()
6617       );
6618       return;
6619     }
6620 
6621     // For a value class, only java/lang/Object is an acceptable super class
6622     if (_access_flags.get_flags() & JVM_ACC_VALUE) {
6623       guarantee_property(_super_klass->name() == vmSymbols::java_lang_Object(),
6624         "Value type must have java.lang.Object as superclass in class file %s",
6625         CHECK);
6626     }
6627 
6628     // Make sure super class is not final
6629     if (_super_klass->is_final()) {
6630       THROW_MSG(vmSymbols::java_lang_VerifyError(), "Cannot inherit from final class");
6631     }
6632   }
6633 
6634   // Compute the transitive list of all unique interfaces implemented by this class
6635   _transitive_interfaces =
6636     compute_transitive_interfaces(_super_klass,
6637                                   _local_interfaces,
6638                                   _loader_data,
6639                                   CHECK);
6640 
6641   assert(_transitive_interfaces != NULL, "invariant");
6642 
6643   // sort methods
6644   _method_ordering = sort_methods(_methods);
6645 
6646   _all_mirandas = new GrowableArray<Method*>(20);
6647 
6648   Handle loader(THREAD, _loader_data->class_loader());
6649   klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
6650                                                     &_num_miranda_methods,
6651                                                     _all_mirandas,
6652                                                     _super_klass,
6653                                                     _methods,
6654                                                     _access_flags,
6655                                                     _major_version,
6656                                                     loader,
6657                                                     _class_name,
6658                                                     _local_interfaces,
6659                                                     CHECK);
6660 
6661   // Size of Java itable (in words)
6662   _itable_size = _access_flags.is_interface() ? 0 :
6663     klassItable::compute_itable_size(_transitive_interfaces);
6664 
6665   assert(_fac != NULL, "invariant");
6666   assert(_parsed_annotations != NULL, "invariant");
6667 
6668 
6669   for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
6670     if (fs.is_flattenable() && !fs.access_flags().is_static()) {
6671       // Pre-load value class
6672       Klass* klass = SystemDictionary::resolve_flattenable_field_or_fail(&fs,
6673           Handle(THREAD, _loader_data->class_loader()),
6674           _protection_domain, true, CHECK);
6675       assert(klass != NULL, "Sanity check");
6676       assert(klass->access_flags().is_value_type(), "Value type expected");
6677       _has_flattenable_fields = true;
6678     }
6679   }
6680 
6681   _field_info = new FieldLayoutInfo();
6682   if (UseNewLayout) {
6683     FieldLayoutBuilder lb(this, _field_info);
6684     if (this->is_value_type()) {
6685       lb.compute_inline_class_layout(CHECK);
6686       _alignment = lb.get_alignment();
6687       _first_field_offset = lb.get_first_field_offset();
6688       _exact_size_in_bytes = lb.get_exact_size_in_byte();
6689     } else {
6690       lb.compute_regular_layout(CHECK);
6691     }
6692   } else {
6693     layout_fields(cp, _fac, _parsed_annotations, _field_info, CHECK);
6694   }
6695 
6696   // Compute reference type
6697   _rt = (NULL ==_super_klass) ? REF_NONE : _super_klass->reference_type();
6698 
6699 }
6700 
6701 void ClassFileParser::set_klass(InstanceKlass* klass) {
6702 
6703 #ifdef ASSERT
6704   if (klass != NULL) {
6705     assert(NULL == _klass, "leaking?");
6706   }
6707 #endif
6708 
6709   _klass = klass;
6710 }
6711 
6712 void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) {
6713 
6714 #ifdef ASSERT
6715   if (klass != NULL) {
6716     assert(NULL == _klass_to_deallocate, "leaking?");
6717   }
6718 #endif
6719 
6720   _klass_to_deallocate = klass;
6721 }
6722 
6723 // Caller responsible for ResourceMark
6724 // clone stream with rewound position
6725 const ClassFileStream* ClassFileParser::clone_stream() const {
6726   assert(_stream != NULL, "invariant");
6727 
6728   return _stream->clone();
6729 }
6730 
6731 // ----------------------------------------------------------------------------
6732 // debugging
6733 
6734 #ifdef ASSERT
6735 
6736 // return true if class_name contains no '.' (internal format is '/')
6737 bool ClassFileParser::is_internal_format(Symbol* class_name) {
6738   if (class_name != NULL) {
6739     ResourceMark rm;
6740     char* name = class_name->as_C_string();
6741     return strchr(name, '.') == NULL;
6742   } else {
6743     return true;
6744   }
6745 }
6746 
6747 #endif