< prev index next >

src/hotspot/share/classfile/classFileParser.cpp

Print this page

   1 /*
   2  * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */

  24 #include "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/bsmAttribute.inline.hpp"
  51 #include "oops/constantPool.inline.hpp"
  52 #include "oops/fieldInfo.hpp"
  53 #include "oops/fieldStreams.inline.hpp"

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

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

 139 #define JAVA_18_VERSION                   62
 140 
 141 #define JAVA_19_VERSION                   63
 142 
 143 #define JAVA_20_VERSION                   64
 144 
 145 #define JAVA_21_VERSION                   65
 146 
 147 #define JAVA_22_VERSION                   66
 148 
 149 #define JAVA_23_VERSION                   67
 150 
 151 #define JAVA_24_VERSION                   68
 152 
 153 #define JAVA_25_VERSION                   69
 154 
 155 #define JAVA_26_VERSION                   70
 156 
 157 #define JAVA_27_VERSION                   71
 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) {

3356   cp->bsm_entries().end_extension(iter, _loader_data, CHECK);
3357   guarantee_property(current_before_parsing + attribute_byte_length == cfs->current(),
3358                      "Bad length on BootstrapMethods in class file %s",
3359                      CHECK);
3360 }
3361 
3362 void ClassFileParser::parse_classfile_attributes(const ClassFileStream* const cfs,
3363                                                  ConstantPool* cp,
3364                  ClassFileParser::ClassAnnotationCollector* parsed_annotations,
3365                                                  TRAPS) {
3366   assert(cfs != nullptr, "invariant");
3367   assert(cp != nullptr, "invariant");
3368   assert(parsed_annotations != nullptr, "invariant");
3369 
3370   // Set inner classes attribute to default sentinel
3371   _inner_classes = Universe::the_empty_short_array();
3372   // Set nest members attribute to default sentinel
3373   _nest_members = Universe::the_empty_short_array();
3374   // Set _permitted_subclasses attribute to default sentinel
3375   _permitted_subclasses = Universe::the_empty_short_array();


3376   cfs->guarantee_more(2, CHECK);  // attributes_count
3377   u2 attributes_count = cfs->get_u2_fast();
3378   bool parsed_sourcefile_attribute = false;
3379   bool parsed_innerclasses_attribute = false;
3380   bool parsed_nest_members_attribute = false;
3381   bool parsed_permitted_subclasses_attribute = false;

3382   bool parsed_nest_host_attribute = false;
3383   bool parsed_record_attribute = false;
3384   bool parsed_enclosingmethod_attribute = false;
3385   bool parsed_bootstrap_methods_attribute = false;
3386   const u1* runtime_visible_annotations = nullptr;
3387   int runtime_visible_annotations_length = 0;
3388   const u1* runtime_visible_type_annotations = nullptr;
3389   int runtime_visible_type_annotations_length = 0;
3390   bool runtime_invisible_type_annotations_exists = false;
3391   bool runtime_invisible_annotations_exists = false;
3392   bool parsed_source_debug_ext_annotations_exist = false;
3393   const u1* inner_classes_attribute_start = nullptr;
3394   u4  inner_classes_attribute_length = 0;
3395   u2  enclosing_method_class_index = 0;
3396   u2  enclosing_method_method_index = 0;
3397   const u1* nest_members_attribute_start = nullptr;
3398   u4  nest_members_attribute_length = 0;
3399   const u1* record_attribute_start = nullptr;
3400   u4  record_attribute_length = 0;
3401   const u1* permitted_subclasses_attribute_start = nullptr;
3402   u4  permitted_subclasses_attribute_length = 0;


3403 
3404   // Iterate over attributes
3405   while (attributes_count--) {
3406     cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
3407     const u2 attribute_name_index = cfs->get_u2_fast();
3408     const u4 attribute_length = cfs->get_u4_fast();
3409     guarantee_property(
3410       valid_symbol_at(attribute_name_index),
3411       "Attribute name has bad constant pool index %u in class file %s",
3412       attribute_name_index, CHECK);
3413     const Symbol* const tag = cp->symbol_at(attribute_name_index);
3414     if (tag == vmSymbols::tag_source_file()) {
3415       // Check for SourceFile tag
3416       if (_need_verify) {
3417         guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
3418       }
3419       if (parsed_sourcefile_attribute) {
3420         classfile_parse_error("Multiple SourceFile attributes in class file %s", THREAD);
3421         return;
3422       } else {

3598               return;
3599             }
3600             parsed_record_attribute = true;
3601             record_attribute_start = cfs->current();
3602             record_attribute_length = attribute_length;
3603           } else if (_major_version >= JAVA_17_VERSION) {
3604             if (tag == vmSymbols::tag_permitted_subclasses()) {
3605               if (parsed_permitted_subclasses_attribute) {
3606                 classfile_parse_error("Multiple PermittedSubclasses attributes in class file %s", CHECK);
3607                 return;
3608               }
3609               // Classes marked ACC_FINAL cannot have a PermittedSubclasses attribute.
3610               if (_access_flags.is_final()) {
3611                 classfile_parse_error("PermittedSubclasses attribute in final class file %s", CHECK);
3612                 return;
3613               }
3614               parsed_permitted_subclasses_attribute = true;
3615               permitted_subclasses_attribute_start = cfs->current();
3616               permitted_subclasses_attribute_length = attribute_length;
3617             }









3618           }
3619           // Skip attribute_length for any attribute where major_verson >= JAVA_17_VERSION
3620           cfs->skip_u1(attribute_length, CHECK);
3621         } else {
3622           // Unknown attribute
3623           cfs->skip_u1(attribute_length, CHECK);
3624         }
3625       } else {
3626         // Unknown attribute
3627         cfs->skip_u1(attribute_length, CHECK);
3628       }
3629     } else {
3630       // Unknown attribute
3631       cfs->skip_u1(attribute_length, CHECK);
3632     }
3633   }
3634   _class_annotations = allocate_annotations(runtime_visible_annotations,
3635                                             runtime_visible_annotations_length,
3636                                             CHECK);
3637   _class_type_annotations = allocate_annotations(runtime_visible_type_annotations,

3674                             CHECK);
3675     if (_need_verify) {
3676       guarantee_property(record_attribute_length == calculated_attr_length,
3677                          "Record attribute has wrong length in class file %s",
3678                          CHECK);
3679     }
3680   }
3681 
3682   if (parsed_permitted_subclasses_attribute) {
3683     const u2 num_subclasses = parse_classfile_permitted_subclasses_attribute(
3684                             cfs,
3685                             permitted_subclasses_attribute_start,
3686                             CHECK);
3687     if (_need_verify) {
3688       guarantee_property(
3689         permitted_subclasses_attribute_length == sizeof(num_subclasses) + sizeof(u2) * num_subclasses,
3690         "Wrong PermittedSubclasses attribute length in class file %s", CHECK);
3691     }
3692   }
3693 












