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