< prev index next >

src/hotspot/share/classfile/classFileParser.cpp

Print this page

   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 "cds/cdsConfig.hpp"
  25 #include "classfile/classFileParser.hpp"
  26 #include "classfile/classFileStream.hpp"
  27 #include "classfile/classLoader.hpp"
  28 #include "classfile/classLoaderData.inline.hpp"
  29 #include "classfile/classLoadInfo.hpp"
  30 #include "classfile/defaultMethods.hpp"
  31 #include "classfile/fieldLayoutBuilder.hpp"
  32 #include "classfile/javaClasses.inline.hpp"
  33 #include "classfile/moduleEntry.hpp"
  34 #include "classfile/packageEntry.hpp"
  35 #include "classfile/symbolTable.hpp"
  36 #include "classfile/systemDictionary.hpp"
  37 #include "classfile/verificationType.hpp"
  38 #include "classfile/verifier.hpp"
  39 #include "classfile/vmClasses.hpp"
  40 #include "classfile/vmSymbols.hpp"
  41 #include "jvm.h"
  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/fieldInfo.hpp"
  52 #include "oops/fieldStreams.inline.hpp"

  53 #include "oops/instanceKlass.inline.hpp"
  54 #include "oops/instanceMirrorKlass.hpp"
  55 #include "oops/klass.inline.hpp"
  56 #include "oops/klassVtable.hpp"
  57 #include "oops/metadata.hpp"
  58 #include "oops/method.inline.hpp"
  59 #include "oops/oop.inline.hpp"
  60 #include "oops/recordComponent.hpp"
  61 #include "oops/symbol.hpp"
  62 #include "prims/jvmtiExport.hpp"
  63 #include "prims/jvmtiThreadState.hpp"
  64 #include "runtime/arguments.hpp"
  65 #include "runtime/fieldDescriptor.inline.hpp"
  66 #include "runtime/handles.inline.hpp"
  67 #include "runtime/javaCalls.hpp"
  68 #include "runtime/os.hpp"
  69 #include "runtime/perfData.hpp"
  70 #include "runtime/reflection.hpp"
  71 #include "runtime/safepointVerifiers.hpp"
  72 #include "runtime/signature.hpp"
  73 #include "runtime/timer.hpp"
  74 #include "services/classLoadingService.hpp"
  75 #include "services/threadService.hpp"
  76 #include "utilities/align.hpp"
  77 #include "utilities/bitMap.inline.hpp"
  78 #include "utilities/checkedCast.hpp"
  79 #include "utilities/copy.hpp"
  80 #include "utilities/exceptions.hpp"
  81 #include "utilities/formatBuffer.hpp"
  82 #include "utilities/globalDefinitions.hpp"
  83 #include "utilities/growableArray.hpp"
  84 #include "utilities/hashTable.hpp"
  85 #include "utilities/macros.hpp"
  86 #include "utilities/ostream.hpp"

  87 #include "utilities/utf8.hpp"
  88 #if INCLUDE_CDS
  89 #include "classfile/systemDictionaryShared.hpp"
  90 #endif
  91 #if INCLUDE_JFR
  92 #include "jfr/support/jfrTraceIdExtension.hpp"
  93 #endif
  94 
  95 // We generally try to create the oops directly when parsing, rather than
  96 // allocating temporary data structures and copying the bytes twice. A
  97 // temporary area is only needed when parsing utf8 entries in the constant
  98 // pool and when parsing line number tables.
  99 
 100 // We add assert in debug mode when class format is not checked.
 101 
 102 #define JAVA_CLASSFILE_MAGIC              0xCAFEBABE
 103 #define JAVA_MIN_SUPPORTED_VERSION        45
 104 #define JAVA_PREVIEW_MINOR_VERSION        65535
 105 
 106 // Used for two backward compatibility reasons:

 139 #define JAVA_17_VERSION                   61
 140 
 141 #define JAVA_18_VERSION                   62
 142 
 143 #define JAVA_19_VERSION                   63
 144 
 145 #define JAVA_20_VERSION                   64
 146 
 147 #define JAVA_21_VERSION                   65
 148 
 149 #define JAVA_22_VERSION                   66
 150 
 151 #define JAVA_23_VERSION                   67
 152 
 153 #define JAVA_24_VERSION                   68
 154 
 155 #define JAVA_25_VERSION                   69
 156 
 157 #define JAVA_26_VERSION                   70
 158 


 159 void ClassFileParser::set_class_bad_constant_seen(short bad_constant) {
 160   assert((bad_constant == JVM_CONSTANT_Module ||
 161           bad_constant == JVM_CONSTANT_Package) && _major_version >= JAVA_9_VERSION,
 162          "Unexpected bad constant pool entry");
 163   if (_bad_constant_seen == 0) _bad_constant_seen = bad_constant;
 164 }
 165 
 166 void ClassFileParser::parse_constant_pool_entries(const ClassFileStream* const stream,
 167                                                   ConstantPool* cp,
 168                                                   const int length,
 169                                                   TRAPS) {
 170   assert(stream != nullptr, "invariant");
 171   assert(cp != nullptr, "invariant");
 172 
 173   // Use a local copy of ClassFileStream. It helps the C++ compiler to optimize
 174   // this function (_current can be allocated in a register, with scalar
 175   // replacement of aggregates). The _current pointer is copied back to
 176   // stream() when this function returns. DON'T call another method within
 177   // this method that uses stream().
 178   const ClassFileStream cfs1 = *stream;
 179   const ClassFileStream* const cfs = &cfs1;
 180 
 181   DEBUG_ONLY(const u1* const old_current = stream->current();)
 182 
 183   // Used for batching symbol allocations.
 184   const char* names[SymbolTable::symbol_alloc_batch_size];
 185   int lengths[SymbolTable::symbol_alloc_batch_size];
 186   int indices[SymbolTable::symbol_alloc_batch_size];
 187   unsigned int hashValues[SymbolTable::symbol_alloc_batch_size];
 188   int names_count = 0;
 189 
 190   // parsing  Index 0 is unused
 191   for (int index = 1; index < length; index++) {
 192     // Each of the following case guarantees one more byte in the stream
 193     // for the following tag or the access_flags following constant pool,
 194     // so we don't need bounds-check for reading tag.
 195     const u1 tag = cfs->get_u1_fast();
 196     switch (tag) {
 197       case JVM_CONSTANT_Class : {
 198         cfs->guarantee_more(3, CHECK);  // name_index, tag/access_flags
 199         const u2 name_index = cfs->get_u2_fast();
 200         cp->klass_index_at_put(index, name_index);
 201         break;
 202       }
 203       case JVM_CONSTANT_Fieldref: {
 204         cfs->guarantee_more(5, CHECK);  // class_index, name_and_type_index, tag/access_flags
 205         const u2 class_index = cfs->get_u2_fast();
 206         const u2 name_and_type_index = cfs->get_u2_fast();
 207         cp->field_at_put(index, class_index, name_and_type_index);
 208         break;
 209       }
 210       case JVM_CONSTANT_Methodref: {
 211         cfs->guarantee_more(5, CHECK);  // class_index, name_and_type_index, tag/access_flags
 212         const u2 class_index = cfs->get_u2_fast();
 213         const u2 name_and_type_index = cfs->get_u2_fast();
 214         cp->method_at_put(index, class_index, name_and_type_index);
 215         break;
 216       }
 217       case JVM_CONSTANT_InterfaceMethodref: {

 481         guarantee_property(valid_symbol_at(name_ref_index),
 482           "Invalid constant pool index %u in class file %s",
 483           name_ref_index, CHECK);
 484         guarantee_property(valid_symbol_at(signature_ref_index),
 485           "Invalid constant pool index %u in class file %s",
 486           signature_ref_index, CHECK);
 487         break;
 488       }
 489       case JVM_CONSTANT_Utf8:
 490         break;
 491       case JVM_CONSTANT_UnresolvedClass:         // fall-through
 492       case JVM_CONSTANT_UnresolvedClassInError: {
 493         ShouldNotReachHere();     // Only JVM_CONSTANT_ClassIndex should be present
 494         break;
 495       }
 496       case JVM_CONSTANT_ClassIndex: {
 497         const int class_index = cp->klass_index_at(index);
 498         guarantee_property(valid_symbol_at(class_index),
 499           "Invalid constant pool index %u in class file %s",
 500           class_index, CHECK);



 501         cp->unresolved_klass_at_put(index, class_index, num_klasses++);
 502         break;
 503       }
 504       case JVM_CONSTANT_StringIndex: {
 505         const int string_index = cp->string_index_at(index);
 506         guarantee_property(valid_symbol_at(string_index),
 507           "Invalid constant pool index %u in class file %s",
 508           string_index, CHECK);
 509         Symbol* const sym = cp->symbol_at(string_index);
 510         cp->unresolved_string_at_put(index, sym);
 511         break;
 512       }
 513       case JVM_CONSTANT_MethodHandle: {
 514         const int ref_index = cp->method_handle_index_at(index);
 515         guarantee_property(valid_cp_range(ref_index, length),
 516           "Invalid constant pool index %u in class file %s",
 517           ref_index, CHECK);
 518         const constantTag tag = cp->tag_at(ref_index);
 519         const int ref_kind = cp->method_handle_ref_kind_at(index);
 520 

 690             }
 691           }
 692         } else {
 693           if (_need_verify) {
 694             // Method name and signature are individually verified above, when iterating
 695             // NameAndType_info.  Need to check here that signature is non-zero length and
 696             // the right type.
 697             if (!Signature::is_method(signature)) {
 698               throwIllegalSignature("Method", name, signature, CHECK);
 699             }
 700           }
 701           // If a class method name begins with '<', it must be "<init>" and have void signature.
 702           const unsigned int name_len = name->utf8_length();
 703           if (tag == JVM_CONSTANT_Methodref && name_len != 0 &&
 704               name->char_at(0) == JVM_SIGNATURE_SPECIAL) {
 705             if (name != vmSymbols::object_initializer_name()) {
 706               classfile_parse_error(
 707                 "Bad method name at constant pool index %u in class file %s",
 708                 name_ref_index, THREAD);
 709               return;
 710             } else if (!Signature::is_void_method(signature)) { // must have void signature.
 711               throwIllegalSignature("Method", name, signature, CHECK);
 712             }
 713           }
 714         }
 715         break;
 716       }
 717       case JVM_CONSTANT_MethodHandle: {
 718         const int ref_index = cp->method_handle_index_at(index);
 719         const int ref_kind = cp->method_handle_ref_kind_at(index);
 720         switch (ref_kind) {
 721           case JVM_REF_invokeVirtual:
 722           case JVM_REF_invokeStatic:
 723           case JVM_REF_invokeSpecial:
 724           case JVM_REF_newInvokeSpecial: {
 725             const int name_and_type_ref_index =
 726               cp->uncached_name_and_type_ref_index_at(ref_index);
 727             const int name_ref_index =
 728               cp->name_ref_index_at(name_and_type_ref_index);
 729             const Symbol* const name = cp->symbol_at(name_ref_index);
 730             if (ref_kind == JVM_REF_newInvokeSpecial) {
 731               if (name != vmSymbols::object_initializer_name()) {

 732                 classfile_parse_error(
 733                   "Bad constructor name at constant pool index %u in class file %s",
 734                     name_ref_index, THREAD);
 735                 return;
 736               }
 737             } else {
 738               if (name == vmSymbols::object_initializer_name()) {








 739                 classfile_parse_error(
 740                   "Bad method name at constant pool index %u in class file %s",
 741                   name_ref_index, THREAD);
 742                 return;
 743               }
 744             }
 745             break;
 746           }
 747           // Other ref_kinds are already fully checked in previous pass.
 748         } // switch(ref_kind)
 749         break;
 750       }
 751       case JVM_CONSTANT_MethodType: {
 752         const Symbol* const no_name = vmSymbols::type_name(); // place holder
 753         const Symbol* const signature = cp->method_type_signature_at(index);
 754         verify_legal_method_signature(no_name, signature, CHECK);
 755         break;
 756       }
 757       case JVM_CONSTANT_Utf8: {
 758         assert(cp->symbol_at(index)->refcount() != 0, "count corrupted");

 770 
 771   NameSigHash(Symbol* name, Symbol* sig) :
 772     _name(name),
 773     _sig(sig) {}
 774 
 775   static unsigned int hash(NameSigHash const& namesig) {
 776     return namesig._name->identity_hash() ^ namesig._sig->identity_hash();
 777   }
 778 
 779   static bool equals(NameSigHash const& e0, NameSigHash const& e1) {
 780     return (e0._name == e1._name) &&
 781           (e0._sig  == e1._sig);
 782   }
 783 };
 784 
 785 using NameSigHashtable = HashTable<NameSigHash, int,
 786                                            NameSigHash::HASH_ROW_SIZE,
 787                                            AnyObj::RESOURCE_AREA, mtInternal,
 788                                            &NameSigHash::hash, &NameSigHash::equals>;
 789 
 790 // Side-effects: populates the _local_interfaces field
 791 void ClassFileParser::parse_interfaces(const ClassFileStream* const stream,
 792                                        const int itfs_len,
 793                                        ConstantPool* const cp,









 794                                        bool* const has_nonstatic_concrete_methods,






 795                                        TRAPS) {
 796   assert(stream != nullptr, "invariant");
 797   assert(cp != nullptr, "invariant");
 798   assert(has_nonstatic_concrete_methods != nullptr, "invariant");
 799 
 800   if (itfs_len == 0) {
 801     _local_interfaces = Universe::the_empty_instance_klass_array();

 802   } else {
 803     assert(itfs_len > 0, "only called for len>0");
 804     _local_interfaces = MetadataFactory::new_array<InstanceKlass*>(_loader_data, itfs_len, nullptr, CHECK);
 805 
 806     int index;
 807     for (index = 0; index < itfs_len; index++) {
 808       const u2 interface_index = stream->get_u2(CHECK);
 809       Klass* interf;
 810       guarantee_property(
 811         valid_klass_reference_at(interface_index),
 812         "Interface name has bad constant pool index %u in class file %s",
 813         interface_index, CHECK);
 814       if (cp->tag_at(interface_index).is_klass()) {
 815         interf = cp->resolved_klass_at(interface_index);
 816       } else {
 817         Symbol* const unresolved_klass  = cp->klass_name_at(interface_index);
 818 
 819         // Don't need to check legal name because it's checked when parsing constant pool.
 820         // But need to make sure it's not an array type.
 821         guarantee_property(unresolved_klass->char_at(0) != JVM_SIGNATURE_ARRAY,
 822                            "Bad interface name in class file %s", CHECK);
 823 
 824         // Call resolve on the interface class name with class circularity checking
 825         interf = SystemDictionary::resolve_super_or_fail(_class_name,
 826                                                          unresolved_klass,
 827                                                          Handle(THREAD, _loader_data->class_loader()),
 828                                                          false, CHECK);
 829       }
 830 
 831       if (!interf->is_interface()) {
 832         THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
 833                   err_msg("class %s can not implement %s, because it is not an interface (%s)",
 834                           _class_name->as_klass_external_name(),
 835                           interf->external_name(),
 836                           interf->class_in_module_of_loader()));
 837       }
 838 
 839       if (InstanceKlass::cast(interf)->has_nonstatic_concrete_methods()) {
 840         *has_nonstatic_concrete_methods = true;
 841       }
 842       _local_interfaces->at_put(index, InstanceKlass::cast(interf));
 843     }
 844 
 845     if (!_need_verify || itfs_len <= 1) {
 846       return;
 847     }
 848 
 849     // Check if there's any duplicates in interfaces
 850     ResourceMark rm(THREAD);
 851     // Set containing interface names
 852     HashTable<Symbol*, int>* interface_names = new HashTable<Symbol*, int>();
 853     for (index = 0; index < itfs_len; index++) {
 854       const InstanceKlass* const k = _local_interfaces->at(index);
 855       Symbol* interface_name = k->name();
 856       // If no duplicates, add (name, nullptr) in hashtable interface_names.
 857       if (!interface_names->put(interface_name, 0)) {
 858         classfile_parse_error("Duplicate interface name \"%s\" in class file %s",
 859                                interface_name->as_C_string(), THREAD);
 860         return;
 861       }
 862     }
 863   }
 864 }
 865 
 866 void ClassFileParser::verify_constantvalue(const ConstantPool* const cp,
 867                                            int constantvalue_index,
 868                                            int signature_index,
 869                                            TRAPS) const {
 870   // Make sure the constant pool entry is of a type appropriate to this field
 871   guarantee_property(
 872     (constantvalue_index > 0 &&
 873       constantvalue_index < cp->length()),
 874     "Bad initial value index %u in ConstantValue attribute in class file %s",
 875     constantvalue_index, CHECK);

 922 class AnnotationCollector : public ResourceObj{
 923 public:
 924   enum Location { _in_field, _in_method, _in_class };
 925   enum ID {
 926     _unknown = 0,
 927     _method_CallerSensitive,
 928     _method_ForceInline,
 929     _method_DontInline,
 930     _method_ChangesCurrentThread,
 931     _method_JvmtiHideEvents,
 932     _method_JvmtiMountTransition,
 933     _method_InjectedProfile,
 934     _method_LambdaForm_Compiled,
 935     _method_Hidden,
 936     _method_Scoped,
 937     _method_IntrinsicCandidate,
 938     _jdk_internal_vm_annotation_Contended,
 939     _field_Stable,
 940     _jdk_internal_vm_annotation_ReservedStackAccess,
 941     _jdk_internal_ValueBased,


 942     _java_lang_Deprecated,
 943     _java_lang_Deprecated_for_removal,
 944     _jdk_internal_vm_annotation_AOTSafeClassInitializer,
 945     _method_AOTRuntimeSetup,
 946     _annotation_LIMIT
 947   };
 948   const Location _location;
 949   int _annotations_present;
 950   u2 _contended_group;
 951 
 952   AnnotationCollector(Location location)
 953     : _location(location), _annotations_present(0), _contended_group(0)
 954   {
 955     assert((int)_annotation_LIMIT <= (int)sizeof(_annotations_present) * BitsPerByte, "");
 956   }
 957   // If this annotation name has an ID, report it (or _none).
 958   ID annotation_index(const ClassLoaderData* loader_data, const Symbol* name, bool can_access_vm_annotations);
 959   // Set the annotation name:
 960   void set_annotation(ID id) {
 961     assert((int)id >= 0 && (int)id < (int)_annotation_LIMIT, "oob");

1348   }
1349 
1350   *constantvalue_index_addr = constantvalue_index;
1351   *is_synthetic_addr = is_synthetic;
1352   *generic_signature_index_addr = generic_signature_index;
1353   AnnotationArray* a = allocate_annotations(runtime_visible_annotations,
1354                                             runtime_visible_annotations_length,
1355                                             CHECK);
1356   parsed_annotations->set_field_annotations(a);
1357   a = allocate_annotations(runtime_visible_type_annotations,
1358                            runtime_visible_type_annotations_length,
1359                            CHECK);
1360   parsed_annotations->set_field_type_annotations(a);
1361   return;
1362 }
1363 
1364 
1365 // Side-effects: populates the _fields, _fields_annotations,
1366 // _fields_type_annotations fields
1367 void ClassFileParser::parse_fields(const ClassFileStream* const cfs,
1368                                    bool is_interface,
1369                                    ConstantPool* cp,
1370                                    const int cp_size,
1371                                    u2* const java_fields_count_ptr,
1372                                    TRAPS) {
1373 
1374   assert(cfs != nullptr, "invariant");
1375   assert(cp != nullptr, "invariant");
1376   assert(java_fields_count_ptr != nullptr, "invariant");
1377 
1378   assert(nullptr == _fields_annotations, "invariant");
1379   assert(nullptr == _fields_type_annotations, "invariant");
1380 


1381   cfs->guarantee_more(2, CHECK);  // length
1382   const u2 length = cfs->get_u2_fast();
1383   *java_fields_count_ptr = length;
1384 
1385   int num_injected = 0;
1386   const InjectedField* const injected = JavaClasses::get_injected(_class_name,
1387                                                                   &num_injected);
1388   const int total_fields = length + num_injected;





1389 
1390   // Allocate a temporary resource array to collect field data.
1391   // After parsing all fields, data are stored in a UNSIGNED5 compressed stream.
1392   _temp_field_info = new GrowableArray<FieldInfo>(total_fields);
1393 

1394   ResourceMark rm(THREAD);
1395   for (int n = 0; n < length; n++) {
1396     // access_flags, name_index, descriptor_index, attributes_count
1397     cfs->guarantee_more(8, CHECK);
1398 







1399     AccessFlags access_flags;
1400     const jint flags = cfs->get_u2_fast() & JVM_RECOGNIZED_FIELD_MODIFIERS;
1401     verify_legal_field_modifiers(flags, is_interface, CHECK);
1402     access_flags.set_flags(flags);
1403     FieldInfo::FieldFlags fieldFlags(0);
1404 
1405     const u2 name_index = cfs->get_u2_fast();
1406     guarantee_property(valid_symbol_at(name_index),
1407       "Invalid constant pool index %u for field name in class file %s",
1408       name_index, CHECK);
1409     const Symbol* const name = cp->symbol_at(name_index);
1410     verify_legal_field_name(name, CHECK);
1411 
1412     const u2 signature_index = cfs->get_u2_fast();
1413     guarantee_property(valid_symbol_at(signature_index),
1414       "Invalid constant pool index %u for field signature in class file %s",
1415       signature_index, CHECK);
1416     const Symbol* const sig = cp->symbol_at(signature_index);
1417     verify_legal_field_signature(name, sig, CHECK);

1418 
1419     u2 constantvalue_index = 0;
1420     bool is_synthetic = false;
1421     u2 generic_signature_index = 0;
1422     const bool is_static = access_flags.is_static();
1423     FieldAnnotationCollector parsed_annotations(_loader_data);
1424 


1425     const u2 attributes_count = cfs->get_u2_fast();
1426     if (attributes_count > 0) {
1427       parse_field_attributes(cfs,
1428                              attributes_count,
1429                              is_static,
1430                              signature_index,
1431                              &constantvalue_index,
1432                              &is_synthetic,
1433                              &generic_signature_index,
1434                              &parsed_annotations,
1435                              CHECK);
1436 
1437       if (parsed_annotations.field_annotations() != nullptr) {
1438         if (_fields_annotations == nullptr) {
1439           _fields_annotations = MetadataFactory::new_array<AnnotationArray*>(
1440                                              _loader_data, length, nullptr,
1441                                              CHECK);
1442         }
1443         _fields_annotations->at_put(n, parsed_annotations.field_annotations());


















1444         parsed_annotations.set_field_annotations(nullptr);
1445       }
1446       if (parsed_annotations.field_type_annotations() != nullptr) {
1447         if (_fields_type_annotations == nullptr) {
1448           _fields_type_annotations =
1449             MetadataFactory::new_array<AnnotationArray*>(_loader_data,
1450                                                          length,
1451                                                          nullptr,
1452                                                          CHECK);
1453         }
1454         _fields_type_annotations->at_put(n, parsed_annotations.field_type_annotations());
1455         parsed_annotations.set_field_type_annotations(nullptr);
1456       }
1457 
1458       if (is_synthetic) {
1459         access_flags.set_is_synthetic();
1460       }
1461       if (generic_signature_index != 0) {
1462         fieldFlags.update_generic(true);
1463       }
1464     }
1465 




1466     const BasicType type = cp->basic_type_for_signature_at(signature_index);
1467 
1468     // Update number of static oop fields.
1469     if (is_static && is_reference_type(type)) {
1470       _static_oop_count++;
1471     }
1472 
1473     FieldInfo fi(access_flags, name_index, signature_index, constantvalue_index, fieldFlags);
1474     fi.set_index(n);
1475     if (fieldFlags.is_generic()) {
1476       fi.set_generic_signature_index(generic_signature_index);
1477     }
1478     parsed_annotations.apply_to(&fi);
1479     if (fi.field_flags().is_contended()) {
1480       _has_contended_fields = true;
1481     }



1482     _temp_field_info->append(fi);
1483   }
1484   assert(_temp_field_info->length() == length, "Must be");
1485 
1486   int index = length;
1487   if (num_injected != 0) {
1488     for (int n = 0; n < num_injected; n++) {
1489       // Check for duplicates
1490       if (injected[n].may_be_java) {
1491         const Symbol* const name      = injected[n].name();
1492         const Symbol* const signature = injected[n].signature();
1493         bool duplicate = false;
1494         for (int i = 0; i < length; i++) {
1495           const FieldInfo* const f = _temp_field_info->adr_at(i);
1496           if (name      == cp->symbol_at(f->name_index()) &&
1497               signature == cp->symbol_at(f->signature_index())) {
1498             // Symbol is desclared in Java so skip this one
1499             duplicate = true;
1500             break;
1501           }
1502         }
1503         if (duplicate) {
1504           // These will be removed from the field array at the end
1505           continue;
1506         }
1507       }
1508 
1509       // Injected field
1510       FieldInfo::FieldFlags fflags(0);
1511       fflags.update_injected(true);
1512       AccessFlags aflags;
1513       FieldInfo fi(aflags, (u2)(injected[n].name_index), (u2)(injected[n].signature_index), 0, fflags);
1514       fi.set_index(index);
1515       _temp_field_info->append(fi);
1516       index++;
1517     }
1518   }
1519 
1520   assert(_temp_field_info->length() == index, "Must be");
































1521 
1522   if (_need_verify && length > 1) {
1523     // Check duplicated fields
1524     ResourceMark rm(THREAD);
1525     // Set containing name-signature pairs
1526     NameSigHashtable* names_and_sigs = new NameSigHashtable();
1527     for (int i = 0; i < _temp_field_info->length(); i++) {
1528       NameSigHash name_and_sig(_temp_field_info->adr_at(i)->name(_cp),
1529                                _temp_field_info->adr_at(i)->signature(_cp));
1530       // If no duplicates, add name/signature in hashtable names_and_sigs.
1531       if(!names_and_sigs->put(name_and_sig, 0)) {
1532         classfile_parse_error("Duplicate field name \"%s\" with signature \"%s\" in class file %s",
1533                                name_and_sig._name->as_C_string(), name_and_sig._sig->as_klass_external_name(), THREAD);
1534         return;
1535       }
1536     }
1537   }
1538 }
1539 
1540 

1880     }
1881     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Contended_signature): {
1882       if (_location != _in_field && _location != _in_class) {
1883         break;  // only allow for fields and classes
1884       }
1885       if (!EnableContended || (RestrictContended && !privileged)) {
1886         break;  // honor privileges
1887       }
1888       return _jdk_internal_vm_annotation_Contended;
1889     }
1890     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ReservedStackAccess_signature): {
1891       if (_location != _in_method)  break;  // only allow for methods
1892       if (RestrictReservedStack && !privileged) break; // honor privileges
1893       return _jdk_internal_vm_annotation_ReservedStackAccess;
1894     }
1895     case VM_SYMBOL_ENUM_NAME(jdk_internal_ValueBased_signature): {
1896       if (_location != _in_class)   break;  // only allow for classes
1897       if (!privileged)              break;  // only allow in privileged code
1898       return _jdk_internal_ValueBased;
1899     }








1900     case VM_SYMBOL_ENUM_NAME(java_lang_Deprecated): {
1901       return _java_lang_Deprecated;
1902     }
1903     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_AOTSafeClassInitializer_signature): {
1904       if (_location != _in_class)   break;  // only allow for classes
1905       if (!privileged)              break;  // only allow in privileged code
1906       return _jdk_internal_vm_annotation_AOTSafeClassInitializer;
1907     }
1908     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_AOTRuntimeSetup_signature): {
1909       if (_location != _in_method)  break;  // only allow for methods
1910       if (!privileged)              break;  // only allow in privileged code
1911       return _method_AOTRuntimeSetup;
1912     }
1913     default: {
1914       break;
1915     }
1916   }
1917   return AnnotationCollector::_unknown;
1918 }
1919 