3694   if (_max_bootstrap_specifier_index >= 0) {
3695     guarantee_property(parsed_bootstrap_methods_attribute,
3696                        "Missing BootstrapMethods attribute in class file %s", CHECK);
3697   }
3698 }
3699 
3700 void ClassFileParser::apply_parsed_class_attributes(InstanceKlass* k) {
3701   assert(k != nullptr, "invariant");
3702 
3703   if (_synthetic_flag)
3704     k->set_is_synthetic();
3705   if (_sourcefile_index != 0) {
3706     k->set_source_file_name_index(_sourcefile_index);
3707   }
3708   if (_generic_signature_index != 0) {
3709     k->set_generic_signature_index(_generic_signature_index);
3710   }
3711   if (_sde_buffer != nullptr) {
3712     k->set_source_debug_extension(_sde_buffer, _sde_length);
3713   }

3740     _class_type_annotations  = nullptr;
3741     _fields_annotations      = nullptr;
3742     _fields_type_annotations = nullptr;
3743 }
3744 
3745 // Transfer ownership of metadata allocated to the InstanceKlass.
3746 void ClassFileParser::apply_parsed_class_metadata(
3747                                             InstanceKlass* this_klass,
3748                                             int java_fields_count) {
3749   assert(this_klass != nullptr, "invariant");
3750 
3751   _cp->set_pool_holder(this_klass);
3752   this_klass->set_constants(_cp);
3753   this_klass->set_fieldinfo_stream(_fieldinfo_stream);
3754   this_klass->set_fieldinfo_search_table(_fieldinfo_search_table);
3755   this_klass->set_fields_status(_fields_status);
3756   this_klass->set_methods(_methods);
3757   this_klass->set_inner_classes(_inner_classes);
3758   this_klass->set_nest_members(_nest_members);
3759   this_klass->set_nest_host_index(_nest_host);

3760   this_klass->set_annotations(_combined_annotations);
3761   this_klass->set_permitted_subclasses(_permitted_subclasses);
3762   this_klass->set_record_components(_record_components);

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

3974   // See documentation of InstanceKlass::can_be_fastpath_allocated().
3975   assert(ik->size_helper() > 0, "layout_helper is initialized");
3976   if (ik->is_abstract() || ik->is_interface()
3977       || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == nullptr)
3978       || ik->size_helper() >= FastAllocateSizeLimit) {
3979     // Forbid fast-path allocation.
3980     const jint lh = Klass::instance_layout_helper(ik->size_helper(), true);
3981     ik->set_layout_helper(lh);
3982   }
3983 
3984   // Propagate the AOT runtimeSetup method discovery
3985   if (_has_aot_runtime_setup_method) {
3986     ik->set_is_runtime_setup_required();
3987     if (log_is_enabled(Info, aot, init)) {
3988       ResourceMark rm;
3989       log_info(aot, init)("Found @AOTRuntimeSetup class %s", ik->external_name());
3990     }
3991   }
3992 }
3993 






