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