2116   }
2117 
2118   if (runtime_visible_type_annotations_length > 0) {
2119     a = allocate_annotations(runtime_visible_type_annotations,
2120                              runtime_visible_type_annotations_length,
2121                              CHECK);
2122     cm->set_type_annotations(a);
2123   }
2124 }
2125 
2126 
2127 // Note: the parse_method below is big and clunky because all parsing of the code and exceptions
2128 // attribute is inlined. This is cumbersome to avoid since we inline most of the parts in the
2129 // Method* to save footprint, so we only know the size of the resulting Method* when the
2130 // entire method attribute is parsed.
2131 //
2132 // The has_localvariable_table parameter is used to pass up the value to InstanceKlass.
2133 
2134 Method* ClassFileParser::parse_method(const ClassFileStream* const cfs,
2135                                       bool is_interface,


2136                                       const ConstantPool* cp,
2137                                       bool* const has_localvariable_table,
2138                                       TRAPS) {
2139   assert(cfs != nullptr, "invariant");
2140   assert(cp != nullptr, "invariant");
2141   assert(has_localvariable_table != nullptr, "invariant");
2142 
2143   ResourceMark rm(THREAD);
2144   // Parse fixed parts:
2145   // access_flags, name_index, descriptor_index, attributes_count
2146   cfs->guarantee_more(8, CHECK_NULL);
2147 
2148   u2 flags = cfs->get_u2_fast();
2149   const u2 name_index = cfs->get_u2_fast();
2150   const int cp_size = cp->length();
2151   guarantee_property(
2152     valid_symbol_at(name_index),
2153     "Illegal constant pool index %u for method name in class file %s",
2154     name_index, CHECK_NULL);
2155   const Symbol* const name = cp->symbol_at(name_index);

2157 
2158   const u2 signature_index = cfs->get_u2_fast();
2159   guarantee_property(
2160     valid_symbol_at(signature_index),
2161     "Illegal constant pool index %u for method signature in class file %s",
2162     signature_index, CHECK_NULL);
2163   const Symbol* const signature = cp->symbol_at(signature_index);
2164 
2165   if (name == vmSymbols::class_initializer_name()) {
2166     // We ignore the other access flags for a valid class initializer.
2167     // (JVM Spec 2nd ed., chapter 4.6)
2168     if (_major_version < 51) { // backward compatibility
2169       flags = JVM_ACC_STATIC;
2170     } else if ((flags & JVM_ACC_STATIC) == JVM_ACC_STATIC) {
2171       flags &= JVM_ACC_STATIC | (_major_version <= JAVA_16_VERSION ? JVM_ACC_STRICT : 0);
2172     } else {
2173       classfile_parse_error("Method <clinit> is not static in class file %s", THREAD);
2174       return nullptr;
2175     }
2176   } else {
2177     verify_legal_method_modifiers(flags, is_interface, name, CHECK_NULL);
2178   }
2179 
2180   if (name == vmSymbols::object_initializer_name() && is_interface) {
2181     classfile_parse_error("Interface cannot have a method named <init>, class file %s", THREAD);
2182     return nullptr;
2183   }
2184 









2185   int args_size = -1;  // only used when _need_verify is true
2186   if (_need_verify) {
2187     verify_legal_name_with_signature(name, signature, CHECK_NULL);
2188     args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) +
2189                  verify_legal_method_signature(name, signature, CHECK_NULL);
2190     if (args_size > MAX_ARGS_SIZE) {
2191       classfile_parse_error("Too many arguments in method signature in class file %s", THREAD);
2192       return nullptr;
2193     }
2194   }
2195 
2196   AccessFlags access_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS);
2197 
2198   // Default values for code and exceptions attribute elements
2199   u2 max_stack = 0;
2200   u2 max_locals = 0;
2201   u4 code_length = 0;
2202   const u1* code_start = nullptr;
2203   u2 exception_table_length = 0;
2204   const unsafe_u2* exception_table_start = nullptr; // (potentially unaligned) pointer to array of u2 elements

2699                           CHECK_NULL);
2700 
2701   if (InstanceKlass::is_finalization_enabled() &&
2702       name == vmSymbols::finalize_method_name() &&
2703       signature == vmSymbols::void_method_signature()) {
2704     if (m->is_empty_method()) {
2705       _has_empty_finalizer = true;
2706     } else {
2707       _has_finalizer = true;
2708     }
2709   }
2710 
2711   NOT_PRODUCT(m->verify());
2712   return m;
2713 }
2714 
2715 
2716 // Side-effects: populates the _methods field in the parser
2717 void ClassFileParser::parse_methods(const ClassFileStream* const cfs,
2718                                     bool is_interface,


2719                                     bool* const has_localvariable_table,
2720                                     bool* has_final_method,
2721                                     bool* declares_nonstatic_concrete_methods,
2722                                     TRAPS) {
2723   assert(cfs != nullptr, "invariant");
2724   assert(has_localvariable_table != nullptr, "invariant");
2725   assert(has_final_method != nullptr, "invariant");
2726   assert(declares_nonstatic_concrete_methods != nullptr, "invariant");
2727 
2728   assert(nullptr == _methods, "invariant");
2729 
2730   cfs->guarantee_more(2, CHECK);  // length
2731   const u2 length = cfs->get_u2_fast();
2732   if (length == 0) {
2733     _methods = Universe::the_empty_method_array();
2734   } else {
2735     _methods = MetadataFactory::new_array<Method*>(_loader_data,
2736                                                    length,
2737                                                    nullptr,
2738                                                    CHECK);
2739 
2740     for (int index = 0; index < length; index++) {
2741       Method* method = parse_method(cfs,
2742                                     is_interface,


2743                                     _cp,
2744                                     has_localvariable_table,
2745                                     CHECK);
2746 
2747       if (method->is_final()) {
2748         *has_final_method = true;
2749       }
2750       // declares_nonstatic_concrete_methods: declares concrete instance methods, any access flags
2751       // used for interface initialization, and default method inheritance analysis
2752       if (is_interface && !(*declares_nonstatic_concrete_methods)
2753         && !method->is_abstract() && !method->is_static()) {
2754         *declares_nonstatic_concrete_methods = true;
2755       }
2756       _methods->at_put(index, method);
2757     }
2758 
2759     if (_need_verify && length > 1) {
2760       // Check duplicated methods
2761       ResourceMark rm(THREAD);
2762       // Set containing name-signature pairs

2988         valid_klass_reference_at(outer_class_info_index),
2989       "outer_class_info_index %u has bad constant type in class file %s",
2990       outer_class_info_index, CHECK_0);
2991 
2992     if (outer_class_info_index != 0) {
2993       const Symbol* const outer_class_name = cp->klass_name_at(outer_class_info_index);
2994       char* bytes = (char*)outer_class_name->bytes();
2995       guarantee_property(bytes[0] != JVM_SIGNATURE_ARRAY,
2996                          "Outer class is an array class in class file %s", CHECK_0);
2997     }
2998     // Inner class name
2999     const u2 inner_name_index = cfs->get_u2_fast();
3000     guarantee_property(
3001       inner_name_index == 0 || valid_symbol_at(inner_name_index),
3002       "inner_name_index %u has bad constant type in class file %s",
3003       inner_name_index, CHECK_0);
3004     if (_need_verify) {
3005       guarantee_property(inner_class_info_index != outer_class_info_index,
3006                          "Class is both outer and inner class in class file %s", CHECK_0);
3007     }

3008     // Access flags
3009     u2 flags;
3010     // JVM_ACC_MODULE is defined in JDK-9 and later.
3011     if (_major_version >= JAVA_9_VERSION) {
3012       flags = cfs->get_u2_fast() & (RECOGNIZED_INNER_CLASS_MODIFIERS | JVM_ACC_MODULE);
3013     } else {
3014       flags = cfs->get_u2_fast() & RECOGNIZED_INNER_CLASS_MODIFIERS;
3015     }

3016     if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
3017       // Set abstract bit for old class files for backward compatibility
3018       flags |= JVM_ACC_ABSTRACT;
3019     }
3020 








3021     Symbol* inner_name_symbol = inner_name_index == 0 ? nullptr : cp->symbol_at(inner_name_index);
3022     verify_legal_class_modifiers(flags, inner_name_symbol, inner_name_index == 0, CHECK_0);
3023     AccessFlags inner_access_flags(flags);
3024 
3025     inner_classes->at_put(index++, inner_class_info_index);
3026     inner_classes->at_put(index++, outer_class_info_index);
3027     inner_classes->at_put(index++, inner_name_index);
3028     inner_classes->at_put(index++, inner_access_flags.as_unsigned_short());
3029   }
3030 
3031   // Check for circular and duplicate entries.
3032   bool has_circularity = false;
3033   if (_need_verify) {
3034     has_circularity = check_inner_classes_circularity(cp, length * 4, CHECK_0);
3035     if (has_circularity) {
3036       // If circularity check failed then ignore InnerClasses attribute.
3037       MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
3038       index = 0;
3039       if (parsed_enclosingmethod_attribute) {
3040         inner_classes = MetadataFactory::new_array<u2>(_loader_data, 2, CHECK_0);

3106   if (length > 0) {
3107     int index = 0;
3108     cfs->guarantee_more(2 * length, CHECK_0);
3109     for (int n = 0; n < length; n++) {
3110       const u2 class_info_index = cfs->get_u2_fast();
3111       guarantee_property(
3112         valid_klass_reference_at(class_info_index),
3113         "Permitted subclass class_info_index %u has bad constant type in class file %s",
3114         class_info_index, CHECK_0);
3115       permitted_subclasses->at_put(index++, class_info_index);
3116     }
3117     assert(index == size, "wrong size");
3118   }
3119 
3120   // Restore buffer's current position.
3121   cfs->set_current(current_mark);
3122 
3123   return length;
3124 }
3125 











































3126 //  Record {
3127 //    u2 attribute_name_index;
3128 //    u4 attribute_length;
3129 //    u2 components_count;
3130 //    component_info components[components_count];
3131 //  }
3132 //  component_info {
3133 //    u2 name_index;
3134 //    u2 descriptor_index
3135 //    u2 attributes_count;
3136 //    attribute_info_attributes[attributes_count];
3137 //  }
3138 u4 ClassFileParser::parse_classfile_record_attribute(const ClassFileStream* const cfs,
3139                                                      const ConstantPool* cp,
3140                                                      const u1* const record_attribute_start,
3141                                                      TRAPS) {
3142   const u1* const current_mark = cfs->current();
3143   int components_count = 0;
3144   unsigned int calculate_attr_size = 0;
3145   if (record_attribute_start != nullptr) {

3371   }
3372   guarantee_property(current_start + attribute_byte_length == cfs->current(),
3373                      "Bad length on BootstrapMethods in class file %s",
3374                      CHECK);
3375 }
3376 
3377 void ClassFileParser::parse_classfile_attributes(const ClassFileStream* const cfs,
3378                                                  ConstantPool* cp,
3379                  ClassFileParser::ClassAnnotationCollector* parsed_annotations,
3380                                                  TRAPS) {
3381   assert(cfs != nullptr, "invariant");
3382   assert(cp != nullptr, "invariant");
3383   assert(parsed_annotations != nullptr, "invariant");
3384 
3385   // Set inner classes attribute to default sentinel
3386   _inner_classes = Universe::the_empty_short_array();
3387   // Set nest members attribute to default sentinel
3388   _nest_members = Universe::the_empty_short_array();
3389   // Set _permitted_subclasses attribute to default sentinel
3390   _permitted_subclasses = Universe::the_empty_short_array();


3391   cfs->guarantee_more(2, CHECK);  // attributes_count
3392   u2 attributes_count = cfs->get_u2_fast();
3393   bool parsed_sourcefile_attribute = false;
3394   bool parsed_innerclasses_attribute = false;
3395   bool parsed_nest_members_attribute = false;
3396   bool parsed_permitted_subclasses_attribute = false;

3397   bool parsed_nest_host_attribute = false;
3398   bool parsed_record_attribute = false;
3399   bool parsed_enclosingmethod_attribute = false;
3400   bool parsed_bootstrap_methods_attribute = false;
3401   const u1* runtime_visible_annotations = nullptr;
3402   int runtime_visible_annotations_length = 0;
3403   const u1* runtime_visible_type_annotations = nullptr;
3404   int runtime_visible_type_annotations_length = 0;
3405   bool runtime_invisible_type_annotations_exists = false;
3406   bool runtime_invisible_annotations_exists = false;
3407   bool parsed_source_debug_ext_annotations_exist = false;
3408   const u1* inner_classes_attribute_start = nullptr;
3409   u4  inner_classes_attribute_length = 0;
3410   u2  enclosing_method_class_index = 0;
3411   u2  enclosing_method_method_index = 0;
3412   const u1* nest_members_attribute_start = nullptr;
3413   u4  nest_members_attribute_length = 0;
3414   const u1* record_attribute_start = nullptr;
3415   u4  record_attribute_length = 0;
3416   const u1* permitted_subclasses_attribute_start = nullptr;
3417   u4  permitted_subclasses_attribute_length = 0;


3418 
3419   // Iterate over attributes
3420   while (attributes_count--) {
3421     cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
3422     const u2 attribute_name_index = cfs->get_u2_fast();
3423     const u4 attribute_length = cfs->get_u4_fast();
3424     guarantee_property(
3425       valid_symbol_at(attribute_name_index),
3426       "Attribute name has bad constant pool index %u in class file %s",
3427       attribute_name_index, CHECK);
3428     const Symbol* const tag = cp->symbol_at(attribute_name_index);
3429     if (tag == vmSymbols::tag_source_file()) {
3430       // Check for SourceFile tag
3431       if (_need_verify) {
3432         guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
3433       }
3434       if (parsed_sourcefile_attribute) {
3435         classfile_parse_error("Multiple SourceFile attributes in class file %s", THREAD);
3436         return;
3437       } else {

3613               return;
3614             }
3615             parsed_record_attribute = true;
3616             record_attribute_start = cfs->current();
3617             record_attribute_length = attribute_length;
3618           } else if (_major_version >= JAVA_17_VERSION) {
3619             if (tag == vmSymbols::tag_permitted_subclasses()) {
3620               if (parsed_permitted_subclasses_attribute) {
3621                 classfile_parse_error("Multiple PermittedSubclasses attributes in class file %s", CHECK);
3622                 return;
3623               }
3624               // Classes marked ACC_FINAL cannot have a PermittedSubclasses attribute.
3625               if (_access_flags.is_final()) {
3626                 classfile_parse_error("PermittedSubclasses attribute in final class file %s", CHECK);
3627                 return;
3628               }
3629               parsed_permitted_subclasses_attribute = true;
3630               permitted_subclasses_attribute_start = cfs->current();
3631               permitted_subclasses_attribute_length = attribute_length;
3632             }









3633           }
3634           // Skip attribute_length for any attribute where major_verson >= JAVA_17_VERSION
3635           cfs->skip_u1(attribute_length, CHECK);
3636         } else {
3637           // Unknown attribute
3638           cfs->skip_u1(attribute_length, CHECK);
3639         }
3640       } else {
3641         // Unknown attribute
3642         cfs->skip_u1(attribute_length, CHECK);
3643       }
3644     } else {
3645       // Unknown attribute
3646       cfs->skip_u1(attribute_length, CHECK);
3647     }
3648   }
3649   _class_annotations = allocate_annotations(runtime_visible_annotations,
3650                                             runtime_visible_annotations_length,
3651                                             CHECK);
3652   _class_type_annotations = allocate_annotations(runtime_visible_type_annotations,

3689                             CHECK);
3690     if (_need_verify) {
3691       guarantee_property(record_attribute_length == calculated_attr_length,
3692                          "Record attribute has wrong length in class file %s",
3693                          CHECK);
3694     }
3695   }
3696 
3697   if (parsed_permitted_subclasses_attribute) {
3698     const u2 num_subclasses = parse_classfile_permitted_subclasses_attribute(
3699                             cfs,
3700                             permitted_subclasses_attribute_start,
3701                             CHECK);
3702     if (_need_verify) {
3703       guarantee_property(
3704         permitted_subclasses_attribute_length == sizeof(num_subclasses) + sizeof(u2) * num_subclasses,
3705         "Wrong PermittedSubclasses attribute length in class file %s", CHECK);
3706     }
3707   }
3708 












3709   if (_max_bootstrap_specifier_index >= 0) {
3710     guarantee_property(parsed_bootstrap_methods_attribute,
3711                        "Missing BootstrapMethods attribute in class file %s", CHECK);
3712   }
3713 }
3714 
3715 void ClassFileParser::apply_parsed_class_attributes(InstanceKlass* k) {
3716   assert(k != nullptr, "invariant");
3717 
3718   if (_synthetic_flag)
3719     k->set_is_synthetic();
3720   if (_sourcefile_index != 0) {
3721     k->set_source_file_name_index(_sourcefile_index);
3722   }
3723   if (_generic_signature_index != 0) {
3724     k->set_generic_signature_index(_generic_signature_index);
3725   }
3726   if (_sde_buffer != nullptr) {
3727     k->set_source_debug_extension(_sde_buffer, _sde_length);
3728   }

3755     _class_type_annotations  = nullptr;
3756     _fields_annotations      = nullptr;
3757     _fields_type_annotations = nullptr;
3758 }
3759 
3760 // Transfer ownership of metadata allocated to the InstanceKlass.
3761 void ClassFileParser::apply_parsed_class_metadata(
3762                                             InstanceKlass* this_klass,
3763                                             int java_fields_count) {
3764   assert(this_klass != nullptr, "invariant");
3765 
3766   _cp->set_pool_holder(this_klass);
3767   this_klass->set_constants(_cp);
3768   this_klass->set_fieldinfo_stream(_fieldinfo_stream);
3769   this_klass->set_fieldinfo_search_table(_fieldinfo_search_table);
3770   this_klass->set_fields_status(_fields_status);
3771   this_klass->set_methods(_methods);
3772   this_klass->set_inner_classes(_inner_classes);
3773   this_klass->set_nest_members(_nest_members);
3774   this_klass->set_nest_host_index(_nest_host);

3775   this_klass->set_annotations(_combined_annotations);
3776   this_klass->set_permitted_subclasses(_permitted_subclasses);
3777   this_klass->set_record_components(_record_components);

3778 
3779   DEBUG_ONLY(FieldInfoStream::validate_search_table(_cp, _fieldinfo_stream, _fieldinfo_search_table));
3780 
3781   // Delay the setting of _local_interfaces and _transitive_interfaces until after
3782   // initialize_supers() in fill_instance_klass(). It is because the _local_interfaces could
3783   // be shared with _transitive_interfaces and _transitive_interfaces may be shared with
3784   // its _super. If an OOM occurs while loading the current klass, its _super field
3785   // may not have been set. When GC tries to free the klass, the _transitive_interfaces
3786   // may be deallocated mistakenly in InstanceKlass::deallocate_interfaces(). Subsequent
3787   // dereferences to the deallocated _transitive_interfaces will result in a crash.
3788 
3789   // Clear out these fields so they don't get deallocated by the destructor
3790   clear_class_metadata();
3791 }
3792 
3793 AnnotationArray* ClassFileParser::allocate_annotations(const u1* const anno,
3794                                                        int anno_length,
3795                                                        TRAPS) {
3796   AnnotationArray* annotations = nullptr;
3797   if (anno != nullptr) {
3798     annotations = MetadataFactory::new_array<u1>(_loader_data,
3799                                                  anno_length,
3800                                                  CHECK_(annotations));
3801     for (int i = 0; i < anno_length; i++) {
3802       annotations->at_put(i, anno[i]);
3803     }
3804   }
3805   return annotations;
3806 }
3807 
3808 void ClassFileParser::check_super_class(ConstantPool* const cp,
3809                                         const int super_class_index,
3810                                         const bool need_verify,
3811                                         TRAPS) {
3812   assert(cp != nullptr, "invariant");
3813 
3814   if (super_class_index == 0) {
3815     guarantee_property(_class_name == vmSymbols::java_lang_Object(),
3816                        "Invalid superclass index %u in class file %s",
3817                        super_class_index,
3818                        CHECK);
3819   } else {
3820     guarantee_property(valid_klass_reference_at(super_class_index),
3821                        "Invalid superclass index %u in class file %s",
3822                        super_class_index,
3823                        CHECK);
3824 
3825     // The class name should be legal because it is checked when parsing constant pool.
3826     // However, make sure it is not an array type.
3827     if (need_verify) {
3828       guarantee_property(cp->klass_name_at(super_class_index)->char_at(0) != JVM_SIGNATURE_ARRAY,
3829                         "Bad superclass name in class file %s", CHECK);
3830     }
3831   }
3832 }
3833 
3834 OopMapBlocksBuilder::OopMapBlocksBuilder(unsigned int max_blocks) {
3835   _max_nonstatic_oop_maps = max_blocks;
3836   _nonstatic_oop_map_count = 0;
3837   if (max_blocks == 0) {

3989   // See documentation of InstanceKlass::can_be_fastpath_allocated().
3990   assert(ik->size_helper() > 0, "layout_helper is initialized");
3991   if (ik->is_abstract() || ik->is_interface()
3992       || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == nullptr)
3993       || ik->size_helper() >= FastAllocateSizeLimit) {
3994     // Forbid fast-path allocation.
3995     const jint lh = Klass::instance_layout_helper(ik->size_helper(), true);
3996     ik->set_layout_helper(lh);
3997   }
3998 
3999   // Propagate the AOT runtimeSetup method discovery
4000   if (_has_aot_runtime_setup_method) {
4001     ik->set_is_runtime_setup_required();
4002     if (log_is_enabled(Info, aot, init)) {
4003       ResourceMark rm;
4004       log_info(aot, init)("Found @AOTRuntimeSetup class %s", ik->external_name());
4005     }
4006   }
4007 }
4008 