3994 // utility methods for appending an array with check for duplicates
3995 
3996 static void append_interfaces(GrowableArray<InstanceKlass*>* result,
3997                               const Array<InstanceKlass*>* const ifs) {
3998   // iterate over new interfaces
3999   for (int i = 0; i < ifs->length(); i++) {
4000     InstanceKlass* const e = ifs->at(i);
4001     assert(e->is_klass() && e->is_interface(), "just checking");
4002     // add new interface
4003     result->append_if_missing(e);
4004   }
4005 }
4006 
4007 static Array<InstanceKlass*>* compute_transitive_interfaces(const InstanceKlass* super,
4008                                                             Array<InstanceKlass*>* local_ifs,
4009                                                             ClassLoaderData* loader_data,
4010                                                             TRAPS) {
4011   assert(local_ifs != nullptr, "invariant");
4012   assert(loader_data != nullptr, "invariant");
4013 

4017   // Add superclass transitive interfaces size
4018   if (super != nullptr) {
4019     super_size = super->transitive_interfaces()->length();
4020     max_transitive_size += super_size;
4021   }
4022   // Add local interfaces' super interfaces
4023   const int local_size = local_ifs->length();
4024   for (int i = 0; i < local_size; i++) {
4025     InstanceKlass* const l = local_ifs->at(i);
4026     max_transitive_size += l->transitive_interfaces()->length();
4027   }
4028   // Finally add local interfaces
4029   max_transitive_size += local_size;
4030   // Construct array
4031   if (max_transitive_size == 0) {
4032     // no interfaces, use canonicalized array
4033     return Universe::the_empty_instance_klass_array();
4034   } else if (max_transitive_size == super_size) {
4035     // no new local interfaces added, share superklass' transitive interface array
4036     return super->transitive_interfaces();
4037   } else if (max_transitive_size == local_size) {
4038     // only local interfaces added, share local interface array
4039     return local_ifs;

4040   } else {
4041     ResourceMark rm;
4042     GrowableArray<InstanceKlass*>* const result = new GrowableArray<InstanceKlass*>(max_transitive_size);
4043 
4044     // Copy down from superclass
4045     if (super != nullptr) {
4046       append_interfaces(result, super->transitive_interfaces());
4047     }
4048 
4049     // Copy down from local interfaces' superinterfaces
4050     for (int i = 0; i < local_size; i++) {
4051       InstanceKlass* const l = local_ifs->at(i);
4052       append_interfaces(result, l->transitive_interfaces());
4053     }
4054     // Finally add local interfaces
4055     append_interfaces(result, local_ifs);
4056 
4057     // length will be less than the max_transitive_size if duplicates were removed
4058     const int length = result->length();
4059     assert(length <= max_transitive_size, "just checking");

4060     Array<InstanceKlass*>* const new_result =
4061       MetadataFactory::new_array<InstanceKlass*>(loader_data, length, CHECK_NULL);
4062     for (int i = 0; i < length; i++) {
4063       InstanceKlass* const e = result->at(i);
4064       assert(e != nullptr, "just checking");
4065       new_result->at_put(i, e);
4066     }
4067     return new_result;
4068   }
4069 }
4070 
4071 void ClassFileParser::check_super_class_access(const InstanceKlass* this_klass, TRAPS) {
4072   assert(this_klass != nullptr, "invariant");
4073   const InstanceKlass* const super = this_klass->super();
4074 
4075   if (super != nullptr) {
4076     if (super->is_final()) {
4077       classfile_icce_error("class %s cannot inherit from final class %s", super, THREAD);
4078       return;
4079     }
4080 
4081     if (super->is_sealed()) {
4082       stringStream ss;
4083       ResourceMark rm(THREAD);
4084       if (!super->has_as_permitted_subclass(this_klass, ss)) {
4085         classfile_icce_error(ss.as_string(), THREAD);
4086         return;
4087       }
4088     }
4089 










4090     Reflection::VerifyClassAccessResults vca_result =
4091       Reflection::verify_class_access(this_klass, super, false);
4092     if (vca_result != Reflection::ACCESS_OK) {
4093       ResourceMark rm(THREAD);
4094       char* msg = Reflection::verify_class_access_msg(this_klass,
4095                                                       super,
4096                                                       vca_result);
4097 
4098       // Names are all known to be < 64k so we know this formatted message is not excessively large.
4099       if (msg == nullptr) {
4100         bool same_module = (this_klass->module() == super->module());
4101         Exceptions::fthrow(
4102           THREAD_AND_LOCATION,
4103           vmSymbols::java_lang_IllegalAccessError(),
4104           "class %s cannot access its %ssuperclass %s (%s%s%s)",
4105           this_klass->external_name(),
4106           super->is_abstract() ? "abstract " : "",
4107           super->external_name(),
4108           (same_module) ? this_klass->joint_in_module_of_loader(super) : this_klass->class_in_module_of_loader(),
4109           (same_module) ? "" : "; ",

4262 // Verify the class modifiers for the current class, or an inner class if inner_name is non-null.
4263 void ClassFileParser::verify_legal_class_modifiers(jint flags, Symbol* inner_name, bool is_anonymous_inner_class, TRAPS) const {
4264   const bool is_module = (flags & JVM_ACC_MODULE) != 0;
4265   assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");
4266   if (is_module) {
4267     ResourceMark rm(THREAD);
4268     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4269     Exceptions::fthrow(
4270       THREAD_AND_LOCATION,
4271       vmSymbols::java_lang_NoClassDefFoundError(),
4272       "%s is not a class because access_flag ACC_MODULE is set",
4273       _class_name->as_C_string());
4274     return;
4275   }
4276 
4277   if (!_need_verify) { return; }
4278 
4279   const bool is_interface  = (flags & JVM_ACC_INTERFACE)  != 0;
4280   const bool is_abstract   = (flags & JVM_ACC_ABSTRACT)   != 0;
4281   const bool is_final      = (flags & JVM_ACC_FINAL)      != 0;
4282   const bool is_super      = (flags & JVM_ACC_SUPER)      != 0;
4283   const bool is_enum       = (flags & JVM_ACC_ENUM)       != 0;
4284   const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4285   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;


4286 
4287   if ((is_abstract && is_final) ||
4288       (is_interface && !is_abstract) ||
4289       (is_interface && major_gte_1_5 && (is_super || is_enum)) ||
4290       (!is_interface && major_gte_1_5 && is_annotation)) {

4291     ResourceMark rm(THREAD);




4292     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4293     if (inner_name == nullptr && !is_anonymous_inner_class) {
4294       Exceptions::fthrow(
4295         THREAD_AND_LOCATION,
4296         vmSymbols::java_lang_ClassFormatError(),
4297         "Illegal class modifiers in class %s: 0x%X",
4298         _class_name->as_C_string(), flags
4299       );
4300     } else {
4301       if (is_anonymous_inner_class) {
4302         Exceptions::fthrow(
4303           THREAD_AND_LOCATION,
4304           vmSymbols::java_lang_ClassFormatError(),
4305           "Illegal class modifiers in anonymous inner class of class %s: 0x%X",
4306           _class_name->as_C_string(), flags
4307         );
4308       } else {
4309         Exceptions::fthrow(
4310           THREAD_AND_LOCATION,
4311           vmSymbols::java_lang_ClassFormatError(),

4365         THREAD_AND_LOCATION,
4366         vmSymbols::java_lang_UnsupportedClassVersionError(),
4367         "%s (class file version %u.%u) was compiled with preview features that are unsupported. "
4368         "This version of the Java Runtime only recognizes preview features for class file version %u.%u",
4369         class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION, JAVA_PREVIEW_MINOR_VERSION);
4370       return;
4371     }
4372 
4373     if (!Arguments::enable_preview()) {
4374       classfile_ucve_error("Preview features are not enabled for %s (class file version %u.%u). Try running with '--enable-preview'",
4375                            class_name, major, minor, THREAD);
4376       return;
4377     }
4378 
4379   } else { // minor != JAVA_PREVIEW_MINOR_VERSION
4380     classfile_ucve_error("%s (class file version %u.%u) was compiled with an invalid non-zero minor version",
4381                          class_name, major, minor, THREAD);
4382   }
4383 }
4384 
4385 void ClassFileParser::verify_legal_field_modifiers(jint flags,
4386                                                    bool is_interface,
4387                                                    TRAPS) const {
4388   if (!_need_verify) { return; }
4389 
4390   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4391   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4392   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4393   const bool is_static    = (flags & JVM_ACC_STATIC)    != 0;
4394   const bool is_final     = (flags & JVM_ACC_FINAL)     != 0;
4395   const bool is_volatile  = (flags & JVM_ACC_VOLATILE)  != 0;
4396   const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
4397   const bool is_enum      = (flags & JVM_ACC_ENUM)      != 0;

4398   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4399 
4400   bool is_illegal = false;

4401 
4402   if (is_interface) {
4403     if (!is_public || !is_static || !is_final || is_private ||
4404         is_protected || is_volatile || is_transient ||
4405         (major_gte_1_5 && is_enum)) {
4406       is_illegal = true;
4407     }
4408   } else { // not interface
4409     if (has_illegal_visibility(flags) || (is_final && is_volatile)) {
4410       is_illegal = true;





















4411     }
4412   }
4413 
4414   if (is_illegal) {
4415     ResourceMark rm(THREAD);
4416     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4417     Exceptions::fthrow(
4418       THREAD_AND_LOCATION,
4419       vmSymbols::java_lang_ClassFormatError(),
4420       "Illegal field modifiers in class %s: 0x%X",
4421       _class_name->as_C_string(), flags);
4422     return;
4423   }
4424 }
4425 
4426 void ClassFileParser::verify_legal_method_modifiers(jint flags,
4427                                                     bool is_interface,
4428                                                     const Symbol* name,
4429                                                     TRAPS) const {
4430   if (!_need_verify) { return; }
4431 
4432   const bool is_public       = (flags & JVM_ACC_PUBLIC)       != 0;
4433   const bool is_private      = (flags & JVM_ACC_PRIVATE)      != 0;
4434   const bool is_static       = (flags & JVM_ACC_STATIC)       != 0;
4435   const bool is_final        = (flags & JVM_ACC_FINAL)        != 0;
4436   const bool is_native       = (flags & JVM_ACC_NATIVE)       != 0;
4437   const bool is_abstract     = (flags & JVM_ACC_ABSTRACT)     != 0;
4438   const bool is_bridge       = (flags & JVM_ACC_BRIDGE)       != 0;
4439   const bool is_strict       = (flags & JVM_ACC_STRICT)       != 0;
4440   const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
4441   const bool is_protected    = (flags & JVM_ACC_PROTECTED)    != 0;
4442   const bool major_gte_1_5   = _major_version >= JAVA_1_5_VERSION;
4443   const bool major_gte_8     = _major_version >= JAVA_8_VERSION;
4444   const bool major_gte_17    = _major_version >= JAVA_17_VERSION;
4445   const bool is_initializer  = (name == vmSymbols::object_initializer_name());




4446 
4447   bool is_illegal = false;
4448 

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





4492           }
4493         }
4494       }
4495     }
4496   }
4497 
4498   if (is_illegal) {
4499     ResourceMark rm(THREAD);
4500     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4501     Exceptions::fthrow(
4502       THREAD_AND_LOCATION,
4503       vmSymbols::java_lang_ClassFormatError(),
4504       "Method %s in class %s has illegal modifiers: 0x%X",
4505       name->as_C_string(), _class_name->as_C_string(), flags);

4506     return;
4507   }
4508 }
4509 
4510 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer,
4511                                         int length,
4512                                         TRAPS) const {
4513   assert(_need_verify, "only called when _need_verify is true");
4514   // Note: 0 <= length < 64K, as it comes from a u2 entry in the CP.
4515   if (!UTF8::is_legal_utf8(buffer, static_cast<size_t>(length), _major_version <= 47)) {
4516     classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", THREAD);
4517   }
4518 }
4519 
4520 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
4521 // In class names, '/' separates unqualified names.  This is verified in this function also.
4522 // Method names also may not contain the characters '<' or '>', unless <init>
4523 // or <clinit>.  Note that method names may not be <init> or <clinit> in this
4524 // method.  Because these names have been checked as special cases before
4525 // calling this method in verify_legal_method_name.

4543         if (type == ClassFileParser::LegalClass) {
4544           if (p == name || p+1 >= name+length ||
4545               *(p+1) == JVM_SIGNATURE_SLASH) {
4546             return false;
4547           }
4548         } else {
4549           return false;   // do not permit '/' unless it's class name
4550         }
4551         break;
4552       case JVM_SIGNATURE_SPECIAL:
4553       case JVM_SIGNATURE_ENDSPECIAL:
4554         // do not permit '<' or '>' in method names
4555         if (type == ClassFileParser::LegalMethod) {
4556           return false;
4557         }
4558     }
4559   }
4560   return true;
4561 }
4562 









4563 // Take pointer to a UTF8 byte string (not NUL-terminated).
4564 // Skip over the longest part of the string that could
4565 // be taken as a fieldname. Allow non-trailing '/'s if slash_ok is true.
4566 // Return a pointer to just past the fieldname.
4567 // Return null if no fieldname at all was found, or in the case of slash_ok
4568 // being true, we saw consecutive slashes (meaning we were looking for a
4569 // qualified path but found something that was badly-formed).
4570 static const char* skip_over_field_name(const char* const name,
4571                                         bool slash_ok,
4572                                         unsigned int length) {
4573   const char* p;
4574   jboolean last_is_slash = false;
4575   jboolean not_first_ch = false;
4576 
4577   for (p = name; p != name + length; not_first_ch = true) {
4578     const char* old_p = p;
4579     jchar ch = *p;
4580     if (ch < 128) {
4581       p++;
4582       // quick check for ascii

4644 // be taken as a field signature. Allow "void" if void_ok.
4645 // Return a pointer to just past the signature.
4646 // Return null if no legal signature is found.
4647 const char* ClassFileParser::skip_over_field_signature(const char* signature,
4648                                                        bool void_ok,
4649                                                        unsigned int length,
4650                                                        TRAPS) const {
4651   unsigned int array_dim = 0;
4652   while (length > 0) {
4653     switch (signature[0]) {
4654     case JVM_SIGNATURE_VOID: if (!void_ok) { return nullptr; }
4655     case JVM_SIGNATURE_BOOLEAN:
4656     case JVM_SIGNATURE_BYTE:
4657     case JVM_SIGNATURE_CHAR:
4658     case JVM_SIGNATURE_SHORT:
4659     case JVM_SIGNATURE_INT:
4660     case JVM_SIGNATURE_FLOAT:
4661     case JVM_SIGNATURE_LONG:
4662     case JVM_SIGNATURE_DOUBLE:
4663       return signature + 1;
4664     case JVM_SIGNATURE_CLASS: {

4665       if (_major_version < JAVA_1_5_VERSION) {
4666         signature++;
4667         length--;
4668         // Skip over the class name if one is there
4669         const char* const p = skip_over_field_name(signature, true, length);
4670         assert(p == nullptr || p > signature, "must parse one character at least");
4671         // The next character better be a semicolon
4672         if (p != nullptr                             && // Parse of field name succeeded.
4673             p - signature < static_cast<int>(length) && // There is at least one character left to parse.
4674             p[0] == JVM_SIGNATURE_ENDCLASS) {
4675           return p + 1;
4676         }
4677       }
4678       else {
4679         // Skip leading 'L' and ignore first appearance of ';'
4680         signature++;
4681         const char* c = (const char*) memchr(signature, JVM_SIGNATURE_ENDCLASS, length - 1);
4682         // Format check signature
4683         if (c != nullptr) {
4684           int newlen = pointer_delta_as_int(c, (char*) signature);
4685           bool legal = verify_unqualified_name(signature, newlen, LegalClass);
4686           if (!legal) {
4687             classfile_parse_error("Class name is empty or contains illegal character "
4688                                   "in descriptor in class file %s",
4689                                   THREAD);
4690             return nullptr;
4691           }
4692           return signature + newlen + 1;
4693         }
4694       }
4695       return nullptr;
4696     }
4697     case JVM_SIGNATURE_ARRAY:
4698       array_dim++;
4699       if (array_dim > 255) {

4715 
4716 // Checks if name is a legal class name.
4717 void ClassFileParser::verify_legal_class_name(const Symbol* name, TRAPS) const {
4718   if (!_need_verify) { return; }
4719 
4720   assert(name->refcount() > 0, "symbol must be kept alive");
4721   char* bytes = (char*)name->bytes();
4722   unsigned int length = name->utf8_length();
4723   bool legal = false;
4724 
4725   if (length > 0) {
4726     const char* p;
4727     if (bytes[0] == JVM_SIGNATURE_ARRAY) {
4728       p = skip_over_field_signature(bytes, false, length, CHECK);
4729       legal = (p != nullptr) && ((p - bytes) == (int)length);
4730     } else if (_major_version < JAVA_1_5_VERSION) {
4731       if (bytes[0] != JVM_SIGNATURE_SPECIAL) {
4732         p = skip_over_field_name(bytes, true, length);
4733         legal = (p != nullptr) && ((p - bytes) == (int)length);
4734       }




4735     } else {
4736       // 4900761: relax the constraints based on JSR202 spec
4737       // Class names may be drawn from the entire Unicode character set.
4738       // Identifiers between '/' must be unqualified names.
4739       // The utf8 string has been verified when parsing cpool entries.
4740       legal = verify_unqualified_name(bytes, length, LegalClass);
4741     }
4742   }
4743   if (!legal) {
4744     ResourceMark rm(THREAD);
4745     assert(_class_name != nullptr, "invariant");
4746     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4747     Exceptions::fthrow(
4748       THREAD_AND_LOCATION,
4749       vmSymbols::java_lang_ClassFormatError(),
4750       "Illegal class name \"%.*s\" in class file %s", length, bytes,
4751       _class_name->as_C_string()
4752     );
4753     return;
4754   }

4782       THREAD_AND_LOCATION,
4783       vmSymbols::java_lang_ClassFormatError(),
4784       "Illegal field name \"%.*s\" in class %s", length, bytes,
4785       _class_name->as_C_string()
4786     );
4787     return;
4788   }
4789 }
4790 
4791 // Checks if name is a legal method name.
4792 void ClassFileParser::verify_legal_method_name(const Symbol* name, TRAPS) const {
4793   if (!_need_verify) { return; }
4794 
4795   assert(name != nullptr, "method name is null");
4796   char* bytes = (char*)name->bytes();
4797   unsigned int length = name->utf8_length();
4798   bool legal = false;
4799 
4800   if (length > 0) {
4801     if (bytes[0] == JVM_SIGNATURE_SPECIAL) {
4802       if (name == vmSymbols::object_initializer_name() || name == vmSymbols::class_initializer_name()) {

4803         legal = true;
4804       }
4805     } else if (_major_version < JAVA_1_5_VERSION) {
4806       const char* p;
4807       p = skip_over_field_name(bytes, false, length);
4808       legal = (p != nullptr) && ((p - bytes) == (int)length);
4809     } else {
4810       // 4881221: relax the constraints based on JSR202 spec
4811       legal = verify_unqualified_name(bytes, length, LegalMethod);
4812     }
4813   }
4814 
4815   if (!legal) {
4816     ResourceMark rm(THREAD);
4817     assert(_class_name != nullptr, "invariant");
4818     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4819     Exceptions::fthrow(
4820       THREAD_AND_LOCATION,
4821       vmSymbols::java_lang_ClassFormatError(),
4822       "Illegal method name \"%.*s\" in class %s", length, bytes,
4823       _class_name->as_C_string()
4824     );
4825     return;
4826   }
4827 }
4828 










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

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

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










5080   ik->set_static_oop_field_count(_static_oop_count);
5081 
5082   // this transfers ownership of a lot of arrays from
5083   // the parser onto the InstanceKlass*
5084   apply_parsed_class_metadata(ik, _java_fields_count);
5085 
5086   // can only set dynamic nest-host after static nest information is set
5087   if (cl_inst_info.dynamic_nest_host() != nullptr) {
5088     ik->set_nest_host(cl_inst_info.dynamic_nest_host());
5089   }
5090 
5091   // note that is not safe to use the fields in the parser from this point on
5092   assert(nullptr == _cp, "invariant");
5093   assert(nullptr == _fieldinfo_stream, "invariant");
5094   assert(nullptr == _fieldinfo_search_table, "invariant");
5095   assert(nullptr == _fields_status, "invariant");
5096   assert(nullptr == _methods, "invariant");
5097   assert(nullptr == _inner_classes, "invariant");
5098   assert(nullptr == _nest_members, "invariant");

5099   assert(nullptr == _combined_annotations, "invariant");
5100   assert(nullptr == _record_components, "invariant");
5101   assert(nullptr == _permitted_subclasses, "invariant");

5102 
5103   if (_has_localvariable_table) {
5104     ik->set_has_localvariable_table(true);
5105   }
5106 
5107   if (_has_final_method) {
5108     ik->set_has_final_method();
5109   }
5110 
5111   ik->copy_method_ordering(_method_ordering, CHECK);
5112   // The InstanceKlass::_methods_jmethod_ids cache
5113   // is managed on the assumption that the initial cache
5114   // size is equal to the number of methods in the class. If
5115   // that changes, then InstanceKlass::idnum_can_increment()
5116   // has to be changed accordingly.
5117   ik->set_initial_method_idnum(checked_cast<u2>(ik->methods()->length()));
5118 
5119   ik->set_this_class_index(_this_class_index);
5120 
5121   if (_is_hidden) {

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

5219 
5220   assert(_all_mirandas != nullptr, "invariant");
5221 
5222   // Generate any default methods - default methods are public interface methods
5223   // that have a default implementation.  This is new with Java 8.
5224   if (_has_nonstatic_concrete_methods) {
5225     DefaultMethods::generate_default_methods(ik,
5226                                              _all_mirandas,
5227                                              CHECK);
5228   }
5229 
5230   // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5231   if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5232       !module_entry->has_default_read_edges()) {
5233     if (!module_entry->set_has_default_read_edges()) {
5234       // We won a potential race
5235       JvmtiExport::add_default_read_edges(module_handle, THREAD);
5236     }
5237   }
5238 






























































5239   ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5240 
5241   if (!is_internal()) {
5242     ik->print_class_load_logging(_loader_data, module_entry, _stream);
5243 
5244     if (ik->minor_version() == JAVA_PREVIEW_MINOR_VERSION &&
5245         ik->major_version() == JVM_CLASSFILE_MAJOR_VERSION &&
5246         log_is_enabled(Info, class, preview)) {
5247       ResourceMark rm;
5248       log_info(class, preview)("Loading class %s that depends on preview features (class file version %d.65535)",
5249                                ik->external_name(), JVM_CLASSFILE_MAJOR_VERSION);
5250     }
5251 
5252     if (log_is_enabled(Debug, class, resolve))  {
5253       ResourceMark rm;
5254       // print out the superclass.
5255       const char * from = ik->external_name();
5256       if (ik->super() != nullptr) {
5257         log_debug(class, resolve)("%s %s (super)",
5258                    from,

5299                                  const ClassLoadInfo* cl_info,
5300                                  Publicity pub_level,
5301                                  TRAPS) :
5302   _stream(stream),
5303   _class_name(nullptr),
5304   _loader_data(loader_data),
5305   _is_hidden(cl_info->is_hidden()),
5306   _can_access_vm_annotations(cl_info->can_access_vm_annotations()),
5307   _orig_cp_size(0),
5308   _static_oop_count(0),
5309   _super_klass(),
5310   _cp(nullptr),
5311   _fieldinfo_stream(nullptr),
5312   _fieldinfo_search_table(nullptr),
5313   _fields_status(nullptr),
5314   _methods(nullptr),
5315   _inner_classes(nullptr),
5316   _nest_members(nullptr),
5317   _nest_host(0),
5318   _permitted_subclasses(nullptr),

5319   _record_components(nullptr),
5320   _local_interfaces(nullptr),

5321   _transitive_interfaces(nullptr),
5322   _combined_annotations(nullptr),
5323   _class_annotations(nullptr),
5324   _class_type_annotations(nullptr),
5325   _fields_annotations(nullptr),
5326   _fields_type_annotations(nullptr),
5327   _klass(nullptr),
5328   _klass_to_deallocate(nullptr),
5329   _parsed_annotations(nullptr),
5330   _field_info(nullptr),

5331   _temp_field_info(nullptr),
5332   _method_ordering(nullptr),
5333   _all_mirandas(nullptr),
5334   _vtable_size(0),
5335   _itable_size(0),
5336   _num_miranda_methods(0),
5337   _protection_domain(cl_info->protection_domain()),
5338   _access_flags(),
5339   _pub_level(pub_level),
5340   _bad_constant_seen(0),
5341   _synthetic_flag(false),
5342   _sde_length(false),
5343   _sde_buffer(nullptr),
5344   _sourcefile_index(0),
5345   _generic_signature_index(0),
5346   _major_version(0),
5347   _minor_version(0),
5348   _this_class_index(0),
5349   _super_class_index(0),
5350   _itfs_len(0),
5351   _java_fields_count(0),
5352   _need_verify(false),
5353   _has_nonstatic_concrete_methods(false),
5354   _declares_nonstatic_concrete_methods(false),
5355   _has_localvariable_table(false),
5356   _has_final_method(false),
5357   _has_contended_fields(false),
5358   _has_aot_runtime_setup_method(false),




5359   _has_finalizer(false),
5360   _has_empty_finalizer(false),
5361   _max_bootstrap_specifier_index(-1) {
5362 
5363   _class_name = name != nullptr ? name : vmSymbols::unknown_class_name();
5364   _class_name->increment_refcount();
5365 
5366   assert(_loader_data != nullptr, "invariant");
5367   assert(stream != nullptr, "invariant");
5368   assert(_stream != nullptr, "invariant");
5369   assert(_stream->buffer() == _stream->current(), "invariant");
5370   assert(_class_name != nullptr, "invariant");
5371   assert(0 == _access_flags.as_unsigned_short(), "invariant");
5372 
5373   // Figure out whether we can skip format checking (matching classic VM behavior)
5374   // Always verify CFLH bytes from the user agents.
5375   _need_verify = stream->from_class_file_load_hook() ? true : Verifier::should_verify_for(_loader_data->class_loader());
5376 
5377   // synch back verification state to stream to check for truncation.
5378   stream->set_need_verify(_need_verify);
5379 
5380   parse_stream(stream, CHECK);
5381 
5382   post_process_parsed_stream(stream, _cp, CHECK);
5383 }
5384 
5385 void ClassFileParser::clear_class_metadata() {
5386   // metadata created before the instance klass is created.  Must be
5387   // deallocated if classfile parsing returns an error.
5388   _cp = nullptr;
5389   _fieldinfo_stream = nullptr;
5390   _fieldinfo_search_table = nullptr;
5391   _fields_status = nullptr;
5392   _methods = nullptr;
5393   _inner_classes = nullptr;
5394   _nest_members = nullptr;
5395   _permitted_subclasses = nullptr;

5396   _combined_annotations = nullptr;
5397   _class_annotations = _class_type_annotations = nullptr;
5398   _fields_annotations = _fields_type_annotations = nullptr;
5399   _record_components = nullptr;

5400 }
5401 
5402 // Destructor to clean up
5403 ClassFileParser::~ClassFileParser() {
5404   _class_name->decrement_refcount();
5405 
5406   if (_cp != nullptr) {
5407     MetadataFactory::free_metadata(_loader_data, _cp);
5408   }
5409 
5410   if (_fieldinfo_stream != nullptr) {
5411     MetadataFactory::free_array<u1>(_loader_data, _fieldinfo_stream);
5412   }
5413   MetadataFactory::free_array<u1>(_loader_data, _fieldinfo_search_table);
5414 
5415   if (_fields_status != nullptr) {
5416     MetadataFactory::free_array<FieldStatus>(_loader_data, _fields_status);
5417   }
5418 




5419   if (_methods != nullptr) {
5420     // Free methods
5421     InstanceKlass::deallocate_methods(_loader_data, _methods);
5422   }
5423 
5424   // beware of the Universe::empty_blah_array!!
5425   if (_inner_classes != nullptr && _inner_classes != Universe::the_empty_short_array()) {
5426     MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
5427   }
5428 
5429   if (_nest_members != nullptr && _nest_members != Universe::the_empty_short_array()) {
5430     MetadataFactory::free_array<u2>(_loader_data, _nest_members);
5431   }
5432 
5433   if (_record_components != nullptr) {
5434     InstanceKlass::deallocate_record_components(_loader_data, _record_components);
5435   }
5436 
5437   if (_permitted_subclasses != nullptr && _permitted_subclasses != Universe::the_empty_short_array()) {
5438     MetadataFactory::free_array<u2>(_loader_data, _permitted_subclasses);
5439   }
5440 




5441   // Free interfaces
5442   InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
5443                                        _local_interfaces, _transitive_interfaces);
5444 
5445   if (_combined_annotations != nullptr) {
5446     // After all annotations arrays have been created, they are installed into the
5447     // Annotations object that will be assigned to the InstanceKlass being created.
5448 
5449     // Deallocate the Annotations object and the installed annotations arrays.
5450     _combined_annotations->deallocate_contents(_loader_data);
5451 
5452     // If the _combined_annotations pointer is non-null,
5453     // then the other annotations fields should have been cleared.
5454     assert(_class_annotations       == nullptr, "Should have been cleared");
5455     assert(_class_type_annotations  == nullptr, "Should have been cleared");
5456     assert(_fields_annotations      == nullptr, "Should have been cleared");
5457     assert(_fields_type_annotations == nullptr, "Should have been cleared");
5458   } else {
5459     // If the annotations arrays were not installed into the Annotations object,
5460     // then they have to be deallocated explicitly.

5520 
5521   assert(cp_size == (u2)cp->length(), "invariant");
5522 
5523   // ACCESS FLAGS
5524   stream->guarantee_more(8, CHECK);  // flags, this_class, super_class, infs_len
5525 
5526   // Access flags
5527   u2 flags;
5528   // JVM_ACC_MODULE is defined in JDK-9 and later.
5529   if (_major_version >= JAVA_9_VERSION) {
5530     flags = stream->get_u2_fast() & (JVM_RECOGNIZED_CLASS_MODIFIERS | JVM_ACC_MODULE);
5531   } else {
5532     flags = stream->get_u2_fast() & JVM_RECOGNIZED_CLASS_MODIFIERS;
5533   }
5534 
5535   if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
5536     // Set abstract bit for old class files for backward compatibility
5537     flags |= JVM_ACC_ABSTRACT;
5538   }
5539 









5540   verify_legal_class_modifiers(flags, nullptr, false, CHECK);
5541 
5542   short bad_constant = class_bad_constant_seen();
5543   if (bad_constant != 0) {
5544     // Do not throw CFE until after the access_flags are checked because if
5545     // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
5546     classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, THREAD);
5547     return;
5548   }
5549 
5550   _access_flags.set_flags(flags);
5551 
5552   // This class and superclass
5553   _this_class_index = stream->get_u2_fast();
5554   guarantee_property(
5555     valid_cp_range(_this_class_index, cp_size) &&
5556       cp->tag_at(_this_class_index).is_unresolved_klass(),
5557     "Invalid this class index %u in constant pool in class file %s",
5558     _this_class_index, CHECK);
5559 

5623       }
5624       ls.cr();
5625     }
5626   }
5627 
5628   // SUPERKLASS
5629   _super_class_index = stream->get_u2_fast();
5630   check_super_class(cp,
5631                     _super_class_index,
5632                     _need_verify,
5633                     CHECK);
5634 
5635   // Interfaces
5636   _itfs_len = stream->get_u2_fast();
5637   parse_interfaces(stream,
5638                    _itfs_len,
5639                    cp,
5640                    &_has_nonstatic_concrete_methods,
5641                    CHECK);
5642 
5643   assert(_local_interfaces != nullptr, "invariant");
5644 
5645   // Fields (offsets are filled in later)
5646   parse_fields(stream,
5647                _access_flags.is_interface(),
5648                cp,
5649                cp_size,
5650                &_java_fields_count,
5651                CHECK);
5652 
5653   assert(_temp_field_info != nullptr, "invariant");
5654 
5655   // Methods
5656   parse_methods(stream,
5657                 _access_flags.is_interface(),


5658                 &_has_localvariable_table,
5659                 &_has_final_method,
5660                 &_declares_nonstatic_concrete_methods,
5661                 CHECK);
5662 
5663   assert(_methods != nullptr, "invariant");
5664 
5665   if (_declares_nonstatic_concrete_methods) {
5666     _has_nonstatic_concrete_methods = true;
5667   }
5668 
5669   // Additional attributes/annotations
5670   _parsed_annotations = new ClassAnnotationCollector();
5671   parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK);
5672 
5673   assert(_inner_classes != nullptr, "invariant");
5674 
5675   // Finalize the Annotations metadata object,
5676   // now that all annotation arrays have been created.
5677   create_combined_annotations(CHECK);

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














5767     if (_super_klass->has_nonstatic_concrete_methods()) {
5768       _has_nonstatic_concrete_methods = true;
5769     }

5770 
5771     if (_super_klass->is_interface()) {
5772       classfile_icce_error("class %s has interface %s as super class", _super_klass, THREAD);
5773       return;


































































5774     }
5775   }

5776 
5777   // Compute the transitive list of all unique interfaces implemented by this class
5778   _transitive_interfaces =
5779     compute_transitive_interfaces(_super_klass,
5780                                   _local_interfaces,
5781                                   _loader_data,
5782                                   CHECK);
5783 
5784   assert(_transitive_interfaces != nullptr, "invariant");
5785 
5786   // sort methods
5787   _method_ordering = sort_methods(_methods);
5788 
5789   _all_mirandas = new GrowableArray<Method*>(20);
5790 
5791   Handle loader(THREAD, _loader_data->class_loader());
5792   klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
5793                                                     &_num_miranda_methods,
5794                                                     _all_mirandas,
5795                                                     _super_klass,
5796                                                     _methods,
5797                                                     _access_flags,
5798                                                     _major_version,
5799                                                     loader,
5800                                                     _class_name,
5801                                                     _local_interfaces);
5802 
5803   // Size of Java itable (in words)
5804   _itable_size = _access_flags.is_interface() ? 0 :
5805     klassItable::compute_itable_size(_transitive_interfaces);
5806 
5807   assert(_parsed_annotations != nullptr, "invariant");
5808 
5809   _field_info = new FieldLayoutInfo();
5810   FieldLayoutBuilder lb(class_name(), super_klass(), _cp, /*_fields*/ _temp_field_info,
5811                         _parsed_annotations->is_contended(), _field_info);
























































































5812   lb.build_layout();
5813 








5814   int injected_fields_count = _temp_field_info->length() - _java_fields_count;
5815   _fieldinfo_stream =
5816     FieldInfoStream::create_FieldInfoStream(_temp_field_info, _java_fields_count,
5817                                             injected_fields_count, loader_data(), CHECK);
5818   _fieldinfo_search_table = FieldInfoStream::create_search_table(_cp, _fieldinfo_stream, _loader_data, CHECK);
5819   _fields_status =
5820     MetadataFactory::new_array<FieldStatus>(_loader_data, _temp_field_info->length(),
5821                                             FieldStatus(0), CHECK);





















5822 }
5823 
5824 void ClassFileParser::set_klass(InstanceKlass* klass) {
5825 
5826 #ifdef ASSERT
5827   if (klass != nullptr) {
5828     assert(nullptr == _klass, "leaking?");
5829   }
5830 #endif
5831 
5832   _klass = klass;
5833 }
5834 