4009 // utility methods for appending an array with check for duplicates
4010 
4011 static void append_interfaces(GrowableArray<InstanceKlass*>* result,
4012                               const Array<InstanceKlass*>* const ifs) {
4013   // iterate over new interfaces
4014   for (int i = 0; i < ifs->length(); i++) {
4015     InstanceKlass* const e = ifs->at(i);
4016     assert(e->is_klass() && e->is_interface(), "just checking");
4017     // add new interface
4018     result->append_if_missing(e);
4019   }
4020 }
4021 
4022 static Array<InstanceKlass*>* compute_transitive_interfaces(const InstanceKlass* super,
4023                                                             Array<InstanceKlass*>* local_ifs,
4024                                                             ClassLoaderData* loader_data,
4025                                                             TRAPS) {
4026   assert(local_ifs != nullptr, "invariant");
4027   assert(loader_data != nullptr, "invariant");
4028 

4032   // Add superclass transitive interfaces size
4033   if (super != nullptr) {
4034     super_size = super->transitive_interfaces()->length();
4035     max_transitive_size += super_size;
4036   }
4037   // Add local interfaces' super interfaces
4038   const int local_size = local_ifs->length();
4039   for (int i = 0; i < local_size; i++) {
4040     InstanceKlass* const l = local_ifs->at(i);
4041     max_transitive_size += l->transitive_interfaces()->length();
4042   }
4043   // Finally add local interfaces
4044   max_transitive_size += local_size;
4045   // Construct array
4046   if (max_transitive_size == 0) {
4047     // no interfaces, use canonicalized array
4048     return Universe::the_empty_instance_klass_array();
4049   } else if (max_transitive_size == super_size) {
4050     // no new local interfaces added, share superklass' transitive interface array
4051     return super->transitive_interfaces();
4052   } else if (max_transitive_size == local_size) {
4053     // only local interfaces added, share local interface array
4054     return local_ifs;

4055   } else {
4056     ResourceMark rm;
4057     GrowableArray<InstanceKlass*>* const result = new GrowableArray<InstanceKlass*>(max_transitive_size);
4058 
4059     // Copy down from superclass
4060     if (super != nullptr) {
4061       append_interfaces(result, super->transitive_interfaces());
4062     }
4063 
4064     // Copy down from local interfaces' superinterfaces
4065     for (int i = 0; i < local_size; i++) {
4066       InstanceKlass* const l = local_ifs->at(i);
4067       append_interfaces(result, l->transitive_interfaces());
4068     }
4069     // Finally add local interfaces
4070     append_interfaces(result, local_ifs);
4071 
4072     // length will be less than the max_transitive_size if duplicates were removed
4073     const int length = result->length();
4074     assert(length <= max_transitive_size, "just checking");

4075     Array<InstanceKlass*>* const new_result =
4076       MetadataFactory::new_array<InstanceKlass*>(loader_data, length, CHECK_NULL);
4077     for (int i = 0; i < length; i++) {
4078       InstanceKlass* const e = result->at(i);
4079       assert(e != nullptr, "just checking");
4080       new_result->at_put(i, e);
4081     }
4082     return new_result;
4083   }
4084 }
4085 
4086 void ClassFileParser::check_super_class_access(const InstanceKlass* this_klass, TRAPS) {
4087   assert(this_klass != nullptr, "invariant");
4088   const InstanceKlass* const super = this_klass->super();
4089 
4090   if (super != nullptr) {
4091     if (super->is_final()) {
4092       classfile_icce_error("class %s cannot inherit from final class %s", super, THREAD);
4093       return;
4094     }
4095 
4096     if (super->is_sealed()) {
4097       stringStream ss;
4098       ResourceMark rm(THREAD);
4099       if (!super->has_as_permitted_subclass(this_klass, ss)) {
4100         classfile_icce_error(ss.as_string(), THREAD);
4101         return;
4102       }
4103     }
4104 










4105     Reflection::VerifyClassAccessResults vca_result =
4106       Reflection::verify_class_access(this_klass, super, false);
4107     if (vca_result != Reflection::ACCESS_OK) {
4108       ResourceMark rm(THREAD);
4109       char* msg = Reflection::verify_class_access_msg(this_klass,
4110                                                       super,
4111                                                       vca_result);
4112 
4113       // Names are all known to be < 64k so we know this formatted message is not excessively large.
4114       if (msg == nullptr) {
4115         bool same_module = (this_klass->module() == super->module());
4116         Exceptions::fthrow(
4117           THREAD_AND_LOCATION,
4118           vmSymbols::java_lang_IllegalAccessError(),
4119           "class %s cannot access its %ssuperclass %s (%s%s%s)",
4120           this_klass->external_name(),
4121           super->is_abstract() ? "abstract " : "",
4122           super->external_name(),
4123           (same_module) ? this_klass->joint_in_module_of_loader(super) : this_klass->class_in_module_of_loader(),
4124           (same_module) ? "" : "; ",

4277 // Verify the class modifiers for the current class, or an inner class if inner_name is non-null.
4278 void ClassFileParser::verify_legal_class_modifiers(jint flags, Symbol* inner_name, bool is_anonymous_inner_class, TRAPS) const {
4279   const bool is_module = (flags & JVM_ACC_MODULE) != 0;
4280   assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");
4281   if (is_module) {
4282     ResourceMark rm(THREAD);
4283     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4284     Exceptions::fthrow(
4285       THREAD_AND_LOCATION,
4286       vmSymbols::java_lang_NoClassDefFoundError(),
4287       "%s is not a class because access_flag ACC_MODULE is set",
4288       _class_name->as_C_string());
4289     return;
4290   }
4291 
4292   if (!_need_verify) { return; }
4293 
4294   const bool is_interface  = (flags & JVM_ACC_INTERFACE)  != 0;
4295   const bool is_abstract   = (flags & JVM_ACC_ABSTRACT)   != 0;
4296   const bool is_final      = (flags & JVM_ACC_FINAL)      != 0;
4297   const bool is_super      = (flags & JVM_ACC_SUPER)      != 0;
4298   const bool is_enum       = (flags & JVM_ACC_ENUM)       != 0;
4299   const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4300   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;


4301 
4302   if ((is_abstract && is_final) ||
4303       (is_interface && !is_abstract) ||
4304       (is_interface && major_gte_1_5 && (is_super || is_enum)) ||
4305       (!is_interface && major_gte_1_5 && is_annotation)) {

4306     ResourceMark rm(THREAD);




4307     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4308     if (inner_name == nullptr && !is_anonymous_inner_class) {
4309       Exceptions::fthrow(
4310         THREAD_AND_LOCATION,
4311         vmSymbols::java_lang_ClassFormatError(),
4312         "Illegal class modifiers in class %s: 0x%X",
4313         _class_name->as_C_string(), flags
4314       );
4315     } else {
4316       if (is_anonymous_inner_class) {
4317         Exceptions::fthrow(
4318           THREAD_AND_LOCATION,
4319           vmSymbols::java_lang_ClassFormatError(),
4320           "Illegal class modifiers in anonymous inner class of class %s: 0x%X",
4321           _class_name->as_C_string(), flags
4322         );
4323       } else {
4324         Exceptions::fthrow(
4325           THREAD_AND_LOCATION,
4326           vmSymbols::java_lang_ClassFormatError(),

4380         THREAD_AND_LOCATION,
4381         vmSymbols::java_lang_UnsupportedClassVersionError(),
4382         "%s (class file version %u.%u) was compiled with preview features that are unsupported. "
4383         "This version of the Java Runtime only recognizes preview features for class file version %u.%u",
4384         class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION, JAVA_PREVIEW_MINOR_VERSION);
4385       return;
4386     }
4387 
4388     if (!Arguments::enable_preview()) {
4389       classfile_ucve_error("Preview features are not enabled for %s (class file version %u.%u). Try running with '--enable-preview'",
4390                            class_name, major, minor, THREAD);
4391       return;
4392     }
4393 
4394   } else { // minor != JAVA_PREVIEW_MINOR_VERSION
4395     classfile_ucve_error("%s (class file version %u.%u) was compiled with an invalid non-zero minor version",
4396                          class_name, major, minor, THREAD);
4397   }
4398 }
4399 
4400 void ClassFileParser::verify_legal_field_modifiers(jint flags,
4401                                                    bool is_interface,
4402                                                    TRAPS) const {
4403   if (!_need_verify) { return; }
4404 
4405   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4406   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4407   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4408   const bool is_static    = (flags & JVM_ACC_STATIC)    != 0;
4409   const bool is_final     = (flags & JVM_ACC_FINAL)     != 0;
4410   const bool is_volatile  = (flags & JVM_ACC_VOLATILE)  != 0;
4411   const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
4412   const bool is_enum      = (flags & JVM_ACC_ENUM)      != 0;

4413   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4414 
4415   bool is_illegal = false;

4416 
4417   if (is_interface) {
4418     if (!is_public || !is_static || !is_final || is_private ||
4419         is_protected || is_volatile || is_transient ||
4420         (major_gte_1_5 && is_enum)) {
4421       is_illegal = true;
4422     }
4423   } else { // not interface
4424     if (has_illegal_visibility(flags) || (is_final && is_volatile)) {
4425       is_illegal = true;





















4426     }
4427   }
4428 
4429   if (is_illegal) {
4430     ResourceMark rm(THREAD);
4431     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4432     Exceptions::fthrow(
4433       THREAD_AND_LOCATION,
4434       vmSymbols::java_lang_ClassFormatError(),
4435       "Illegal field modifiers in class %s: 0x%X",
4436       _class_name->as_C_string(), flags);
4437     return;
4438   }
4439 }
4440 
4441 void ClassFileParser::verify_legal_method_modifiers(jint flags,
4442                                                     bool is_interface,
4443                                                     const Symbol* name,
4444                                                     TRAPS) const {
4445   if (!_need_verify) { return; }
4446 
4447   const bool is_public       = (flags & JVM_ACC_PUBLIC)       != 0;
4448   const bool is_private      = (flags & JVM_ACC_PRIVATE)      != 0;
4449   const bool is_static       = (flags & JVM_ACC_STATIC)       != 0;
4450   const bool is_final        = (flags & JVM_ACC_FINAL)        != 0;
4451   const bool is_native       = (flags & JVM_ACC_NATIVE)       != 0;
4452   const bool is_abstract     = (flags & JVM_ACC_ABSTRACT)     != 0;
4453   const bool is_bridge       = (flags & JVM_ACC_BRIDGE)       != 0;
4454   const bool is_strict       = (flags & JVM_ACC_STRICT)       != 0;
4455   const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
4456   const bool is_protected    = (flags & JVM_ACC_PROTECTED)    != 0;
4457   const bool major_gte_1_5   = _major_version >= JAVA_1_5_VERSION;
4458   const bool major_gte_8     = _major_version >= JAVA_8_VERSION;
4459   const bool major_gte_17    = _major_version >= JAVA_17_VERSION;
4460   const bool is_initializer  = (name == vmSymbols::object_initializer_name());




4461 
4462   bool is_illegal = false;
4463 

4464   if (is_interface) {
4465     if (major_gte_8) {
4466       // Class file version is JAVA_8_VERSION or later Methods of
4467       // interfaces may set any of the flags except ACC_PROTECTED,
4468       // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must
4469       // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.
4470       if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
4471           (is_native || is_protected || is_final || is_synchronized) ||
4472           // If a specific method of a class or interface has its
4473           // ACC_ABSTRACT flag set, it must not have any of its
4474           // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,
4475           // ACC_STRICT, or ACC_SYNCHRONIZED flags set.  No need to
4476           // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as
4477           // those flags are illegal irrespective of ACC_ABSTRACT being set or not.
4478           (is_abstract && (is_private || is_static || (!major_gte_17 && is_strict)))) {
4479         is_illegal = true;
4480       }
4481     } else if (major_gte_1_5) {
4482       // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)
4483       if (!is_public || is_private || is_protected || is_static || is_final ||
4484           is_synchronized || is_native || !is_abstract || is_strict) {
4485         is_illegal = true;
4486       }
4487     } else {
4488       // Class file version is pre-JAVA_1_5_VERSION
4489       if (!is_public || is_static || is_final || is_native || !is_abstract) {
4490         is_illegal = true;
4491       }
4492     }
4493   } else { // not interface
4494     if (has_illegal_visibility(flags)) {
4495       is_illegal = true;
4496     } else {
4497       if (is_initializer) {
4498         if (is_static || is_final || is_synchronized || is_native ||
4499             is_abstract || (major_gte_1_5 && is_bridge)) {
4500           is_illegal = true;
4501         }
4502       } else { // not initializer
4503         if (is_abstract) {
4504           if ((is_final || is_native || is_private || is_static ||
4505               (major_gte_1_5 && (is_synchronized || (!major_gte_17 && is_strict))))) {
4506             is_illegal = true;





4507           }
4508         }
4509       }
4510     }
4511   }
4512 
4513   if (is_illegal) {
4514     ResourceMark rm(THREAD);
4515     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4516     Exceptions::fthrow(
4517       THREAD_AND_LOCATION,
4518       vmSymbols::java_lang_ClassFormatError(),
4519       "Method %s in class %s has illegal modifiers: 0x%X",
4520       name->as_C_string(), _class_name->as_C_string(), flags);

4521     return;
4522   }
4523 }
4524 
4525 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer,
4526                                         int length,
4527                                         TRAPS) const {
4528   assert(_need_verify, "only called when _need_verify is true");
4529   // Note: 0 <= length < 64K, as it comes from a u2 entry in the CP.
4530   if (!UTF8::is_legal_utf8(buffer, static_cast<size_t>(length), _major_version <= 47)) {
4531     classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", THREAD);
4532   }
4533 }
4534 
4535 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
4536 // In class names, '/' separates unqualified names.  This is verified in this function also.
4537 // Method names also may not contain the characters '<' or '>', unless <init>
4538 // or <clinit>.  Note that method names may not be <init> or <clinit> in this
4539 // method.  Because these names have been checked as special cases before
4540 // calling this method in verify_legal_method_name.

4558         if (type == ClassFileParser::LegalClass) {
4559           if (p == name || p+1 >= name+length ||
4560               *(p+1) == JVM_SIGNATURE_SLASH) {
4561             return false;
4562           }
4563         } else {
4564           return false;   // do not permit '/' unless it's class name
4565         }
4566         break;
4567       case JVM_SIGNATURE_SPECIAL:
4568       case JVM_SIGNATURE_ENDSPECIAL:
4569         // do not permit '<' or '>' in method names
4570         if (type == ClassFileParser::LegalMethod) {
4571           return false;
4572         }
4573     }
4574   }
4575   return true;
4576 }
4577 









4578 // Take pointer to a UTF8 byte string (not NUL-terminated).
4579 // Skip over the longest part of the string that could
4580 // be taken as a fieldname. Allow non-trailing '/'s if slash_ok is true.
4581 // Return a pointer to just past the fieldname.
4582 // Return null if no fieldname at all was found, or in the case of slash_ok
4583 // being true, we saw consecutive slashes (meaning we were looking for a
4584 // qualified path but found something that was badly-formed).
4585 static const char* skip_over_field_name(const char* const name,
4586                                         bool slash_ok,
4587                                         unsigned int length) {
4588   const char* p;
4589   jboolean last_is_slash = false;
4590   jboolean not_first_ch = false;
4591 
4592   for (p = name; p != name + length; not_first_ch = true) {
4593     const char* old_p = p;
4594     jchar ch = *p;
4595     if (ch < 128) {
4596       p++;
4597       // quick check for ascii

4659 // be taken as a field signature. Allow "void" if void_ok.
4660 // Return a pointer to just past the signature.
4661 // Return null if no legal signature is found.
4662 const char* ClassFileParser::skip_over_field_signature(const char* signature,
4663                                                        bool void_ok,
4664                                                        unsigned int length,
4665                                                        TRAPS) const {
4666   unsigned int array_dim = 0;
4667   while (length > 0) {
4668     switch (signature[0]) {
4669     case JVM_SIGNATURE_VOID: if (!void_ok) { return nullptr; }
4670     case JVM_SIGNATURE_BOOLEAN:
4671     case JVM_SIGNATURE_BYTE:
4672     case JVM_SIGNATURE_CHAR:
4673     case JVM_SIGNATURE_SHORT:
4674     case JVM_SIGNATURE_INT:
4675     case JVM_SIGNATURE_FLOAT:
4676     case JVM_SIGNATURE_LONG:
4677     case JVM_SIGNATURE_DOUBLE:
4678       return signature + 1;
4679     case JVM_SIGNATURE_CLASS: {

4680       if (_major_version < JAVA_1_5_VERSION) {
4681         signature++;
4682         length--;
4683         // Skip over the class name if one is there
4684         const char* const p = skip_over_field_name(signature, true, length);
4685         assert(p == nullptr || p > signature, "must parse one character at least");
4686         // The next character better be a semicolon
4687         if (p != nullptr                             && // Parse of field name succeeded.
4688             p - signature < static_cast<int>(length) && // There is at least one character left to parse.
4689             p[0] == JVM_SIGNATURE_ENDCLASS) {
4690           return p + 1;
4691         }
4692       }
4693       else {
4694         // Skip leading 'L' and ignore first appearance of ';'
4695         signature++;
4696         const char* c = (const char*) memchr(signature, JVM_SIGNATURE_ENDCLASS, length - 1);
4697         // Format check signature
4698         if (c != nullptr) {
4699           int newlen = pointer_delta_as_int(c, (char*) signature);
4700           bool legal = verify_unqualified_name(signature, newlen, LegalClass);
4701           if (!legal) {
4702             classfile_parse_error("Class name is empty or contains illegal character "
4703                                   "in descriptor in class file %s",
4704                                   THREAD);
4705             return nullptr;
4706           }
4707           return signature + newlen + 1;
4708         }
4709       }
4710       return nullptr;
4711     }
4712     case JVM_SIGNATURE_ARRAY:
4713       array_dim++;
4714       if (array_dim > 255) {

4730 
4731 // Checks if name is a legal class name.
4732 void ClassFileParser::verify_legal_class_name(const Symbol* name, TRAPS) const {
4733   if (!_need_verify) { return; }
4734 
4735   assert(name->refcount() > 0, "symbol must be kept alive");
4736   char* bytes = (char*)name->bytes();
4737   unsigned int length = name->utf8_length();
4738   bool legal = false;
4739 
4740   if (length > 0) {
4741     const char* p;
4742     if (bytes[0] == JVM_SIGNATURE_ARRAY) {
4743       p = skip_over_field_signature(bytes, false, length, CHECK);
4744       legal = (p != nullptr) && ((p - bytes) == (int)length);
4745     } else if (_major_version < JAVA_1_5_VERSION) {
4746       if (bytes[0] != JVM_SIGNATURE_SPECIAL) {
4747         p = skip_over_field_name(bytes, true, length);
4748         legal = (p != nullptr) && ((p - bytes) == (int)length);
4749       }




4750     } else {
4751       // 4900761: relax the constraints based on JSR202 spec
4752       // Class names may be drawn from the entire Unicode character set.
4753       // Identifiers between '/' must be unqualified names.
4754       // The utf8 string has been verified when parsing cpool entries.
4755       legal = verify_unqualified_name(bytes, length, LegalClass);
4756     }
4757   }
4758   if (!legal) {
4759     ResourceMark rm(THREAD);
4760     assert(_class_name != nullptr, "invariant");
4761     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4762     Exceptions::fthrow(
4763       THREAD_AND_LOCATION,
4764       vmSymbols::java_lang_ClassFormatError(),
4765       "Illegal class name \"%.*s\" in class file %s", length, bytes,
4766       _class_name->as_C_string()
4767     );
4768     return;
4769   }

4797       THREAD_AND_LOCATION,
4798       vmSymbols::java_lang_ClassFormatError(),
4799       "Illegal field name \"%.*s\" in class %s", length, bytes,
4800       _class_name->as_C_string()
4801     );
4802     return;
4803   }
4804 }
4805 
4806 // Checks if name is a legal method name.
4807 void ClassFileParser::verify_legal_method_name(const Symbol* name, TRAPS) const {
4808   if (!_need_verify) { return; }
4809 
4810   assert(name != nullptr, "method name is null");
4811   char* bytes = (char*)name->bytes();
4812   unsigned int length = name->utf8_length();
4813   bool legal = false;
4814 
4815   if (length > 0) {
4816     if (bytes[0] == JVM_SIGNATURE_SPECIAL) {
4817       if (name == vmSymbols::object_initializer_name() || name == vmSymbols::class_initializer_name()) {

4818         legal = true;
4819       }
4820     } else if (_major_version < JAVA_1_5_VERSION) {
4821       const char* p;
4822       p = skip_over_field_name(bytes, false, length);
4823       legal = (p != nullptr) && ((p - bytes) == (int)length);
4824     } else {
4825       // 4881221: relax the constraints based on JSR202 spec
4826       legal = verify_unqualified_name(bytes, length, LegalMethod);
4827     }
4828   }
4829 
4830   if (!legal) {
4831     ResourceMark rm(THREAD);
4832     assert(_class_name != nullptr, "invariant");
4833     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4834     Exceptions::fthrow(
4835       THREAD_AND_LOCATION,
4836       vmSymbols::java_lang_ClassFormatError(),
4837       "Illegal method name \"%.*s\" in class %s", length, bytes,
4838       _class_name->as_C_string()
4839     );
4840     return;
4841   }
4842 }
4843 










4844 
4845 // Checks if signature is a legal field signature.
4846 void ClassFileParser::verify_legal_field_signature(const Symbol* name,
4847                                                    const Symbol* signature,
4848                                                    TRAPS) const {
4849   if (!_need_verify) { return; }
4850 
4851   const char* const bytes = (const char*)signature->bytes();
4852   const unsigned int length = signature->utf8_length();
4853   const char* const p = skip_over_field_signature(bytes, false, length, CHECK);
4854 
4855   if (p == nullptr || (p - bytes) != (int)length) {
4856     throwIllegalSignature("Field", name, signature, CHECK);
4857   }
4858 }
4859 
4860 // Check that the signature is compatible with the method name.  For example,
4861 // check that <init> has a void signature.
4862 void ClassFileParser::verify_legal_name_with_signature(const Symbol* name,
4863                                                        const Symbol* signature,
4864                                                        TRAPS) const {
4865   if (!_need_verify) {
4866     return;
4867   }
4868 
4869   // Class initializers cannot have args for class format version >= 51.
4870   if (name == vmSymbols::class_initializer_name() &&
4871       signature != vmSymbols::void_method_signature() &&
4872       _major_version >= JAVA_7_VERSION) {
4873     throwIllegalSignature("Method", name, signature, THREAD);
4874     return;
4875   }
4876 
4877   int sig_length = signature->utf8_length();
4878   if (name->utf8_length() > 0 &&
4879       name->char_at(0) == JVM_SIGNATURE_SPECIAL &&
4880       sig_length > 0 &&
4881       signature->char_at(sig_length - 1) != JVM_SIGNATURE_VOID) {
4882     throwIllegalSignature("Method", name, signature, THREAD);
4883   }
4884 }
4885 
4886 // Checks if signature is a legal method signature.
4887 // Returns number of parameters
4888 int ClassFileParser::verify_legal_method_signature(const Symbol* name,
4889                                                    const Symbol* signature,
4890                                                    TRAPS) const {
4891   if (!_need_verify) {
4892     // make sure caller's args_size will be less than 0 even for non-static
4893     // method so it will be recomputed in compute_size_of_parameters().
4894     return -2;
4895   }
4896 
4897   unsigned int args_size = 0;
4898   const char* p = (const char*)signature->bytes();
4899   unsigned int length = signature->utf8_length();
4900   const char* nextp;
4901 

4912       length -= pointer_delta_as_int(nextp, p);
4913       p = nextp;
4914       nextp = skip_over_field_signature(p, false, length, CHECK_0);
4915     }
4916     // The first non-signature thing better be a ')'
4917     if ((length > 0) && (*p++ == JVM_SIGNATURE_ENDFUNC)) {
4918       length--;
4919       // Now we better just have a return value
4920       nextp = skip_over_field_signature(p, true, length, CHECK_0);
4921       if (nextp && ((int)length == (nextp - p))) {
4922         return args_size;
4923       }
4924     }
4925   }
4926   // Report error
4927   throwIllegalSignature("Method", name, signature, THREAD);
4928   return 0;
4929 }
4930 
4931 int ClassFileParser::static_field_size() const {
4932   assert(_field_info != nullptr, "invariant");
4933   return _field_info->_static_field_size;
4934 }
4935 
4936 int ClassFileParser::total_oop_map_count() const {
4937   assert(_field_info != nullptr, "invariant");
4938   return _field_info->oop_map_blocks->_nonstatic_oop_map_count;
4939 }
4940 
4941 jint ClassFileParser::layout_size() const {
4942   assert(_field_info != nullptr, "invariant");
4943   return _field_info->_instance_size;
4944 }
4945 
4946 static void check_methods_for_intrinsics(const InstanceKlass* ik,
4947                                          const Array<Method*>* methods) {
4948   assert(ik != nullptr, "invariant");
4949   assert(methods != nullptr, "invariant");
4950 
4951   // Set up Method*::intrinsic_id as soon as we know the names of methods.
4952   // (We used to do this lazily, but now we query it in Rewriter,
4953   // which is eagerly done for every method, so we might as well do it now,
4954   // when everything is fresh in memory.)
4955   const vmSymbolID klass_id = Method::klass_id_for_intrinsics(ik);
4956 
4957   if (klass_id != vmSymbolID::NO_SID) {
4958     for (int j = 0; j < methods->length(); ++j) {
4959       Method* method = methods->at(j);
4960       method->init_intrinsic_id(klass_id);
4961 
4962       if (CheckIntrinsics) {
4963         // Check if an intrinsic is defined for method 'method',

5038   }
5039 }
5040 
5041 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook,
5042                                                       const ClassInstanceInfo& cl_inst_info,
5043                                                       TRAPS) {
5044   if (_klass != nullptr) {
5045     return _klass;
5046   }
5047 
5048   InstanceKlass* const ik =
5049     InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
5050 
5051   if (is_hidden()) {
5052     mangle_hidden_class_name(ik);
5053   }
5054 
5055   fill_instance_klass(ik, changed_by_loadhook, cl_inst_info, CHECK_NULL);
5056 
5057   assert(_klass == ik, "invariant");
5058 
5059   return ik;
5060 }
5061 
5062 void ClassFileParser::fill_instance_klass(InstanceKlass* ik,
5063                                           bool changed_by_loadhook,
5064                                           const ClassInstanceInfo& cl_inst_info,
5065                                           TRAPS) {
5066   assert(ik != nullptr, "invariant");
5067 
5068   // Set name and CLD before adding to CLD
5069   ik->set_class_loader_data(_loader_data);
5070   ik->set_class_loader_type();
5071   ik->set_name(_class_name);
5072 
5073   // Add all classes to our internal class loader list here,
5074   // including classes in the bootstrap (null) class loader.
5075   const bool publicize = !is_internal();
5076 
5077   _loader_data->add_class(ik, publicize);
5078 
5079   set_klass_to_deallocate(ik);
5080 
5081   assert(_field_info != nullptr, "invariant");
5082   assert(ik->static_field_size() == _field_info->_static_field_size, "sanity");
5083   assert(ik->nonstatic_oop_map_count() == _field_info->oop_map_blocks->_nonstatic_oop_map_count,
5084          "sanity");
5085 
5086   assert(ik->is_instance_klass(), "sanity");
5087   assert(ik->size_helper() == _field_info->_instance_size, "sanity");
5088 
5089   // Fill in information already parsed
5090   ik->set_should_verify_class(_need_verify);
5091 
5092   // Not yet: supers are done below to support the new subtype-checking fields
5093   ik->set_nonstatic_field_size(_field_info->_nonstatic_field_size);
5094   ik->set_has_nonstatic_fields(_field_info->_has_nonstatic_fields);










5095   ik->set_static_oop_field_count(_static_oop_count);
5096 
5097   // this transfers ownership of a lot of arrays from
5098   // the parser onto the InstanceKlass*
5099   apply_parsed_class_metadata(ik, _java_fields_count);



5100 
5101   // can only set dynamic nest-host after static nest information is set
5102   if (cl_inst_info.dynamic_nest_host() != nullptr) {
5103     ik->set_nest_host(cl_inst_info.dynamic_nest_host());
5104   }
5105 
5106   // note that is not safe to use the fields in the parser from this point on
5107   assert(nullptr == _cp, "invariant");
5108   assert(nullptr == _fieldinfo_stream, "invariant");
5109   assert(nullptr == _fieldinfo_search_table, "invariant");
5110   assert(nullptr == _fields_status, "invariant");
5111   assert(nullptr == _methods, "invariant");
5112   assert(nullptr == _inner_classes, "invariant");
5113   assert(nullptr == _nest_members, "invariant");

5114   assert(nullptr == _combined_annotations, "invariant");
5115   assert(nullptr == _record_components, "invariant");
5116   assert(nullptr == _permitted_subclasses, "invariant");

5117 
5118   if (_has_localvariable_table) {
5119     ik->set_has_localvariable_table(true);
5120   }
5121 
5122   if (_has_final_method) {
5123     ik->set_has_final_method();
5124   }
5125 
5126   ik->copy_method_ordering(_method_ordering, CHECK);
5127   // The InstanceKlass::_methods_jmethod_ids cache
5128   // is managed on the assumption that the initial cache
5129   // size is equal to the number of methods in the class. If
5130   // that changes, then InstanceKlass::idnum_can_increment()
5131   // has to be changed accordingly.
5132   ik->set_initial_method_idnum(checked_cast<u2>(ik->methods()->length()));
5133 
5134   ik->set_this_class_index(_this_class_index);
5135 
5136   if (_is_hidden) {

5173   if ((_num_miranda_methods > 0) ||
5174       // if this class introduced new miranda methods or
5175       (_super_klass != nullptr && _super_klass->has_miranda_methods())
5176         // super class exists and this class inherited miranda methods
5177      ) {
5178        ik->set_has_miranda_methods(); // then set a flag
5179   }
5180 
5181   // Fill in information needed to compute superclasses.
5182   ik->initialize_supers(const_cast<InstanceKlass*>(_super_klass), _transitive_interfaces, CHECK);
5183   ik->set_transitive_interfaces(_transitive_interfaces);
5184   ik->set_local_interfaces(_local_interfaces);
5185   _transitive_interfaces = nullptr;
5186   _local_interfaces = nullptr;
5187 
5188   // Initialize itable offset tables
5189   klassItable::setup_itable_offset_table(ik);
5190 
5191   // Compute transitive closure of interfaces this class implements
5192   // Do final class setup
5193   OopMapBlocksBuilder* oop_map_blocks = _field_info->oop_map_blocks;
5194   if (oop_map_blocks->_nonstatic_oop_map_count > 0) {
5195     oop_map_blocks->copy(ik->start_of_nonstatic_oop_maps());
5196   }
5197 
5198   if (_has_contended_fields || _parsed_annotations->is_contended() ||
5199       ( _super_klass != nullptr && _super_klass->has_contended_annotations())) {
5200     ik->set_has_contended_annotations(true);
5201   }
5202 
5203   // Fill in has_finalizer and layout_helper
5204   set_precomputed_flags(ik);
5205 
5206   // check if this class can access its super class
5207   check_super_class_access(ik, CHECK);
5208 
5209   // check if this class can access its superinterfaces
5210   check_super_interface_access(ik, CHECK);
5211 
5212   // check if this class overrides any final method
5213   check_final_method_override(ik, CHECK);

5234 
5235   assert(_all_mirandas != nullptr, "invariant");
5236 
5237   // Generate any default methods - default methods are public interface methods
5238   // that have a default implementation.  This is new with Java 8.
5239   if (_has_nonstatic_concrete_methods) {
5240     DefaultMethods::generate_default_methods(ik,
5241                                              _all_mirandas,
5242                                              CHECK);
5243   }
5244 
5245   // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5246   if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5247       !module_entry->has_default_read_edges()) {
5248     if (!module_entry->set_has_default_read_edges()) {
5249       // We won a potential race
5250       JvmtiExport::add_default_read_edges(module_handle, THREAD);
5251     }
5252   }
5253 

















































5254   ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5255 
5256   if (!is_internal()) {
5257     ik->print_class_load_logging(_loader_data, module_entry, _stream);
5258 
5259     if (ik->minor_version() == JAVA_PREVIEW_MINOR_VERSION &&
5260         ik->major_version() == JVM_CLASSFILE_MAJOR_VERSION &&
5261         log_is_enabled(Info, class, preview)) {
5262       ResourceMark rm;
5263       log_info(class, preview)("Loading class %s that depends on preview features (class file version %d.65535)",
5264                                ik->external_name(), JVM_CLASSFILE_MAJOR_VERSION);
5265     }
5266 
5267     if (log_is_enabled(Debug, class, resolve))  {
5268       ResourceMark rm;
5269       // print out the superclass.
5270       const char * from = ik->external_name();
5271       if (ik->super() != nullptr) {
5272         log_debug(class, resolve)("%s %s (super)",
5273                    from,

5316                                  const ClassLoadInfo* cl_info,
5317                                  Publicity pub_level,
5318                                  TRAPS) :
5319   _stream(stream),
5320   _class_name(nullptr),
5321   _loader_data(loader_data),
5322   _is_hidden(cl_info->is_hidden()),
5323   _can_access_vm_annotations(cl_info->can_access_vm_annotations()),
5324   _orig_cp_size(0),
5325   _static_oop_count(0),
5326   _super_klass(),
5327   _cp(nullptr),
5328   _fieldinfo_stream(nullptr),
5329   _fieldinfo_search_table(nullptr),
5330   _fields_status(nullptr),
5331   _methods(nullptr),
5332   _inner_classes(nullptr),
5333   _nest_members(nullptr),
5334   _nest_host(0),
5335   _permitted_subclasses(nullptr),

5336   _record_components(nullptr),
5337   _local_interfaces(nullptr),

5338   _transitive_interfaces(nullptr),
5339   _combined_annotations(nullptr),
5340   _class_annotations(nullptr),
5341   _class_type_annotations(nullptr),
5342   _fields_annotations(nullptr),
5343   _fields_type_annotations(nullptr),
5344   _klass(nullptr),
5345   _klass_to_deallocate(nullptr),
5346   _parsed_annotations(nullptr),
5347   _field_info(nullptr),

5348   _temp_field_info(nullptr),
5349   _method_ordering(nullptr),
5350   _all_mirandas(nullptr),
5351   _vtable_size(0),
5352   _itable_size(0),
5353   _num_miranda_methods(0),
5354   _protection_domain(cl_info->protection_domain()),
5355   _access_flags(),
5356   _pub_level(pub_level),
5357   _bad_constant_seen(0),
5358   _synthetic_flag(false),
5359   _sde_length(false),
5360   _sde_buffer(nullptr),
5361   _sourcefile_index(0),
5362   _generic_signature_index(0),
5363   _major_version(0),
5364   _minor_version(0),
5365   _this_class_index(0),
5366   _super_class_index(0),
5367   _itfs_len(0),
5368   _java_fields_count(0),
5369   _need_verify(false),
5370   _has_nonstatic_concrete_methods(false),
5371   _declares_nonstatic_concrete_methods(false),
5372   _has_localvariable_table(false),
5373   _has_final_method(false),
5374   _has_contended_fields(false),
5375   _has_aot_runtime_setup_method(false),





5376   _has_finalizer(false),
5377   _has_empty_finalizer(false),
5378   _max_bootstrap_specifier_index(-1) {
5379 
5380   _class_name = name != nullptr ? name : vmSymbols::unknown_class_name();
5381   _class_name->increment_refcount();
5382 
5383   assert(_loader_data != nullptr, "invariant");
5384   assert(stream != nullptr, "invariant");
5385   assert(_stream != nullptr, "invariant");
5386   assert(_stream->buffer() == _stream->current(), "invariant");
5387   assert(_class_name != nullptr, "invariant");
5388   assert(0 == _access_flags.as_unsigned_short(), "invariant");
5389 
5390   // Figure out whether we can skip format checking (matching classic VM behavior)
5391   // Always verify CFLH bytes from the user agents.
5392   _need_verify = stream->from_class_file_load_hook() ? true : Verifier::should_verify_for(_loader_data->class_loader());
5393 
5394   // synch back verification state to stream to check for truncation.
5395   stream->set_need_verify(_need_verify);
5396 
5397   parse_stream(stream, CHECK);
5398 
5399   post_process_parsed_stream(stream, _cp, CHECK);
5400 }
5401 
5402 void ClassFileParser::clear_class_metadata() {
5403   // metadata created before the instance klass is created.  Must be
5404   // deallocated if classfile parsing returns an error.
5405   _cp = nullptr;
5406   _fieldinfo_stream = nullptr;
5407   _fieldinfo_search_table = nullptr;
5408   _fields_status = nullptr;
5409   _methods = nullptr;
5410   _inner_classes = nullptr;
5411   _nest_members = nullptr;
5412   _permitted_subclasses = nullptr;

5413   _combined_annotations = nullptr;
5414   _class_annotations = _class_type_annotations = nullptr;
5415   _fields_annotations = _fields_type_annotations = nullptr;
5416   _record_components = nullptr;

5417 }
5418 
5419 // Destructor to clean up
5420 ClassFileParser::~ClassFileParser() {
5421   _class_name->decrement_refcount();
5422 
5423   if (_cp != nullptr) {
5424     MetadataFactory::free_metadata(_loader_data, _cp);
5425   }
5426 
5427   if (_fieldinfo_stream != nullptr) {
5428     MetadataFactory::free_array<u1>(_loader_data, _fieldinfo_stream);
5429   }
5430   MetadataFactory::free_array<u1>(_loader_data, _fieldinfo_search_table);
5431 
5432   if (_fields_status != nullptr) {
5433     MetadataFactory::free_array<FieldStatus>(_loader_data, _fields_status);
5434   }
5435 




5436   if (_methods != nullptr) {
5437     // Free methods
5438     InstanceKlass::deallocate_methods(_loader_data, _methods);
5439   }
5440 
5441   // beware of the Universe::empty_blah_array!!
5442   if (_inner_classes != nullptr && _inner_classes != Universe::the_empty_short_array()) {
5443     MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
5444   }
5445 
5446   if (_nest_members != nullptr && _nest_members != Universe::the_empty_short_array()) {
5447     MetadataFactory::free_array<u2>(_loader_data, _nest_members);
5448   }
5449 
5450   if (_record_components != nullptr) {
5451     InstanceKlass::deallocate_record_components(_loader_data, _record_components);
5452   }
5453 
5454   if (_permitted_subclasses != nullptr && _permitted_subclasses != Universe::the_empty_short_array()) {
5455     MetadataFactory::free_array<u2>(_loader_data, _permitted_subclasses);
5456   }
5457 




5458   // Free interfaces
5459   InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
5460                                        _local_interfaces, _transitive_interfaces);
5461 
5462   if (_combined_annotations != nullptr) {
5463     // After all annotations arrays have been created, they are installed into the
5464     // Annotations object that will be assigned to the InstanceKlass being created.
5465 
5466     // Deallocate the Annotations object and the installed annotations arrays.
5467     _combined_annotations->deallocate_contents(_loader_data);
5468 
5469     // If the _combined_annotations pointer is non-null,
5470     // then the other annotations fields should have been cleared.
5471     assert(_class_annotations       == nullptr, "Should have been cleared");
5472     assert(_class_type_annotations  == nullptr, "Should have been cleared");
5473     assert(_fields_annotations      == nullptr, "Should have been cleared");
5474     assert(_fields_type_annotations == nullptr, "Should have been cleared");
5475   } else {
5476     // If the annotations arrays were not installed into the Annotations object,
5477     // then they have to be deallocated explicitly.

5536 
5537   assert(cp_size == (u2)cp->length(), "invariant");
5538 
5539   // ACCESS FLAGS
5540   stream->guarantee_more(8, CHECK);  // flags, this_class, super_class, infs_len
5541 
5542   // Access flags
5543   u2 flags;
5544   // JVM_ACC_MODULE is defined in JDK-9 and later.
5545   if (_major_version >= JAVA_9_VERSION) {
5546     flags = stream->get_u2_fast() & (JVM_RECOGNIZED_CLASS_MODIFIERS | JVM_ACC_MODULE);
5547   } else {
5548     flags = stream->get_u2_fast() & JVM_RECOGNIZED_CLASS_MODIFIERS;
5549   }
5550 
5551   if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
5552     // Set abstract bit for old class files for backward compatibility
5553     flags |= JVM_ACC_ABSTRACT;
5554   }
5555 









5556   verify_legal_class_modifiers(flags, nullptr, false, CHECK);
5557 
5558   short bad_constant = class_bad_constant_seen();
5559   if (bad_constant != 0) {
5560     // Do not throw CFE until after the access_flags are checked because if
5561     // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
5562     classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, THREAD);
5563     return;
5564   }
5565 
5566   _access_flags.set_flags(flags);
5567 
5568   // This class and superclass
5569   _this_class_index = stream->get_u2_fast();
5570   guarantee_property(
5571     valid_cp_range(_this_class_index, cp_size) &&
5572       cp->tag_at(_this_class_index).is_unresolved_klass(),
5573     "Invalid this class index %u in constant pool in class file %s",
5574     _this_class_index, CHECK);
5575 

5639       }
5640       ls.cr();
5641     }
5642   }
5643 
5644   // SUPERKLASS
5645   _super_class_index = stream->get_u2_fast();
5646   check_super_class(cp,
5647                     _super_class_index,
5648                     _need_verify,
5649                     CHECK);
5650 
5651   // Interfaces
5652   _itfs_len = stream->get_u2_fast();
5653   parse_interfaces(stream,
5654                    _itfs_len,
5655                    cp,
5656                    &_has_nonstatic_concrete_methods,
5657                    CHECK);
5658 
5659   assert(_local_interfaces != nullptr, "invariant");
5660 
5661   // Fields (offsets are filled in later)
5662   parse_fields(stream,
5663                _access_flags.is_interface(),
5664                cp,
5665                cp_size,
5666                &_java_fields_count,
5667                CHECK);
5668 
5669   assert(_temp_field_info != nullptr, "invariant");
5670 
5671   // Methods
5672   parse_methods(stream,
5673                 _access_flags.is_interface(),


5674                 &_has_localvariable_table,
5675                 &_has_final_method,
5676                 &_declares_nonstatic_concrete_methods,
5677                 CHECK);
5678 
5679   assert(_methods != nullptr, "invariant");
5680 
5681   if (_declares_nonstatic_concrete_methods) {
5682     _has_nonstatic_concrete_methods = true;
5683   }
5684 
5685   // Additional attributes/annotations
5686   _parsed_annotations = new ClassAnnotationCollector();
5687   parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK);
5688 
5689   assert(_inner_classes != nullptr, "invariant");
5690 
5691   // Finalize the Annotations metadata object,
5692   // now that all annotation arrays have been created.
5693   create_combined_annotations(CHECK);

5741 }
5742 
5743 void ClassFileParser::post_process_parsed_stream(const ClassFileStream* const stream,
5744                                                  ConstantPool* cp,
5745                                                  TRAPS) {
5746   assert(stream != nullptr, "invariant");
5747   assert(stream->at_eos(), "invariant");
5748   assert(cp != nullptr, "invariant");
5749   assert(_loader_data != nullptr, "invariant");
5750 
5751   if (_class_name == vmSymbols::java_lang_Object()) {
5752     precond(_super_class_index == 0);
5753     precond(_super_klass == nullptr);
5754     guarantee_property(_local_interfaces == Universe::the_empty_instance_klass_array(),
5755                        "java.lang.Object cannot implement an interface in class file %s",
5756                        CHECK);
5757   } else {
5758     // Set _super_klass after class file is parsed and format is checked
5759     assert(_super_class_index > 0, "any class other than Object must have a super class");
5760     Symbol* const super_class_name = cp->klass_name_at(_super_class_index);
5761     if (_access_flags.is_interface()) {
5762       // Before attempting to resolve the superclass, check for class format
5763       // errors not checked yet.
5764       guarantee_property(super_class_name == vmSymbols::java_lang_Object(),
5765         "Interfaces must have java.lang.Object as superclass in class file %s",
5766         CHECK);
5767     }
5768     Handle loader(THREAD, _loader_data->class_loader());
5769     if (loader.is_null() && super_class_name == vmSymbols::java_lang_Object()) {
5770       // fast path to avoid lookup
5771       _super_klass = vmClasses::Object_klass();
5772     } else {
5773       _super_klass = (const InstanceKlass*)
5774                        SystemDictionary::resolve_super_or_fail(_class_name,
5775                                                                super_class_name,
5776                                                                loader,
5777                                                                true,
5778                                                                CHECK);
5779     }
5780   }
5781 
5782   if (_super_klass != nullptr) {














5783     if (_super_klass->has_nonstatic_concrete_methods()) {
5784       _has_nonstatic_concrete_methods = true;
5785     }

5786 
5787     if (_super_klass->is_interface()) {
5788       classfile_icce_error("class %s has interface %s as super class", _super_klass, THREAD);
5789       return;





















5790     }
5791   }
5792 














































5793   // Compute the transitive list of all unique interfaces implemented by this class
5794   _transitive_interfaces =
5795     compute_transitive_interfaces(_super_klass,
5796                                   _local_interfaces,
5797                                   _loader_data,
5798                                   CHECK);
5799 
5800   assert(_transitive_interfaces != nullptr, "invariant");
5801 
5802   // sort methods
5803   _method_ordering = sort_methods(_methods);
5804 
5805   _all_mirandas = new GrowableArray<Method*>(20);
5806 
5807   Handle loader(THREAD, _loader_data->class_loader());
5808   klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
5809                                                     &_num_miranda_methods,
5810                                                     _all_mirandas,
5811                                                     _super_klass,
5812                                                     _methods,
5813                                                     _access_flags,
5814                                                     _major_version,
5815                                                     loader,
5816                                                     _class_name,
5817                                                     _local_interfaces);
5818 
5819   // Size of Java itable (in words)
5820   _itable_size = _access_flags.is_interface() ? 0 :
5821     klassItable::compute_itable_size(_transitive_interfaces);
5822 
5823   assert(_parsed_annotations != nullptr, "invariant");
5824 
5825   _field_info = new FieldLayoutInfo();
5826   FieldLayoutBuilder lb(class_name(), super_klass(), _cp, /*_fields*/ _temp_field_info,
5827                         _parsed_annotations->is_contended(), _field_info);

























































































5828   lb.build_layout();

5829 
5830   int injected_fields_count = _temp_field_info->length() - _java_fields_count;
5831   _fieldinfo_stream =
5832     FieldInfoStream::create_FieldInfoStream(_temp_field_info, _java_fields_count,
5833                                             injected_fields_count, loader_data(), CHECK);
5834   _fieldinfo_search_table = FieldInfoStream::create_search_table(_cp, _fieldinfo_stream, _loader_data, CHECK);
5835   _fields_status =
5836     MetadataFactory::new_array<FieldStatus>(_loader_data, _temp_field_info->length(),
5837                                             FieldStatus(0), CHECK);





















5838 }
5839 
5840 void ClassFileParser::set_klass(InstanceKlass* klass) {
5841 
5842 #ifdef ASSERT
5843   if (klass != nullptr) {
5844     assert(nullptr == _klass, "leaking?");
5845   }
5846 #endif
5847 
5848   _klass = klass;
5849 }
5850 
5851 void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) {
5852 
5853 #ifdef ASSERT
5854   if (klass != nullptr) {
5855     assert(nullptr == _klass_to_deallocate, "leaking?");
5856   }
5857 #endif

   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "cds/cdsConfig.hpp"
  26 #include "classfile/classFileParser.hpp"
  27 #include "classfile/classFileStream.hpp"
  28 #include "classfile/classLoader.hpp"
  29 #include "classfile/classLoaderData.inline.hpp"
  30 #include "classfile/classLoadInfo.hpp"
  31 #include "classfile/defaultMethods.hpp"
  32 #include "classfile/fieldLayoutBuilder.hpp"
  33 #include "classfile/javaClasses.inline.hpp"
  34 #include "classfile/moduleEntry.hpp"
  35 #include "classfile/packageEntry.hpp"
  36 #include "classfile/symbolTable.hpp"
  37 #include "classfile/systemDictionary.hpp"
  38 #include "classfile/verificationType.hpp"
  39 #include "classfile/verifier.hpp"
  40 #include "classfile/vmClasses.hpp"
  41 #include "classfile/vmSymbols.hpp"
  42 #include "jvm.h"
  43 #include "logging/log.hpp"
  44 #include "logging/logStream.hpp"
  45 #include "memory/allocation.hpp"
  46 #include "memory/metadataFactory.hpp"
  47 #include "memory/oopFactory.hpp"
  48 #include "memory/resourceArea.hpp"
  49 #include "memory/universe.hpp"
  50 #include "oops/annotations.hpp"
  51 #include "oops/constantPool.inline.hpp"
  52 #include "oops/fieldInfo.hpp"
  53 #include "oops/fieldStreams.inline.hpp"
  54 #include "oops/inlineKlass.inline.hpp"
  55 #include "oops/instanceKlass.inline.hpp"
  56 #include "oops/instanceMirrorKlass.hpp"
  57 #include "oops/klass.inline.hpp"
  58 #include "oops/klassVtable.hpp"
  59 #include "oops/metadata.hpp"
  60 #include "oops/method.inline.hpp"
  61 #include "oops/oop.inline.hpp"
  62 #include "oops/recordComponent.hpp"
  63 #include "oops/symbol.hpp"
  64 #include "prims/jvmtiExport.hpp"
  65 #include "prims/jvmtiThreadState.hpp"
  66 #include "runtime/arguments.hpp"
  67 #include "runtime/fieldDescriptor.inline.hpp"
  68 #include "runtime/handles.inline.hpp"
  69 #include "runtime/javaCalls.hpp"
  70 #include "runtime/os.hpp"
  71 #include "runtime/perfData.hpp"
  72 #include "runtime/reflection.hpp"
  73 #include "runtime/safepointVerifiers.hpp"
  74 #include "runtime/signature.hpp"
  75 #include "runtime/timer.hpp"
  76 #include "services/classLoadingService.hpp"
  77 #include "services/threadService.hpp"
  78 #include "utilities/align.hpp"
  79 #include "utilities/bitMap.inline.hpp"
  80 #include "utilities/checkedCast.hpp"
  81 #include "utilities/copy.hpp"
  82 #include "utilities/exceptions.hpp"
  83 #include "utilities/formatBuffer.hpp"
  84 #include "utilities/globalDefinitions.hpp"
  85 #include "utilities/growableArray.hpp"
  86 #include "utilities/hashTable.hpp"
  87 #include "utilities/macros.hpp"
  88 #include "utilities/ostream.hpp"
  89 #include "utilities/stringUtils.hpp"
  90 #include "utilities/utf8.hpp"
  91 #if INCLUDE_CDS
  92 #include "classfile/systemDictionaryShared.hpp"
  93 #endif
  94 #if INCLUDE_JFR
  95 #include "jfr/support/jfrTraceIdExtension.hpp"
  96 #endif
  97 
  98 // We generally try to create the oops directly when parsing, rather than
  99 // allocating temporary data structures and copying the bytes twice. A
 100 // temporary area is only needed when parsing utf8 entries in the constant
 101 // pool and when parsing line number tables.
 102 
 103 // We add assert in debug mode when class format is not checked.
 104 
 105 #define JAVA_CLASSFILE_MAGIC              0xCAFEBABE
 106 #define JAVA_MIN_SUPPORTED_VERSION        45
 107 #define JAVA_PREVIEW_MINOR_VERSION        65535
 108 
 109 // Used for two backward compatibility reasons:

 142 #define JAVA_17_VERSION                   61
 143 
 144 #define JAVA_18_VERSION                   62
 145 
 146 #define JAVA_19_VERSION                   63
 147 
 148 #define JAVA_20_VERSION                   64
 149 
 150 #define JAVA_21_VERSION                   65
 151 
 152 #define JAVA_22_VERSION                   66
 153 
 154 #define JAVA_23_VERSION                   67
 155 
 156 #define JAVA_24_VERSION                   68
 157 
 158 #define JAVA_25_VERSION                   69
 159 
 160 #define JAVA_26_VERSION                   70
 161 
 162 #define CONSTANT_CLASS_DESCRIPTORS        70
 163 
 164 void ClassFileParser::set_class_bad_constant_seen(short bad_constant) {
 165   assert((bad_constant == JVM_CONSTANT_Module ||
 166           bad_constant == JVM_CONSTANT_Package) && _major_version >= JAVA_9_VERSION,
 167          "Unexpected bad constant pool entry");
 168   if (_bad_constant_seen == 0) _bad_constant_seen = bad_constant;
 169 }
 170 
 171 void ClassFileParser::parse_constant_pool_entries(const ClassFileStream* const stream,
 172                                                   ConstantPool* cp,
 173                                                   const int length,
 174                                                   TRAPS) {
 175   assert(stream != nullptr, "invariant");
 176   assert(cp != nullptr, "invariant");
 177 
 178   // Use a local copy of ClassFileStream. It helps the C++ compiler to optimize
 179   // this function (_current can be allocated in a register, with scalar
 180   // replacement of aggregates). The _current pointer is copied back to
 181   // stream() when this function returns. DON'T call another method within
 182   // this method that uses stream().
 183   const ClassFileStream cfs1 = *stream;
 184   const ClassFileStream* const cfs = &cfs1;
 185 
 186   DEBUG_ONLY(const u1* const old_current = stream->current();)
 187 
 188   // Used for batching symbol allocations.
 189   const char* names[SymbolTable::symbol_alloc_batch_size];
 190   int lengths[SymbolTable::symbol_alloc_batch_size];
 191   int indices[SymbolTable::symbol_alloc_batch_size];
 192   unsigned int hashValues[SymbolTable::symbol_alloc_batch_size];
 193   int names_count = 0;
 194 
 195   // parsing  Index 0 is unused
 196   for (int index = 1; index < length; index++) {
 197     // Each of the following case guarantees one more byte in the stream
 198     // for the following tag or the access_flags following constant pool,
 199     // so we don't need bounds-check for reading tag.
 200     const u1 tag = cfs->get_u1_fast();
 201     switch (tag) {
 202       case JVM_CONSTANT_Class: {
 203         cfs->guarantee_more(3, CHECK);  // name_index, tag/access_flags
 204         const u2 name_index = cfs->get_u2_fast();
 205         cp->klass_index_at_put(index, name_index);
 206         break;
 207       }
 208       case JVM_CONSTANT_Fieldref: {
 209         cfs->guarantee_more(5, CHECK);  // class_index, name_and_type_index, tag/access_flags
 210         const u2 class_index = cfs->get_u2_fast();
 211         const u2 name_and_type_index = cfs->get_u2_fast();
 212         cp->field_at_put(index, class_index, name_and_type_index);
 213         break;
 214       }
 215       case JVM_CONSTANT_Methodref: {
 216         cfs->guarantee_more(5, CHECK);  // class_index, name_and_type_index, tag/access_flags
 217         const u2 class_index = cfs->get_u2_fast();
 218         const u2 name_and_type_index = cfs->get_u2_fast();
 219         cp->method_at_put(index, class_index, name_and_type_index);
 220         break;
 221       }
 222       case JVM_CONSTANT_InterfaceMethodref: {

 486         guarantee_property(valid_symbol_at(name_ref_index),
 487           "Invalid constant pool index %u in class file %s",
 488           name_ref_index, CHECK);
 489         guarantee_property(valid_symbol_at(signature_ref_index),
 490           "Invalid constant pool index %u in class file %s",
 491           signature_ref_index, CHECK);
 492         break;
 493       }
 494       case JVM_CONSTANT_Utf8:
 495         break;
 496       case JVM_CONSTANT_UnresolvedClass:         // fall-through
 497       case JVM_CONSTANT_UnresolvedClassInError: {
 498         ShouldNotReachHere();     // Only JVM_CONSTANT_ClassIndex should be present
 499         break;
 500       }
 501       case JVM_CONSTANT_ClassIndex: {
 502         const int class_index = cp->klass_index_at(index);
 503         guarantee_property(valid_symbol_at(class_index),
 504           "Invalid constant pool index %u in class file %s",
 505           class_index, CHECK);
 506 
 507         Symbol* const name = cp->symbol_at(class_index);
 508         const unsigned int name_len = name->utf8_length();
 509         cp->unresolved_klass_at_put(index, class_index, num_klasses++);
 510         break;
 511       }
 512       case JVM_CONSTANT_StringIndex: {
 513         const int string_index = cp->string_index_at(index);
 514         guarantee_property(valid_symbol_at(string_index),
 515           "Invalid constant pool index %u in class file %s",
 516           string_index, CHECK);
 517         Symbol* const sym = cp->symbol_at(string_index);
 518         cp->unresolved_string_at_put(index, sym);
 519         break;
 520       }
 521       case JVM_CONSTANT_MethodHandle: {
 522         const int ref_index = cp->method_handle_index_at(index);
 523         guarantee_property(valid_cp_range(ref_index, length),
 524           "Invalid constant pool index %u in class file %s",
 525           ref_index, CHECK);
 526         const constantTag tag = cp->tag_at(ref_index);
 527         const int ref_kind = cp->method_handle_ref_kind_at(index);
 528 

 698             }
 699           }
 700         } else {
 701           if (_need_verify) {
 702             // Method name and signature are individually verified above, when iterating
 703             // NameAndType_info.  Need to check here that signature is non-zero length and
 704             // the right type.
 705             if (!Signature::is_method(signature)) {
 706               throwIllegalSignature("Method", name, signature, CHECK);
 707             }
 708           }
 709           // If a class method name begins with '<', it must be "<init>" and have void signature.
 710           const unsigned int name_len = name->utf8_length();
 711           if (tag == JVM_CONSTANT_Methodref && name_len != 0 &&
 712               name->char_at(0) == JVM_SIGNATURE_SPECIAL) {
 713             if (name != vmSymbols::object_initializer_name()) {
 714               classfile_parse_error(
 715                 "Bad method name at constant pool index %u in class file %s",
 716                 name_ref_index, THREAD);
 717               return;
 718             } else if (!Signature::is_void_method(signature)) {  // must have void signature.
 719               throwIllegalSignature("Method", name, signature, CHECK);
 720             }
 721           }
 722         }
 723         break;
 724       }
 725       case JVM_CONSTANT_MethodHandle: {
 726         const int ref_index = cp->method_handle_index_at(index);
 727         const int ref_kind = cp->method_handle_ref_kind_at(index);
 728         switch (ref_kind) {
 729           case JVM_REF_invokeVirtual:
 730           case JVM_REF_invokeStatic:
 731           case JVM_REF_invokeSpecial:
 732           case JVM_REF_newInvokeSpecial: {
 733             const int name_and_type_ref_index =
 734               cp->uncached_name_and_type_ref_index_at(ref_index);
 735             const int name_ref_index =
 736               cp->name_ref_index_at(name_and_type_ref_index);
 737             const Symbol* const name = cp->symbol_at(name_ref_index);
 738 
 739             if (name != vmSymbols::object_initializer_name()) { // !<init>
 740               if (ref_kind == JVM_REF_newInvokeSpecial) {
 741                 classfile_parse_error(
 742                   "Bad constructor name at constant pool index %u in class file %s",
 743                     name_ref_index, THREAD);
 744                 return;
 745               }
 746             } else { // <init>
 747               // The allowed invocation mode of <init> depends on its signature.
 748               // This test corresponds to verify_invoke_instructions in the verifier.
 749               const int signature_ref_index =
 750                 cp->signature_ref_index_at(name_and_type_ref_index);
 751               const Symbol* const signature = cp->symbol_at(signature_ref_index);
 752               if (signature->is_void_method_signature()
 753                   && ref_kind == JVM_REF_newInvokeSpecial) {
 754                 // OK, could be a constructor call
 755               } else {
 756                 classfile_parse_error(
 757                   "Bad method name at constant pool index %u in class file %s",
 758                   name_ref_index, THREAD);
 759                 return;
 760               }
 761             }
 762             break;
 763           }
 764           // Other ref_kinds are already fully checked in previous pass.
 765         } // switch(ref_kind)
 766         break;
 767       }
 768       case JVM_CONSTANT_MethodType: {
 769         const Symbol* const no_name = vmSymbols::type_name(); // place holder
 770         const Symbol* const signature = cp->method_type_signature_at(index);
 771         verify_legal_method_signature(no_name, signature, CHECK);
 772         break;
 773       }
 774       case JVM_CONSTANT_Utf8: {
 775         assert(cp->symbol_at(index)->refcount() != 0, "count corrupted");

 787 
 788   NameSigHash(Symbol* name, Symbol* sig) :
 789     _name(name),
 790     _sig(sig) {}
 791 
 792   static unsigned int hash(NameSigHash const& namesig) {
 793     return namesig._name->identity_hash() ^ namesig._sig->identity_hash();
 794   }
 795 
 796   static bool equals(NameSigHash const& e0, NameSigHash const& e1) {
 797     return (e0._name == e1._name) &&
 798           (e0._sig  == e1._sig);
 799   }
 800 };
 801 
 802 using NameSigHashtable = HashTable<NameSigHash, int,
 803                                            NameSigHash::HASH_ROW_SIZE,
 804                                            AnyObj::RESOURCE_AREA, mtInternal,
 805                                            &NameSigHash::hash, &NameSigHash::equals>;
 806 
 807 static void check_identity_and_value_modifiers(ClassFileParser* current, const InstanceKlass* super_type, TRAPS) {
 808   assert(super_type != nullptr,"Method doesn't support null super type");
 809   if (super_type->access_flags().is_identity_class() && !current->access_flags().is_identity_class()
 810       && super_type->name() != vmSymbols::java_lang_Object()) {
 811       THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
 812                 err_msg("Value type %s has an identity type as supertype",
 813                 current->class_name()->as_klass_external_name()));
 814   }
 815 }
 816 
 817 void ClassFileParser::parse_interfaces(const ClassFileStream* stream,
 818                                        int itfs_len,
 819                                        ConstantPool* cp,
 820                                        bool* const has_nonstatic_concrete_methods,
 821                                        // FIXME: lots of these functions
 822                                        // declare their parameters as const,
 823                                        // which adds only noise to the code.
 824                                        // Remove the spurious const modifiers.
 825                                        // Many are of the form "const int x"
 826                                        // or "T* const x".
 827                                        TRAPS) {
 828   assert(stream != nullptr, "invariant");
 829   assert(cp != nullptr, "invariant");
 830   assert(has_nonstatic_concrete_methods != nullptr, "invariant");
 831 
 832   if (itfs_len == 0) {
 833     _local_interfaces = Universe::the_empty_instance_klass_array();
 834 
 835   } else {
 836     assert(itfs_len > 0, "only called for len>0");
 837     _local_interface_indexes = new GrowableArray<u2>(itfs_len);
 838     int index = 0;

 839     for (index = 0; index < itfs_len; index++) {
 840       const u2 interface_index = stream->get_u2(CHECK);

 841       guarantee_property(
 842         valid_klass_reference_at(interface_index),
 843         "Interface name has bad constant pool index %u in class file %s",
 844         interface_index, CHECK);
 845       _local_interface_indexes->at_put_grow(index, interface_index);




























 846     }
 847 
 848     if (!_need_verify || itfs_len <= 1) {
 849       return;
 850     }
 851 
 852     // Check if there's any duplicates in interfaces
 853     ResourceMark rm(THREAD);
 854     // Set containing interface names
 855     HashTable<Symbol*, int>* interface_names = new HashTable<Symbol*, int>();
 856     for (index = 0; index < itfs_len; index++) {
 857       Symbol* interface_name = cp->klass_name_at(_local_interface_indexes->at(index));

 858       // If no duplicates, add (name, nullptr) in hashtable interface_names.
 859       if (!interface_names->put(interface_name, 0)) {
 860         classfile_parse_error("Duplicate interface name \"%s\" in class file %s",
 861                                interface_name->as_C_string(), THREAD);
 862         return;
 863       }
 864     }
 865   }
 866 }
 867 
 868 void ClassFileParser::verify_constantvalue(const ConstantPool* const cp,
 869                                            int constantvalue_index,
 870                                            int signature_index,
 871                                            TRAPS) const {
 872   // Make sure the constant pool entry is of a type appropriate to this field
 873   guarantee_property(
 874     (constantvalue_index > 0 &&
 875       constantvalue_index < cp->length()),
 876     "Bad initial value index %u in ConstantValue attribute in class file %s",
 877     constantvalue_index, CHECK);

 924 class AnnotationCollector : public ResourceObj{
 925 public:
 926   enum Location { _in_field, _in_method, _in_class };
 927   enum ID {
 928     _unknown = 0,
 929     _method_CallerSensitive,
 930     _method_ForceInline,
 931     _method_DontInline,
 932     _method_ChangesCurrentThread,
 933     _method_JvmtiHideEvents,
 934     _method_JvmtiMountTransition,
 935     _method_InjectedProfile,
 936     _method_LambdaForm_Compiled,
 937     _method_Hidden,
 938     _method_Scoped,
 939     _method_IntrinsicCandidate,
 940     _jdk_internal_vm_annotation_Contended,
 941     _field_Stable,
 942     _jdk_internal_vm_annotation_ReservedStackAccess,
 943     _jdk_internal_ValueBased,
 944     _jdk_internal_LooselyConsistentValue,
 945     _jdk_internal_NullRestricted,
 946     _java_lang_Deprecated,
 947     _java_lang_Deprecated_for_removal,
 948     _jdk_internal_vm_annotation_AOTSafeClassInitializer,
 949     _method_AOTRuntimeSetup,
 950     _annotation_LIMIT
 951   };
 952   const Location _location;
 953   int _annotations_present;
 954   u2 _contended_group;
 955 
 956   AnnotationCollector(Location location)
 957     : _location(location), _annotations_present(0), _contended_group(0)
 958   {
 959     assert((int)_annotation_LIMIT <= (int)sizeof(_annotations_present) * BitsPerByte, "");
 960   }
 961   // If this annotation name has an ID, report it (or _none).
 962   ID annotation_index(const ClassLoaderData* loader_data, const Symbol* name, bool can_access_vm_annotations);
 963   // Set the annotation name:
 964   void set_annotation(ID id) {
 965     assert((int)id >= 0 && (int)id < (int)_annotation_LIMIT, "oob");

1352   }
1353 
1354   *constantvalue_index_addr = constantvalue_index;
1355   *is_synthetic_addr = is_synthetic;
1356   *generic_signature_index_addr = generic_signature_index;
1357   AnnotationArray* a = allocate_annotations(runtime_visible_annotations,
1358                                             runtime_visible_annotations_length,
1359                                             CHECK);
1360   parsed_annotations->set_field_annotations(a);
1361   a = allocate_annotations(runtime_visible_type_annotations,
1362                            runtime_visible_type_annotations_length,
1363                            CHECK);
1364   parsed_annotations->set_field_type_annotations(a);
1365   return;
1366 }
1367 
1368 
1369 // Side-effects: populates the _fields, _fields_annotations,
1370 // _fields_type_annotations fields
1371 void ClassFileParser::parse_fields(const ClassFileStream* const cfs,
1372                                    AccessFlags class_access_flags,
1373                                    ConstantPool* cp,
1374                                    const int cp_size,
1375                                    u2* const java_fields_count_ptr,
1376                                    TRAPS) {
1377 
1378   assert(cfs != nullptr, "invariant");
1379   assert(cp != nullptr, "invariant");
1380   assert(java_fields_count_ptr != nullptr, "invariant");
1381 
1382   assert(nullptr == _fields_annotations, "invariant");
1383   assert(nullptr == _fields_type_annotations, "invariant");
1384 
1385   bool is_inline_type = !class_access_flags.is_identity_class() && !class_access_flags.is_abstract();
1386   bool is_value_class = !class_access_flags.is_identity_class() && !class_access_flags.is_interface();
1387   cfs->guarantee_more(2, CHECK);  // length
1388   const u2 length = cfs->get_u2_fast();
1389   *java_fields_count_ptr = length;
1390 
1391   int num_injected = 0;
1392   const InjectedField* const injected = JavaClasses::get_injected(_class_name,
1393                                                                   &num_injected);
1394 
1395   // two more slots are required for inline classes:
1396   // one for the static field with a reference to the pre-allocated default value
1397   // one for the field the JVM injects when detecting an empty inline class
1398   const int total_fields = length + num_injected + (is_inline_type ? 2 : 0)
1399                            + ((UseAltSubstitutabilityMethod && is_value_class) ? 1 : 0);
1400 
1401   // Allocate a temporary resource array to collect field data.
1402   // After parsing all fields, data are stored in a UNSIGNED5 compressed stream.
1403   _temp_field_info = new GrowableArray<FieldInfo>(total_fields);
1404 
1405   int instance_fields_count = 0;
1406   ResourceMark rm(THREAD);
1407   for (int n = 0; n < length; n++) {
1408     // access_flags, name_index, descriptor_index, attributes_count
1409     cfs->guarantee_more(8, CHECK);
1410 
1411     jint recognized_modifiers = JVM_RECOGNIZED_FIELD_MODIFIERS;
1412     if (!supports_inline_types()) {
1413       recognized_modifiers &= ~JVM_ACC_STRICT;
1414     }
1415 
1416     const jint flags = cfs->get_u2_fast() & recognized_modifiers;
1417     verify_legal_field_modifiers(flags, class_access_flags, CHECK);
1418     AccessFlags access_flags;


1419     access_flags.set_flags(flags);
1420     FieldInfo::FieldFlags fieldFlags(0);
1421 
1422     const u2 name_index = cfs->get_u2_fast();
1423     guarantee_property(valid_symbol_at(name_index),
1424       "Invalid constant pool index %u for field name in class file %s",
1425       name_index, CHECK);
1426     const Symbol* const name = cp->symbol_at(name_index);
1427     verify_legal_field_name(name, CHECK);
1428 
1429     const u2 signature_index = cfs->get_u2_fast();
1430     guarantee_property(valid_symbol_at(signature_index),
1431       "Invalid constant pool index %u for field signature in class file %s",
1432       signature_index, CHECK);
1433     const Symbol* const sig = cp->symbol_at(signature_index);
1434     verify_legal_field_signature(name, sig, CHECK);
1435     if (!access_flags.is_static()) instance_fields_count++;
1436 
1437     u2 constantvalue_index = 0;
1438     bool is_synthetic = false;
1439     u2 generic_signature_index = 0;
1440     const bool is_static = access_flags.is_static();
1441     FieldAnnotationCollector parsed_annotations(_loader_data);
1442 
1443     bool is_null_restricted = false;
1444 
1445     const u2 attributes_count = cfs->get_u2_fast();
1446     if (attributes_count > 0) {
1447       parse_field_attributes(cfs,
1448                              attributes_count,
1449                              is_static,
1450                              signature_index,
1451                              &constantvalue_index,
1452                              &is_synthetic,
1453                              &generic_signature_index,
1454                              &parsed_annotations,
1455                              CHECK);
1456 
1457       if (parsed_annotations.field_annotations() != nullptr) {
1458         if (_fields_annotations == nullptr) {
1459           _fields_annotations = MetadataFactory::new_array<AnnotationArray*>(
1460                                              _loader_data, length, nullptr,
1461                                              CHECK);
1462         }
1463         _fields_annotations->at_put(n, parsed_annotations.field_annotations());
1464         if (parsed_annotations.has_annotation(AnnotationCollector::_jdk_internal_NullRestricted)) {
1465           if (!Signature::has_envelope(sig)) {
1466             Exceptions::fthrow(
1467               THREAD_AND_LOCATION,
1468               vmSymbols::java_lang_ClassFormatError(),
1469               "Illegal use of @jdk.internal.vm.annotation.NullRestricted annotation on field %s.%s with signature %s (primitive types can never be null)",
1470               class_name()->as_C_string(), name->as_C_string(), sig->as_C_string());
1471           }
1472           const bool is_strict = (flags & JVM_ACC_STRICT) != 0;
1473           if (!is_strict) {
1474             Exceptions::fthrow(
1475               THREAD_AND_LOCATION,
1476               vmSymbols::java_lang_ClassFormatError(),
1477               "Illegal use of @jdk.internal.vm.annotation.NullRestricted annotation on field %s.%s which doesn't have the @jdk.internal.vm.annotation.Strict annotation",
1478               class_name()->as_C_string(), name->as_C_string());
1479           }
1480           is_null_restricted = true;
1481         }
1482         parsed_annotations.set_field_annotations(nullptr);
1483       }
1484       if (parsed_annotations.field_type_annotations() != nullptr) {
1485         if (_fields_type_annotations == nullptr) {
1486           _fields_type_annotations =
1487             MetadataFactory::new_array<AnnotationArray*>(_loader_data,
1488                                                          length,
1489                                                          nullptr,
1490                                                          CHECK);
1491         }
1492         _fields_type_annotations->at_put(n, parsed_annotations.field_type_annotations());
1493         parsed_annotations.set_field_type_annotations(nullptr);
1494       }
1495 
1496       if (is_synthetic) {
1497         access_flags.set_is_synthetic();
1498       }
1499       if (generic_signature_index != 0) {
1500         fieldFlags.update_generic(true);
1501       }
1502     }
1503 
1504     if (is_null_restricted) {
1505       fieldFlags.update_null_free_inline_type(true);
1506     }
1507 
1508     const BasicType type = cp->basic_type_for_signature_at(signature_index);
1509 
1510     // Update number of static oop fields.
1511     if (is_static && is_reference_type(type)) {
1512       _static_oop_count++;
1513     }
1514 
1515     FieldInfo fi(access_flags, name_index, signature_index, constantvalue_index, fieldFlags);
1516     fi.set_index(n);
1517     if (fieldFlags.is_generic()) {
1518       fi.set_generic_signature_index(generic_signature_index);
1519     }
1520     parsed_annotations.apply_to(&fi);
1521     if (fi.field_flags().is_contended()) {
1522       _has_contended_fields = true;
1523     }
1524     if (access_flags.is_strict() && access_flags.is_static()) {
1525       _has_strict_static_fields = true;
1526     }
1527     _temp_field_info->append(fi);
1528   }
1529   assert(_temp_field_info->length() == length, "Must be");
1530 

1531   if (num_injected != 0) {
1532     for (int n = 0; n < num_injected; n++) {
1533       // Check for duplicates
1534       if (injected[n].may_be_java) {
1535         const Symbol* const name      = injected[n].name();
1536         const Symbol* const signature = injected[n].signature();
1537         bool duplicate = false;
1538         for (int i = 0; i < length; i++) {
1539           const FieldInfo* const f = _temp_field_info->adr_at(i);
1540           if (name      == cp->symbol_at(f->name_index()) &&
1541               signature == cp->symbol_at(f->signature_index())) {
1542             // Symbol is desclared in Java so skip this one
1543             duplicate = true;
1544             break;
1545           }
1546         }
1547         if (duplicate) {
1548           // These will be removed from the field array at the end
1549           continue;
1550         }
1551       }
1552 
1553       // Injected field
1554       FieldInfo::FieldFlags fflags(0);
1555       fflags.update_injected(true);
1556       AccessFlags aflags;
1557       FieldInfo fi(aflags, (u2)(injected[n].name_index), (u2)(injected[n].signature_index), 0, fflags);
1558       int idx = _temp_field_info->append(fi);
1559       _temp_field_info->adr_at(idx)->set_index(idx);

1560     }
1561   }
1562 
1563   if (is_inline_type) {
1564     // Inject static ".null_reset" field. This is an all-zero value with its null-channel set to zero.
1565     // IT should never be seen by user code, it is used when writing "null" to a nullable flat field
1566     // The all-zero value ensure that any embedded oop will be set to null, to avoid keeping dead objects
1567     // alive.
1568     FieldInfo::FieldFlags fflags2(0);
1569     fflags2.update_injected(true);
1570     AccessFlags aflags2(JVM_ACC_STATIC);
1571     FieldInfo fi2(aflags2,
1572                  (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(null_reset_value_name)),
1573                  (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(object_signature)),
1574                  0,
1575                  fflags2);
1576     int idx2 = _temp_field_info->append(fi2);
1577     _temp_field_info->adr_at(idx2)->set_index(idx2);
1578     _static_oop_count++;
1579   }
1580   if (!access_flags().is_identity_class() && !access_flags().is_interface()
1581       && _class_name != vmSymbols::java_lang_Object() && UseAltSubstitutabilityMethod) {
1582     // Acmp map required for abstract and concrete value classes
1583     FieldInfo::FieldFlags fflags2(0);
1584     fflags2.update_injected(true);
1585     fflags2.update_stable(true);
1586     AccessFlags aflags2(JVM_ACC_STATIC | JVM_ACC_FINAL);
1587     FieldInfo fi3(aflags2,
1588                  (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(acmp_maps_name)),
1589                  (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(int_array_signature)),
1590                  0,
1591                  fflags2);
1592     int idx2 = _temp_field_info->append(fi3);
1593     _temp_field_info->adr_at(idx2)->set_index(idx2);
1594     _static_oop_count++;
1595   }
1596 
1597   if (_need_verify && length > 1) {
1598     // Check duplicated fields
1599     ResourceMark rm(THREAD);
1600     // Set containing name-signature pairs
1601     NameSigHashtable* names_and_sigs = new NameSigHashtable();
1602     for (int i = 0; i < _temp_field_info->length(); i++) {
1603       NameSigHash name_and_sig(_temp_field_info->adr_at(i)->name(_cp),
1604                                _temp_field_info->adr_at(i)->signature(_cp));
1605       // If no duplicates, add name/signature in hashtable names_and_sigs.
1606       if(!names_and_sigs->put(name_and_sig, 0)) {
1607         classfile_parse_error("Duplicate field name \"%s\" with signature \"%s\" in class file %s",
1608                                name_and_sig._name->as_C_string(), name_and_sig._sig->as_klass_external_name(), THREAD);
1609         return;
1610       }
1611     }
1612   }
1613 }
1614 
1615 

1955     }
1956     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Contended_signature): {
1957       if (_location != _in_field && _location != _in_class) {
1958         break;  // only allow for fields and classes
1959       }
1960       if (!EnableContended || (RestrictContended && !privileged)) {
1961         break;  // honor privileges
1962       }
1963       return _jdk_internal_vm_annotation_Contended;
1964     }
1965     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ReservedStackAccess_signature): {
1966       if (_location != _in_method)  break;  // only allow for methods
1967       if (RestrictReservedStack && !privileged) break; // honor privileges
1968       return _jdk_internal_vm_annotation_ReservedStackAccess;
1969     }
1970     case VM_SYMBOL_ENUM_NAME(jdk_internal_ValueBased_signature): {
1971       if (_location != _in_class)   break;  // only allow for classes
1972       if (!privileged)              break;  // only allow in privileged code
1973       return _jdk_internal_ValueBased;
1974     }
1975     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_LooselyConsistentValue_signature): {
1976       if (_location != _in_class)   break; // only allow for classes
1977       return _jdk_internal_LooselyConsistentValue;
1978     }
1979     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_NullRestricted_signature): {
1980       if (_location != _in_field)   break; // only allow for fields
1981       return _jdk_internal_NullRestricted;
1982     }
1983     case VM_SYMBOL_ENUM_NAME(java_lang_Deprecated): {
1984       return _java_lang_Deprecated;
1985     }
1986     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_AOTSafeClassInitializer_signature): {
1987       if (_location != _in_class)   break;  // only allow for classes
1988       if (!privileged)              break;  // only allow in privileged code
1989       return _jdk_internal_vm_annotation_AOTSafeClassInitializer;
1990     }
1991     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_AOTRuntimeSetup_signature): {
1992       if (_location != _in_method)  break;  // only allow for methods
1993       if (!privileged)              break;  // only allow in privileged code
1994       return _method_AOTRuntimeSetup;
1995     }
1996     default: {
1997       break;
1998     }
1999   }
2000   return AnnotationCollector::_unknown;
2001 }
2002 