5835 void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) {
5836 
5837 #ifdef ASSERT
5838   if (klass != nullptr) {
5839     assert(nullptr == _klass_to_deallocate, "leaking?");
5840   }
5841 #endif
5842 
5843   _klass_to_deallocate = klass;
5844 }
5845 
5846 // Caller responsible for ResourceMark
5847 // clone stream with rewound position
5848 const ClassFileStream* ClassFileParser::clone_stream() const {
5849   assert(_stream != nullptr, "invariant");
5850 
5851   return _stream->clone();
5852 }
5853 
5854 ReferenceType ClassFileParser::super_reference_type() const {

   1 /*
   2  * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "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/bsmAttribute.inline.hpp"
  52 #include "oops/constantPool.inline.hpp"
  53 #include "oops/fieldInfo.hpp"
  54 #include "oops/fieldStreams.inline.hpp"
  55 #include "oops/inlineKlass.inline.hpp"
  56 #include "oops/instanceKlass.inline.hpp"
  57 #include "oops/instanceMirrorKlass.hpp"
  58 #include "oops/klass.inline.hpp"
  59 #include "oops/klassVtable.hpp"
  60 #include "oops/metadata.hpp"
  61 #include "oops/method.inline.hpp"
  62 #include "oops/oop.inline.hpp"
  63 #include "oops/recordComponent.hpp"
  64 #include "oops/symbol.hpp"
  65 #include "prims/jvmtiExport.hpp"
  66 #include "prims/jvmtiThreadState.hpp"
  67 #include "runtime/arguments.hpp"
  68 #include "runtime/fieldDescriptor.inline.hpp"
  69 #include "runtime/handles.inline.hpp"
  70 #include "runtime/javaCalls.hpp"
  71 #include "runtime/os.hpp"
  72 #include "runtime/perfData.hpp"
  73 #include "runtime/reflection.hpp"
  74 #include "runtime/safepointVerifiers.hpp"
  75 #include "runtime/signature.hpp"
  76 #include "runtime/timer.hpp"
  77 #include "services/classLoadingService.hpp"
  78 #include "services/threadService.hpp"
  79 #include "utilities/align.hpp"
  80 #include "utilities/bitMap.inline.hpp"
  81 #include "utilities/checkedCast.hpp"
  82 #include "utilities/copy.hpp"
  83 #include "utilities/exceptions.hpp"
  84 #include "utilities/formatBuffer.hpp"
  85 #include "utilities/globalDefinitions.hpp"
  86 #include "utilities/growableArray.hpp"
  87 #include "utilities/hashTable.hpp"
  88 #include "utilities/macros.hpp"
  89 #include "utilities/ostream.hpp"
  90 #include "utilities/stringUtils.hpp"
  91 #include "utilities/utf8.hpp"
  92 #if INCLUDE_CDS
  93 #include "classfile/systemDictionaryShared.hpp"
  94 #endif
  95 
  96 // We generally try to create the oops directly when parsing, rather than
  97 // allocating temporary data structures and copying the bytes twice. A
  98 // temporary area is only needed when parsing utf8 entries in the constant
  99 // pool and when parsing line number tables.
 100 
 101 // We add assert in debug mode when class format is not checked.
 102 
 103 #define JAVA_CLASSFILE_MAGIC              0xCAFEBABE
 104 #define JAVA_MIN_SUPPORTED_VERSION        45
 105 #define JAVA_PREVIEW_MINOR_VERSION        65535
 106 
 107 // Used for two backward compatibility reasons:
 108 // - to check for new additions to the class file format in JDK1.5
 109 // - to check for bug fixes in the format checker in JDK1.5
 110 #define JAVA_1_5_VERSION                  49

 142 #define JAVA_18_VERSION                   62
 143 
 144 #define JAVA_19_VERSION                   63
 145 
 146 #define JAVA_20_VERSION                   64
 147 
 148 #define JAVA_21_VERSION                   65
 149 
 150 #define JAVA_22_VERSION                   66
 151 
 152 #define JAVA_23_VERSION                   67
 153 
 154 #define JAVA_24_VERSION                   68
 155 
 156 #define JAVA_25_VERSION                   69
 157 
 158 #define JAVA_26_VERSION                   70
 159 
 160 #define JAVA_27_VERSION                   71
 161 
 162 #define CONSTANT_CLASS_DESCRIPTORS        71
 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   // "inline type" means concrete value class
1386   bool is_inline_type = !class_access_flags.is_identity_class() && !class_access_flags.is_abstract();
1387   // "value class" can be either abstract or concrete value class
1388   bool is_value_class = !class_access_flags.is_identity_class() && !class_access_flags.is_interface();
1389   cfs->guarantee_more(2, CHECK);  // length
1390   const u2 length = cfs->get_u2_fast();
1391   *java_fields_count_ptr = length;
1392 
1393   int num_injected = 0;
1394   const InjectedField* const injected = JavaClasses::get_injected(_class_name,
1395                                                                   &num_injected);
1396 
1397   // Two more slots are required for inline classes:
1398   //   - The static field ".null_reset" which carries the nullable flat layout
1399   //     representation of null, added below
1400   //   - The nonstatic field ".empty" the JVM injects when detecting an empty
1401   //     inline class, added in FieldLayoutBuilder::compute_inline_class_layout
1402   // One more slot is required for both abstract value class and inline classes:
1403   //   - The static field ".acmp_maps" for acmp and identity hash, tracks
1404   //     nonstatic fields both inherited or declared, added below
1405   const int total_fields = length + num_injected + (is_inline_type ? 2 : 0)
1406                            + (is_value_class ? 1 : 0);
1407 
1408   // Allocate a temporary resource array to collect field data.
1409   // After parsing all fields, data are stored in a UNSIGNED5 compressed stream.
1410   _temp_field_info = new GrowableArray<FieldInfo>(total_fields);
1411 
1412   ResourceMark rm(THREAD);
1413   for (int n = 0; n < length; n++) {
1414     // access_flags, name_index, descriptor_index, attributes_count
1415     cfs->guarantee_more(8, CHECK);
1416 
1417     jint recognized_modifiers = JVM_RECOGNIZED_FIELD_MODIFIERS;
1418     if (!supports_inline_types()) {
1419       recognized_modifiers &= ~JVM_ACC_STRICT_INIT;
1420     }
1421 
1422     const jint flags = cfs->get_u2_fast() & recognized_modifiers;
1423     verify_legal_field_modifiers(flags, class_access_flags, CHECK);
1424     AccessFlags access_flags;


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

1545   if (num_injected != 0) {
1546     for (int n = 0; n < num_injected; n++) {
1547       // Check for duplicates
1548       if (injected[n].may_be_java) {
1549         const Symbol* const name      = injected[n].name();
1550         const Symbol* const signature = injected[n].signature();
1551         bool duplicate = false;
1552         for (int i = 0; i < length; i++) {
1553           const FieldInfo* const f = _temp_field_info->adr_at(i);
1554           if (name      == cp->symbol_at(f->name_index()) &&
1555               signature == cp->symbol_at(f->signature_index())) {
1556             // Symbol is desclared in Java so skip this one
1557             duplicate = true;
1558             break;
1559           }
1560         }
1561         if (duplicate) {
1562           // These will be removed from the field array at the end
1563           continue;
1564         }
1565       }
1566 
1567       // Injected field
1568       FieldInfo::FieldFlags fflags(0);
1569       fflags.update_injected(true);
1570       AccessFlags aflags;
1571       FieldInfo fi(aflags, (u2)(injected[n].name_index), (u2)(injected[n].signature_index), 0, fflags);
1572       int idx = _temp_field_info->append(fi);
1573       _temp_field_info->adr_at(idx)->set_index(idx);

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

1969     }
1970     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Contended_signature): {
1971       if (_location != _in_field && _location != _in_class) {
1972         break;  // only allow for fields and classes
1973       }
1974       if (!EnableContended || (RestrictContended && !privileged)) {
1975         break;  // honor privileges
1976       }
1977       return _jdk_internal_vm_annotation_Contended;
1978     }
1979     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ReservedStackAccess_signature): {
1980       if (_location != _in_method)  break;  // only allow for methods
1981       if (RestrictReservedStack && !privileged) break; // honor privileges
1982       return _jdk_internal_vm_annotation_ReservedStackAccess;
1983     }
1984     case VM_SYMBOL_ENUM_NAME(jdk_internal_ValueBased_signature): {
1985       if (_location != _in_class)   break;  // only allow for classes
1986       if (!privileged)              break;  // only allow in privileged code
1987       return _jdk_internal_ValueBased;
1988     }
1989     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_LooselyConsistentValue_signature): {
1990       if (_location != _in_class)   break; // only allow for classes
1991       return _jdk_internal_LooselyConsistentValue;
1992     }
1993     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_NullRestricted_signature): {
1994       if (_location != _in_field)   break; // only allow for fields
1995       return _jdk_internal_NullRestricted;
1996     }
1997     case VM_SYMBOL_ENUM_NAME(java_lang_Deprecated): {
1998       return _java_lang_Deprecated;
1999     }
2000     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_AOTSafeClassInitializer_signature): {
2001       if (_location != _in_class)   break;  // only allow for classes
2002       if (!privileged)              break;  // only allow in privileged code
2003       return _jdk_internal_vm_annotation_AOTSafeClassInitializer;
2004     }
2005     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_AOTRuntimeSetup_signature): {
2006       if (_location != _in_method)  break;  // only allow for methods
2007       if (!privileged)              break;  // only allow in privileged code
2008       return _method_AOTRuntimeSetup;
2009     }
2010     default: {
2011       break;
2012     }
2013   }
2014   return AnnotationCollector::_unknown;
2015 }
2016 

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

5998       }
5999       ls.cr();
6000     }
6001   }
6002 
6003   // SUPERKLASS
6004   _super_class_index = stream->get_u2_fast();
6005   check_super_class(cp,
6006                     _super_class_index,
6007                     _need_verify,
6008                     CHECK);
6009 
6010   // Interfaces
6011   _itfs_len = stream->get_u2_fast();
6012   parse_interfaces(stream,
6013                    _itfs_len,
6014                    cp,
6015                    &_has_nonstatic_concrete_methods,
6016                    CHECK);
6017 


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

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