2199   }
2200 
2201   if (runtime_visible_type_annotations_length > 0) {
2202     a = allocate_annotations(runtime_visible_type_annotations,
2203                              runtime_visible_type_annotations_length,
2204                              CHECK);
2205     cm->set_type_annotations(a);
2206   }
2207 }
2208 
2209 
2210 // Note: the parse_method below is big and clunky because all parsing of the code and exceptions
2211 // attribute is inlined. This is cumbersome to avoid since we inline most of the parts in the
2212 // Method* to save footprint, so we only know the size of the resulting Method* when the
2213 // entire method attribute is parsed.
2214 //
2215 // The has_localvariable_table parameter is used to pass up the value to InstanceKlass.
2216 
2217 Method* ClassFileParser::parse_method(const ClassFileStream* const cfs,
2218                                       bool is_interface,
2219                                       bool is_value_class,
2220                                       bool is_abstract_class,
2221                                       const ConstantPool* cp,
2222                                       bool* const has_localvariable_table,
2223                                       TRAPS) {
2224   assert(cfs != nullptr, "invariant");
2225   assert(cp != nullptr, "invariant");
2226   assert(has_localvariable_table != nullptr, "invariant");
2227 
2228   ResourceMark rm(THREAD);
2229   // Parse fixed parts:
2230   // access_flags, name_index, descriptor_index, attributes_count
2231   cfs->guarantee_more(8, CHECK_NULL);
2232 
2233   u2 flags = cfs->get_u2_fast();
2234   const u2 name_index = cfs->get_u2_fast();
2235   const int cp_size = cp->length();
2236   guarantee_property(
2237     valid_symbol_at(name_index),
2238     "Illegal constant pool index %u for method name in class file %s",
2239     name_index, CHECK_NULL);
2240   const Symbol* const name = cp->symbol_at(name_index);

2242 
2243   const u2 signature_index = cfs->get_u2_fast();
2244   guarantee_property(
2245     valid_symbol_at(signature_index),
2246     "Illegal constant pool index %u for method signature in class file %s",
2247     signature_index, CHECK_NULL);
2248   const Symbol* const signature = cp->symbol_at(signature_index);
2249 
2250   if (name == vmSymbols::class_initializer_name()) {
2251     // We ignore the other access flags for a valid class initializer.
2252     // (JVM Spec 2nd ed., chapter 4.6)
2253     if (_major_version < 51) { // backward compatibility
2254       flags = JVM_ACC_STATIC;
2255     } else if ((flags & JVM_ACC_STATIC) == JVM_ACC_STATIC) {
2256       flags &= JVM_ACC_STATIC | (_major_version <= JAVA_16_VERSION ? JVM_ACC_STRICT : 0);
2257     } else {
2258       classfile_parse_error("Method <clinit> is not static in class file %s", THREAD);
2259       return nullptr;
2260     }
2261   } else {
2262     verify_legal_method_modifiers(flags, access_flags() , name, CHECK_NULL);
2263   }
2264 
2265   if (name == vmSymbols::object_initializer_name() && is_interface) {
2266     classfile_parse_error("Interface cannot have a method named <init>, class file %s", THREAD);
2267     return nullptr;
2268   }
2269 
2270   if (EnableValhalla) {
2271     if (((flags & JVM_ACC_SYNCHRONIZED) == JVM_ACC_SYNCHRONIZED)
2272         && ((flags & JVM_ACC_STATIC) == 0 )
2273         && !_access_flags.is_identity_class()) {
2274       classfile_parse_error("Invalid synchronized method in non-identity class %s", THREAD);
2275         return nullptr;
2276     }
2277   }
2278 
2279   int args_size = -1;  // only used when _need_verify is true
2280   if (_need_verify) {
2281     verify_legal_name_with_signature(name, signature, CHECK_NULL);
2282     args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) +
2283                  verify_legal_method_signature(name, signature, CHECK_NULL);
2284     if (args_size > MAX_ARGS_SIZE) {
2285       classfile_parse_error("Too many arguments in method signature in class file %s", THREAD);
2286       return nullptr;
2287     }
2288   }
2289 
2290   AccessFlags access_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS);
2291 
2292   // Default values for code and exceptions attribute elements
2293   u2 max_stack = 0;
2294   u2 max_locals = 0;
2295   u4 code_length = 0;
2296   const u1* code_start = nullptr;
2297   u2 exception_table_length = 0;
2298   const unsafe_u2* exception_table_start = nullptr; // (potentially unaligned) pointer to array of u2 elements

2793                           CHECK_NULL);
2794 
2795   if (InstanceKlass::is_finalization_enabled() &&
2796       name == vmSymbols::finalize_method_name() &&
2797       signature == vmSymbols::void_method_signature()) {
2798     if (m->is_empty_method()) {
2799       _has_empty_finalizer = true;
2800     } else {
2801       _has_finalizer = true;
2802     }
2803   }
2804 
2805   NOT_PRODUCT(m->verify());
2806   return m;
2807 }
2808 
2809 
2810 // Side-effects: populates the _methods field in the parser
2811 void ClassFileParser::parse_methods(const ClassFileStream* const cfs,
2812                                     bool is_interface,
2813                                     bool is_value_class,
2814                                     bool is_abstract_type,
2815                                     bool* const has_localvariable_table,
2816                                     bool* has_final_method,
2817                                     bool* declares_nonstatic_concrete_methods,
2818                                     TRAPS) {
2819   assert(cfs != nullptr, "invariant");
2820   assert(has_localvariable_table != nullptr, "invariant");
2821   assert(has_final_method != nullptr, "invariant");
2822   assert(declares_nonstatic_concrete_methods != nullptr, "invariant");
2823 
2824   assert(nullptr == _methods, "invariant");
2825 
2826   cfs->guarantee_more(2, CHECK);  // length
2827   const u2 length = cfs->get_u2_fast();
2828   if (length == 0) {
2829     _methods = Universe::the_empty_method_array();
2830   } else {
2831     _methods = MetadataFactory::new_array<Method*>(_loader_data,
2832                                                    length,
2833                                                    nullptr,
2834                                                    CHECK);
2835 
2836     for (int index = 0; index < length; index++) {
2837       Method* method = parse_method(cfs,
2838                                     is_interface,
2839                                     is_value_class,
2840                                     is_abstract_type,
2841                                     _cp,
2842                                     has_localvariable_table,
2843                                     CHECK);
2844 
2845       if (method->is_final()) {
2846         *has_final_method = true;
2847       }
2848       // declares_nonstatic_concrete_methods: declares concrete instance methods, any access flags
2849       // used for interface initialization, and default method inheritance analysis
2850       if (is_interface && !(*declares_nonstatic_concrete_methods)
2851         && !method->is_abstract() && !method->is_static()) {
2852         *declares_nonstatic_concrete_methods = true;
2853       }
2854       _methods->at_put(index, method);
2855     }
2856 
2857     if (_need_verify && length > 1) {
2858       // Check duplicated methods
2859       ResourceMark rm(THREAD);
2860       // Set containing name-signature pairs

3086         valid_klass_reference_at(outer_class_info_index),
3087       "outer_class_info_index %u has bad constant type in class file %s",
3088       outer_class_info_index, CHECK_0);
3089 
3090     if (outer_class_info_index != 0) {
3091       const Symbol* const outer_class_name = cp->klass_name_at(outer_class_info_index);
3092       char* bytes = (char*)outer_class_name->bytes();
3093       guarantee_property(bytes[0] != JVM_SIGNATURE_ARRAY,
3094                          "Outer class is an array class in class file %s", CHECK_0);
3095     }
3096     // Inner class name
3097     const u2 inner_name_index = cfs->get_u2_fast();
3098     guarantee_property(
3099       inner_name_index == 0 || valid_symbol_at(inner_name_index),
3100       "inner_name_index %u has bad constant type in class file %s",
3101       inner_name_index, CHECK_0);
3102     if (_need_verify) {
3103       guarantee_property(inner_class_info_index != outer_class_info_index,
3104                          "Class is both outer and inner class in class file %s", CHECK_0);
3105     }
3106 
3107     // Access flags
3108     u2 flags;
3109     // JVM_ACC_MODULE is defined in JDK-9 and later.
3110     if (_major_version >= JAVA_9_VERSION) {
3111       flags = cfs->get_u2_fast() & (RECOGNIZED_INNER_CLASS_MODIFIERS | JVM_ACC_MODULE);
3112     } else {
3113       flags = cfs->get_u2_fast() & RECOGNIZED_INNER_CLASS_MODIFIERS;
3114     }
3115 
3116     if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
3117       // Set abstract bit for old class files for backward compatibility
3118       flags |= JVM_ACC_ABSTRACT;
3119     }
3120 
3121     if (!supports_inline_types()) {
3122       const bool is_module = (flags & JVM_ACC_MODULE) != 0;
3123       const bool is_interface = (flags & JVM_ACC_INTERFACE) != 0;
3124       if (!is_module && !is_interface) {
3125         flags |= JVM_ACC_IDENTITY;
3126       }
3127     }
3128 
3129     Symbol* inner_name_symbol = inner_name_index == 0 ? nullptr : cp->symbol_at(inner_name_index);
3130     verify_legal_class_modifiers(flags, inner_name_symbol, inner_name_index == 0, CHECK_0);
3131     AccessFlags inner_access_flags(flags);
3132 
3133     inner_classes->at_put(index++, inner_class_info_index);
3134     inner_classes->at_put(index++, outer_class_info_index);
3135     inner_classes->at_put(index++, inner_name_index);
3136     inner_classes->at_put(index++, inner_access_flags.as_unsigned_short());
3137   }
3138 
3139   // Check for circular and duplicate entries.
3140   bool has_circularity = false;
3141   if (_need_verify) {
3142     has_circularity = check_inner_classes_circularity(cp, length * 4, CHECK_0);
3143     if (has_circularity) {
3144       // If circularity check failed then ignore InnerClasses attribute.
3145       MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
3146       index = 0;
3147       if (parsed_enclosingmethod_attribute) {
3148         inner_classes = MetadataFactory::new_array<u2>(_loader_data, 2, CHECK_0);

3214   if (length > 0) {
3215     int index = 0;
3216     cfs->guarantee_more(2 * length, CHECK_0);
3217     for (int n = 0; n < length; n++) {
3218       const u2 class_info_index = cfs->get_u2_fast();
3219       guarantee_property(
3220         valid_klass_reference_at(class_info_index),
3221         "Permitted subclass class_info_index %u has bad constant type in class file %s",
3222         class_info_index, CHECK_0);
3223       permitted_subclasses->at_put(index++, class_info_index);
3224     }
3225     assert(index == size, "wrong size");
3226   }
3227 
3228   // Restore buffer's current position.
3229   cfs->set_current(current_mark);
3230 
3231   return length;
3232 }
3233 
3234 u2 ClassFileParser::parse_classfile_loadable_descriptors_attribute(const ClassFileStream* const cfs,
3235                                                                    const u1* const loadable_descriptors_attribute_start,
3236                                                                    TRAPS) {
3237   const u1* const current_mark = cfs->current();
3238   u2 length = 0;
3239   if (loadable_descriptors_attribute_start != nullptr) {
3240     cfs->set_current(loadable_descriptors_attribute_start);
3241     cfs->guarantee_more(2, CHECK_0);  // length
3242     length = cfs->get_u2_fast();
3243   }
3244   const int size = length;
3245   Array<u2>* const loadable_descriptors = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
3246   _loadable_descriptors = loadable_descriptors;
3247   if (length > 0) {
3248     int index = 0;
3249     cfs->guarantee_more(2 * length, CHECK_0);
3250     for (int n = 0; n < length; n++) {
3251       const u2 descriptor_index = cfs->get_u2_fast();
3252       guarantee_property(
3253         valid_symbol_at(descriptor_index),
3254         "LoadableDescriptors descriptor_index %u has bad constant type in class file %s",
3255         descriptor_index, CHECK_0);
3256       Symbol* descriptor = _cp->symbol_at(descriptor_index);
3257       bool valid = legal_field_signature(descriptor, CHECK_0);
3258       if(!valid) {
3259         ResourceMark rm(THREAD);
3260         Exceptions::fthrow(THREAD_AND_LOCATION,
3261           vmSymbols::java_lang_ClassFormatError(),
3262           "Descriptor from LoadableDescriptors attribute at index \"%d\" in class %s has illegal signature \"%s\"",
3263           descriptor_index, _class_name->as_C_string(), descriptor->as_C_string());
3264         return 0;
3265       }
3266       loadable_descriptors->at_put(index++, descriptor_index);
3267     }
3268     assert(index == size, "wrong size");
3269   }
3270 
3271   // Restore buffer's current position.
3272   cfs->set_current(current_mark);
3273 
3274   return length;
3275 }
3276 
3277 //  Record {
3278 //    u2 attribute_name_index;
3279 //    u4 attribute_length;
3280 //    u2 components_count;
3281 //    component_info components[components_count];
3282 //  }
3283 //  component_info {
3284 //    u2 name_index;
3285 //    u2 descriptor_index
3286 //    u2 attributes_count;
3287 //    attribute_info_attributes[attributes_count];
3288 //  }
3289 u4 ClassFileParser::parse_classfile_record_attribute(const ClassFileStream* const cfs,
3290                                                      const ConstantPool* cp,
3291                                                      const u1* const record_attribute_start,
3292                                                      TRAPS) {
3293   const u1* const current_mark = cfs->current();
3294   int components_count = 0;
3295   unsigned int calculate_attr_size = 0;
3296   if (record_attribute_start != nullptr) {

3522   }
3523   guarantee_property(current_start + attribute_byte_length == cfs->current(),
3524                      "Bad length on BootstrapMethods in class file %s",
3525                      CHECK);
3526 }
3527 
3528 void ClassFileParser::parse_classfile_attributes(const ClassFileStream* const cfs,
3529                                                  ConstantPool* cp,
3530                  ClassFileParser::ClassAnnotationCollector* parsed_annotations,
3531                                                  TRAPS) {
3532   assert(cfs != nullptr, "invariant");
3533   assert(cp != nullptr, "invariant");
3534   assert(parsed_annotations != nullptr, "invariant");
3535 
3536   // Set inner classes attribute to default sentinel
3537   _inner_classes = Universe::the_empty_short_array();
3538   // Set nest members attribute to default sentinel
3539   _nest_members = Universe::the_empty_short_array();
3540   // Set _permitted_subclasses attribute to default sentinel
3541   _permitted_subclasses = Universe::the_empty_short_array();
3542   // Set _loadable_descriptors attribute to default sentinel
3543   _loadable_descriptors = Universe::the_empty_short_array();
3544   cfs->guarantee_more(2, CHECK);  // attributes_count
3545   u2 attributes_count = cfs->get_u2_fast();
3546   bool parsed_sourcefile_attribute = false;
3547   bool parsed_innerclasses_attribute = false;
3548   bool parsed_nest_members_attribute = false;
3549   bool parsed_permitted_subclasses_attribute = false;
3550   bool parsed_loadable_descriptors_attribute = false;
3551   bool parsed_nest_host_attribute = false;
3552   bool parsed_record_attribute = false;
3553   bool parsed_enclosingmethod_attribute = false;
3554   bool parsed_bootstrap_methods_attribute = false;
3555   const u1* runtime_visible_annotations = nullptr;
3556   int runtime_visible_annotations_length = 0;
3557   const u1* runtime_visible_type_annotations = nullptr;
3558   int runtime_visible_type_annotations_length = 0;
3559   bool runtime_invisible_type_annotations_exists = false;
3560   bool runtime_invisible_annotations_exists = false;
3561   bool parsed_source_debug_ext_annotations_exist = false;
3562   const u1* inner_classes_attribute_start = nullptr;
3563   u4  inner_classes_attribute_length = 0;
3564   u2  enclosing_method_class_index = 0;
3565   u2  enclosing_method_method_index = 0;
3566   const u1* nest_members_attribute_start = nullptr;
3567   u4  nest_members_attribute_length = 0;
3568   const u1* record_attribute_start = nullptr;
3569   u4  record_attribute_length = 0;
3570   const u1* permitted_subclasses_attribute_start = nullptr;
3571   u4  permitted_subclasses_attribute_length = 0;
3572   const u1* loadable_descriptors_attribute_start = nullptr;
3573   u4  loadable_descriptors_attribute_length = 0;
3574 
3575   // Iterate over attributes
3576   while (attributes_count--) {
3577     cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
3578     const u2 attribute_name_index = cfs->get_u2_fast();
3579     const u4 attribute_length = cfs->get_u4_fast();
3580     guarantee_property(
3581       valid_symbol_at(attribute_name_index),
3582       "Attribute name has bad constant pool index %u in class file %s",
3583       attribute_name_index, CHECK);
3584     const Symbol* const tag = cp->symbol_at(attribute_name_index);
3585     if (tag == vmSymbols::tag_source_file()) {
3586       // Check for SourceFile tag
3587       if (_need_verify) {
3588         guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
3589       }
3590       if (parsed_sourcefile_attribute) {
3591         classfile_parse_error("Multiple SourceFile attributes in class file %s", THREAD);
3592         return;
3593       } else {

3769               return;
3770             }
3771             parsed_record_attribute = true;
3772             record_attribute_start = cfs->current();
3773             record_attribute_length = attribute_length;
3774           } else if (_major_version >= JAVA_17_VERSION) {
3775             if (tag == vmSymbols::tag_permitted_subclasses()) {
3776               if (parsed_permitted_subclasses_attribute) {
3777                 classfile_parse_error("Multiple PermittedSubclasses attributes in class file %s", CHECK);
3778                 return;
3779               }
3780               // Classes marked ACC_FINAL cannot have a PermittedSubclasses attribute.
3781               if (_access_flags.is_final()) {
3782                 classfile_parse_error("PermittedSubclasses attribute in final class file %s", CHECK);
3783                 return;
3784               }
3785               parsed_permitted_subclasses_attribute = true;
3786               permitted_subclasses_attribute_start = cfs->current();
3787               permitted_subclasses_attribute_length = attribute_length;
3788             }
3789             if (EnableValhalla && tag == vmSymbols::tag_loadable_descriptors()) {
3790               if (parsed_loadable_descriptors_attribute) {
3791                 classfile_parse_error("Multiple LoadableDescriptors attributes in class file %s", CHECK);
3792                 return;
3793               }
3794               parsed_loadable_descriptors_attribute = true;
3795               loadable_descriptors_attribute_start = cfs->current();
3796               loadable_descriptors_attribute_length = attribute_length;
3797             }
3798           }
3799           // Skip attribute_length for any attribute where major_verson >= JAVA_17_VERSION
3800           cfs->skip_u1(attribute_length, CHECK);
3801         } else {
3802           // Unknown attribute
3803           cfs->skip_u1(attribute_length, CHECK);
3804         }
3805       } else {
3806         // Unknown attribute
3807         cfs->skip_u1(attribute_length, CHECK);
3808       }
3809     } else {
3810       // Unknown attribute
3811       cfs->skip_u1(attribute_length, CHECK);
3812     }
3813   }
3814   _class_annotations = allocate_annotations(runtime_visible_annotations,
3815                                             runtime_visible_annotations_length,
3816                                             CHECK);
3817   _class_type_annotations = allocate_annotations(runtime_visible_type_annotations,

3854                             CHECK);
3855     if (_need_verify) {
3856       guarantee_property(record_attribute_length == calculated_attr_length,
3857                          "Record attribute has wrong length in class file %s",
3858                          CHECK);
3859     }
3860   }
3861 
3862   if (parsed_permitted_subclasses_attribute) {
3863     const u2 num_subclasses = parse_classfile_permitted_subclasses_attribute(
3864                             cfs,
3865                             permitted_subclasses_attribute_start,
3866                             CHECK);
3867     if (_need_verify) {
3868       guarantee_property(
3869         permitted_subclasses_attribute_length == sizeof(num_subclasses) + sizeof(u2) * num_subclasses,
3870         "Wrong PermittedSubclasses attribute length in class file %s", CHECK);
3871     }
3872   }
3873 
3874   if (parsed_loadable_descriptors_attribute) {
3875     const u2 num_classes = parse_classfile_loadable_descriptors_attribute(
3876                             cfs,
3877                             loadable_descriptors_attribute_start,
3878                             CHECK);
3879     if (_need_verify) {
3880       guarantee_property(
3881         loadable_descriptors_attribute_length == sizeof(num_classes) + sizeof(u2) * num_classes,
3882         "Wrong LoadableDescriptors attribute length in class file %s", CHECK);
3883     }
3884   }
3885 
3886   if (_max_bootstrap_specifier_index >= 0) {
3887     guarantee_property(parsed_bootstrap_methods_attribute,
3888                        "Missing BootstrapMethods attribute in class file %s", CHECK);
3889   }
3890 }
3891 
3892 void ClassFileParser::apply_parsed_class_attributes(InstanceKlass* k) {
3893   assert(k != nullptr, "invariant");
3894 
3895   if (_synthetic_flag)
3896     k->set_is_synthetic();
3897   if (_sourcefile_index != 0) {
3898     k->set_source_file_name_index(_sourcefile_index);
3899   }
3900   if (_generic_signature_index != 0) {
3901     k->set_generic_signature_index(_generic_signature_index);
3902   }
3903   if (_sde_buffer != nullptr) {
3904     k->set_source_debug_extension(_sde_buffer, _sde_length);
3905   }

3932     _class_type_annotations  = nullptr;
3933     _fields_annotations      = nullptr;
3934     _fields_type_annotations = nullptr;
3935 }
3936 
3937 // Transfer ownership of metadata allocated to the InstanceKlass.
3938 void ClassFileParser::apply_parsed_class_metadata(
3939                                             InstanceKlass* this_klass,
3940                                             int java_fields_count) {
3941   assert(this_klass != nullptr, "invariant");
3942 
3943   _cp->set_pool_holder(this_klass);
3944   this_klass->set_constants(_cp);
3945   this_klass->set_fieldinfo_stream(_fieldinfo_stream);
3946   this_klass->set_fieldinfo_search_table(_fieldinfo_search_table);
3947   this_klass->set_fields_status(_fields_status);
3948   this_klass->set_methods(_methods);
3949   this_klass->set_inner_classes(_inner_classes);
3950   this_klass->set_nest_members(_nest_members);
3951   this_klass->set_nest_host_index(_nest_host);
3952   this_klass->set_loadable_descriptors(_loadable_descriptors);
3953   this_klass->set_annotations(_combined_annotations);
3954   this_klass->set_permitted_subclasses(_permitted_subclasses);
3955   this_klass->set_record_components(_record_components);
3956   this_klass->set_inline_layout_info_array(_inline_layout_info_array);
3957 
3958   DEBUG_ONLY(FieldInfoStream::validate_search_table(_cp, _fieldinfo_stream, _fieldinfo_search_table));
3959 
3960   // Delay the setting of _local_interfaces and _transitive_interfaces until after
3961   // initialize_supers() in fill_instance_klass(). It is because the _local_interfaces could
3962   // be shared with _transitive_interfaces and _transitive_interfaces may be shared with
3963   // its _super. If an OOM occurs while loading the current klass, its _super field
3964   // may not have been set. When GC tries to free the klass, the _transitive_interfaces
3965   // may be deallocated mistakenly in InstanceKlass::deallocate_interfaces(). Subsequent
3966   // dereferences to the deallocated _transitive_interfaces will result in a crash.
3967 
3968   // Clear out these fields so they don't get deallocated by the destructor
3969   clear_class_metadata();
3970 }
3971 
3972 AnnotationArray* ClassFileParser::allocate_annotations(const u1* const anno,
3973                                                        int anno_length,
3974                                                        TRAPS) {
3975   AnnotationArray* annotations = nullptr;
3976   if (anno != nullptr) {
3977     annotations = MetadataFactory::new_array<u1>(_loader_data,
3978                                                  anno_length,
3979                                                  CHECK_(annotations));
3980     for (int i = 0; i < anno_length; i++) {
3981       annotations->at_put(i, anno[i]);
3982     }
3983   }
3984   return annotations;
3985 }
3986 
3987 void ClassFileParser::check_super_class(ConstantPool* const cp,
3988                                         const int super_class_index,
3989                                         const bool need_verify,
3990                                         TRAPS) {
3991   assert(cp != nullptr, "invariant");
3992 
3993   if (super_class_index == 0) {
3994     guarantee_property(_class_name == vmSymbols::java_lang_Object(),
3995                        "Invalid superclass index 0 in class file %s",

3996                        CHECK);
3997   } else {
3998     guarantee_property(valid_klass_reference_at(super_class_index),
3999                        "Invalid superclass index %u in class file %s",
4000                        super_class_index,
4001                        CHECK);
4002 
4003     // The class name should be legal because it is checked when parsing constant pool.
4004     // However, make sure it is not an array type.
4005     if (need_verify) {
4006       guarantee_property(cp->klass_name_at(super_class_index)->char_at(0) != JVM_SIGNATURE_ARRAY,
4007                         "Bad superclass name in class file %s", CHECK);
4008     }
4009   }
4010 }
4011 
4012 OopMapBlocksBuilder::OopMapBlocksBuilder(unsigned int max_blocks) {
4013   _max_nonstatic_oop_maps = max_blocks;
4014   _nonstatic_oop_map_count = 0;
4015   if (max_blocks == 0) {

4167   // See documentation of InstanceKlass::can_be_fastpath_allocated().
4168   assert(ik->size_helper() > 0, "layout_helper is initialized");
4169   if (ik->is_abstract() || ik->is_interface()
4170       || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == nullptr)
4171       || ik->size_helper() >= FastAllocateSizeLimit) {
4172     // Forbid fast-path allocation.
4173     const jint lh = Klass::instance_layout_helper(ik->size_helper(), true);
4174     ik->set_layout_helper(lh);
4175   }
4176 
4177   // Propagate the AOT runtimeSetup method discovery
4178   if (_has_aot_runtime_setup_method) {
4179     ik->set_is_runtime_setup_required();
4180     if (log_is_enabled(Info, aot, init)) {
4181       ResourceMark rm;
4182       log_info(aot, init)("Found @AOTRuntimeSetup class %s", ik->external_name());
4183     }
4184   }
4185 }
4186 
4187 bool ClassFileParser::supports_inline_types() const {
4188   // Inline types are only supported by class file version 70.65535 and later
4189   return _major_version > JAVA_26_VERSION ||
4190          (_major_version == JAVA_26_VERSION && _minor_version == JAVA_PREVIEW_MINOR_VERSION);
4191 }
4192 
4193 // utility methods for appending an array with check for duplicates
4194 
4195 static void append_interfaces(GrowableArray<InstanceKlass*>* result,
4196                               const Array<InstanceKlass*>* const ifs) {
4197   // iterate over new interfaces
4198   for (int i = 0; i < ifs->length(); i++) {
4199     InstanceKlass* const e = ifs->at(i);
4200     assert(e->is_klass() && e->is_interface(), "just checking");
4201     // add new interface
4202     result->append_if_missing(e);
4203   }
4204 }
4205 
4206 static Array<InstanceKlass*>* compute_transitive_interfaces(const InstanceKlass* super,
4207                                                             Array<InstanceKlass*>* local_ifs,
4208                                                             ClassLoaderData* loader_data,
4209                                                             TRAPS) {
4210   assert(local_ifs != nullptr, "invariant");
4211   assert(loader_data != nullptr, "invariant");
4212 

4216   // Add superclass transitive interfaces size
4217   if (super != nullptr) {
4218     super_size = super->transitive_interfaces()->length();
4219     max_transitive_size += super_size;
4220   }
4221   // Add local interfaces' super interfaces
4222   const int local_size = local_ifs->length();
4223   for (int i = 0; i < local_size; i++) {
4224     InstanceKlass* const l = local_ifs->at(i);
4225     max_transitive_size += l->transitive_interfaces()->length();
4226   }
4227   // Finally add local interfaces
4228   max_transitive_size += local_size;
4229   // Construct array
4230   if (max_transitive_size == 0) {
4231     // no interfaces, use canonicalized array
4232     return Universe::the_empty_instance_klass_array();
4233   } else if (max_transitive_size == super_size) {
4234     // no new local interfaces added, share superklass' transitive interface array
4235     return super->transitive_interfaces();
4236     // The three lines below are commented to work around bug JDK-8245487
4237 //  } else if (max_transitive_size == local_size) {
4238 //    // only local interfaces added, share local interface array
4239 //    return local_ifs;
4240   } else {
4241     ResourceMark rm;
4242     GrowableArray<InstanceKlass*>* const result = new GrowableArray<InstanceKlass*>(max_transitive_size);
4243 
4244     // Copy down from superclass
4245     if (super != nullptr) {
4246       append_interfaces(result, super->transitive_interfaces());
4247     }
4248 
4249     // Copy down from local interfaces' superinterfaces
4250     for (int i = 0; i < local_size; i++) {
4251       InstanceKlass* const l = local_ifs->at(i);
4252       append_interfaces(result, l->transitive_interfaces());
4253     }
4254     // Finally add local interfaces
4255     append_interfaces(result, local_ifs);
4256 
4257     // length will be less than the max_transitive_size if duplicates were removed
4258     const int length = result->length();
4259     assert(length <= max_transitive_size, "just checking");
4260 
4261     Array<InstanceKlass*>* const new_result =
4262       MetadataFactory::new_array<InstanceKlass*>(loader_data, length, CHECK_NULL);
4263     for (int i = 0; i < length; i++) {
4264       InstanceKlass* const e = result->at(i);
4265       assert(e != nullptr, "just checking");
4266       new_result->at_put(i, e);
4267     }
4268     return new_result;
4269   }
4270 }
4271 
4272 void ClassFileParser::check_super_class_access(const InstanceKlass* this_klass, TRAPS) {
4273   assert(this_klass != nullptr, "invariant");
4274   const InstanceKlass* const super = this_klass->super();
4275 
4276   if (super != nullptr) {
4277     if (super->is_final()) {
4278       classfile_icce_error("class %s cannot inherit from final class %s", super, THREAD);
4279       return;
4280     }
4281 
4282     if (super->is_sealed()) {
4283       stringStream ss;
4284       ResourceMark rm(THREAD);
4285       if (!super->has_as_permitted_subclass(this_klass, ss)) {
4286         classfile_icce_error(ss.as_string(), THREAD);
4287         return;
4288       }
4289     }
4290 
4291     // The JVMS says that super classes for value types must not have the ACC_IDENTITY
4292     // flag set. But, java.lang.Object must still be allowed to be a direct super class
4293     // for a value classes.  So, it is treated as a special case for now.
4294     if (!this_klass->access_flags().is_identity_class() &&
4295         super->name() != vmSymbols::java_lang_Object() &&
4296         super->is_identity_class()) {
4297       classfile_icce_error("value class %s cannot inherit from class %s", super, THREAD);
4298       return;
4299     }
4300 
4301     Reflection::VerifyClassAccessResults vca_result =
4302       Reflection::verify_class_access(this_klass, super, false);
4303     if (vca_result != Reflection::ACCESS_OK) {
4304       ResourceMark rm(THREAD);
4305       char* msg = Reflection::verify_class_access_msg(this_klass,
4306                                                       super,
4307                                                       vca_result);
4308 
4309       // Names are all known to be < 64k so we know this formatted message is not excessively large.
4310       if (msg == nullptr) {
4311         bool same_module = (this_klass->module() == super->module());
4312         Exceptions::fthrow(
4313           THREAD_AND_LOCATION,
4314           vmSymbols::java_lang_IllegalAccessError(),
4315           "class %s cannot access its %ssuperclass %s (%s%s%s)",
4316           this_klass->external_name(),
4317           super->is_abstract() ? "abstract " : "",
4318           super->external_name(),
4319           (same_module) ? this_klass->joint_in_module_of_loader(super) : this_klass->class_in_module_of_loader(),
4320           (same_module) ? "" : "; ",

4473 // Verify the class modifiers for the current class, or an inner class if inner_name is non-null.
4474 void ClassFileParser::verify_legal_class_modifiers(jint flags, Symbol* inner_name, bool is_anonymous_inner_class, TRAPS) const {
4475   const bool is_module = (flags & JVM_ACC_MODULE) != 0;
4476   assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");
4477   if (is_module) {
4478     ResourceMark rm(THREAD);
4479     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4480     Exceptions::fthrow(
4481       THREAD_AND_LOCATION,
4482       vmSymbols::java_lang_NoClassDefFoundError(),
4483       "%s is not a class because access_flag ACC_MODULE is set",
4484       _class_name->as_C_string());
4485     return;
4486   }
4487 
4488   if (!_need_verify) { return; }
4489 
4490   const bool is_interface  = (flags & JVM_ACC_INTERFACE)  != 0;
4491   const bool is_abstract   = (flags & JVM_ACC_ABSTRACT)   != 0;
4492   const bool is_final      = (flags & JVM_ACC_FINAL)      != 0;
4493   const bool is_identity   = (flags & JVM_ACC_IDENTITY)   != 0;
4494   const bool is_enum       = (flags & JVM_ACC_ENUM)       != 0;
4495   const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4496   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4497   const bool valid_value_class = is_identity || is_interface ||
4498                                  (supports_inline_types() && (!is_identity && (is_abstract || is_final)));
4499 
4500   if ((is_abstract && is_final) ||
4501       (is_interface && !is_abstract) ||
4502       (is_interface && major_gte_1_5 && (is_identity || is_enum)) ||   //  ACC_SUPER (now ACC_IDENTITY) was illegal for interfaces
4503       (!is_interface && major_gte_1_5 && is_annotation) ||
4504       (!valid_value_class)) {
4505     ResourceMark rm(THREAD);
4506     const char* class_note = "";
4507     if (!valid_value_class) {
4508       class_note = " (a value class must be final or else abstract)";
4509     }
4510     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4511     if (inner_name == nullptr && !is_anonymous_inner_class) {
4512       Exceptions::fthrow(
4513         THREAD_AND_LOCATION,
4514         vmSymbols::java_lang_ClassFormatError(),
4515         "Illegal class modifiers in class %s: 0x%X",
4516         _class_name->as_C_string(), flags
4517       );
4518     } else {
4519       if (is_anonymous_inner_class) {
4520         Exceptions::fthrow(
4521           THREAD_AND_LOCATION,
4522           vmSymbols::java_lang_ClassFormatError(),
4523           "Illegal class modifiers in anonymous inner class of class %s: 0x%X",
4524           _class_name->as_C_string(), flags
4525         );
4526       } else {
4527         Exceptions::fthrow(
4528           THREAD_AND_LOCATION,
4529           vmSymbols::java_lang_ClassFormatError(),

4583         THREAD_AND_LOCATION,
4584         vmSymbols::java_lang_UnsupportedClassVersionError(),
4585         "%s (class file version %u.%u) was compiled with preview features that are unsupported. "
4586         "This version of the Java Runtime only recognizes preview features for class file version %u.%u",
4587         class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION, JAVA_PREVIEW_MINOR_VERSION);
4588       return;
4589     }
4590 
4591     if (!Arguments::enable_preview()) {
4592       classfile_ucve_error("Preview features are not enabled for %s (class file version %u.%u). Try running with '--enable-preview'",
4593                            class_name, major, minor, THREAD);
4594       return;
4595     }
4596 
4597   } else { // minor != JAVA_PREVIEW_MINOR_VERSION
4598     classfile_ucve_error("%s (class file version %u.%u) was compiled with an invalid non-zero minor version",
4599                          class_name, major, minor, THREAD);
4600   }
4601 }
4602 
4603 void ClassFileParser:: verify_legal_field_modifiers(jint flags,
4604                                                    AccessFlags class_access_flags,
4605                                                    TRAPS) const {
4606   if (!_need_verify) { return; }
4607 
4608   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4609   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4610   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4611   const bool is_static    = (flags & JVM_ACC_STATIC)    != 0;
4612   const bool is_final     = (flags & JVM_ACC_FINAL)     != 0;
4613   const bool is_volatile  = (flags & JVM_ACC_VOLATILE)  != 0;
4614   const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
4615   const bool is_enum      = (flags & JVM_ACC_ENUM)      != 0;
4616   const bool is_strict    = (flags & JVM_ACC_STRICT)    != 0;
4617   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4618 
4619   const bool is_interface = class_access_flags.is_interface();
4620   const bool is_identity_class = class_access_flags.is_identity_class();
4621 
4622   bool is_illegal = false;
4623   const char* error_msg = "";
4624 
4625   // There is some overlap in the checks that apply, for example interface fields
4626   // must be static, static fields can't be strict, and therefore interfaces can't
4627   // have strict fields. So we don't have to check every possible invalid combination
4628   // individually as long as all are covered. Once we have found an illegal combination
4629   // we can stop checking.
4630 
4631   if (!is_illegal) {
4632     if (is_interface) {
4633       if (!is_public || !is_static || !is_final || is_private ||
4634           is_protected || is_volatile || is_transient ||
4635           (major_gte_1_5 && is_enum)) {
4636         is_illegal = true;
4637         error_msg = "interface fields must be public, static and final, and may be synthetic";
4638       }
4639     } else { // not interface
4640       if (has_illegal_visibility(flags)) {
4641         is_illegal = true;
4642         error_msg = "invalid visibility flags for class field";
4643       } else if (is_final && is_volatile) {
4644         is_illegal = true;
4645         error_msg = "fields cannot be final and volatile";
4646       } else if (supports_inline_types()) {
4647         if (!is_identity_class && !is_static && (!is_strict || !is_final)) {
4648           is_illegal = true;
4649           error_msg = "value class fields must be either non-static final and strict, or static";
4650         }
4651       }
4652     }
4653   }
4654 
4655   if (is_illegal) {
4656     ResourceMark rm(THREAD);
4657     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4658     Exceptions::fthrow(
4659       THREAD_AND_LOCATION,
4660       vmSymbols::java_lang_ClassFormatError(),
4661       "Illegal field modifiers (%s) in class %s: 0x%X",
4662       error_msg, _class_name->as_C_string(), flags);
4663     return;
4664   }
4665 }
4666 
4667 void ClassFileParser::verify_legal_method_modifiers(jint flags,
4668                                                     AccessFlags class_access_flags,
4669                                                     const Symbol* name,
4670                                                     TRAPS) const {
4671   if (!_need_verify) { return; }
4672 
4673   const bool is_public       = (flags & JVM_ACC_PUBLIC)       != 0;
4674   const bool is_private      = (flags & JVM_ACC_PRIVATE)      != 0;
4675   const bool is_static       = (flags & JVM_ACC_STATIC)       != 0;
4676   const bool is_final        = (flags & JVM_ACC_FINAL)        != 0;
4677   const bool is_native       = (flags & JVM_ACC_NATIVE)       != 0;
4678   const bool is_abstract     = (flags & JVM_ACC_ABSTRACT)     != 0;
4679   const bool is_bridge       = (flags & JVM_ACC_BRIDGE)       != 0;
4680   const bool is_strict       = (flags & JVM_ACC_STRICT)       != 0;
4681   const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
4682   const bool is_protected    = (flags & JVM_ACC_PROTECTED)    != 0;
4683   const bool major_gte_1_5   = _major_version >= JAVA_1_5_VERSION;
4684   const bool major_gte_8     = _major_version >= JAVA_8_VERSION;
4685   const bool major_gte_17    = _major_version >= JAVA_17_VERSION;
4686   const bool is_initializer  = (name == vmSymbols::object_initializer_name());
4687   // LW401 CR required: removal of value factories support
4688   const bool is_interface    = class_access_flags.is_interface();
4689   const bool is_identity_class = class_access_flags.is_identity_class();
4690   const bool is_abstract_class = class_access_flags.is_abstract();
4691 
4692   bool is_illegal = false;
4693 
4694   const char* class_note = "";
4695   if (is_interface) {
4696     if (major_gte_8) {
4697       // Class file version is JAVA_8_VERSION or later Methods of
4698       // interfaces may set any of the flags except ACC_PROTECTED,
4699       // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must
4700       // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.
4701       if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
4702           (is_native || is_protected || is_final || is_synchronized) ||
4703           // If a specific method of a class or interface has its
4704           // ACC_ABSTRACT flag set, it must not have any of its
4705           // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,
4706           // ACC_STRICT, or ACC_SYNCHRONIZED flags set.  No need to
4707           // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as
4708           // those flags are illegal irrespective of ACC_ABSTRACT being set or not.
4709           (is_abstract && (is_private || is_static || (!major_gte_17 && is_strict)))) {
4710         is_illegal = true;
4711       }
4712     } else if (major_gte_1_5) {
4713       // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)
4714       if (!is_public || is_private || is_protected || is_static || is_final ||
4715           is_synchronized || is_native || !is_abstract || is_strict) {
4716         is_illegal = true;
4717       }
4718     } else {
4719       // Class file version is pre-JAVA_1_5_VERSION
4720       if (!is_public || is_static || is_final || is_native || !is_abstract) {
4721         is_illegal = true;
4722       }
4723     }
4724   } else { // not interface
4725     if (has_illegal_visibility(flags)) {
4726       is_illegal = true;
4727     } else {
4728       if (is_initializer) {
4729         if (is_static || is_final || is_synchronized || is_native ||
4730             is_abstract || (major_gte_1_5 && is_bridge)) {
4731           is_illegal = true;
4732         }
4733       } else { // not initializer
4734         if (!is_identity_class && is_synchronized && !is_static) {
4735           is_illegal = true;
4736           class_note = " (not an identity class)";
4737         } else {
4738           if (is_abstract) {
4739             if ((is_final || is_native || is_private || is_static ||
4740                 (major_gte_1_5 && (is_synchronized || (!major_gte_17 && is_strict))))) {
4741               is_illegal = true;
4742             }
4743           }
4744         }
4745       }
4746     }
4747   }
4748 
4749   if (is_illegal) {
4750     ResourceMark rm(THREAD);
4751     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4752     Exceptions::fthrow(
4753       THREAD_AND_LOCATION,
4754       vmSymbols::java_lang_ClassFormatError(),
4755       "Method %s in class %s%s has illegal modifiers: 0x%X",
4756       name->as_C_string(), _class_name->as_C_string(),
4757       class_note, flags);
4758     return;
4759   }
4760 }
4761 
4762 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer,
4763                                         int length,
4764                                         TRAPS) const {
4765   assert(_need_verify, "only called when _need_verify is true");
4766   // Note: 0 <= length < 64K, as it comes from a u2 entry in the CP.
4767   if (!UTF8::is_legal_utf8(buffer, static_cast<size_t>(length), _major_version <= 47)) {
4768     classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", THREAD);
4769   }
4770 }
4771 
4772 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
4773 // In class names, '/' separates unqualified names.  This is verified in this function also.
4774 // Method names also may not contain the characters '<' or '>', unless <init>
4775 // or <clinit>.  Note that method names may not be <init> or <clinit> in this
4776 // method.  Because these names have been checked as special cases before
4777 // calling this method in verify_legal_method_name.

4795         if (type == ClassFileParser::LegalClass) {
4796           if (p == name || p+1 >= name+length ||
4797               *(p+1) == JVM_SIGNATURE_SLASH) {
4798             return false;
4799           }
4800         } else {
4801           return false;   // do not permit '/' unless it's class name
4802         }
4803         break;
4804       case JVM_SIGNATURE_SPECIAL:
4805       case JVM_SIGNATURE_ENDSPECIAL:
4806         // do not permit '<' or '>' in method names
4807         if (type == ClassFileParser::LegalMethod) {
4808           return false;
4809         }
4810     }
4811   }
4812   return true;
4813 }
4814 
4815 bool ClassFileParser::is_class_in_loadable_descriptors_attribute(Symbol *klass) {
4816   if (_loadable_descriptors == nullptr) return false;
4817   for (int i = 0; i < _loadable_descriptors->length(); i++) {
4818         Symbol* class_name = _cp->symbol_at(_loadable_descriptors->at(i));
4819         if (class_name == klass) return true;
4820   }
4821   return false;
4822 }
4823 
4824 // Take pointer to a UTF8 byte string (not NUL-terminated).
4825 // Skip over the longest part of the string that could
4826 // be taken as a fieldname. Allow non-trailing '/'s if slash_ok is true.
4827 // Return a pointer to just past the fieldname.
4828 // Return null if no fieldname at all was found, or in the case of slash_ok
4829 // being true, we saw consecutive slashes (meaning we were looking for a
4830 // qualified path but found something that was badly-formed).
4831 static const char* skip_over_field_name(const char* const name,
4832                                         bool slash_ok,
4833                                         unsigned int length) {
4834   const char* p;
4835   jboolean last_is_slash = false;
4836   jboolean not_first_ch = false;
4837 
4838   for (p = name; p != name + length; not_first_ch = true) {
4839     const char* old_p = p;
4840     jchar ch = *p;
4841     if (ch < 128) {
4842       p++;
4843       // quick check for ascii

4905 // be taken as a field signature. Allow "void" if void_ok.
4906 // Return a pointer to just past the signature.
4907 // Return null if no legal signature is found.
4908 const char* ClassFileParser::skip_over_field_signature(const char* signature,
4909                                                        bool void_ok,
4910                                                        unsigned int length,
4911                                                        TRAPS) const {
4912   unsigned int array_dim = 0;
4913   while (length > 0) {
4914     switch (signature[0]) {
4915     case JVM_SIGNATURE_VOID: if (!void_ok) { return nullptr; }
4916     case JVM_SIGNATURE_BOOLEAN:
4917     case JVM_SIGNATURE_BYTE:
4918     case JVM_SIGNATURE_CHAR:
4919     case JVM_SIGNATURE_SHORT:
4920     case JVM_SIGNATURE_INT:
4921     case JVM_SIGNATURE_FLOAT:
4922     case JVM_SIGNATURE_LONG:
4923     case JVM_SIGNATURE_DOUBLE:
4924       return signature + 1;
4925     case JVM_SIGNATURE_CLASS:
4926     {
4927       if (_major_version < JAVA_1_5_VERSION) {
4928         signature++;
4929         length--;
4930         // Skip over the class name if one is there
4931         const char* const p = skip_over_field_name(signature, true, length);
4932         assert(p == nullptr || p > signature, "must parse one character at least");
4933         // The next character better be a semicolon
4934         if (p != nullptr                             && // Parse of field name succeeded.
4935             p - signature < static_cast<int>(length) && // There is at least one character left to parse.
4936             p[0] == JVM_SIGNATURE_ENDCLASS) {
4937           return p + 1;
4938         }
4939       }
4940       else {
4941         // Skip leading 'L' or 'Q' and ignore first appearance of ';'
4942         signature++;
4943         const char* c = (const char*) memchr(signature, JVM_SIGNATURE_ENDCLASS, length - 1);
4944         // Format check signature
4945         if (c != nullptr) {
4946           int newlen = pointer_delta_as_int(c, (char*) signature);
4947           bool legal = verify_unqualified_name(signature, newlen, LegalClass);
4948           if (!legal) {
4949             classfile_parse_error("Class name is empty or contains illegal character "
4950                                   "in descriptor in class file %s",
4951                                   THREAD);
4952             return nullptr;
4953           }
4954           return signature + newlen + 1;
4955         }
4956       }
4957       return nullptr;
4958     }
4959     case JVM_SIGNATURE_ARRAY:
4960       array_dim++;
4961       if (array_dim > 255) {

4977 
4978 // Checks if name is a legal class name.
4979 void ClassFileParser::verify_legal_class_name(const Symbol* name, TRAPS) const {
4980   if (!_need_verify) { return; }
4981 
4982   assert(name->refcount() > 0, "symbol must be kept alive");
4983   char* bytes = (char*)name->bytes();
4984   unsigned int length = name->utf8_length();
4985   bool legal = false;
4986 
4987   if (length > 0) {
4988     const char* p;
4989     if (bytes[0] == JVM_SIGNATURE_ARRAY) {
4990       p = skip_over_field_signature(bytes, false, length, CHECK);
4991       legal = (p != nullptr) && ((p - bytes) == (int)length);
4992     } else if (_major_version < JAVA_1_5_VERSION) {
4993       if (bytes[0] != JVM_SIGNATURE_SPECIAL) {
4994         p = skip_over_field_name(bytes, true, length);
4995         legal = (p != nullptr) && ((p - bytes) == (int)length);
4996       }
4997     } else if ((_major_version >= CONSTANT_CLASS_DESCRIPTORS || _class_name->starts_with("jdk/internal/reflect/"))
4998                    && bytes[length - 1] == ';' ) {
4999       // Support for L...; descriptors
5000       legal = verify_unqualified_name(bytes + 1, length - 2, LegalClass);
5001     } else {
5002       // 4900761: relax the constraints based on JSR202 spec
5003       // Class names may be drawn from the entire Unicode character set.
5004       // Identifiers between '/' must be unqualified names.
5005       // The utf8 string has been verified when parsing cpool entries.
5006       legal = verify_unqualified_name(bytes, length, LegalClass);
5007     }
5008   }
5009   if (!legal) {
5010     ResourceMark rm(THREAD);
5011     assert(_class_name != nullptr, "invariant");
5012     // Names are all known to be < 64k so we know this formatted message is not excessively large.
5013     Exceptions::fthrow(
5014       THREAD_AND_LOCATION,
5015       vmSymbols::java_lang_ClassFormatError(),
5016       "Illegal class name \"%.*s\" in class file %s", length, bytes,
5017       _class_name->as_C_string()
5018     );
5019     return;
5020   }

5048       THREAD_AND_LOCATION,
5049       vmSymbols::java_lang_ClassFormatError(),
5050       "Illegal field name \"%.*s\" in class %s", length, bytes,
5051       _class_name->as_C_string()
5052     );
5053     return;
5054   }
5055 }
5056 
5057 // Checks if name is a legal method name.
5058 void ClassFileParser::verify_legal_method_name(const Symbol* name, TRAPS) const {
5059   if (!_need_verify) { return; }
5060 
5061   assert(name != nullptr, "method name is null");
5062   char* bytes = (char*)name->bytes();
5063   unsigned int length = name->utf8_length();
5064   bool legal = false;
5065 
5066   if (length > 0) {
5067     if (bytes[0] == JVM_SIGNATURE_SPECIAL) {
5068       if (name == vmSymbols::object_initializer_name() ||
5069           name == vmSymbols::class_initializer_name()) {
5070         legal = true;
5071       }
5072     } else if (_major_version < JAVA_1_5_VERSION) {
5073       const char* p;
5074       p = skip_over_field_name(bytes, false, length);
5075       legal = (p != nullptr) && ((p - bytes) == (int)length);
5076     } else {
5077       // 4881221: relax the constraints based on JSR202 spec
5078       legal = verify_unqualified_name(bytes, length, LegalMethod);
5079     }
5080   }
5081 
5082   if (!legal) {
5083     ResourceMark rm(THREAD);
5084     assert(_class_name != nullptr, "invariant");
5085     // Names are all known to be < 64k so we know this formatted message is not excessively large.
5086     Exceptions::fthrow(
5087       THREAD_AND_LOCATION,
5088       vmSymbols::java_lang_ClassFormatError(),
5089       "Illegal method name \"%.*s\" in class %s", length, bytes,
5090       _class_name->as_C_string()
5091     );
5092     return;
5093   }
5094 }
5095 
5096 bool ClassFileParser::legal_field_signature(const Symbol* signature, TRAPS) const {
5097   const char* const bytes = (const char*)signature->bytes();
5098   const unsigned int length = signature->utf8_length();
5099   const char* const p = skip_over_field_signature(bytes, false, length, CHECK_false);
5100 
5101   if (p == nullptr || (p - bytes) != (int)length) {
5102     return false;
5103   }
5104   return true;
5105 }
5106 
5107 // Checks if signature is a legal field signature.
5108 void ClassFileParser::verify_legal_field_signature(const Symbol* name,
5109                                                    const Symbol* signature,
5110                                                    TRAPS) const {
5111   if (!_need_verify) { return; }
5112 
5113   const char* const bytes = (const char*)signature->bytes();
5114   const unsigned int length = signature->utf8_length();
5115   const char* const p = skip_over_field_signature(bytes, false, length, CHECK);
5116 
5117   if (p == nullptr || (p - bytes) != (int)length) {
5118     throwIllegalSignature("Field", name, signature, CHECK);
5119   }
5120 }
5121 
5122 // Check that the signature is compatible with the method name.  For example,
5123 // check that <init> has a void signature.
5124 void ClassFileParser::verify_legal_name_with_signature(const Symbol* name,
5125                                                        const Symbol* signature,
5126                                                        TRAPS) const {
5127   if (!_need_verify) {
5128     return;
5129   }
5130 
5131   // Class initializers cannot have args for class format version >= 51.
5132   if (name == vmSymbols::class_initializer_name() &&
5133       signature != vmSymbols::void_method_signature() &&
5134       _major_version >= JAVA_7_VERSION) {
5135     throwIllegalSignature("Method", name, signature, THREAD);
5136     return;
5137   }
5138 
5139   int sig_length = signature->utf8_length();
5140   if (name->utf8_length() > 0 &&
5141     name->char_at(0) == JVM_SIGNATURE_SPECIAL &&
5142     sig_length > 0 &&
5143     signature->char_at(sig_length - 1) != JVM_SIGNATURE_VOID) {
5144     throwIllegalSignature("Method", name, signature, THREAD);
5145   }
5146 }
5147 
5148 // Checks if signature is a legal method signature.
5149 // Returns number of parameters
5150 int ClassFileParser::verify_legal_method_signature(const Symbol* name,
5151                                                    const Symbol* signature,
5152                                                    TRAPS) const {
5153   if (!_need_verify) {
5154     // make sure caller's args_size will be less than 0 even for non-static
5155     // method so it will be recomputed in compute_size_of_parameters().
5156     return -2;
5157   }
5158 
5159   unsigned int args_size = 0;
5160   const char* p = (const char*)signature->bytes();
5161   unsigned int length = signature->utf8_length();
5162   const char* nextp;
5163 

5174       length -= pointer_delta_as_int(nextp, p);
5175       p = nextp;
5176       nextp = skip_over_field_signature(p, false, length, CHECK_0);
5177     }
5178     // The first non-signature thing better be a ')'
5179     if ((length > 0) && (*p++ == JVM_SIGNATURE_ENDFUNC)) {
5180       length--;
5181       // Now we better just have a return value
5182       nextp = skip_over_field_signature(p, true, length, CHECK_0);
5183       if (nextp && ((int)length == (nextp - p))) {
5184         return args_size;
5185       }
5186     }
5187   }
5188   // Report error
5189   throwIllegalSignature("Method", name, signature, THREAD);
5190   return 0;
5191 }
5192 
5193 int ClassFileParser::static_field_size() const {
5194   assert(_layout_info != nullptr, "invariant");
5195   return _layout_info->_static_field_size;
5196 }
5197 
5198 int ClassFileParser::total_oop_map_count() const {
5199   assert(_layout_info != nullptr, "invariant");
5200   return _layout_info->oop_map_blocks->_nonstatic_oop_map_count;
5201 }
5202 
5203 jint ClassFileParser::layout_size() const {
5204   assert(_layout_info != nullptr, "invariant");
5205   return _layout_info->_instance_size;
5206 }
5207 
5208 static void check_methods_for_intrinsics(const InstanceKlass* ik,
5209                                          const Array<Method*>* methods) {
5210   assert(ik != nullptr, "invariant");
5211   assert(methods != nullptr, "invariant");
5212 
5213   // Set up Method*::intrinsic_id as soon as we know the names of methods.
5214   // (We used to do this lazily, but now we query it in Rewriter,
5215   // which is eagerly done for every method, so we might as well do it now,
5216   // when everything is fresh in memory.)
5217   const vmSymbolID klass_id = Method::klass_id_for_intrinsics(ik);
5218 
5219   if (klass_id != vmSymbolID::NO_SID) {
5220     for (int j = 0; j < methods->length(); ++j) {
5221       Method* method = methods->at(j);
5222       method->init_intrinsic_id(klass_id);
5223 
5224       if (CheckIntrinsics) {
5225         // Check if an intrinsic is defined for method 'method',

5300   }
5301 }
5302 
5303 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook,
5304                                                       const ClassInstanceInfo& cl_inst_info,
5305                                                       TRAPS) {
5306   if (_klass != nullptr) {
5307     return _klass;
5308   }
5309 
5310   InstanceKlass* const ik =
5311     InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
5312 
5313   if (is_hidden()) {
5314     mangle_hidden_class_name(ik);
5315   }
5316 
5317   fill_instance_klass(ik, changed_by_loadhook, cl_inst_info, CHECK_NULL);
5318 
5319   assert(_klass == ik, "invariant");

5320   return ik;
5321 }
5322 
5323 void ClassFileParser::fill_instance_klass(InstanceKlass* ik,
5324                                           bool changed_by_loadhook,
5325                                           const ClassInstanceInfo& cl_inst_info,
5326                                           TRAPS) {
5327   assert(ik != nullptr, "invariant");
5328 
5329   // Set name and CLD before adding to CLD
5330   ik->set_class_loader_data(_loader_data);
5331   ik->set_class_loader_type();
5332   ik->set_name(_class_name);
5333 
5334   // Add all classes to our internal class loader list here,
5335   // including classes in the bootstrap (null) class loader.
5336   const bool publicize = !is_internal();
5337 
5338   _loader_data->add_class(ik, publicize);
5339 
5340   set_klass_to_deallocate(ik);
5341 
5342   assert(_layout_info != nullptr, "invariant");
5343   assert(ik->static_field_size() == _layout_info->_static_field_size, "sanity");
5344   assert(ik->nonstatic_oop_map_count() == _layout_info->oop_map_blocks->_nonstatic_oop_map_count,
5345          "sanity");
5346 
5347   assert(ik->is_instance_klass(), "sanity");
5348   assert(ik->size_helper() == _layout_info->_instance_size, "sanity");
5349 
5350   // Fill in information already parsed
5351   ik->set_should_verify_class(_need_verify);
5352 
5353   // Not yet: supers are done below to support the new subtype-checking fields
5354   ik->set_nonstatic_field_size(_layout_info->_nonstatic_field_size);
5355   ik->set_has_nonstatic_fields(_layout_info->_has_nonstatic_fields);
5356   ik->set_has_strict_static_fields(_has_strict_static_fields);
5357 
5358   if (_layout_info->_is_naturally_atomic) {
5359     ik->set_is_naturally_atomic();
5360   }
5361 
5362   if (_layout_info->_must_be_atomic) {
5363     ik->set_must_be_atomic();
5364   }
5365 
5366   ik->set_static_oop_field_count(_static_oop_count);
5367 
5368   // this transfers ownership of a lot of arrays from
5369   // the parser onto the InstanceKlass*
5370   apply_parsed_class_metadata(ik, _java_fields_count);
5371   if (ik->is_inline_klass()) {
5372     InlineKlass::cast(ik)->init_fixed_block();
5373   }
5374 
5375   // can only set dynamic nest-host after static nest information is set
5376   if (cl_inst_info.dynamic_nest_host() != nullptr) {
5377     ik->set_nest_host(cl_inst_info.dynamic_nest_host());
5378   }
5379 
5380   // note that is not safe to use the fields in the parser from this point on
5381   assert(nullptr == _cp, "invariant");
5382   assert(nullptr == _fieldinfo_stream, "invariant");
5383   assert(nullptr == _fieldinfo_search_table, "invariant");
5384   assert(nullptr == _fields_status, "invariant");
5385   assert(nullptr == _methods, "invariant");
5386   assert(nullptr == _inner_classes, "invariant");
5387   assert(nullptr == _nest_members, "invariant");
5388   assert(nullptr == _loadable_descriptors, "invariant");
5389   assert(nullptr == _combined_annotations, "invariant");
5390   assert(nullptr == _record_components, "invariant");
5391   assert(nullptr == _permitted_subclasses, "invariant");
5392   assert(nullptr == _inline_layout_info_array, "invariant");
5393 
5394   if (_has_localvariable_table) {
5395     ik->set_has_localvariable_table(true);
5396   }
5397 
5398   if (_has_final_method) {
5399     ik->set_has_final_method();
5400   }
5401 
5402   ik->copy_method_ordering(_method_ordering, CHECK);
5403   // The InstanceKlass::_methods_jmethod_ids cache
5404   // is managed on the assumption that the initial cache
5405   // size is equal to the number of methods in the class. If
5406   // that changes, then InstanceKlass::idnum_can_increment()
5407   // has to be changed accordingly.
5408   ik->set_initial_method_idnum(checked_cast<u2>(ik->methods()->length()));
5409 
5410   ik->set_this_class_index(_this_class_index);
5411 
5412   if (_is_hidden) {

5449   if ((_num_miranda_methods > 0) ||
5450       // if this class introduced new miranda methods or
5451       (_super_klass != nullptr && _super_klass->has_miranda_methods())
5452         // super class exists and this class inherited miranda methods
5453      ) {
5454        ik->set_has_miranda_methods(); // then set a flag
5455   }
5456 
5457   // Fill in information needed to compute superclasses.
5458   ik->initialize_supers(const_cast<InstanceKlass*>(_super_klass), _transitive_interfaces, CHECK);
5459   ik->set_transitive_interfaces(_transitive_interfaces);
5460   ik->set_local_interfaces(_local_interfaces);
5461   _transitive_interfaces = nullptr;
5462   _local_interfaces = nullptr;
5463 
5464   // Initialize itable offset tables
5465   klassItable::setup_itable_offset_table(ik);
5466 
5467   // Compute transitive closure of interfaces this class implements
5468   // Do final class setup
5469   OopMapBlocksBuilder* oop_map_blocks = _layout_info->oop_map_blocks;
5470   if (oop_map_blocks->_nonstatic_oop_map_count > 0) {
5471     oop_map_blocks->copy(ik->start_of_nonstatic_oop_maps());
5472   }
5473 
5474   if (_has_contended_fields || _parsed_annotations->is_contended() ||
5475       ( _super_klass != nullptr && _super_klass->has_contended_annotations())) {
5476     ik->set_has_contended_annotations(true);
5477   }
5478 
5479   // Fill in has_finalizer and layout_helper
5480   set_precomputed_flags(ik);
5481 
5482   // check if this class can access its super class
5483   check_super_class_access(ik, CHECK);
5484 
5485   // check if this class can access its superinterfaces
5486   check_super_interface_access(ik, CHECK);
5487 
5488   // check if this class overrides any final method
5489   check_final_method_override(ik, CHECK);

5510 
5511   assert(_all_mirandas != nullptr, "invariant");
5512 
5513   // Generate any default methods - default methods are public interface methods
5514   // that have a default implementation.  This is new with Java 8.
5515   if (_has_nonstatic_concrete_methods) {
5516     DefaultMethods::generate_default_methods(ik,
5517                                              _all_mirandas,
5518                                              CHECK);
5519   }
5520 
5521   // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5522   if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5523       !module_entry->has_default_read_edges()) {
5524     if (!module_entry->set_has_default_read_edges()) {
5525       // We won a potential race
5526       JvmtiExport::add_default_read_edges(module_handle, THREAD);
5527     }
5528   }
5529 
5530   if (is_inline_type()) {
5531     InlineKlass* vk = InlineKlass::cast(ik);
5532     vk->set_payload_alignment(_layout_info->_payload_alignment);
5533     vk->set_payload_offset(_layout_info->_payload_offset);
5534     vk->set_payload_size_in_bytes(_layout_info->_payload_size_in_bytes);
5535     vk->set_non_atomic_size_in_bytes(_layout_info->_non_atomic_size_in_bytes);
5536     vk->set_non_atomic_alignment(_layout_info->_non_atomic_alignment);
5537     vk->set_atomic_size_in_bytes(_layout_info->_atomic_layout_size_in_bytes);
5538     vk->set_nullable_size_in_bytes(_layout_info->_nullable_layout_size_in_bytes);
5539     vk->set_null_marker_offset(_layout_info->_null_marker_offset);
5540     vk->set_null_reset_value_offset(_layout_info->_null_reset_value_offset);
5541     if (_layout_info->_is_empty_inline_klass) vk->set_is_empty_inline_type();
5542     vk->initialize_calling_convention(CHECK);
5543   }
5544 
5545   if (EnableValhalla && !access_flags().is_identity_class() && !access_flags().is_interface()
5546       && _class_name != vmSymbols::java_lang_Object() && UseAltSubstitutabilityMethod) {
5547     // Both abstract and concrete value classes need a field map for acmp
5548     ik->set_acmp_maps_offset(_layout_info->_acmp_maps_offset);
5549     // Current format of acmp maps:
5550     // All maps are stored contiguously in a single int array because it might
5551     // be too early to instantiate an Object array (to be investigated)
5552     // Format is:
5553     // [number_of_nonoop_entries][offset0][size[0][offset1][size1]...[oop_offset0][oop_offset1]...
5554     //                           ^               ^
5555     //                           |               |
5556     //                           --------------------- Pair of integer describing a segment of
5557     //                                                 contiguous non-oop fields
5558     // First element is the number of segment of contiguous non-oop fields
5559     // Then, each segment of contiguous non-oop fields is described by two consecutive elements:
5560     // the offset then the size.
5561     // After the last segment of contiguous non-oop fields, oop fields are described, one element
5562     // per oop field, containing the offset of the field.
5563     int nonoop_acmp_map_size = _layout_info->_nonoop_acmp_map->length() * 2;
5564     int oop_acmp_map_size = _layout_info->_oop_acmp_map->length();
5565     typeArrayOop map = oopFactory::new_intArray(nonoop_acmp_map_size + oop_acmp_map_size + 1, CHECK);
5566     typeArrayHandle map_h(THREAD, map);
5567     map_h->int_at_put(0, _layout_info->_nonoop_acmp_map->length());
5568     for (int i = 0; i < _layout_info->_nonoop_acmp_map->length(); i++) {
5569       map_h->int_at_put(i * 2 + 1, _layout_info->_nonoop_acmp_map->at(i).first);
5570       map_h->int_at_put(i * 2 + 2, _layout_info->_nonoop_acmp_map->at(i).second);
5571     }
5572     int oop_map_start = nonoop_acmp_map_size + 1;
5573     for (int i = 0; i < _layout_info->_oop_acmp_map->length(); i++) {
5574       map_h->int_at_put(oop_map_start + i, _layout_info->_oop_acmp_map->at(i));
5575     }
5576     ik->java_mirror()->obj_field_put(ik->acmp_maps_offset(), map_h());
5577   }
5578 
5579   ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5580 
5581   if (!is_internal()) {
5582     ik->print_class_load_logging(_loader_data, module_entry, _stream);
5583 
5584     if (ik->minor_version() == JAVA_PREVIEW_MINOR_VERSION &&
5585         ik->major_version() == JVM_CLASSFILE_MAJOR_VERSION &&
5586         log_is_enabled(Info, class, preview)) {
5587       ResourceMark rm;
5588       log_info(class, preview)("Loading class %s that depends on preview features (class file version %d.65535)",
5589                                ik->external_name(), JVM_CLASSFILE_MAJOR_VERSION);
5590     }
5591 
5592     if (log_is_enabled(Debug, class, resolve))  {
5593       ResourceMark rm;
5594       // print out the superclass.
5595       const char * from = ik->external_name();
5596       if (ik->super() != nullptr) {
5597         log_debug(class, resolve)("%s %s (super)",
5598                    from,

5641                                  const ClassLoadInfo* cl_info,
5642                                  Publicity pub_level,
5643                                  TRAPS) :
5644   _stream(stream),
5645   _class_name(nullptr),
5646   _loader_data(loader_data),
5647   _is_hidden(cl_info->is_hidden()),
5648   _can_access_vm_annotations(cl_info->can_access_vm_annotations()),
5649   _orig_cp_size(0),
5650   _static_oop_count(0),
5651   _super_klass(),
5652   _cp(nullptr),
5653   _fieldinfo_stream(nullptr),
5654   _fieldinfo_search_table(nullptr),
5655   _fields_status(nullptr),
5656   _methods(nullptr),
5657   _inner_classes(nullptr),
5658   _nest_members(nullptr),
5659   _nest_host(0),
5660   _permitted_subclasses(nullptr),
5661   _loadable_descriptors(nullptr),
5662   _record_components(nullptr),
5663   _local_interfaces(nullptr),
5664   _local_interface_indexes(nullptr),
5665   _transitive_interfaces(nullptr),
5666   _combined_annotations(nullptr),
5667   _class_annotations(nullptr),
5668   _class_type_annotations(nullptr),
5669   _fields_annotations(nullptr),
5670   _fields_type_annotations(nullptr),
5671   _klass(nullptr),
5672   _klass_to_deallocate(nullptr),
5673   _parsed_annotations(nullptr),
5674   _layout_info(nullptr),
5675   _inline_layout_info_array(nullptr),
5676   _temp_field_info(nullptr),
5677   _method_ordering(nullptr),
5678   _all_mirandas(nullptr),
5679   _vtable_size(0),
5680   _itable_size(0),
5681   _num_miranda_methods(0),
5682   _protection_domain(cl_info->protection_domain()),
5683   _access_flags(),
5684   _pub_level(pub_level),
5685   _bad_constant_seen(0),
5686   _synthetic_flag(false),
5687   _sde_length(false),
5688   _sde_buffer(nullptr),
5689   _sourcefile_index(0),
5690   _generic_signature_index(0),
5691   _major_version(0),
5692   _minor_version(0),
5693   _this_class_index(0),
5694   _super_class_index(0),
5695   _itfs_len(0),
5696   _java_fields_count(0),
5697   _need_verify(false),
5698   _has_nonstatic_concrete_methods(false),
5699   _declares_nonstatic_concrete_methods(false),
5700   _has_localvariable_table(false),
5701   _has_final_method(false),
5702   _has_contended_fields(false),
5703   _has_aot_runtime_setup_method(false),
5704   _has_strict_static_fields(false),
5705   _has_inline_type_fields(false),
5706   _is_naturally_atomic(false),
5707   _must_be_atomic(true),
5708   _has_loosely_consistent_annotation(false),
5709   _has_finalizer(false),
5710   _has_empty_finalizer(false),
5711   _max_bootstrap_specifier_index(-1) {
5712 
5713   _class_name = name != nullptr ? name : vmSymbols::unknown_class_name();
5714   _class_name->increment_refcount();
5715 
5716   assert(_loader_data != nullptr, "invariant");
5717   assert(stream != nullptr, "invariant");
5718   assert(_stream != nullptr, "invariant");
5719   assert(_stream->buffer() == _stream->current(), "invariant");
5720   assert(_class_name != nullptr, "invariant");
5721   assert(0 == _access_flags.as_unsigned_short(), "invariant");
5722 
5723   // Figure out whether we can skip format checking (matching classic VM behavior)
5724   // Always verify CFLH bytes from the user agents.
5725   _need_verify = stream->from_class_file_load_hook() ? true : Verifier::should_verify_for(_loader_data->class_loader());
5726 
5727   // synch back verification state to stream to check for truncation.
5728   stream->set_need_verify(_need_verify);
5729 
5730   parse_stream(stream, CHECK);
5731 
5732   post_process_parsed_stream(stream, _cp, CHECK);
5733 }
5734 
5735 void ClassFileParser::clear_class_metadata() {
5736   // metadata created before the instance klass is created.  Must be
5737   // deallocated if classfile parsing returns an error.
5738   _cp = nullptr;
5739   _fieldinfo_stream = nullptr;
5740   _fieldinfo_search_table = nullptr;
5741   _fields_status = nullptr;
5742   _methods = nullptr;
5743   _inner_classes = nullptr;
5744   _nest_members = nullptr;
5745   _permitted_subclasses = nullptr;
5746   _loadable_descriptors = nullptr;
5747   _combined_annotations = nullptr;
5748   _class_annotations = _class_type_annotations = nullptr;
5749   _fields_annotations = _fields_type_annotations = nullptr;
5750   _record_components = nullptr;
5751   _inline_layout_info_array = nullptr;
5752 }
5753 
5754 // Destructor to clean up
5755 ClassFileParser::~ClassFileParser() {
5756   _class_name->decrement_refcount();
5757 
5758   if (_cp != nullptr) {
5759     MetadataFactory::free_metadata(_loader_data, _cp);
5760   }
5761 
5762   if (_fieldinfo_stream != nullptr) {
5763     MetadataFactory::free_array<u1>(_loader_data, _fieldinfo_stream);
5764   }
5765   MetadataFactory::free_array<u1>(_loader_data, _fieldinfo_search_table);
5766 
5767   if (_fields_status != nullptr) {
5768     MetadataFactory::free_array<FieldStatus>(_loader_data, _fields_status);
5769   }
5770 
5771   if (_inline_layout_info_array != nullptr) {
5772     MetadataFactory::free_array<InlineLayoutInfo>(_loader_data, _inline_layout_info_array);
5773   }
5774 
5775   if (_methods != nullptr) {
5776     // Free methods
5777     InstanceKlass::deallocate_methods(_loader_data, _methods);
5778   }
5779 
5780   // beware of the Universe::empty_blah_array!!
5781   if (_inner_classes != nullptr && _inner_classes != Universe::the_empty_short_array()) {
5782     MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
5783   }
5784 
5785   if (_nest_members != nullptr && _nest_members != Universe::the_empty_short_array()) {
5786     MetadataFactory::free_array<u2>(_loader_data, _nest_members);
5787   }
5788 
5789   if (_record_components != nullptr) {
5790     InstanceKlass::deallocate_record_components(_loader_data, _record_components);
5791   }
5792 
5793   if (_permitted_subclasses != nullptr && _permitted_subclasses != Universe::the_empty_short_array()) {
5794     MetadataFactory::free_array<u2>(_loader_data, _permitted_subclasses);
5795   }
5796 
5797   if (_loadable_descriptors != nullptr && _loadable_descriptors != Universe::the_empty_short_array()) {
5798     MetadataFactory::free_array<u2>(_loader_data, _loadable_descriptors);
5799   }
5800 
5801   // Free interfaces
5802   InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
5803                                        _local_interfaces, _transitive_interfaces);
5804 
5805   if (_combined_annotations != nullptr) {
5806     // After all annotations arrays have been created, they are installed into the
5807     // Annotations object that will be assigned to the InstanceKlass being created.
5808 
5809     // Deallocate the Annotations object and the installed annotations arrays.
5810     _combined_annotations->deallocate_contents(_loader_data);
5811 
5812     // If the _combined_annotations pointer is non-null,
5813     // then the other annotations fields should have been cleared.
5814     assert(_class_annotations       == nullptr, "Should have been cleared");
5815     assert(_class_type_annotations  == nullptr, "Should have been cleared");
5816     assert(_fields_annotations      == nullptr, "Should have been cleared");
5817     assert(_fields_type_annotations == nullptr, "Should have been cleared");
5818   } else {
5819     // If the annotations arrays were not installed into the Annotations object,
5820     // then they have to be deallocated explicitly.

5879 
5880   assert(cp_size == (u2)cp->length(), "invariant");
5881 
5882   // ACCESS FLAGS
5883   stream->guarantee_more(8, CHECK);  // flags, this_class, super_class, infs_len
5884 
5885   // Access flags
5886   u2 flags;
5887   // JVM_ACC_MODULE is defined in JDK-9 and later.
5888   if (_major_version >= JAVA_9_VERSION) {
5889     flags = stream->get_u2_fast() & (JVM_RECOGNIZED_CLASS_MODIFIERS | JVM_ACC_MODULE);
5890   } else {
5891     flags = stream->get_u2_fast() & JVM_RECOGNIZED_CLASS_MODIFIERS;
5892   }
5893 
5894   if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
5895     // Set abstract bit for old class files for backward compatibility
5896     flags |= JVM_ACC_ABSTRACT;
5897   }
5898 
5899   // Fixing ACC_SUPER/ACC_IDENTITY for old class files
5900   if (!supports_inline_types()) {
5901     const bool is_module = (flags & JVM_ACC_MODULE) != 0;
5902     const bool is_interface = (flags & JVM_ACC_INTERFACE) != 0;
5903     if (!is_module && !is_interface) {
5904       flags |= JVM_ACC_IDENTITY;
5905     }
5906   }
5907 
5908   verify_legal_class_modifiers(flags, nullptr, false, CHECK);
5909 
5910   short bad_constant = class_bad_constant_seen();
5911   if (bad_constant != 0) {
5912     // Do not throw CFE until after the access_flags are checked because if
5913     // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
5914     classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, THREAD);
5915     return;
5916   }
5917 
5918   _access_flags.set_flags(flags);
5919 
5920   // This class and superclass
5921   _this_class_index = stream->get_u2_fast();
5922   guarantee_property(
5923     valid_cp_range(_this_class_index, cp_size) &&
5924       cp->tag_at(_this_class_index).is_unresolved_klass(),
5925     "Invalid this class index %u in constant pool in class file %s",
5926     _this_class_index, CHECK);
5927 

5991       }
5992       ls.cr();
5993     }
5994   }
5995 
5996   // SUPERKLASS
5997   _super_class_index = stream->get_u2_fast();
5998   check_super_class(cp,
5999                     _super_class_index,
6000                     _need_verify,
6001                     CHECK);
6002 
6003   // Interfaces
6004   _itfs_len = stream->get_u2_fast();
6005   parse_interfaces(stream,
6006                    _itfs_len,
6007                    cp,
6008                    &_has_nonstatic_concrete_methods,
6009                    CHECK);
6010 


6011   // Fields (offsets are filled in later)
6012   parse_fields(stream,
6013                _access_flags,
6014                cp,
6015                cp_size,
6016                &_java_fields_count,
6017                CHECK);
6018 
6019   assert(_temp_field_info != nullptr, "invariant");
6020 
6021   // Methods
6022   parse_methods(stream,
6023                 is_interface(),
6024                 !is_identity_class(),
6025                 is_abstract_class(),
6026                 &_has_localvariable_table,
6027                 &_has_final_method,
6028                 &_declares_nonstatic_concrete_methods,
6029                 CHECK);
6030 
6031   assert(_methods != nullptr, "invariant");
6032 
6033   if (_declares_nonstatic_concrete_methods) {
6034     _has_nonstatic_concrete_methods = true;
6035   }
6036 
6037   // Additional attributes/annotations
6038   _parsed_annotations = new ClassAnnotationCollector();
6039   parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK);
6040 
6041   assert(_inner_classes != nullptr, "invariant");
6042 
6043   // Finalize the Annotations metadata object,
6044   // now that all annotation arrays have been created.
6045   create_combined_annotations(CHECK);

6093 }
6094 
6095 void ClassFileParser::post_process_parsed_stream(const ClassFileStream* const stream,
6096                                                  ConstantPool* cp,
6097                                                  TRAPS) {
6098   assert(stream != nullptr, "invariant");
6099   assert(stream->at_eos(), "invariant");
6100   assert(cp != nullptr, "invariant");
6101   assert(_loader_data != nullptr, "invariant");
6102 
6103   if (_class_name == vmSymbols::java_lang_Object()) {
6104     precond(_super_class_index == 0);
6105     precond(_super_klass == nullptr);
6106     guarantee_property(_local_interfaces == Universe::the_empty_instance_klass_array(),
6107                        "java.lang.Object cannot implement an interface in class file %s",
6108                        CHECK);
6109   } else {
6110     // Set _super_klass after class file is parsed and format is checked
6111     assert(_super_class_index > 0, "any class other than Object must have a super class");
6112     Symbol* const super_class_name = cp->klass_name_at(_super_class_index);
6113     if (is_interface()) {
6114       // Before attempting to resolve the superclass, check for class format
6115       // errors not checked yet.
6116       guarantee_property(super_class_name == vmSymbols::java_lang_Object(),
6117         "Interfaces must have java.lang.Object as superclass in class file %s",
6118         CHECK);
6119     }
6120     Handle loader(THREAD, _loader_data->class_loader());
6121     if (loader.is_null() && super_class_name == vmSymbols::java_lang_Object()) {
6122       // fast path to avoid lookup
6123       _super_klass = vmClasses::Object_klass();
6124     } else {
6125       _super_klass = (const InstanceKlass*)
6126                        SystemDictionary::resolve_super_or_fail(_class_name,
6127                                                                super_class_name,
6128                                                                loader,
6129                                                                true,
6130                                                                CHECK);
6131     }
6132   }
6133 
6134   if (_super_klass != nullptr) {
6135     if (_super_klass->is_interface()) {
6136       classfile_icce_error("class %s has interface %s as super class", _super_klass, THREAD);
6137       return;
6138     }
6139 
6140     if (_super_klass->is_final()) {
6141       classfile_icce_error("class %s cannot inherit from final class %s", _super_klass, THREAD);
6142       return;
6143     }
6144 
6145     if (EnableValhalla) {
6146       check_identity_and_value_modifiers(this, _super_klass, CHECK);
6147     }
6148 
6149     if (_super_klass->has_nonstatic_concrete_methods()) {
6150       _has_nonstatic_concrete_methods = true;
6151     }
6152   }
6153 
6154   if (_parsed_annotations->has_annotation(AnnotationCollector::_jdk_internal_LooselyConsistentValue) && _access_flags.is_identity_class()) {
6155     THROW_MSG(vmSymbols::java_lang_ClassFormatError(),
6156           err_msg("class %s cannot have annotation jdk.internal.vm.annotation.LooselyConsistentValue, because it is not a value class",
6157                   _class_name->as_klass_external_name()));
6158   }
6159 
6160   // Determining is the class allows tearing or not (default is not)
6161   if (EnableValhalla && !_access_flags.is_identity_class()) {
6162     if (_parsed_annotations->has_annotation(ClassAnnotationCollector::_jdk_internal_LooselyConsistentValue)
6163         && (_super_klass == vmClasses::Object_klass() || !_super_klass->must_be_atomic())) {
6164       // Conditions above are not sufficient to determine atomicity requirements,
6165       // the presence of fields with atomic requirements could force the current class to have atomicy requirements too
6166       // Marking as not needing atomicity for now, can be updated when computing the fields layout
6167       // The InstanceKlass must be filled with the value from the FieldLayoutInfo returned by
6168       // the FieldLayoutBuilder, not with this _must_be_atomic field.
6169       _must_be_atomic = false;
6170     }
6171     // Apply VM options override
6172     if (*ForceNonTearable != '\0') {
6173       // Allow a command line switch to force the same atomicity property:
6174       const char* class_name_str = _class_name->as_C_string();
6175       if (StringUtils::class_list_match(ForceNonTearable, class_name_str)) {
6176         _must_be_atomic = true;
6177       }
6178     }
6179   }
6180 
6181   int itfs_len = _local_interface_indexes == nullptr ? 0 : _local_interface_indexes->length();
6182   _local_interfaces = MetadataFactory::new_array<InstanceKlass*>(_loader_data, itfs_len, nullptr, CHECK);
6183   if (_local_interface_indexes != nullptr) {
6184     for (int i = 0; i < _local_interface_indexes->length(); i++) {
6185       u2 interface_index = _local_interface_indexes->at(i);
6186       Klass* interf;
6187       if (cp->tag_at(interface_index).is_klass()) {
6188         interf = cp->resolved_klass_at(interface_index);
6189       } else {
6190         Symbol* const unresolved_klass  = cp->klass_name_at(interface_index);
6191 
6192         // Don't need to check legal name because it's checked when parsing constant pool.
6193         // But need to make sure it's not an array type.
6194         guarantee_property(unresolved_klass->char_at(0) != JVM_SIGNATURE_ARRAY,
6195                             "Bad interface name in class file %s", CHECK);
6196 
6197         // Call resolve on the interface class name with class circularity checking
6198         interf = SystemDictionary::resolve_super_or_fail(
6199                                                   _class_name,
6200                                                   unresolved_klass,
6201                                                   Handle(THREAD, _loader_data->class_loader()),
6202                                                   false,
6203                                                   CHECK);
6204       }
6205 
6206       if (!interf->is_interface()) {
6207         THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
6208                   err_msg("class %s can not implement %s, because it is not an interface (%s)",
6209                           _class_name->as_klass_external_name(),
6210                           interf->external_name(),
6211                           interf->class_in_module_of_loader()));
6212       }
6213 
6214       if (EnableValhalla) {
6215         // Check modifiers and set carries_identity_modifier/carries_value_modifier flags
6216         check_identity_and_value_modifiers(this, InstanceKlass::cast(interf), CHECK);
6217       }
6218 
6219       if (InstanceKlass::cast(interf)->has_nonstatic_concrete_methods()) {
6220         _has_nonstatic_concrete_methods = true;
6221       }
6222       _local_interfaces->at_put(i, InstanceKlass::cast(interf));
6223     }
6224   }
6225   assert(_local_interfaces != nullptr, "invariant");
6226 
6227   // Compute the transitive list of all unique interfaces implemented by this class
6228   _transitive_interfaces =
6229     compute_transitive_interfaces(_super_klass,
6230                                   _local_interfaces,
6231                                   _loader_data,
6232                                   CHECK);
6233 
6234   assert(_transitive_interfaces != nullptr, "invariant");
6235 
6236   // sort methods
6237   _method_ordering = sort_methods(_methods);
6238 
6239   _all_mirandas = new GrowableArray<Method*>(20);
6240 
6241   Handle loader(THREAD, _loader_data->class_loader());
6242   klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
6243                                                     &_num_miranda_methods,
6244                                                     _all_mirandas,
6245                                                     _super_klass,
6246                                                     _methods,
6247                                                     _access_flags,
6248                                                     _major_version,
6249                                                     loader,
6250                                                     _class_name,
6251                                                     _local_interfaces);
6252 
6253   // Size of Java itable (in words)
6254   _itable_size = is_interface() ? 0 :
6255     klassItable::compute_itable_size(_transitive_interfaces);
6256 
6257   assert(_parsed_annotations != nullptr, "invariant");
6258 
6259   if (EnableValhalla) {
6260     _inline_layout_info_array = MetadataFactory::new_array<InlineLayoutInfo>(_loader_data,
6261                                                    java_fields_count(),
6262                                                    CHECK);
6263     for (GrowableArrayIterator<FieldInfo> it = _temp_field_info->begin(); it != _temp_field_info->end(); ++it) {
6264       FieldInfo fieldinfo = *it;
6265       if (fieldinfo.access_flags().is_static()) continue;  // Only non-static fields are processed at load time
6266       Symbol* sig = fieldinfo.signature(cp);
6267       if (fieldinfo.field_flags().is_null_free_inline_type()) {
6268         // Pre-load classes of null-free fields that are candidate for flattening
6269         TempNewSymbol s = Signature::strip_envelope(sig);
6270         if (s == _class_name) {
6271           THROW_MSG(vmSymbols::java_lang_ClassCircularityError(),
6272                     err_msg("Class %s cannot have a null-free non-static field of its own type", _class_name->as_C_string()));
6273         }
6274         log_info(class, preload)("Preloading of class %s during loading of class %s. "
6275                                   "Cause: a null-free non-static field is declared with this type",
6276                                   s->as_C_string(), _class_name->as_C_string());
6277         InstanceKlass* klass = SystemDictionary::resolve_with_circularity_detection(_class_name, s,
6278                                                                                     Handle(THREAD,
6279                                                                                     _loader_data->class_loader()),
6280                                                                                     false, THREAD);
6281         if (HAS_PENDING_EXCEPTION) {
6282           log_info(class, preload)("Preloading of class %s during loading of class %s "
6283                                       "(cause: null-free non-static field) failed: %s",
6284                                       s->as_C_string(), _class_name->as_C_string(),
6285                                       PENDING_EXCEPTION->klass()->name()->as_C_string());
6286           return; // Exception is still pending
6287         }
6288         assert(klass != nullptr, "Sanity check");
6289         InstanceKlass::check_can_be_annotated_with_NullRestricted(klass, _class_name, CHECK);
6290         InlineKlass* vk = InlineKlass::cast(klass);
6291         _inline_layout_info_array->adr_at(fieldinfo.index())->set_klass(vk);
6292         log_info(class, preload)("Preloading of class %s during loading of class %s "
6293                                  "(cause: null-free non-static field) succeeded",
6294                                  s->as_C_string(), _class_name->as_C_string());
6295       } else if (Signature::has_envelope(sig) && PreloadClasses) {
6296         // Preloading classes for nullable fields that are listed in the LoadableDescriptors attribute
6297         // Those classes would be required later for the flattening of nullable inline type fields
6298         TempNewSymbol name = Signature::strip_envelope(sig);
6299         if (name != _class_name && is_class_in_loadable_descriptors_attribute(sig)) {
6300           log_info(class, preload)("Preloading of class %s during loading of class %s. "
6301                                    "Cause: field type in LoadableDescriptors attribute",
6302                                    name->as_C_string(), _class_name->as_C_string());
6303           oop loader = loader_data()->class_loader();
6304           Klass* klass = SystemDictionary::resolve_super_or_fail(_class_name, name,
6305                                                                  Handle(THREAD, loader),
6306                                                                  false, THREAD);
6307           if (klass != nullptr) {
6308             if (klass->is_inline_klass()) {
6309               _inline_layout_info_array->adr_at(fieldinfo.index())->set_klass(InlineKlass::cast(klass));
6310               log_info(class, preload)("Preloading of class %s during loading of class %s "
6311                                        "(cause: field type in LoadableDescriptors attribute) succeeded",
6312                                        name->as_C_string(), _class_name->as_C_string());
6313             } else {
6314               // Non value class are allowed by the current spec, but it could be an indication of an issue so let's log a warning
6315               log_info(class, preload)("Preloading of class %s during loading of class %s "
6316                                           "(cause: field type in LoadableDescriptors attribute) but loaded class is not a value class",
6317                                           name->as_C_string(), _class_name->as_C_string());
6318             }
6319           } else {
6320             log_info(class, preload)("Preloading of class %s during loading of class %s "
6321                                         "(cause: field type in LoadableDescriptors attribute) failed : %s",
6322                                         name->as_C_string(), _class_name->as_C_string(),
6323                                         PENDING_EXCEPTION->klass()->name()->as_C_string());
6324           }
6325           // Loads triggered by the LoadableDescriptors attribute are speculative, failures must not impact loading of current class
6326           if (HAS_PENDING_EXCEPTION) {
6327             CLEAR_PENDING_EXCEPTION;
6328           }
6329         } else {
6330           // Just poking the system dictionary to see if the class has already be loaded. Looking for migrated classes
6331           // used when --enable-preview when jdk isn't compiled with --enable-preview so doesn't include LoadableDescriptors.
6332           // This is temporary.
6333           oop loader = loader_data()->class_loader();
6334           InstanceKlass* klass = SystemDictionary::find_instance_klass(THREAD, name, Handle(THREAD, loader));
6335           if (klass != nullptr && klass->is_inline_klass()) {
6336             _inline_layout_info_array->adr_at(fieldinfo.index())->set_klass(InlineKlass::cast(klass));
6337             log_info(class, preload)("Preloading of class %s during loading of class %s "
6338                                      "(cause: field type not in LoadableDescriptors attribute) succeeded",
6339                                      name->as_C_string(), _class_name->as_C_string());
6340           }
6341         }
6342       }
6343     }
6344   }
6345 
6346   _layout_info = new FieldLayoutInfo();
6347   FieldLayoutBuilder lb(class_name(), loader_data(), super_klass(), _cp, /*_fields*/ _temp_field_info,
6348       _parsed_annotations->is_contended(), is_inline_type(),
6349       access_flags().is_abstract() && !access_flags().is_identity_class() && !access_flags().is_interface(),
6350       _must_be_atomic, _layout_info, _inline_layout_info_array);
6351   lb.build_layout();
6352   _has_inline_type_fields = _layout_info->_has_inline_fields;
6353 
6354   int injected_fields_count = _temp_field_info->length() - _java_fields_count;
6355   _fieldinfo_stream =
6356     FieldInfoStream::create_FieldInfoStream(_temp_field_info, _java_fields_count,
6357                                             injected_fields_count, loader_data(), CHECK);
6358   _fieldinfo_search_table = FieldInfoStream::create_search_table(_cp, _fieldinfo_stream, _loader_data, CHECK);
6359   _fields_status =
6360     MetadataFactory::new_array<FieldStatus>(_loader_data, _temp_field_info->length(),
6361                                             FieldStatus(0), CHECK);
6362 
6363   // Strict static fields track initialization status from the beginning of time.
6364   // After this class runs <clinit>, they will be verified as being "not unset".
6365   // See Step 8 of InstanceKlass::initialize_impl.
6366   if (_has_strict_static_fields) {
6367     bool found_one = false;
6368     for (int i = 0; i < _temp_field_info->length(); i++) {
6369       FieldInfo& fi = *_temp_field_info->adr_at(i);
6370       if (fi.access_flags().is_strict() && fi.access_flags().is_static()) {
6371         found_one = true;
6372         if (fi.initializer_index() != 0) {
6373           // skip strict static fields with ConstantValue attributes
6374         } else {
6375           _fields_status->adr_at(fi.index())->update_strict_static_unset(true);
6376           _fields_status->adr_at(fi.index())->update_strict_static_unread(true);
6377         }
6378       }
6379     }
6380     assert(found_one == _has_strict_static_fields,
6381            "correct prediction = %d", (int)_has_strict_static_fields);
6382   }
6383 }
6384 
6385 void ClassFileParser::set_klass(InstanceKlass* klass) {
6386 
6387 #ifdef ASSERT
6388   if (klass != nullptr) {
6389     assert(nullptr == _klass, "leaking?");
6390   }
6391 #endif
6392 
6393   _klass = klass;
6394 }
6395 
6396 void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) {
6397 
6398 #ifdef ASSERT
6399   if (klass != nullptr) {
6400     assert(nullptr == _klass_to_deallocate, "leaking?");
6401   }
6402 #endif
< prev index next >