< prev index next >

src/hotspot/share/classfile/classFileParser.cpp

Print this page

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


  24 #include "cds/cdsConfig.hpp"
  25 #include "classfile/classFileParser.hpp"
  26 #include "classfile/classFileStream.hpp"
  27 #include "classfile/classLoader.hpp"
  28 #include "classfile/classLoaderData.inline.hpp"
  29 #include "classfile/classLoadInfo.hpp"
  30 #include "classfile/defaultMethods.hpp"
  31 #include "classfile/fieldLayoutBuilder.hpp"
  32 #include "classfile/javaClasses.inline.hpp"
  33 #include "classfile/moduleEntry.hpp"
  34 #include "classfile/packageEntry.hpp"
  35 #include "classfile/symbolTable.hpp"
  36 #include "classfile/systemDictionary.hpp"
  37 #include "classfile/verificationType.hpp"
  38 #include "classfile/verifier.hpp"
  39 #include "classfile/vmClasses.hpp"
  40 #include "classfile/vmSymbols.hpp"
  41 #include "jvm.h"
  42 #include "logging/log.hpp"
  43 #include "logging/logStream.hpp"
  44 #include "memory/allocation.hpp"
  45 #include "memory/metadataFactory.hpp"
  46 #include "memory/oopFactory.hpp"
  47 #include "memory/resourceArea.hpp"
  48 #include "memory/universe.hpp"
  49 #include "oops/annotations.hpp"
  50 #include "oops/constantPool.inline.hpp"
  51 #include "oops/fieldInfo.hpp"
  52 #include "oops/fieldStreams.inline.hpp"

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

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

 133 #define JAVA_14_VERSION                   58
 134 
 135 #define JAVA_15_VERSION                   59
 136 
 137 #define JAVA_16_VERSION                   60
 138 
 139 #define JAVA_17_VERSION                   61
 140 
 141 #define JAVA_18_VERSION                   62
 142 
 143 #define JAVA_19_VERSION                   63
 144 
 145 #define JAVA_20_VERSION                   64
 146 
 147 #define JAVA_21_VERSION                   65
 148 
 149 #define JAVA_22_VERSION                   66
 150 
 151 #define JAVA_23_VERSION                   67
 152 


 153 #define JAVA_24_VERSION                   68
 154 
 155 #define JAVA_25_VERSION                   69
 156 
 157 void ClassFileParser::set_class_bad_constant_seen(short bad_constant) {
 158   assert((bad_constant == JVM_CONSTANT_Module ||
 159           bad_constant == JVM_CONSTANT_Package) && _major_version >= JAVA_9_VERSION,
 160          "Unexpected bad constant pool entry");
 161   if (_bad_constant_seen == 0) _bad_constant_seen = bad_constant;
 162 }
 163 
 164 void ClassFileParser::parse_constant_pool_entries(const ClassFileStream* const stream,
 165                                                   ConstantPool* cp,
 166                                                   const int length,
 167                                                   TRAPS) {
 168   assert(stream != nullptr, "invariant");
 169   assert(cp != nullptr, "invariant");
 170 
 171   // Use a local copy of ClassFileStream. It helps the C++ compiler to optimize
 172   // this function (_current can be allocated in a register, with scalar

 175   // this method that uses stream().
 176   const ClassFileStream cfs1 = *stream;
 177   const ClassFileStream* const cfs = &cfs1;
 178 
 179   debug_only(const u1* const old_current = stream->current();)
 180 
 181   // Used for batching symbol allocations.
 182   const char* names[SymbolTable::symbol_alloc_batch_size];
 183   int lengths[SymbolTable::symbol_alloc_batch_size];
 184   int indices[SymbolTable::symbol_alloc_batch_size];
 185   unsigned int hashValues[SymbolTable::symbol_alloc_batch_size];
 186   int names_count = 0;
 187 
 188   // parsing  Index 0 is unused
 189   for (int index = 1; index < length; index++) {
 190     // Each of the following case guarantees one more byte in the stream
 191     // for the following tag or the access_flags following constant pool,
 192     // so we don't need bounds-check for reading tag.
 193     const u1 tag = cfs->get_u1_fast();
 194     switch (tag) {
 195       case JVM_CONSTANT_Class : {
 196         cfs->guarantee_more(3, CHECK);  // name_index, tag/access_flags
 197         const u2 name_index = cfs->get_u2_fast();
 198         cp->klass_index_at_put(index, name_index);
 199         break;
 200       }
 201       case JVM_CONSTANT_Fieldref: {
 202         cfs->guarantee_more(5, CHECK);  // class_index, name_and_type_index, tag/access_flags
 203         const u2 class_index = cfs->get_u2_fast();
 204         const u2 name_and_type_index = cfs->get_u2_fast();
 205         cp->field_at_put(index, class_index, name_and_type_index);
 206         break;
 207       }
 208       case JVM_CONSTANT_Methodref: {
 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->method_at_put(index, class_index, name_and_type_index);
 213         break;
 214       }
 215       case JVM_CONSTANT_InterfaceMethodref: {

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



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

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

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








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

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









 792                                        bool* const has_nonstatic_concrete_methods,






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

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

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



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

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

1375   cfs->guarantee_more(2, CHECK);  // length
1376   const u2 length = cfs->get_u2_fast();
1377   *java_fields_count_ptr = length;
1378 
1379   int num_injected = 0;
1380   const InjectedField* const injected = JavaClasses::get_injected(_class_name,
1381                                                                   &num_injected);
1382   const int total_fields = length + num_injected;




1383 
1384   // Allocate a temporary resource array to collect field data.
1385   // After parsing all fields, data are stored in a UNSIGNED5 compressed stream.
1386   _temp_field_info = new GrowableArray<FieldInfo>(total_fields);
1387 

1388   ResourceMark rm(THREAD);
1389   for (int n = 0; n < length; n++) {
1390     // access_flags, name_index, descriptor_index, attributes_count
1391     cfs->guarantee_more(8, CHECK);
1392 







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

1412 
1413     u2 constantvalue_index = 0;
1414     bool is_synthetic = false;
1415     u2 generic_signature_index = 0;
1416     const bool is_static = access_flags.is_static();
1417     FieldAnnotationCollector parsed_annotations(_loader_data);
1418 


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










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




1460     const BasicType type = cp->basic_type_for_signature_at(signature_index);
1461 
1462     // Update number of static oop fields.
1463     if (is_static && is_reference_type(type)) {
1464       _static_oop_count++;
1465     }
1466 
1467     FieldInfo fi(access_flags, name_index, signature_index, constantvalue_index, fieldFlags);
1468     fi.set_index(n);
1469     if (fieldFlags.is_generic()) {
1470       fi.set_generic_signature_index(generic_signature_index);
1471     }
1472     parsed_annotations.apply_to(&fi);
1473     if (fi.field_flags().is_contended()) {
1474       _has_contended_fields = true;
1475     }
1476     _temp_field_info->append(fi);
1477   }
1478   assert(_temp_field_info->length() == length, "Must be");
1479 
1480   int index = length;
1481   if (num_injected != 0) {
1482     for (int n = 0; n < num_injected; n++) {
1483       // Check for duplicates
1484       if (injected[n].may_be_java) {
1485         const Symbol* const name      = injected[n].name();
1486         const Symbol* const signature = injected[n].signature();
1487         bool duplicate = false;
1488         for (int i = 0; i < length; i++) {
1489           const FieldInfo* const f = _temp_field_info->adr_at(i);
1490           if (name      == cp->symbol_at(f->name_index()) &&
1491               signature == cp->symbol_at(f->signature_index())) {
1492             // Symbol is desclared in Java so skip this one
1493             duplicate = true;
1494             break;
1495           }
1496         }
1497         if (duplicate) {
1498           // These will be removed from the field array at the end
1499           continue;
1500         }
1501       }
1502 
1503       // Injected field
1504       FieldInfo::FieldFlags fflags(0);
1505       fflags.update_injected(true);
1506       AccessFlags aflags;
1507       FieldInfo fi(aflags, (u2)(injected[n].name_index), (u2)(injected[n].signature_index), 0, fflags);
1508       fi.set_index(index);
1509       _temp_field_info->append(fi);
1510       index++;
1511     }
1512   }
1513 
1514   assert(_temp_field_info->length() == index, "Must be");

























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

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












1894     case VM_SYMBOL_ENUM_NAME(java_lang_Deprecated): {
1895       return _java_lang_Deprecated;
1896     }
1897     default: {
1898       break;
1899     }
1900   }
1901   return AnnotationCollector::_unknown;
1902 }
1903 
1904 void ClassFileParser::FieldAnnotationCollector::apply_to(FieldInfo* f) {
1905   if (is_contended())
1906     // Setting the contended group also sets the contended bit in field flags
1907     f->set_contended_group(contended_group());
1908   if (is_stable())
1909     (f->field_flags_addr())->update_stable(true);
1910 }
1911 
1912 ClassFileParser::FieldAnnotationCollector::~FieldAnnotationCollector() {
1913   // If there's an error deallocate metadata for field annotations

2097   }
2098 
2099   if (runtime_visible_type_annotations_length > 0) {
2100     a = allocate_annotations(runtime_visible_type_annotations,
2101                              runtime_visible_type_annotations_length,
2102                              CHECK);
2103     cm->set_type_annotations(a);
2104   }
2105 }
2106 
2107 
2108 // Note: the parse_method below is big and clunky because all parsing of the code and exceptions
2109 // attribute is inlined. This is cumbersome to avoid since we inline most of the parts in the
2110 // Method* to save footprint, so we only know the size of the resulting Method* when the
2111 // entire method attribute is parsed.
2112 //
2113 // The has_localvariable_table parameter is used to pass up the value to InstanceKlass.
2114 
2115 Method* ClassFileParser::parse_method(const ClassFileStream* const cfs,
2116                                       bool is_interface,


2117                                       const ConstantPool* cp,
2118                                       bool* const has_localvariable_table,
2119                                       TRAPS) {
2120   assert(cfs != nullptr, "invariant");
2121   assert(cp != nullptr, "invariant");
2122   assert(has_localvariable_table != nullptr, "invariant");
2123 
2124   ResourceMark rm(THREAD);
2125   // Parse fixed parts:
2126   // access_flags, name_index, descriptor_index, attributes_count
2127   cfs->guarantee_more(8, CHECK_NULL);
2128 
2129   u2 flags = cfs->get_u2_fast();
2130   const u2 name_index = cfs->get_u2_fast();
2131   const int cp_size = cp->length();
2132   guarantee_property(
2133     valid_symbol_at(name_index),
2134     "Illegal constant pool index %u for method name in class file %s",
2135     name_index, CHECK_NULL);
2136   const Symbol* const name = cp->symbol_at(name_index);

2138 
2139   const u2 signature_index = cfs->get_u2_fast();
2140   guarantee_property(
2141     valid_symbol_at(signature_index),
2142     "Illegal constant pool index %u for method signature in class file %s",
2143     signature_index, CHECK_NULL);
2144   const Symbol* const signature = cp->symbol_at(signature_index);
2145 
2146   if (name == vmSymbols::class_initializer_name()) {
2147     // We ignore the other access flags for a valid class initializer.
2148     // (JVM Spec 2nd ed., chapter 4.6)
2149     if (_major_version < 51) { // backward compatibility
2150       flags = JVM_ACC_STATIC;
2151     } else if ((flags & JVM_ACC_STATIC) == JVM_ACC_STATIC) {
2152       flags &= JVM_ACC_STATIC | (_major_version <= JAVA_16_VERSION ? JVM_ACC_STRICT : 0);
2153     } else {
2154       classfile_parse_error("Method <clinit> is not static in class file %s", THREAD);
2155       return nullptr;
2156     }
2157   } else {
2158     verify_legal_method_modifiers(flags, is_interface, name, CHECK_NULL);
2159   }
2160 
2161   if (name == vmSymbols::object_initializer_name() && is_interface) {
2162     classfile_parse_error("Interface cannot have a method named <init>, class file %s", THREAD);
2163     return nullptr;
2164   }
2165 









2166   int args_size = -1;  // only used when _need_verify is true
2167   if (_need_verify) {
2168     verify_legal_name_with_signature(name, signature, CHECK_NULL);
2169     args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) +
2170                  verify_legal_method_signature(name, signature, CHECK_NULL);
2171     if (args_size > MAX_ARGS_SIZE) {
2172       classfile_parse_error("Too many arguments in method signature in class file %s", THREAD);
2173       return nullptr;
2174     }
2175   }
2176 
2177   AccessFlags access_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS);
2178 
2179   // Default values for code and exceptions attribute elements
2180   u2 max_stack = 0;
2181   u2 max_locals = 0;
2182   u4 code_length = 0;
2183   const u1* code_start = nullptr;
2184   u2 exception_table_length = 0;
2185   const unsafe_u2* exception_table_start = nullptr; // (potentially unaligned) pointer to array of u2 elements

2673                           CHECK_NULL);
2674 
2675   if (InstanceKlass::is_finalization_enabled() &&
2676       name == vmSymbols::finalize_method_name() &&
2677       signature == vmSymbols::void_method_signature()) {
2678     if (m->is_empty_method()) {
2679       _has_empty_finalizer = true;
2680     } else {
2681       _has_finalizer = true;
2682     }
2683   }
2684 
2685   NOT_PRODUCT(m->verify());
2686   return m;
2687 }
2688 
2689 
2690 // Side-effects: populates the _methods field in the parser
2691 void ClassFileParser::parse_methods(const ClassFileStream* const cfs,
2692                                     bool is_interface,


2693                                     bool* const has_localvariable_table,
2694                                     bool* has_final_method,
2695                                     bool* declares_nonstatic_concrete_methods,
2696                                     TRAPS) {
2697   assert(cfs != nullptr, "invariant");
2698   assert(has_localvariable_table != nullptr, "invariant");
2699   assert(has_final_method != nullptr, "invariant");
2700   assert(declares_nonstatic_concrete_methods != nullptr, "invariant");
2701 
2702   assert(nullptr == _methods, "invariant");
2703 
2704   cfs->guarantee_more(2, CHECK);  // length
2705   const u2 length = cfs->get_u2_fast();
2706   if (length == 0) {
2707     _methods = Universe::the_empty_method_array();
2708   } else {
2709     _methods = MetadataFactory::new_array<Method*>(_loader_data,
2710                                                    length,
2711                                                    nullptr,
2712                                                    CHECK);
2713 
2714     for (int index = 0; index < length; index++) {
2715       Method* method = parse_method(cfs,
2716                                     is_interface,


2717                                     _cp,
2718                                     has_localvariable_table,
2719                                     CHECK);
2720 
2721       if (method->is_final()) {
2722         *has_final_method = true;
2723       }
2724       // declares_nonstatic_concrete_methods: declares concrete instance methods, any access flags
2725       // used for interface initialization, and default method inheritance analysis
2726       if (is_interface && !(*declares_nonstatic_concrete_methods)
2727         && !method->is_abstract() && !method->is_static()) {
2728         *declares_nonstatic_concrete_methods = true;
2729       }
2730       _methods->at_put(index, method);
2731     }
2732 
2733     if (_need_verify && length > 1) {
2734       // Check duplicated methods
2735       ResourceMark rm(THREAD);
2736       // Set containing name-signature pairs

2962         valid_klass_reference_at(outer_class_info_index),
2963       "outer_class_info_index %u has bad constant type in class file %s",
2964       outer_class_info_index, CHECK_0);
2965 
2966     if (outer_class_info_index != 0) {
2967       const Symbol* const outer_class_name = cp->klass_name_at(outer_class_info_index);
2968       char* bytes = (char*)outer_class_name->bytes();
2969       guarantee_property(bytes[0] != JVM_SIGNATURE_ARRAY,
2970                          "Outer class is an array class in class file %s", CHECK_0);
2971     }
2972     // Inner class name
2973     const u2 inner_name_index = cfs->get_u2_fast();
2974     guarantee_property(
2975       inner_name_index == 0 || valid_symbol_at(inner_name_index),
2976       "inner_name_index %u has bad constant type in class file %s",
2977       inner_name_index, CHECK_0);
2978     if (_need_verify) {
2979       guarantee_property(inner_class_info_index != outer_class_info_index,
2980                          "Class is both outer and inner class in class file %s", CHECK_0);
2981     }
2982     // Access flags
2983     u2 flags;
2984     // JVM_ACC_MODULE is defined in JDK-9 and later.
2985     if (_major_version >= JAVA_9_VERSION) {
2986       flags = cfs->get_u2_fast() & (RECOGNIZED_INNER_CLASS_MODIFIERS | JVM_ACC_MODULE);
2987     } else {
2988       flags = cfs->get_u2_fast() & RECOGNIZED_INNER_CLASS_MODIFIERS;
2989     }




2990     if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
2991       // Set abstract bit for old class files for backward compatibility
2992       flags |= JVM_ACC_ABSTRACT;
2993     }
2994     verify_legal_class_modifiers(flags, CHECK_0);










2995     AccessFlags inner_access_flags(flags);
2996 
2997     inner_classes->at_put(index++, inner_class_info_index);
2998     inner_classes->at_put(index++, outer_class_info_index);
2999     inner_classes->at_put(index++, inner_name_index);
3000     inner_classes->at_put(index++, inner_access_flags.as_unsigned_short());
3001   }
3002 
3003   // Check for circular and duplicate entries.
3004   bool has_circularity = false;
3005   if (_need_verify) {
3006     has_circularity = check_inner_classes_circularity(cp, length * 4, CHECK_0);
3007     if (has_circularity) {
3008       // If circularity check failed then ignore InnerClasses attribute.
3009       MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
3010       index = 0;
3011       if (parsed_enclosingmethod_attribute) {
3012         inner_classes = MetadataFactory::new_array<u2>(_loader_data, 2, CHECK_0);
3013         _inner_classes = inner_classes;
3014       } else {

3078   if (length > 0) {
3079     int index = 0;
3080     cfs->guarantee_more(2 * length, CHECK_0);
3081     for (int n = 0; n < length; n++) {
3082       const u2 class_info_index = cfs->get_u2_fast();
3083       guarantee_property(
3084         valid_klass_reference_at(class_info_index),
3085         "Permitted subclass class_info_index %u has bad constant type in class file %s",
3086         class_info_index, CHECK_0);
3087       permitted_subclasses->at_put(index++, class_info_index);
3088     }
3089     assert(index == size, "wrong size");
3090   }
3091 
3092   // Restore buffer's current position.
3093   cfs->set_current(current_mark);
3094 
3095   return length;
3096 }
3097 











































3098 //  Record {
3099 //    u2 attribute_name_index;
3100 //    u4 attribute_length;
3101 //    u2 components_count;
3102 //    component_info components[components_count];
3103 //  }
3104 //  component_info {
3105 //    u2 name_index;
3106 //    u2 descriptor_index
3107 //    u2 attributes_count;
3108 //    attribute_info_attributes[attributes_count];
3109 //  }
3110 u4 ClassFileParser::parse_classfile_record_attribute(const ClassFileStream* const cfs,
3111                                                      const ConstantPool* cp,
3112                                                      const u1* const record_attribute_start,
3113                                                      TRAPS) {
3114   const u1* const current_mark = cfs->current();
3115   int components_count = 0;
3116   unsigned int calculate_attr_size = 0;
3117   if (record_attribute_start != nullptr) {

3343   }
3344   guarantee_property(current_start + attribute_byte_length == cfs->current(),
3345                      "Bad length on BootstrapMethods in class file %s",
3346                      CHECK);
3347 }
3348 
3349 void ClassFileParser::parse_classfile_attributes(const ClassFileStream* const cfs,
3350                                                  ConstantPool* cp,
3351                  ClassFileParser::ClassAnnotationCollector* parsed_annotations,
3352                                                  TRAPS) {
3353   assert(cfs != nullptr, "invariant");
3354   assert(cp != nullptr, "invariant");
3355   assert(parsed_annotations != nullptr, "invariant");
3356 
3357   // Set inner classes attribute to default sentinel
3358   _inner_classes = Universe::the_empty_short_array();
3359   // Set nest members attribute to default sentinel
3360   _nest_members = Universe::the_empty_short_array();
3361   // Set _permitted_subclasses attribute to default sentinel
3362   _permitted_subclasses = Universe::the_empty_short_array();


3363   cfs->guarantee_more(2, CHECK);  // attributes_count
3364   u2 attributes_count = cfs->get_u2_fast();
3365   bool parsed_sourcefile_attribute = false;
3366   bool parsed_innerclasses_attribute = false;
3367   bool parsed_nest_members_attribute = false;
3368   bool parsed_permitted_subclasses_attribute = false;

3369   bool parsed_nest_host_attribute = false;
3370   bool parsed_record_attribute = false;
3371   bool parsed_enclosingmethod_attribute = false;
3372   bool parsed_bootstrap_methods_attribute = false;
3373   const u1* runtime_visible_annotations = nullptr;
3374   int runtime_visible_annotations_length = 0;
3375   const u1* runtime_visible_type_annotations = nullptr;
3376   int runtime_visible_type_annotations_length = 0;
3377   bool runtime_invisible_type_annotations_exists = false;
3378   bool runtime_invisible_annotations_exists = false;
3379   bool parsed_source_debug_ext_annotations_exist = false;
3380   const u1* inner_classes_attribute_start = nullptr;
3381   u4  inner_classes_attribute_length = 0;
3382   u2  enclosing_method_class_index = 0;
3383   u2  enclosing_method_method_index = 0;
3384   const u1* nest_members_attribute_start = nullptr;
3385   u4  nest_members_attribute_length = 0;
3386   const u1* record_attribute_start = nullptr;
3387   u4  record_attribute_length = 0;
3388   const u1* permitted_subclasses_attribute_start = nullptr;
3389   u4  permitted_subclasses_attribute_length = 0;


3390 
3391   // Iterate over attributes
3392   while (attributes_count--) {
3393     cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
3394     const u2 attribute_name_index = cfs->get_u2_fast();
3395     const u4 attribute_length = cfs->get_u4_fast();
3396     guarantee_property(
3397       valid_symbol_at(attribute_name_index),
3398       "Attribute name has bad constant pool index %u in class file %s",
3399       attribute_name_index, CHECK);
3400     const Symbol* const tag = cp->symbol_at(attribute_name_index);
3401     if (tag == vmSymbols::tag_source_file()) {
3402       // Check for SourceFile tag
3403       if (_need_verify) {
3404         guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
3405       }
3406       if (parsed_sourcefile_attribute) {
3407         classfile_parse_error("Multiple SourceFile attributes in class file %s", THREAD);
3408         return;
3409       } else {

3585               return;
3586             }
3587             parsed_record_attribute = true;
3588             record_attribute_start = cfs->current();
3589             record_attribute_length = attribute_length;
3590           } else if (_major_version >= JAVA_17_VERSION) {
3591             if (tag == vmSymbols::tag_permitted_subclasses()) {
3592               if (parsed_permitted_subclasses_attribute) {
3593                 classfile_parse_error("Multiple PermittedSubclasses attributes in class file %s", CHECK);
3594                 return;
3595               }
3596               // Classes marked ACC_FINAL cannot have a PermittedSubclasses attribute.
3597               if (_access_flags.is_final()) {
3598                 classfile_parse_error("PermittedSubclasses attribute in final class file %s", CHECK);
3599                 return;
3600               }
3601               parsed_permitted_subclasses_attribute = true;
3602               permitted_subclasses_attribute_start = cfs->current();
3603               permitted_subclasses_attribute_length = attribute_length;
3604             }









3605           }
3606           // Skip attribute_length for any attribute where major_verson >= JAVA_17_VERSION
3607           cfs->skip_u1(attribute_length, CHECK);
3608         } else {
3609           // Unknown attribute
3610           cfs->skip_u1(attribute_length, CHECK);
3611         }
3612       } else {
3613         // Unknown attribute
3614         cfs->skip_u1(attribute_length, CHECK);
3615       }
3616     } else {
3617       // Unknown attribute
3618       cfs->skip_u1(attribute_length, CHECK);
3619     }
3620   }
3621   _class_annotations = allocate_annotations(runtime_visible_annotations,
3622                                             runtime_visible_annotations_length,
3623                                             CHECK);
3624   _class_type_annotations = allocate_annotations(runtime_visible_type_annotations,

3661                             CHECK);
3662     if (_need_verify) {
3663       guarantee_property(record_attribute_length == calculated_attr_length,
3664                          "Record attribute has wrong length in class file %s",
3665                          CHECK);
3666     }
3667   }
3668 
3669   if (parsed_permitted_subclasses_attribute) {
3670     const u2 num_subclasses = parse_classfile_permitted_subclasses_attribute(
3671                             cfs,
3672                             permitted_subclasses_attribute_start,
3673                             CHECK);
3674     if (_need_verify) {
3675       guarantee_property(
3676         permitted_subclasses_attribute_length == sizeof(num_subclasses) + sizeof(u2) * num_subclasses,
3677         "Wrong PermittedSubclasses attribute length in class file %s", CHECK);
3678     }
3679   }
3680 












3681   if (_max_bootstrap_specifier_index >= 0) {
3682     guarantee_property(parsed_bootstrap_methods_attribute,
3683                        "Missing BootstrapMethods attribute in class file %s", CHECK);
3684   }
3685 }
3686 
3687 void ClassFileParser::apply_parsed_class_attributes(InstanceKlass* k) {
3688   assert(k != nullptr, "invariant");
3689 
3690   if (_synthetic_flag)
3691     k->set_is_synthetic();
3692   if (_sourcefile_index != 0) {
3693     k->set_source_file_name_index(_sourcefile_index);
3694   }
3695   if (_generic_signature_index != 0) {
3696     k->set_generic_signature_index(_generic_signature_index);
3697   }
3698   if (_sde_buffer != nullptr) {
3699     k->set_source_debug_extension(_sde_buffer, _sde_length);
3700   }

3726     _class_annotations       = nullptr;
3727     _class_type_annotations  = nullptr;
3728     _fields_annotations      = nullptr;
3729     _fields_type_annotations = nullptr;
3730 }
3731 
3732 // Transfer ownership of metadata allocated to the InstanceKlass.
3733 void ClassFileParser::apply_parsed_class_metadata(
3734                                             InstanceKlass* this_klass,
3735                                             int java_fields_count) {
3736   assert(this_klass != nullptr, "invariant");
3737 
3738   _cp->set_pool_holder(this_klass);
3739   this_klass->set_constants(_cp);
3740   this_klass->set_fieldinfo_stream(_fieldinfo_stream);
3741   this_klass->set_fields_status(_fields_status);
3742   this_klass->set_methods(_methods);
3743   this_klass->set_inner_classes(_inner_classes);
3744   this_klass->set_nest_members(_nest_members);
3745   this_klass->set_nest_host_index(_nest_host);

3746   this_klass->set_annotations(_combined_annotations);
3747   this_klass->set_permitted_subclasses(_permitted_subclasses);
3748   this_klass->set_record_components(_record_components);

3749 
3750   // Delay the setting of _local_interfaces and _transitive_interfaces until after
3751   // initialize_supers() in fill_instance_klass(). It is because the _local_interfaces could
3752   // be shared with _transitive_interfaces and _transitive_interfaces may be shared with
3753   // its _super. If an OOM occurs while loading the current klass, its _super field
3754   // may not have been set. When GC tries to free the klass, the _transitive_interfaces
3755   // may be deallocated mistakenly in InstanceKlass::deallocate_interfaces(). Subsequent
3756   // dereferences to the deallocated _transitive_interfaces will result in a crash.
3757 
3758   // Clear out these fields so they don't get deallocated by the destructor
3759   clear_class_metadata();
3760 }
3761 
3762 AnnotationArray* ClassFileParser::allocate_annotations(const u1* const anno,
3763                                                        int anno_length,
3764                                                        TRAPS) {
3765   AnnotationArray* annotations = nullptr;
3766   if (anno != nullptr) {
3767     annotations = MetadataFactory::new_array<u1>(_loader_data,
3768                                                  anno_length,
3769                                                  CHECK_(annotations));
3770     for (int i = 0; i < anno_length; i++) {
3771       annotations->at_put(i, anno[i]);
3772     }
3773   }
3774   return annotations;
3775 }
3776 
3777 const InstanceKlass* ClassFileParser::parse_super_class(ConstantPool* const cp,
3778                                                         const int super_class_index,
3779                                                         const bool need_verify,
3780                                                         TRAPS) {
3781   assert(cp != nullptr, "invariant");
3782   const InstanceKlass* super_klass = nullptr;
3783 
3784   if (super_class_index == 0) {
3785     guarantee_property(_class_name == vmSymbols::java_lang_Object(),
3786                        "Invalid superclass index %u in class file %s",
3787                        super_class_index,
3788                        CHECK_NULL);
3789   } else {
3790     guarantee_property(valid_klass_reference_at(super_class_index),
3791                        "Invalid superclass index %u in class file %s",
3792                        super_class_index,
3793                        CHECK_NULL);
3794     // The class name should be legal because it is checked when parsing constant pool.
3795     // However, make sure it is not an array type.
3796     bool is_array = false;
3797     if (cp->tag_at(super_class_index).is_klass()) {
3798       super_klass = InstanceKlass::cast(cp->resolved_klass_at(super_class_index));
3799       if (need_verify)
3800         is_array = super_klass->is_array_klass();
3801     } else if (need_verify) {
3802       is_array = (cp->klass_name_at(super_class_index)->char_at(0) == JVM_SIGNATURE_ARRAY);
3803     }
3804     if (need_verify) {

3805       guarantee_property(!is_array,
3806                         "Bad superclass name in class file %s", CHECK_NULL);
3807     }
3808   }
3809   return super_klass;
3810 }
3811 
3812 OopMapBlocksBuilder::OopMapBlocksBuilder(unsigned int max_blocks) {
3813   _max_nonstatic_oop_maps = max_blocks;
3814   _nonstatic_oop_map_count = 0;
3815   if (max_blocks == 0) {
3816     _nonstatic_oop_maps = nullptr;
3817   } else {
3818     _nonstatic_oop_maps =
3819         NEW_RESOURCE_ARRAY(OopMapBlock, _max_nonstatic_oop_maps);
3820     memset(_nonstatic_oop_maps, 0, sizeof(OopMapBlock) * max_blocks);
3821   }
3822 }
3823 
3824 OopMapBlock* OopMapBlocksBuilder::last_oop_map() const {

3958 
3959   // Check if this klass supports the java.lang.Cloneable interface
3960   if (vmClasses::Cloneable_klass_loaded()) {
3961     if (ik->is_subtype_of(vmClasses::Cloneable_klass())) {
3962       ik->set_is_cloneable();
3963     }
3964   }
3965 
3966   // If it cannot be fast-path allocated, set a bit in the layout helper.
3967   // See documentation of InstanceKlass::can_be_fastpath_allocated().
3968   assert(ik->size_helper() > 0, "layout_helper is initialized");
3969   if (ik->is_abstract() || ik->is_interface()
3970       || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == nullptr)
3971       || ik->size_helper() >= FastAllocateSizeLimit) {
3972     // Forbid fast-path allocation.
3973     const jint lh = Klass::instance_layout_helper(ik->size_helper(), true);
3974     ik->set_layout_helper(lh);
3975   }
3976 }
3977 






3978 // utility methods for appending an array with check for duplicates
3979 
3980 static void append_interfaces(GrowableArray<InstanceKlass*>* result,
3981                               const Array<InstanceKlass*>* const ifs) {
3982   // iterate over new interfaces
3983   for (int i = 0; i < ifs->length(); i++) {
3984     InstanceKlass* const e = ifs->at(i);
3985     assert(e->is_klass() && e->is_interface(), "just checking");
3986     // add new interface
3987     result->append_if_missing(e);
3988   }
3989 }
3990 
3991 static Array<InstanceKlass*>* compute_transitive_interfaces(const InstanceKlass* super,
3992                                                             Array<InstanceKlass*>* local_ifs,
3993                                                             ClassLoaderData* loader_data,
3994                                                             TRAPS) {
3995   assert(local_ifs != nullptr, "invariant");
3996   assert(loader_data != nullptr, "invariant");
3997 

4001   // Add superclass transitive interfaces size
4002   if (super != nullptr) {
4003     super_size = super->transitive_interfaces()->length();
4004     max_transitive_size += super_size;
4005   }
4006   // Add local interfaces' super interfaces
4007   const int local_size = local_ifs->length();
4008   for (int i = 0; i < local_size; i++) {
4009     InstanceKlass* const l = local_ifs->at(i);
4010     max_transitive_size += l->transitive_interfaces()->length();
4011   }
4012   // Finally add local interfaces
4013   max_transitive_size += local_size;
4014   // Construct array
4015   if (max_transitive_size == 0) {
4016     // no interfaces, use canonicalized array
4017     return Universe::the_empty_instance_klass_array();
4018   } else if (max_transitive_size == super_size) {
4019     // no new local interfaces added, share superklass' transitive interface array
4020     return super->transitive_interfaces();
4021   } else if (max_transitive_size == local_size) {
4022     // only local interfaces added, share local interface array
4023     return local_ifs;

4024   } else {
4025     ResourceMark rm;
4026     GrowableArray<InstanceKlass*>* const result = new GrowableArray<InstanceKlass*>(max_transitive_size);
4027 
4028     // Copy down from superclass
4029     if (super != nullptr) {
4030       append_interfaces(result, super->transitive_interfaces());
4031     }
4032 
4033     // Copy down from local interfaces' superinterfaces
4034     for (int i = 0; i < local_size; i++) {
4035       InstanceKlass* const l = local_ifs->at(i);
4036       append_interfaces(result, l->transitive_interfaces());
4037     }
4038     // Finally add local interfaces
4039     append_interfaces(result, local_ifs);
4040 
4041     // length will be less than the max_transitive_size if duplicates were removed
4042     const int length = result->length();
4043     assert(length <= max_transitive_size, "just checking");

4044     Array<InstanceKlass*>* const new_result =
4045       MetadataFactory::new_array<InstanceKlass*>(loader_data, length, CHECK_NULL);
4046     for (int i = 0; i < length; i++) {
4047       InstanceKlass* const e = result->at(i);
4048       assert(e != nullptr, "just checking");
4049       new_result->at_put(i, e);
4050     }
4051     return new_result;
4052   }
4053 }
4054 
4055 void ClassFileParser::check_super_class_access(const InstanceKlass* this_klass, TRAPS) {
4056   assert(this_klass != nullptr, "invariant");
4057   const Klass* const super = this_klass->super();
4058 
4059   if (super != nullptr) {
4060     const InstanceKlass* super_ik = InstanceKlass::cast(super);
4061 
4062     if (super->is_final()) {
4063       classfile_icce_error("class %s cannot inherit from final class %s", super_ik, THREAD);
4064       return;
4065     }
4066 
4067     if (super_ik->is_sealed()) {
4068       stringStream ss;
4069       ResourceMark rm(THREAD);
4070       if (!super_ik->has_as_permitted_subclass(this_klass, ss)) {
4071         classfile_icce_error(ss.as_string(), THREAD);
4072         return;
4073       }
4074     }
4075 










4076     Reflection::VerifyClassAccessResults vca_result =
4077       Reflection::verify_class_access(this_klass, InstanceKlass::cast(super), false);
4078     if (vca_result != Reflection::ACCESS_OK) {
4079       ResourceMark rm(THREAD);
4080       char* msg = Reflection::verify_class_access_msg(this_klass,
4081                                                       InstanceKlass::cast(super),
4082                                                       vca_result);
4083 
4084       // Names are all known to be < 64k so we know this formatted message is not excessively large.
4085       if (msg == nullptr) {
4086         bool same_module = (this_klass->module() == super->module());
4087         Exceptions::fthrow(
4088           THREAD_AND_LOCATION,
4089           vmSymbols::java_lang_IllegalAccessError(),
4090           "class %s cannot access its %ssuperclass %s (%s%s%s)",
4091           this_klass->external_name(),
4092           super->is_abstract() ? "abstract " : "",
4093           super->external_name(),
4094           (same_module) ? this_klass->joint_in_module_of_loader(super) : this_klass->class_in_module_of_loader(),
4095           (same_module) ? "" : "; ",

4228     const Method* const m = methods->at(index);
4229     // if m is static and not the init method, throw a verify error
4230     if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) {
4231       ResourceMark rm(THREAD);
4232 
4233       // Names are all known to be < 64k so we know this formatted message is not excessively large.
4234       Exceptions::fthrow(
4235         THREAD_AND_LOCATION,
4236         vmSymbols::java_lang_VerifyError(),
4237         "Illegal static method %s in interface %s",
4238         m->name()->as_C_string(),
4239         this_klass->external_name()
4240       );
4241       return;
4242     }
4243   }
4244 }
4245 
4246 // utility methods for format checking
4247 
4248 void ClassFileParser::verify_legal_class_modifiers(jint flags, TRAPS) const {
4249   const bool is_module = (flags & JVM_ACC_MODULE) != 0;

4250   assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");
4251   if (is_module) {
4252     ResourceMark rm(THREAD);
4253     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4254     Exceptions::fthrow(
4255       THREAD_AND_LOCATION,
4256       vmSymbols::java_lang_NoClassDefFoundError(),
4257       "%s is not a class because access_flag ACC_MODULE is set",
4258       _class_name->as_C_string());
4259     return;
4260   }
4261 
4262   if (!_need_verify) { return; }
4263 
4264   const bool is_interface  = (flags & JVM_ACC_INTERFACE)  != 0;
4265   const bool is_abstract   = (flags & JVM_ACC_ABSTRACT)   != 0;
4266   const bool is_final      = (flags & JVM_ACC_FINAL)      != 0;
4267   const bool is_super      = (flags & JVM_ACC_SUPER)      != 0;
4268   const bool is_enum       = (flags & JVM_ACC_ENUM)       != 0;
4269   const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4270   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;


4271 
4272   if ((is_abstract && is_final) ||
4273       (is_interface && !is_abstract) ||
4274       (is_interface && major_gte_1_5 && (is_super || is_enum)) ||
4275       (!is_interface && major_gte_1_5 && is_annotation)) {

4276     ResourceMark rm(THREAD);
4277     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4278     Exceptions::fthrow(
4279       THREAD_AND_LOCATION,
4280       vmSymbols::java_lang_ClassFormatError(),
4281       "Illegal class modifiers in class %s: 0x%X",
4282       _class_name->as_C_string(), flags
4283     );
4284     return;














4285   }
4286 }
4287 
4288 static bool has_illegal_visibility(jint flags) {
4289   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4290   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4291   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4292 
4293   return ((is_public && is_protected) ||
4294           (is_public && is_private) ||
4295           (is_protected && is_private));
4296 }
4297 
4298 // A legal major_version.minor_version must be one of the following:
4299 //
4300 //  Major_version >= 45 and major_version < 56, any minor_version.
4301 //  Major_version >= 56 and major_version <= JVM_CLASSFILE_MAJOR_VERSION and minor_version = 0.
4302 //  Major_version = JVM_CLASSFILE_MAJOR_VERSION and minor_version = 65535 and --enable-preview is present.
4303 //
4304 void ClassFileParser::verify_class_version(u2 major, u2 minor, Symbol* class_name, TRAPS){

4332         THREAD_AND_LOCATION,
4333         vmSymbols::java_lang_UnsupportedClassVersionError(),
4334         "%s (class file version %u.%u) was compiled with preview features that are unsupported. "
4335         "This version of the Java Runtime only recognizes preview features for class file version %u.%u",
4336         class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION, JAVA_PREVIEW_MINOR_VERSION);
4337       return;
4338     }
4339 
4340     if (!Arguments::enable_preview()) {
4341       classfile_ucve_error("Preview features are not enabled for %s (class file version %u.%u). Try running with '--enable-preview'",
4342                            class_name, major, minor, THREAD);
4343       return;
4344     }
4345 
4346   } else { // minor != JAVA_PREVIEW_MINOR_VERSION
4347     classfile_ucve_error("%s (class file version %u.%u) was compiled with an invalid non-zero minor version",
4348                          class_name, major, minor, THREAD);
4349   }
4350 }
4351 
4352 void ClassFileParser::verify_legal_field_modifiers(jint flags,
4353                                                    bool is_interface,
4354                                                    TRAPS) const {
4355   if (!_need_verify) { return; }
4356 
4357   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4358   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4359   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4360   const bool is_static    = (flags & JVM_ACC_STATIC)    != 0;
4361   const bool is_final     = (flags & JVM_ACC_FINAL)     != 0;
4362   const bool is_volatile  = (flags & JVM_ACC_VOLATILE)  != 0;
4363   const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
4364   const bool is_enum      = (flags & JVM_ACC_ENUM)      != 0;

4365   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4366 



4367   bool is_illegal = false;

4368 
4369   if (is_interface) {
4370     if (!is_public || !is_static || !is_final || is_private ||
4371         is_protected || is_volatile || is_transient ||
4372         (major_gte_1_5 && is_enum)) {




4373       is_illegal = true;

4374     }
4375   } else { // not interface
4376     if (has_illegal_visibility(flags) || (is_final && is_volatile)) {
4377       is_illegal = true;

























4378     }
4379   }
4380 
4381   if (is_illegal) {
4382     ResourceMark rm(THREAD);
4383     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4384     Exceptions::fthrow(
4385       THREAD_AND_LOCATION,
4386       vmSymbols::java_lang_ClassFormatError(),
4387       "Illegal field modifiers in class %s: 0x%X",
4388       _class_name->as_C_string(), flags);
4389     return;
4390   }
4391 }
4392 
4393 void ClassFileParser::verify_legal_method_modifiers(jint flags,
4394                                                     bool is_interface,
4395                                                     const Symbol* name,
4396                                                     TRAPS) const {
4397   if (!_need_verify) { return; }
4398 
4399   const bool is_public       = (flags & JVM_ACC_PUBLIC)       != 0;
4400   const bool is_private      = (flags & JVM_ACC_PRIVATE)      != 0;
4401   const bool is_static       = (flags & JVM_ACC_STATIC)       != 0;
4402   const bool is_final        = (flags & JVM_ACC_FINAL)        != 0;
4403   const bool is_native       = (flags & JVM_ACC_NATIVE)       != 0;
4404   const bool is_abstract     = (flags & JVM_ACC_ABSTRACT)     != 0;
4405   const bool is_bridge       = (flags & JVM_ACC_BRIDGE)       != 0;
4406   const bool is_strict       = (flags & JVM_ACC_STRICT)       != 0;
4407   const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
4408   const bool is_protected    = (flags & JVM_ACC_PROTECTED)    != 0;
4409   const bool major_gte_1_5   = _major_version >= JAVA_1_5_VERSION;
4410   const bool major_gte_8     = _major_version >= JAVA_8_VERSION;
4411   const bool major_gte_17    = _major_version >= JAVA_17_VERSION;
4412   const bool is_initializer  = (name == vmSymbols::object_initializer_name());




4413 
4414   bool is_illegal = false;
4415 

4416   if (is_interface) {
4417     if (major_gte_8) {
4418       // Class file version is JAVA_8_VERSION or later Methods of
4419       // interfaces may set any of the flags except ACC_PROTECTED,
4420       // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must
4421       // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.
4422       if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
4423           (is_native || is_protected || is_final || is_synchronized) ||
4424           // If a specific method of a class or interface has its
4425           // ACC_ABSTRACT flag set, it must not have any of its
4426           // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,
4427           // ACC_STRICT, or ACC_SYNCHRONIZED flags set.  No need to
4428           // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as
4429           // those flags are illegal irrespective of ACC_ABSTRACT being set or not.
4430           (is_abstract && (is_private || is_static || (!major_gte_17 && is_strict)))) {
4431         is_illegal = true;
4432       }
4433     } else if (major_gte_1_5) {
4434       // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)
4435       if (!is_public || is_private || is_protected || is_static || is_final ||
4436           is_synchronized || is_native || !is_abstract || is_strict) {
4437         is_illegal = true;
4438       }
4439     } else {
4440       // Class file version is pre-JAVA_1_5_VERSION
4441       if (!is_public || is_static || is_final || is_native || !is_abstract) {
4442         is_illegal = true;
4443       }
4444     }
4445   } else { // not interface
4446     if (has_illegal_visibility(flags)) {
4447       is_illegal = true;
4448     } else {
4449       if (is_initializer) {
4450         if (is_static || is_final || is_synchronized || is_native ||
4451             is_abstract || (major_gte_1_5 && is_bridge)) {
4452           is_illegal = true;
4453         }
4454       } else { // not initializer
4455         if (is_abstract) {
4456           if ((is_final || is_native || is_private || is_static ||
4457               (major_gte_1_5 && (is_synchronized || (!major_gte_17 && is_strict))))) {
4458             is_illegal = true;





4459           }
4460         }
4461       }
4462     }
4463   }
4464 
4465   if (is_illegal) {
4466     ResourceMark rm(THREAD);
4467     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4468     Exceptions::fthrow(
4469       THREAD_AND_LOCATION,
4470       vmSymbols::java_lang_ClassFormatError(),
4471       "Method %s in class %s has illegal modifiers: 0x%X",
4472       name->as_C_string(), _class_name->as_C_string(), flags);

4473     return;
4474   }
4475 }
4476 
4477 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer,
4478                                         int length,
4479                                         TRAPS) const {
4480   assert(_need_verify, "only called when _need_verify is true");
4481   // Note: 0 <= length < 64K, as it comes from a u2 entry in the CP.
4482   if (!UTF8::is_legal_utf8(buffer, static_cast<size_t>(length), _major_version <= 47)) {
4483     classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", THREAD);
4484   }
4485 }
4486 
4487 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
4488 // In class names, '/' separates unqualified names.  This is verified in this function also.
4489 // Method names also may not contain the characters '<' or '>', unless <init>
4490 // or <clinit>.  Note that method names may not be <init> or <clinit> in this
4491 // method.  Because these names have been checked as special cases before
4492 // calling this method in verify_legal_method_name.

4510         if (type == ClassFileParser::LegalClass) {
4511           if (p == name || p+1 >= name+length ||
4512               *(p+1) == JVM_SIGNATURE_SLASH) {
4513             return false;
4514           }
4515         } else {
4516           return false;   // do not permit '/' unless it's class name
4517         }
4518         break;
4519       case JVM_SIGNATURE_SPECIAL:
4520       case JVM_SIGNATURE_ENDSPECIAL:
4521         // do not permit '<' or '>' in method names
4522         if (type == ClassFileParser::LegalMethod) {
4523           return false;
4524         }
4525     }
4526   }
4527   return true;
4528 }
4529 









4530 // Take pointer to a UTF8 byte string (not NUL-terminated).
4531 // Skip over the longest part of the string that could
4532 // be taken as a fieldname. Allow non-trailing '/'s if slash_ok is true.
4533 // Return a pointer to just past the fieldname.
4534 // Return null if no fieldname at all was found, or in the case of slash_ok
4535 // being true, we saw consecutive slashes (meaning we were looking for a
4536 // qualified path but found something that was badly-formed).
4537 static const char* skip_over_field_name(const char* const name,
4538                                         bool slash_ok,
4539                                         unsigned int length) {
4540   const char* p;
4541   jboolean last_is_slash = false;
4542   jboolean not_first_ch = false;
4543 
4544   for (p = name; p != name + length; not_first_ch = true) {
4545     const char* old_p = p;
4546     jchar ch = *p;
4547     if (ch < 128) {
4548       p++;
4549       // quick check for ascii

4611 // be taken as a field signature. Allow "void" if void_ok.
4612 // Return a pointer to just past the signature.
4613 // Return null if no legal signature is found.
4614 const char* ClassFileParser::skip_over_field_signature(const char* signature,
4615                                                        bool void_ok,
4616                                                        unsigned int length,
4617                                                        TRAPS) const {
4618   unsigned int array_dim = 0;
4619   while (length > 0) {
4620     switch (signature[0]) {
4621     case JVM_SIGNATURE_VOID: if (!void_ok) { return nullptr; }
4622     case JVM_SIGNATURE_BOOLEAN:
4623     case JVM_SIGNATURE_BYTE:
4624     case JVM_SIGNATURE_CHAR:
4625     case JVM_SIGNATURE_SHORT:
4626     case JVM_SIGNATURE_INT:
4627     case JVM_SIGNATURE_FLOAT:
4628     case JVM_SIGNATURE_LONG:
4629     case JVM_SIGNATURE_DOUBLE:
4630       return signature + 1;
4631     case JVM_SIGNATURE_CLASS: {

4632       if (_major_version < JAVA_1_5_VERSION) {
4633         // Skip over the class name if one is there
4634         const char* const p = skip_over_field_name(signature + 1, true, --length);
4635 
4636         // The next character better be a semicolon
4637         if (p && (p - signature) > 1 && p[0] == JVM_SIGNATURE_ENDCLASS) {
4638           return p + 1;
4639         }
4640       }
4641       else {
4642         // Skip leading 'L' and ignore first appearance of ';'
4643         signature++;
4644         const char* c = (const char*) memchr(signature, JVM_SIGNATURE_ENDCLASS, length - 1);
4645         // Format check signature
4646         if (c != nullptr) {
4647           int newlen = pointer_delta_as_int(c, (char*) signature);
4648           bool legal = verify_unqualified_name(signature, newlen, LegalClass);
4649           if (!legal) {
4650             classfile_parse_error("Class name is empty or contains illegal character "
4651                                   "in descriptor in class file %s",
4652                                   THREAD);
4653             return nullptr;
4654           }
4655           return signature + newlen + 1;
4656         }
4657       }
4658       return nullptr;
4659     }
4660     case JVM_SIGNATURE_ARRAY:
4661       array_dim++;
4662       if (array_dim > 255) {

4678 
4679 // Checks if name is a legal class name.
4680 void ClassFileParser::verify_legal_class_name(const Symbol* name, TRAPS) const {
4681   if (!_need_verify) { return; }
4682 
4683   assert(name->refcount() > 0, "symbol must be kept alive");
4684   char* bytes = (char*)name->bytes();
4685   unsigned int length = name->utf8_length();
4686   bool legal = false;
4687 
4688   if (length > 0) {
4689     const char* p;
4690     if (bytes[0] == JVM_SIGNATURE_ARRAY) {
4691       p = skip_over_field_signature(bytes, false, length, CHECK);
4692       legal = (p != nullptr) && ((p - bytes) == (int)length);
4693     } else if (_major_version < JAVA_1_5_VERSION) {
4694       if (bytes[0] != JVM_SIGNATURE_SPECIAL) {
4695         p = skip_over_field_name(bytes, true, length);
4696         legal = (p != nullptr) && ((p - bytes) == (int)length);
4697       }




4698     } else {
4699       // 4900761: relax the constraints based on JSR202 spec
4700       // Class names may be drawn from the entire Unicode character set.
4701       // Identifiers between '/' must be unqualified names.
4702       // The utf8 string has been verified when parsing cpool entries.
4703       legal = verify_unqualified_name(bytes, length, LegalClass);
4704     }
4705   }
4706   if (!legal) {
4707     ResourceMark rm(THREAD);
4708     assert(_class_name != nullptr, "invariant");
4709     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4710     Exceptions::fthrow(
4711       THREAD_AND_LOCATION,
4712       vmSymbols::java_lang_ClassFormatError(),
4713       "Illegal class name \"%.*s\" in class file %s", length, bytes,
4714       _class_name->as_C_string()
4715     );
4716     return;
4717   }

4745       THREAD_AND_LOCATION,
4746       vmSymbols::java_lang_ClassFormatError(),
4747       "Illegal field name \"%.*s\" in class %s", length, bytes,
4748       _class_name->as_C_string()
4749     );
4750     return;
4751   }
4752 }
4753 
4754 // Checks if name is a legal method name.
4755 void ClassFileParser::verify_legal_method_name(const Symbol* name, TRAPS) const {
4756   if (!_need_verify) { return; }
4757 
4758   assert(name != nullptr, "method name is null");
4759   char* bytes = (char*)name->bytes();
4760   unsigned int length = name->utf8_length();
4761   bool legal = false;
4762 
4763   if (length > 0) {
4764     if (bytes[0] == JVM_SIGNATURE_SPECIAL) {
4765       if (name == vmSymbols::object_initializer_name() || name == vmSymbols::class_initializer_name()) {

4766         legal = true;
4767       }
4768     } else if (_major_version < JAVA_1_5_VERSION) {
4769       const char* p;
4770       p = skip_over_field_name(bytes, false, length);
4771       legal = (p != nullptr) && ((p - bytes) == (int)length);
4772     } else {
4773       // 4881221: relax the constraints based on JSR202 spec
4774       legal = verify_unqualified_name(bytes, length, LegalMethod);
4775     }
4776   }
4777 
4778   if (!legal) {
4779     ResourceMark rm(THREAD);
4780     assert(_class_name != nullptr, "invariant");
4781     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4782     Exceptions::fthrow(
4783       THREAD_AND_LOCATION,
4784       vmSymbols::java_lang_ClassFormatError(),
4785       "Illegal method name \"%.*s\" in class %s", length, bytes,
4786       _class_name->as_C_string()
4787     );
4788     return;
4789   }
4790 }
4791 










4792 
4793 // Checks if signature is a legal field signature.
4794 void ClassFileParser::verify_legal_field_signature(const Symbol* name,
4795                                                    const Symbol* signature,
4796                                                    TRAPS) const {
4797   if (!_need_verify) { return; }
4798 
4799   const char* const bytes = (const char*)signature->bytes();
4800   const unsigned int length = signature->utf8_length();
4801   const char* const p = skip_over_field_signature(bytes, false, length, CHECK);
4802 
4803   if (p == nullptr || (p - bytes) != (int)length) {
4804     throwIllegalSignature("Field", name, signature, CHECK);
4805   }
4806 }
4807 
4808 // Check that the signature is compatible with the method name.  For example,
4809 // check that <init> has a void signature.
4810 void ClassFileParser::verify_legal_name_with_signature(const Symbol* name,
4811                                                        const Symbol* signature,
4812                                                        TRAPS) const {
4813   if (!_need_verify) {
4814     return;
4815   }
4816 
4817   // Class initializers cannot have args for class format version >= 51.
4818   if (name == vmSymbols::class_initializer_name() &&
4819       signature != vmSymbols::void_method_signature() &&
4820       _major_version >= JAVA_7_VERSION) {
4821     throwIllegalSignature("Method", name, signature, THREAD);
4822     return;
4823   }
4824 
4825   int sig_length = signature->utf8_length();
4826   if (name->utf8_length() > 0 &&
4827       name->char_at(0) == JVM_SIGNATURE_SPECIAL &&
4828       sig_length > 0 &&
4829       signature->char_at(sig_length - 1) != JVM_SIGNATURE_VOID) {
4830     throwIllegalSignature("Method", name, signature, THREAD);
4831   }
4832 }
4833 
4834 // Checks if signature is a legal method signature.
4835 // Returns number of parameters
4836 int ClassFileParser::verify_legal_method_signature(const Symbol* name,
4837                                                    const Symbol* signature,
4838                                                    TRAPS) const {
4839   if (!_need_verify) {
4840     // make sure caller's args_size will be less than 0 even for non-static
4841     // method so it will be recomputed in compute_size_of_parameters().
4842     return -2;
4843   }
4844 
4845   unsigned int args_size = 0;
4846   const char* p = (const char*)signature->bytes();
4847   unsigned int length = signature->utf8_length();
4848   const char* nextp;
4849 

4860       length -= pointer_delta_as_int(nextp, p);
4861       p = nextp;
4862       nextp = skip_over_field_signature(p, false, length, CHECK_0);
4863     }
4864     // The first non-signature thing better be a ')'
4865     if ((length > 0) && (*p++ == JVM_SIGNATURE_ENDFUNC)) {
4866       length--;
4867       // Now we better just have a return value
4868       nextp = skip_over_field_signature(p, true, length, CHECK_0);
4869       if (nextp && ((int)length == (nextp - p))) {
4870         return args_size;
4871       }
4872     }
4873   }
4874   // Report error
4875   throwIllegalSignature("Method", name, signature, THREAD);
4876   return 0;
4877 }
4878 
4879 int ClassFileParser::static_field_size() const {
4880   assert(_field_info != nullptr, "invariant");
4881   return _field_info->_static_field_size;
4882 }
4883 
4884 int ClassFileParser::total_oop_map_count() const {
4885   assert(_field_info != nullptr, "invariant");
4886   return _field_info->oop_map_blocks->_nonstatic_oop_map_count;
4887 }
4888 
4889 jint ClassFileParser::layout_size() const {
4890   assert(_field_info != nullptr, "invariant");
4891   return _field_info->_instance_size;
4892 }
4893 
4894 static void check_methods_for_intrinsics(const InstanceKlass* ik,
4895                                          const Array<Method*>* methods) {
4896   assert(ik != nullptr, "invariant");
4897   assert(methods != nullptr, "invariant");
4898 
4899   // Set up Method*::intrinsic_id as soon as we know the names of methods.
4900   // (We used to do this lazily, but now we query it in Rewriter,
4901   // which is eagerly done for every method, so we might as well do it now,
4902   // when everything is fresh in memory.)
4903   const vmSymbolID klass_id = Method::klass_id_for_intrinsics(ik);
4904 
4905   if (klass_id != vmSymbolID::NO_SID) {
4906     for (int j = 0; j < methods->length(); ++j) {
4907       Method* method = methods->at(j);
4908       method->init_intrinsic_id(klass_id);
4909 
4910       if (CheckIntrinsics) {
4911         // Check if an intrinsic is defined for method 'method',

4986   }
4987 }
4988 
4989 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook,
4990                                                       const ClassInstanceInfo& cl_inst_info,
4991                                                       TRAPS) {
4992   if (_klass != nullptr) {
4993     return _klass;
4994   }
4995 
4996   InstanceKlass* const ik =
4997     InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
4998 
4999   if (is_hidden()) {
5000     mangle_hidden_class_name(ik);
5001   }
5002 
5003   fill_instance_klass(ik, changed_by_loadhook, cl_inst_info, CHECK_NULL);
5004 
5005   assert(_klass == ik, "invariant");
5006 
5007   return ik;
5008 }
5009 
5010 void ClassFileParser::fill_instance_klass(InstanceKlass* ik,
5011                                           bool changed_by_loadhook,
5012                                           const ClassInstanceInfo& cl_inst_info,
5013                                           TRAPS) {
5014   assert(ik != nullptr, "invariant");
5015 
5016   // Set name and CLD before adding to CLD
5017   ik->set_class_loader_data(_loader_data);
5018   ik->set_name(_class_name);
5019 
5020   // Add all classes to our internal class loader list here,
5021   // including classes in the bootstrap (null) class loader.
5022   const bool publicize = !is_internal();
5023 
5024   _loader_data->add_class(ik, publicize);
5025 
5026   set_klass_to_deallocate(ik);
5027 
5028   assert(_field_info != nullptr, "invariant");
5029   assert(ik->static_field_size() == _field_info->_static_field_size, "sanity");
5030   assert(ik->nonstatic_oop_map_count() == _field_info->oop_map_blocks->_nonstatic_oop_map_count,
5031          "sanity");
5032 
5033   assert(ik->is_instance_klass(), "sanity");
5034   assert(ik->size_helper() == _field_info->_instance_size, "sanity");
5035 
5036   // Fill in information already parsed
5037   ik->set_should_verify_class(_need_verify);
5038 
5039   // Not yet: supers are done below to support the new subtype-checking fields
5040   ik->set_nonstatic_field_size(_field_info->_nonstatic_field_size);
5041   ik->set_has_nonstatic_fields(_field_info->_has_nonstatic_fields);












5042   ik->set_static_oop_field_count(_static_oop_count);
5043 
5044   // this transfers ownership of a lot of arrays from
5045   // the parser onto the InstanceKlass*
5046   apply_parsed_class_metadata(ik, _java_fields_count);



5047 
5048   // can only set dynamic nest-host after static nest information is set
5049   if (cl_inst_info.dynamic_nest_host() != nullptr) {
5050     ik->set_nest_host(cl_inst_info.dynamic_nest_host());
5051   }
5052 
5053   // note that is not safe to use the fields in the parser from this point on
5054   assert(nullptr == _cp, "invariant");
5055   assert(nullptr == _fieldinfo_stream, "invariant");
5056   assert(nullptr == _fields_status, "invariant");
5057   assert(nullptr == _methods, "invariant");
5058   assert(nullptr == _inner_classes, "invariant");
5059   assert(nullptr == _nest_members, "invariant");

5060   assert(nullptr == _combined_annotations, "invariant");
5061   assert(nullptr == _record_components, "invariant");
5062   assert(nullptr == _permitted_subclasses, "invariant");

5063 
5064   if (_has_localvariable_table) {
5065     ik->set_has_localvariable_table(true);
5066   }
5067 
5068   if (_has_final_method) {
5069     ik->set_has_final_method();
5070   }
5071 
5072   ik->copy_method_ordering(_method_ordering, CHECK);
5073   // The InstanceKlass::_methods_jmethod_ids cache
5074   // is managed on the assumption that the initial cache
5075   // size is equal to the number of methods in the class. If
5076   // that changes, then InstanceKlass::idnum_can_increment()
5077   // has to be changed accordingly.
5078   ik->set_initial_method_idnum(checked_cast<u2>(ik->methods()->length()));
5079 
5080   ik->set_this_class_index(_this_class_index);
5081 
5082   if (_is_hidden) {

5120   if ((_num_miranda_methods > 0) ||
5121       // if this class introduced new miranda methods or
5122       (_super_klass != nullptr && _super_klass->has_miranda_methods())
5123         // super class exists and this class inherited miranda methods
5124      ) {
5125        ik->set_has_miranda_methods(); // then set a flag
5126   }
5127 
5128   // Fill in information needed to compute superclasses.
5129   ik->initialize_supers(const_cast<InstanceKlass*>(_super_klass), _transitive_interfaces, CHECK);
5130   ik->set_transitive_interfaces(_transitive_interfaces);
5131   ik->set_local_interfaces(_local_interfaces);
5132   _transitive_interfaces = nullptr;
5133   _local_interfaces = nullptr;
5134 
5135   // Initialize itable offset tables
5136   klassItable::setup_itable_offset_table(ik);
5137 
5138   // Compute transitive closure of interfaces this class implements
5139   // Do final class setup
5140   OopMapBlocksBuilder* oop_map_blocks = _field_info->oop_map_blocks;
5141   if (oop_map_blocks->_nonstatic_oop_map_count > 0) {
5142     oop_map_blocks->copy(ik->start_of_nonstatic_oop_maps());
5143   }
5144 
5145   if (_has_contended_fields || _parsed_annotations->is_contended() ||
5146       ( _super_klass != nullptr && _super_klass->has_contended_annotations())) {
5147     ik->set_has_contended_annotations(true);
5148   }
5149 
5150   // Fill in has_finalizer and layout_helper
5151   set_precomputed_flags(ik);
5152 
5153   // check if this class can access its super class
5154   check_super_class_access(ik, CHECK);
5155 
5156   // check if this class can access its superinterfaces
5157   check_super_interface_access(ik, CHECK);
5158 
5159   // check if this class overrides any final method
5160   check_final_method_override(ik, CHECK);

5181 
5182   assert(_all_mirandas != nullptr, "invariant");
5183 
5184   // Generate any default methods - default methods are public interface methods
5185   // that have a default implementation.  This is new with Java 8.
5186   if (_has_nonstatic_concrete_methods) {
5187     DefaultMethods::generate_default_methods(ik,
5188                                              _all_mirandas,
5189                                              CHECK);
5190   }
5191 
5192   // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5193   if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5194       !module_entry->has_default_read_edges()) {
5195     if (!module_entry->set_has_default_read_edges()) {
5196       // We won a potential race
5197       JvmtiExport::add_default_read_edges(module_handle, THREAD);
5198     }
5199   }
5200 
















5201   ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5202 
5203   if (!is_internal()) {
5204     ik->print_class_load_logging(_loader_data, module_entry, _stream);
5205 
5206     if (ik->minor_version() == JAVA_PREVIEW_MINOR_VERSION &&
5207         ik->major_version() == JVM_CLASSFILE_MAJOR_VERSION &&
5208         log_is_enabled(Info, class, preview)) {
5209       ResourceMark rm;
5210       log_info(class, preview)("Loading class %s that depends on preview features (class file version %d.65535)",
5211                                ik->external_name(), JVM_CLASSFILE_MAJOR_VERSION);
5212     }
5213 
5214     if (log_is_enabled(Debug, class, resolve))  {
5215       ResourceMark rm;
5216       // print out the superclass.
5217       const char * from = ik->external_name();
5218       if (ik->java_super() != nullptr) {
5219         log_debug(class, resolve)("%s %s (super)",
5220                    from,

5262                                  ClassLoaderData* loader_data,
5263                                  const ClassLoadInfo* cl_info,
5264                                  Publicity pub_level,
5265                                  TRAPS) :
5266   _stream(stream),
5267   _class_name(nullptr),
5268   _loader_data(loader_data),
5269   _is_hidden(cl_info->is_hidden()),
5270   _can_access_vm_annotations(cl_info->can_access_vm_annotations()),
5271   _orig_cp_size(0),
5272   _static_oop_count(0),
5273   _super_klass(),
5274   _cp(nullptr),
5275   _fieldinfo_stream(nullptr),
5276   _fields_status(nullptr),
5277   _methods(nullptr),
5278   _inner_classes(nullptr),
5279   _nest_members(nullptr),
5280   _nest_host(0),
5281   _permitted_subclasses(nullptr),

5282   _record_components(nullptr),
5283   _local_interfaces(nullptr),

5284   _transitive_interfaces(nullptr),
5285   _combined_annotations(nullptr),
5286   _class_annotations(nullptr),
5287   _class_type_annotations(nullptr),
5288   _fields_annotations(nullptr),
5289   _fields_type_annotations(nullptr),
5290   _klass(nullptr),
5291   _klass_to_deallocate(nullptr),
5292   _parsed_annotations(nullptr),
5293   _field_info(nullptr),

5294   _temp_field_info(nullptr),
5295   _method_ordering(nullptr),
5296   _all_mirandas(nullptr),
5297   _vtable_size(0),
5298   _itable_size(0),
5299   _num_miranda_methods(0),
5300   _protection_domain(cl_info->protection_domain()),
5301   _access_flags(),
5302   _pub_level(pub_level),
5303   _bad_constant_seen(0),
5304   _synthetic_flag(false),
5305   _sde_length(false),
5306   _sde_buffer(nullptr),
5307   _sourcefile_index(0),
5308   _generic_signature_index(0),
5309   _major_version(0),
5310   _minor_version(0),
5311   _this_class_index(0),
5312   _super_class_index(0),
5313   _itfs_len(0),
5314   _java_fields_count(0),
5315   _need_verify(false),
5316   _has_nonstatic_concrete_methods(false),
5317   _declares_nonstatic_concrete_methods(false),
5318   _has_localvariable_table(false),
5319   _has_final_method(false),
5320   _has_contended_fields(false),






5321   _has_finalizer(false),
5322   _has_empty_finalizer(false),
5323   _max_bootstrap_specifier_index(-1) {
5324 
5325   _class_name = name != nullptr ? name : vmSymbols::unknown_class_name();
5326   _class_name->increment_refcount();
5327 
5328   assert(_loader_data != nullptr, "invariant");
5329   assert(stream != nullptr, "invariant");
5330   assert(_stream != nullptr, "invariant");
5331   assert(_stream->buffer() == _stream->current(), "invariant");
5332   assert(_class_name != nullptr, "invariant");
5333   assert(0 == _access_flags.as_unsigned_short(), "invariant");
5334 
5335   // Figure out whether we can skip format checking (matching classic VM behavior)
5336   _need_verify = Verifier::should_verify_for(_loader_data->class_loader());
5337 
5338   // synch back verification state to stream to check for truncation.
5339   stream->set_need_verify(_need_verify);
5340 
5341   parse_stream(stream, CHECK);
5342 
5343   post_process_parsed_stream(stream, _cp, CHECK);
5344 }
5345 
5346 void ClassFileParser::clear_class_metadata() {
5347   // metadata created before the instance klass is created.  Must be
5348   // deallocated if classfile parsing returns an error.
5349   _cp = nullptr;
5350   _fieldinfo_stream = nullptr;
5351   _fields_status = nullptr;
5352   _methods = nullptr;
5353   _inner_classes = nullptr;
5354   _nest_members = nullptr;
5355   _permitted_subclasses = nullptr;

5356   _combined_annotations = nullptr;
5357   _class_annotations = _class_type_annotations = nullptr;
5358   _fields_annotations = _fields_type_annotations = nullptr;
5359   _record_components = nullptr;

5360 }
5361 
5362 // Destructor to clean up
5363 ClassFileParser::~ClassFileParser() {
5364   _class_name->decrement_refcount();
5365 
5366   if (_cp != nullptr) {
5367     MetadataFactory::free_metadata(_loader_data, _cp);
5368   }
5369 
5370   if (_fieldinfo_stream != nullptr) {
5371     MetadataFactory::free_array<u1>(_loader_data, _fieldinfo_stream);
5372   }
5373 
5374   if (_fields_status != nullptr) {
5375     MetadataFactory::free_array<FieldStatus>(_loader_data, _fields_status);
5376   }
5377 




5378   if (_methods != nullptr) {
5379     // Free methods
5380     InstanceKlass::deallocate_methods(_loader_data, _methods);
5381   }
5382 
5383   // beware of the Universe::empty_blah_array!!
5384   if (_inner_classes != nullptr && _inner_classes != Universe::the_empty_short_array()) {
5385     MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
5386   }
5387 
5388   if (_nest_members != nullptr && _nest_members != Universe::the_empty_short_array()) {
5389     MetadataFactory::free_array<u2>(_loader_data, _nest_members);
5390   }
5391 
5392   if (_record_components != nullptr) {
5393     InstanceKlass::deallocate_record_components(_loader_data, _record_components);
5394   }
5395 
5396   if (_permitted_subclasses != nullptr && _permitted_subclasses != Universe::the_empty_short_array()) {
5397     MetadataFactory::free_array<u2>(_loader_data, _permitted_subclasses);
5398   }
5399 




5400   // Free interfaces
5401   InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
5402                                        _local_interfaces, _transitive_interfaces);
5403 
5404   if (_combined_annotations != nullptr) {
5405     // After all annotations arrays have been created, they are installed into the
5406     // Annotations object that will be assigned to the InstanceKlass being created.
5407 
5408     // Deallocate the Annotations object and the installed annotations arrays.
5409     _combined_annotations->deallocate_contents(_loader_data);
5410 
5411     // If the _combined_annotations pointer is non-null,
5412     // then the other annotations fields should have been cleared.
5413     assert(_class_annotations       == nullptr, "Should have been cleared");
5414     assert(_class_type_annotations  == nullptr, "Should have been cleared");
5415     assert(_fields_annotations      == nullptr, "Should have been cleared");
5416     assert(_fields_type_annotations == nullptr, "Should have been cleared");
5417   } else {
5418     // If the annotations arrays were not installed into the Annotations object,
5419     // then they have to be deallocated explicitly.

5464     cp_size, CHECK);
5465 
5466   _orig_cp_size = cp_size;
5467   if (is_hidden()) { // Add a slot for hidden class name.
5468     cp_size++;
5469   }
5470 
5471   _cp = ConstantPool::allocate(_loader_data,
5472                                cp_size,
5473                                CHECK);
5474 
5475   ConstantPool* const cp = _cp;
5476 
5477   parse_constant_pool(stream, cp, _orig_cp_size, CHECK);
5478 
5479   assert(cp_size == (u2)cp->length(), "invariant");
5480 
5481   // ACCESS FLAGS
5482   stream->guarantee_more(8, CHECK);  // flags, this_class, super_class, infs_len
5483 
5484   // Access flags
5485   u2 flags;
5486   // JVM_ACC_MODULE is defined in JDK-9 and later.
5487   if (_major_version >= JAVA_9_VERSION) {
5488     flags = stream->get_u2_fast() & (JVM_RECOGNIZED_CLASS_MODIFIERS | JVM_ACC_MODULE);
5489   } else {
5490     flags = stream->get_u2_fast() & JVM_RECOGNIZED_CLASS_MODIFIERS;
5491   }
5492 



5493   if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
5494     // Set abstract bit for old class files for backward compatibility
5495     flags |= JVM_ACC_ABSTRACT;
5496   }
5497 
5498   verify_legal_class_modifiers(flags, CHECK);
5499 
5500   short bad_constant = class_bad_constant_seen();
5501   if (bad_constant != 0) {
5502     // Do not throw CFE until after the access_flags are checked because if
5503     // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
5504     classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, THREAD);
5505     return;
5506   }
5507 
5508   _access_flags.set_flags(flags);
5509 
5510   // This class and superclass
5511   _this_class_index = stream->get_u2_fast();
5512   guarantee_property(
5513     valid_cp_range(_this_class_index, cp_size) &&
5514       cp->tag_at(_this_class_index).is_unresolved_klass(),
5515     "Invalid this class index %u in constant pool in class file %s",
5516     _this_class_index, CHECK);
5517 
5518   Symbol* const class_name_in_cp = cp->klass_name_at(_this_class_index);
5519   assert(class_name_in_cp != nullptr, "class_name can't be null");
5520 














5521   // Don't need to check whether this class name is legal or not.
5522   // It has been checked when constant pool is parsed.
5523   // However, make sure it is not an array type.
5524   if (_need_verify) {
5525     guarantee_property(class_name_in_cp->char_at(0) != JVM_SIGNATURE_ARRAY,
5526                        "Bad class name in class file %s",
5527                        CHECK);
5528   }
5529 
5530 #ifdef ASSERT
5531   // Basic sanity checks
5532   if (_is_hidden) {
5533     assert(_class_name != vmSymbols::unknown_class_name(), "hidden classes should have a special name");
5534   }
5535 #endif
5536 
5537   // Update the _class_name as needed depending on whether this is a named, un-named, or hidden class.
5538 
5539   if (_is_hidden) {
5540     assert(_class_name != nullptr, "Unexpected null _class_name");

5581       }
5582       ls.cr();
5583     }
5584   }
5585 
5586   // SUPERKLASS
5587   _super_class_index = stream->get_u2_fast();
5588   _super_klass = parse_super_class(cp,
5589                                    _super_class_index,
5590                                    _need_verify,
5591                                    CHECK);
5592 
5593   // Interfaces
5594   _itfs_len = stream->get_u2_fast();
5595   parse_interfaces(stream,
5596                    _itfs_len,
5597                    cp,
5598                    &_has_nonstatic_concrete_methods,
5599                    CHECK);
5600 
5601   assert(_local_interfaces != nullptr, "invariant");
5602 
5603   // Fields (offsets are filled in later)
5604   parse_fields(stream,
5605                _access_flags.is_interface(),
5606                cp,
5607                cp_size,
5608                &_java_fields_count,
5609                CHECK);
5610 
5611   assert(_temp_field_info != nullptr, "invariant");
5612 
5613   // Methods
5614   parse_methods(stream,
5615                 _access_flags.is_interface(),


5616                 &_has_localvariable_table,
5617                 &_has_final_method,
5618                 &_declares_nonstatic_concrete_methods,
5619                 CHECK);
5620 
5621   assert(_methods != nullptr, "invariant");
5622 
5623   if (_declares_nonstatic_concrete_methods) {
5624     _has_nonstatic_concrete_methods = true;
5625   }
5626 
5627   // Additional attributes/annotations
5628   _parsed_annotations = new ClassAnnotationCollector();
5629   parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK);
5630 
5631   assert(_inner_classes != nullptr, "invariant");
5632 
5633   // Finalize the Annotations metadata object,
5634   // now that all annotation arrays have been created.
5635   create_combined_annotations(CHECK);

5675   // Update this_class_index's slot in the constant pool with the new Utf8 entry.
5676   // We have to update the resolved_klass_index and the name_index together
5677   // so extract the existing resolved_klass_index first.
5678   CPKlassSlot cp_klass_slot = _cp->klass_slot_at(_this_class_index);
5679   int resolved_klass_index = cp_klass_slot.resolved_klass_index();
5680   _cp->unresolved_klass_at_put(_this_class_index, hidden_index, resolved_klass_index);
5681   assert(_cp->klass_slot_at(_this_class_index).name_index() == _orig_cp_size,
5682          "Bad name_index");
5683 }
5684 
5685 void ClassFileParser::post_process_parsed_stream(const ClassFileStream* const stream,
5686                                                  ConstantPool* cp,
5687                                                  TRAPS) {
5688   assert(stream != nullptr, "invariant");
5689   assert(stream->at_eos(), "invariant");
5690   assert(cp != nullptr, "invariant");
5691   assert(_loader_data != nullptr, "invariant");
5692 
5693   if (_class_name == vmSymbols::java_lang_Object()) {
5694     guarantee_property(_local_interfaces == Universe::the_empty_instance_klass_array(),
5695                        "java.lang.Object cannot implement an interface in class file %s",
5696                        CHECK);
5697   }
5698   // We check super class after class file is parsed and format is checked
5699   if (_super_class_index > 0 && nullptr == _super_klass) {
5700     Symbol* const super_class_name = cp->klass_name_at(_super_class_index);
5701     if (_access_flags.is_interface()) {
5702       // Before attempting to resolve the superclass, check for class format
5703       // errors not checked yet.
5704       guarantee_property(super_class_name == vmSymbols::java_lang_Object(),
5705         "Interfaces must have java.lang.Object as superclass in class file %s",
5706         CHECK);
5707     }
5708     Handle loader(THREAD, _loader_data->class_loader());
5709     if (loader.is_null() && super_class_name == vmSymbols::java_lang_Object()) {
5710       _super_klass = vmClasses::Object_klass();
5711     } else {
5712       _super_klass = (const InstanceKlass*)
5713                        SystemDictionary::resolve_super_or_fail(_class_name,
5714                                                                super_class_name,
5715                                                                loader,
5716                                                                true,
5717                                                                CHECK);
5718     }
5719   }
5720 
5721   if (_super_klass != nullptr) {














5722     if (_super_klass->has_nonstatic_concrete_methods()) {
5723       _has_nonstatic_concrete_methods = true;
5724     }

5725 
5726     if (_super_klass->is_interface()) {
5727       classfile_icce_error("class %s has interface %s as super class", _super_klass, THREAD);
5728       return;































5729     }
5730   }
5731 














































5732   // Compute the transitive list of all unique interfaces implemented by this class
5733   _transitive_interfaces =
5734     compute_transitive_interfaces(_super_klass,
5735                                   _local_interfaces,
5736                                   _loader_data,
5737                                   CHECK);
5738 
5739   assert(_transitive_interfaces != nullptr, "invariant");
5740 
5741   // sort methods
5742   _method_ordering = sort_methods(_methods);
5743 
5744   _all_mirandas = new GrowableArray<Method*>(20);
5745 
5746   Handle loader(THREAD, _loader_data->class_loader());
5747   klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
5748                                                     &_num_miranda_methods,
5749                                                     _all_mirandas,
5750                                                     _super_klass,
5751                                                     _methods,
5752                                                     _access_flags,
5753                                                     _major_version,
5754                                                     loader,
5755                                                     _class_name,
5756                                                     _local_interfaces);
5757 
5758   // Size of Java itable (in words)
5759   _itable_size = _access_flags.is_interface() ? 0 :
5760     klassItable::compute_itable_size(_transitive_interfaces);
5761 
5762   assert(_parsed_annotations != nullptr, "invariant");
5763 
5764   _field_info = new FieldLayoutInfo();
5765   FieldLayoutBuilder lb(class_name(), super_klass(), _cp, /*_fields*/ _temp_field_info,
5766                         _parsed_annotations->is_contended(), _field_info);













































































5767   lb.build_layout();

5768 
5769   int injected_fields_count = _temp_field_info->length() - _java_fields_count;
5770   _fieldinfo_stream =
5771     FieldInfoStream::create_FieldInfoStream(_temp_field_info, _java_fields_count,
5772                                             injected_fields_count, loader_data(), CHECK);

5773   _fields_status =
5774     MetadataFactory::new_array<FieldStatus>(_loader_data, _temp_field_info->length(),
5775                                             FieldStatus(0), CHECK);
5776 }
5777 
5778 void ClassFileParser::set_klass(InstanceKlass* klass) {
5779 
5780 #ifdef ASSERT
5781   if (klass != nullptr) {
5782     assert(nullptr == _klass, "leaking?");
5783   }
5784 #endif
5785 
5786   _klass = klass;
5787 }
5788 
5789 void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) {
5790 
5791 #ifdef ASSERT
5792   if (klass != nullptr) {

   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 "oops/inlineKlass.hpp"
  26 #include "cds/cdsConfig.hpp"
  27 #include "classfile/classFileParser.hpp"
  28 #include "classfile/classFileStream.hpp"
  29 #include "classfile/classLoader.hpp"
  30 #include "classfile/classLoaderData.inline.hpp"
  31 #include "classfile/classLoadInfo.hpp"
  32 #include "classfile/defaultMethods.hpp"
  33 #include "classfile/fieldLayoutBuilder.hpp"
  34 #include "classfile/javaClasses.inline.hpp"
  35 #include "classfile/moduleEntry.hpp"
  36 #include "classfile/packageEntry.hpp"
  37 #include "classfile/symbolTable.hpp"
  38 #include "classfile/systemDictionary.hpp"
  39 #include "classfile/verificationType.hpp"
  40 #include "classfile/verifier.hpp"
  41 #include "classfile/vmClasses.hpp"
  42 #include "classfile/vmSymbols.hpp"
  43 #include "jvm.h"
  44 #include "logging/log.hpp"
  45 #include "logging/logStream.hpp"
  46 #include "memory/allocation.hpp"
  47 #include "memory/metadataFactory.hpp"
  48 #include "memory/oopFactory.hpp"
  49 #include "memory/resourceArea.hpp"
  50 #include "memory/universe.hpp"
  51 #include "oops/annotations.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/formatBuffer.hpp"
  84 #include "utilities/exceptions.hpp"
  85 #include "utilities/globalDefinitions.hpp"
  86 #include "utilities/growableArray.hpp"
  87 #include "utilities/macros.hpp"
  88 #include "utilities/ostream.hpp"
  89 #include "utilities/resourceHash.hpp"
  90 #include "utilities/stringUtils.hpp"
  91 #include "utilities/utf8.hpp"
  92 #if INCLUDE_CDS
  93 #include "classfile/systemDictionaryShared.hpp"
  94 #endif
  95 #if INCLUDE_JFR
  96 #include "jfr/support/jfrTraceIdExtension.hpp"
  97 #endif
  98 
  99 // We generally try to create the oops directly when parsing, rather than
 100 // allocating temporary data structures and copying the bytes twice. A
 101 // temporary area is only needed when parsing utf8 entries in the constant
 102 // pool and when parsing line number tables.
 103 
 104 // We add assert in debug mode when class format is not checked.
 105 
 106 #define JAVA_CLASSFILE_MAGIC              0xCAFEBABE
 107 #define JAVA_MIN_SUPPORTED_VERSION        45
 108 #define JAVA_PREVIEW_MINOR_VERSION        65535
 109 
 110 // Used for two backward compatibility reasons:

 137 #define JAVA_14_VERSION                   58
 138 
 139 #define JAVA_15_VERSION                   59
 140 
 141 #define JAVA_16_VERSION                   60
 142 
 143 #define JAVA_17_VERSION                   61
 144 
 145 #define JAVA_18_VERSION                   62
 146 
 147 #define JAVA_19_VERSION                   63
 148 
 149 #define JAVA_20_VERSION                   64
 150 
 151 #define JAVA_21_VERSION                   65
 152 
 153 #define JAVA_22_VERSION                   66
 154 
 155 #define JAVA_23_VERSION                   67
 156 
 157 #define CONSTANT_CLASS_DESCRIPTORS        69
 158 
 159 #define JAVA_24_VERSION                   68
 160 
 161 #define JAVA_25_VERSION                   69
 162 
 163 void ClassFileParser::set_class_bad_constant_seen(short bad_constant) {
 164   assert((bad_constant == JVM_CONSTANT_Module ||
 165           bad_constant == JVM_CONSTANT_Package) && _major_version >= JAVA_9_VERSION,
 166          "Unexpected bad constant pool entry");
 167   if (_bad_constant_seen == 0) _bad_constant_seen = bad_constant;
 168 }
 169 
 170 void ClassFileParser::parse_constant_pool_entries(const ClassFileStream* const stream,
 171                                                   ConstantPool* cp,
 172                                                   const int length,
 173                                                   TRAPS) {
 174   assert(stream != nullptr, "invariant");
 175   assert(cp != nullptr, "invariant");
 176 
 177   // Use a local copy of ClassFileStream. It helps the C++ compiler to optimize
 178   // this function (_current can be allocated in a register, with scalar

 181   // this method that uses stream().
 182   const ClassFileStream cfs1 = *stream;
 183   const ClassFileStream* const cfs = &cfs1;
 184 
 185   debug_only(const u1* const old_current = stream->current();)
 186 
 187   // Used for batching symbol allocations.
 188   const char* names[SymbolTable::symbol_alloc_batch_size];
 189   int lengths[SymbolTable::symbol_alloc_batch_size];
 190   int indices[SymbolTable::symbol_alloc_batch_size];
 191   unsigned int hashValues[SymbolTable::symbol_alloc_batch_size];
 192   int names_count = 0;
 193 
 194   // parsing  Index 0 is unused
 195   for (int index = 1; index < length; index++) {
 196     // Each of the following case guarantees one more byte in the stream
 197     // for the following tag or the access_flags following constant pool,
 198     // so we don't need bounds-check for reading tag.
 199     const u1 tag = cfs->get_u1_fast();
 200     switch (tag) {
 201       case JVM_CONSTANT_Class: {
 202         cfs->guarantee_more(3, CHECK);  // name_index, tag/access_flags
 203         const u2 name_index = cfs->get_u2_fast();
 204         cp->klass_index_at_put(index, name_index);
 205         break;
 206       }
 207       case JVM_CONSTANT_Fieldref: {
 208         cfs->guarantee_more(5, CHECK);  // class_index, name_and_type_index, tag/access_flags
 209         const u2 class_index = cfs->get_u2_fast();
 210         const u2 name_and_type_index = cfs->get_u2_fast();
 211         cp->field_at_put(index, class_index, name_and_type_index);
 212         break;
 213       }
 214       case JVM_CONSTANT_Methodref: {
 215         cfs->guarantee_more(5, CHECK);  // class_index, name_and_type_index, tag/access_flags
 216         const u2 class_index = cfs->get_u2_fast();
 217         const u2 name_and_type_index = cfs->get_u2_fast();
 218         cp->method_at_put(index, class_index, name_and_type_index);
 219         break;
 220       }
 221       case JVM_CONSTANT_InterfaceMethodref: {

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

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

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

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

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




























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

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

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

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                                    AccessFlags class_access_flags,
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   bool is_inline_type = !class_access_flags.is_identity_class() && !class_access_flags.is_abstract();
1382   cfs->guarantee_more(2, CHECK);  // length
1383   const u2 length = cfs->get_u2_fast();
1384   *java_fields_count_ptr = length;
1385 
1386   int num_injected = 0;
1387   const InjectedField* const injected = JavaClasses::get_injected(_class_name,
1388                                                                   &num_injected);
1389 
1390   // two more slots are required for inline classes:
1391   // one for the static field with a reference to the pre-allocated default value
1392   // one for the field the JVM injects when detecting an empty inline class
1393   const int total_fields = length + num_injected + (is_inline_type ? 2 : 0);
1394 
1395   // Allocate a temporary resource array to collect field data.
1396   // After parsing all fields, data are stored in a UNSIGNED5 compressed stream.
1397   _temp_field_info = new GrowableArray<FieldInfo>(total_fields);
1398 
1399   int instance_fields_count = 0;
1400   ResourceMark rm(THREAD);
1401   for (int n = 0; n < length; n++) {
1402     // access_flags, name_index, descriptor_index, attributes_count
1403     cfs->guarantee_more(8, CHECK);
1404 
1405     jint recognized_modifiers = JVM_RECOGNIZED_FIELD_MODIFIERS;
1406     if (!supports_inline_types()) {
1407       recognized_modifiers &= ~JVM_ACC_STRICT;
1408     }
1409 
1410     const jint flags = cfs->get_u2_fast() & recognized_modifiers;
1411     verify_legal_field_modifiers(flags, class_access_flags, CHECK);
1412     AccessFlags access_flags;


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

1514   if (num_injected != 0) {
1515     for (int n = 0; n < num_injected; n++) {
1516       // Check for duplicates
1517       if (injected[n].may_be_java) {
1518         const Symbol* const name      = injected[n].name();
1519         const Symbol* const signature = injected[n].signature();
1520         bool duplicate = false;
1521         for (int i = 0; i < length; i++) {
1522           const FieldInfo* const f = _temp_field_info->adr_at(i);
1523           if (name      == cp->symbol_at(f->name_index()) &&
1524               signature == cp->symbol_at(f->signature_index())) {
1525             // Symbol is desclared in Java so skip this one
1526             duplicate = true;
1527             break;
1528           }
1529         }
1530         if (duplicate) {
1531           // These will be removed from the field array at the end
1532           continue;
1533         }
1534       }
1535 
1536       // Injected field
1537       FieldInfo::FieldFlags fflags(0);
1538       fflags.update_injected(true);
1539       AccessFlags aflags;
1540       FieldInfo fi(aflags, (u2)(injected[n].name_index), (u2)(injected[n].signature_index), 0, fflags);
1541       int idx = _temp_field_info->append(fi);
1542       _temp_field_info->adr_at(idx)->set_index(idx);

1543     }
1544   }
1545 
1546   if (is_inline_type) {
1547     // Inject static ".default" field
1548     FieldInfo::FieldFlags fflags(0);
1549     fflags.update_injected(true);
1550     AccessFlags aflags(JVM_ACC_STATIC);
1551     FieldInfo fi(aflags,
1552                  (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(default_value_name)),
1553                  (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(object_signature)),
1554                  0,
1555                  fflags);
1556     int idx = _temp_field_info->append(fi);
1557     _temp_field_info->adr_at(idx)->set_index(idx);
1558     _static_oop_count++;
1559     // Inject static ".null_reset" field. This is the same as the .default field but will never have its null-channel set to non-zero.
1560     FieldInfo::FieldFlags fflags2(0);
1561     fflags2.update_injected(true);
1562     AccessFlags aflags2(JVM_ACC_STATIC);
1563     FieldInfo fi2(aflags2,
1564                  (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(null_reset_value_name)),
1565                  (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(object_signature)),
1566                  0,
1567                  fflags2);
1568     int idx2 = _temp_field_info->append(fi2);
1569     _temp_field_info->adr_at(idx2)->set_index(idx2);
1570     _static_oop_count++;
1571   }
1572 
1573   if (_need_verify && length > 1) {
1574     // Check duplicated fields
1575     ResourceMark rm(THREAD);
1576     // Set containing name-signature pairs
1577     NameSigHashtable* names_and_sigs = new NameSigHashtable();
1578     for (int i = 0; i < _temp_field_info->length(); i++) {
1579       NameSigHash name_and_sig(_temp_field_info->adr_at(i)->name(_cp),
1580                                _temp_field_info->adr_at(i)->signature(_cp));
1581       // If no duplicates, add name/signature in hashtable names_and_sigs.
1582       if(!names_and_sigs->put(name_and_sig, 0)) {
1583         classfile_parse_error("Duplicate field name \"%s\" with signature \"%s\" in class file %s",
1584                                name_and_sig._name->as_C_string(), name_and_sig._sig->as_klass_external_name(), THREAD);
1585         return;
1586       }
1587     }
1588   }
1589 }
1590 
1591 

1931     }
1932     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Contended_signature): {
1933       if (_location != _in_field && _location != _in_class) {
1934         break;  // only allow for fields and classes
1935       }
1936       if (!EnableContended || (RestrictContended && !privileged)) {
1937         break;  // honor privileges
1938       }
1939       return _jdk_internal_vm_annotation_Contended;
1940     }
1941     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ReservedStackAccess_signature): {
1942       if (_location != _in_method)  break;  // only allow for methods
1943       if (RestrictReservedStack && !privileged) break; // honor privileges
1944       return _jdk_internal_vm_annotation_ReservedStackAccess;
1945     }
1946     case VM_SYMBOL_ENUM_NAME(jdk_internal_ValueBased_signature): {
1947       if (_location != _in_class)   break;  // only allow for classes
1948       if (!privileged)              break;  // only allow in privileged code
1949       return _jdk_internal_ValueBased;
1950     }
1951     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ImplicitlyConstructible_signature): {
1952       if (_location != _in_class)   break; // only allow for classes
1953       return _jdk_internal_ImplicitlyConstructible;
1954     }
1955     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_LooselyConsistentValue_signature): {
1956       if (_location != _in_class)   break; // only allow for classes
1957       return _jdk_internal_LooselyConsistentValue;
1958     }
1959     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_NullRestricted_signature): {
1960       if (_location != _in_field)   break; // only allow for fields
1961       return _jdk_internal_NullRestricted;
1962     }
1963     case VM_SYMBOL_ENUM_NAME(java_lang_Deprecated): {
1964       return _java_lang_Deprecated;
1965     }
1966     default: {
1967       break;
1968     }
1969   }
1970   return AnnotationCollector::_unknown;
1971 }
1972 
1973 void ClassFileParser::FieldAnnotationCollector::apply_to(FieldInfo* f) {
1974   if (is_contended())
1975     // Setting the contended group also sets the contended bit in field flags
1976     f->set_contended_group(contended_group());
1977   if (is_stable())
1978     (f->field_flags_addr())->update_stable(true);
1979 }
1980 
1981 ClassFileParser::FieldAnnotationCollector::~FieldAnnotationCollector() {
1982   // If there's an error deallocate metadata for field annotations

2166   }
2167 
2168   if (runtime_visible_type_annotations_length > 0) {
2169     a = allocate_annotations(runtime_visible_type_annotations,
2170                              runtime_visible_type_annotations_length,
2171                              CHECK);
2172     cm->set_type_annotations(a);
2173   }
2174 }
2175 
2176 
2177 // Note: the parse_method below is big and clunky because all parsing of the code and exceptions
2178 // attribute is inlined. This is cumbersome to avoid since we inline most of the parts in the
2179 // Method* to save footprint, so we only know the size of the resulting Method* when the
2180 // entire method attribute is parsed.
2181 //
2182 // The has_localvariable_table parameter is used to pass up the value to InstanceKlass.
2183 
2184 Method* ClassFileParser::parse_method(const ClassFileStream* const cfs,
2185                                       bool is_interface,
2186                                       bool is_value_class,
2187                                       bool is_abstract_class,
2188                                       const ConstantPool* cp,
2189                                       bool* const has_localvariable_table,
2190                                       TRAPS) {
2191   assert(cfs != nullptr, "invariant");
2192   assert(cp != nullptr, "invariant");
2193   assert(has_localvariable_table != nullptr, "invariant");
2194 
2195   ResourceMark rm(THREAD);
2196   // Parse fixed parts:
2197   // access_flags, name_index, descriptor_index, attributes_count
2198   cfs->guarantee_more(8, CHECK_NULL);
2199 
2200   u2 flags = cfs->get_u2_fast();
2201   const u2 name_index = cfs->get_u2_fast();
2202   const int cp_size = cp->length();
2203   guarantee_property(
2204     valid_symbol_at(name_index),
2205     "Illegal constant pool index %u for method name in class file %s",
2206     name_index, CHECK_NULL);
2207   const Symbol* const name = cp->symbol_at(name_index);

2209 
2210   const u2 signature_index = cfs->get_u2_fast();
2211   guarantee_property(
2212     valid_symbol_at(signature_index),
2213     "Illegal constant pool index %u for method signature in class file %s",
2214     signature_index, CHECK_NULL);
2215   const Symbol* const signature = cp->symbol_at(signature_index);
2216 
2217   if (name == vmSymbols::class_initializer_name()) {
2218     // We ignore the other access flags for a valid class initializer.
2219     // (JVM Spec 2nd ed., chapter 4.6)
2220     if (_major_version < 51) { // backward compatibility
2221       flags = JVM_ACC_STATIC;
2222     } else if ((flags & JVM_ACC_STATIC) == JVM_ACC_STATIC) {
2223       flags &= JVM_ACC_STATIC | (_major_version <= JAVA_16_VERSION ? JVM_ACC_STRICT : 0);
2224     } else {
2225       classfile_parse_error("Method <clinit> is not static in class file %s", THREAD);
2226       return nullptr;
2227     }
2228   } else {
2229     verify_legal_method_modifiers(flags, access_flags() , name, CHECK_NULL);
2230   }
2231 
2232   if (name == vmSymbols::object_initializer_name() && is_interface) {
2233     classfile_parse_error("Interface cannot have a method named <init>, class file %s", THREAD);
2234     return nullptr;
2235   }
2236 
2237   if (EnableValhalla) {
2238     if (((flags & JVM_ACC_SYNCHRONIZED) == JVM_ACC_SYNCHRONIZED)
2239         && ((flags & JVM_ACC_STATIC) == 0 )
2240         && !_access_flags.is_identity_class()) {
2241       classfile_parse_error("Invalid synchronized method in non-identity class %s", THREAD);
2242         return nullptr;
2243     }
2244   }
2245 
2246   int args_size = -1;  // only used when _need_verify is true
2247   if (_need_verify) {
2248     verify_legal_name_with_signature(name, signature, CHECK_NULL);
2249     args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) +
2250                  verify_legal_method_signature(name, signature, CHECK_NULL);
2251     if (args_size > MAX_ARGS_SIZE) {
2252       classfile_parse_error("Too many arguments in method signature in class file %s", THREAD);
2253       return nullptr;
2254     }
2255   }
2256 
2257   AccessFlags access_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS);
2258 
2259   // Default values for code and exceptions attribute elements
2260   u2 max_stack = 0;
2261   u2 max_locals = 0;
2262   u4 code_length = 0;
2263   const u1* code_start = nullptr;
2264   u2 exception_table_length = 0;
2265   const unsafe_u2* exception_table_start = nullptr; // (potentially unaligned) pointer to array of u2 elements

2753                           CHECK_NULL);
2754 
2755   if (InstanceKlass::is_finalization_enabled() &&
2756       name == vmSymbols::finalize_method_name() &&
2757       signature == vmSymbols::void_method_signature()) {
2758     if (m->is_empty_method()) {
2759       _has_empty_finalizer = true;
2760     } else {
2761       _has_finalizer = true;
2762     }
2763   }
2764 
2765   NOT_PRODUCT(m->verify());
2766   return m;
2767 }
2768 
2769 
2770 // Side-effects: populates the _methods field in the parser
2771 void ClassFileParser::parse_methods(const ClassFileStream* const cfs,
2772                                     bool is_interface,
2773                                     bool is_value_class,
2774                                     bool is_abstract_type,
2775                                     bool* const has_localvariable_table,
2776                                     bool* has_final_method,
2777                                     bool* declares_nonstatic_concrete_methods,
2778                                     TRAPS) {
2779   assert(cfs != nullptr, "invariant");
2780   assert(has_localvariable_table != nullptr, "invariant");
2781   assert(has_final_method != nullptr, "invariant");
2782   assert(declares_nonstatic_concrete_methods != nullptr, "invariant");
2783 
2784   assert(nullptr == _methods, "invariant");
2785 
2786   cfs->guarantee_more(2, CHECK);  // length
2787   const u2 length = cfs->get_u2_fast();
2788   if (length == 0) {
2789     _methods = Universe::the_empty_method_array();
2790   } else {
2791     _methods = MetadataFactory::new_array<Method*>(_loader_data,
2792                                                    length,
2793                                                    nullptr,
2794                                                    CHECK);
2795 
2796     for (int index = 0; index < length; index++) {
2797       Method* method = parse_method(cfs,
2798                                     is_interface,
2799                                     is_value_class,
2800                                     is_abstract_type,
2801                                     _cp,
2802                                     has_localvariable_table,
2803                                     CHECK);
2804 
2805       if (method->is_final()) {
2806         *has_final_method = true;
2807       }
2808       // declares_nonstatic_concrete_methods: declares concrete instance methods, any access flags
2809       // used for interface initialization, and default method inheritance analysis
2810       if (is_interface && !(*declares_nonstatic_concrete_methods)
2811         && !method->is_abstract() && !method->is_static()) {
2812         *declares_nonstatic_concrete_methods = true;
2813       }
2814       _methods->at_put(index, method);
2815     }
2816 
2817     if (_need_verify && length > 1) {
2818       // Check duplicated methods
2819       ResourceMark rm(THREAD);
2820       // Set containing name-signature pairs

3046         valid_klass_reference_at(outer_class_info_index),
3047       "outer_class_info_index %u has bad constant type in class file %s",
3048       outer_class_info_index, CHECK_0);
3049 
3050     if (outer_class_info_index != 0) {
3051       const Symbol* const outer_class_name = cp->klass_name_at(outer_class_info_index);
3052       char* bytes = (char*)outer_class_name->bytes();
3053       guarantee_property(bytes[0] != JVM_SIGNATURE_ARRAY,
3054                          "Outer class is an array class in class file %s", CHECK_0);
3055     }
3056     // Inner class name
3057     const u2 inner_name_index = cfs->get_u2_fast();
3058     guarantee_property(
3059       inner_name_index == 0 || valid_symbol_at(inner_name_index),
3060       "inner_name_index %u has bad constant type in class file %s",
3061       inner_name_index, CHECK_0);
3062     if (_need_verify) {
3063       guarantee_property(inner_class_info_index != outer_class_info_index,
3064                          "Class is both outer and inner class in class file %s", CHECK_0);
3065     }
3066 
3067     u2 recognized_modifiers = RECOGNIZED_INNER_CLASS_MODIFIERS;
3068     // JVM_ACC_MODULE is defined in JDK-9 and later.
3069     if (_major_version >= JAVA_9_VERSION) {
3070       recognized_modifiers |= JVM_ACC_MODULE;


3071     }
3072 
3073     // Access flags
3074     u2 flags = cfs->get_u2_fast() & recognized_modifiers;
3075 
3076     if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
3077       // Set abstract bit for old class files for backward compatibility
3078       flags |= JVM_ACC_ABSTRACT;
3079     }
3080 
3081     if (!supports_inline_types()) {
3082       const bool is_module = (flags & JVM_ACC_MODULE) != 0;
3083       const bool is_interface = (flags & JVM_ACC_INTERFACE) != 0;
3084       if (!is_module && !is_interface) {
3085         flags |= JVM_ACC_IDENTITY;
3086       }
3087     }
3088 
3089     const char* name = inner_name_index == 0 ? "unnamed" : cp->symbol_at(inner_name_index)->as_utf8();
3090     verify_legal_class_modifiers(flags, name, false, CHECK_0);
3091     AccessFlags inner_access_flags(flags);
3092 
3093     inner_classes->at_put(index++, inner_class_info_index);
3094     inner_classes->at_put(index++, outer_class_info_index);
3095     inner_classes->at_put(index++, inner_name_index);
3096     inner_classes->at_put(index++, inner_access_flags.as_unsigned_short());
3097   }
3098 
3099   // Check for circular and duplicate entries.
3100   bool has_circularity = false;
3101   if (_need_verify) {
3102     has_circularity = check_inner_classes_circularity(cp, length * 4, CHECK_0);
3103     if (has_circularity) {
3104       // If circularity check failed then ignore InnerClasses attribute.
3105       MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
3106       index = 0;
3107       if (parsed_enclosingmethod_attribute) {
3108         inner_classes = MetadataFactory::new_array<u2>(_loader_data, 2, CHECK_0);
3109         _inner_classes = inner_classes;
3110       } else {

3174   if (length > 0) {
3175     int index = 0;
3176     cfs->guarantee_more(2 * length, CHECK_0);
3177     for (int n = 0; n < length; n++) {
3178       const u2 class_info_index = cfs->get_u2_fast();
3179       guarantee_property(
3180         valid_klass_reference_at(class_info_index),
3181         "Permitted subclass class_info_index %u has bad constant type in class file %s",
3182         class_info_index, CHECK_0);
3183       permitted_subclasses->at_put(index++, class_info_index);
3184     }
3185     assert(index == size, "wrong size");
3186   }
3187 
3188   // Restore buffer's current position.
3189   cfs->set_current(current_mark);
3190 
3191   return length;
3192 }
3193 
3194 u2 ClassFileParser::parse_classfile_loadable_descriptors_attribute(const ClassFileStream* const cfs,
3195                                                                    const u1* const loadable_descriptors_attribute_start,
3196                                                                    TRAPS) {
3197   const u1* const current_mark = cfs->current();
3198   u2 length = 0;
3199   if (loadable_descriptors_attribute_start != nullptr) {
3200     cfs->set_current(loadable_descriptors_attribute_start);
3201     cfs->guarantee_more(2, CHECK_0);  // length
3202     length = cfs->get_u2_fast();
3203   }
3204   const int size = length;
3205   Array<u2>* const loadable_descriptors = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
3206   _loadable_descriptors = loadable_descriptors;
3207   if (length > 0) {
3208     int index = 0;
3209     cfs->guarantee_more(2 * length, CHECK_0);
3210     for (int n = 0; n < length; n++) {
3211       const u2 descriptor_index = cfs->get_u2_fast();
3212       guarantee_property(
3213         valid_symbol_at(descriptor_index),
3214         "LoadableDescriptors descriptor_index %u has bad constant type in class file %s",
3215         descriptor_index, CHECK_0);
3216       Symbol* descriptor = _cp->symbol_at(descriptor_index);
3217       bool valid = legal_field_signature(descriptor, CHECK_0);
3218       if(!valid) {
3219         ResourceMark rm(THREAD);
3220         Exceptions::fthrow(THREAD_AND_LOCATION,
3221           vmSymbols::java_lang_ClassFormatError(),
3222           "Descriptor from LoadableDescriptors attribute at index \"%d\" in class %s has illegal signature \"%s\"",
3223           descriptor_index, _class_name->as_C_string(), descriptor->as_C_string());
3224         return 0;
3225       }
3226       loadable_descriptors->at_put(index++, descriptor_index);
3227     }
3228     assert(index == size, "wrong size");
3229   }
3230 
3231   // Restore buffer's current position.
3232   cfs->set_current(current_mark);
3233 
3234   return length;
3235 }
3236 
3237 //  Record {
3238 //    u2 attribute_name_index;
3239 //    u4 attribute_length;
3240 //    u2 components_count;
3241 //    component_info components[components_count];
3242 //  }
3243 //  component_info {
3244 //    u2 name_index;
3245 //    u2 descriptor_index
3246 //    u2 attributes_count;
3247 //    attribute_info_attributes[attributes_count];
3248 //  }
3249 u4 ClassFileParser::parse_classfile_record_attribute(const ClassFileStream* const cfs,
3250                                                      const ConstantPool* cp,
3251                                                      const u1* const record_attribute_start,
3252                                                      TRAPS) {
3253   const u1* const current_mark = cfs->current();
3254   int components_count = 0;
3255   unsigned int calculate_attr_size = 0;
3256   if (record_attribute_start != nullptr) {

3482   }
3483   guarantee_property(current_start + attribute_byte_length == cfs->current(),
3484                      "Bad length on BootstrapMethods in class file %s",
3485                      CHECK);
3486 }
3487 
3488 void ClassFileParser::parse_classfile_attributes(const ClassFileStream* const cfs,
3489                                                  ConstantPool* cp,
3490                  ClassFileParser::ClassAnnotationCollector* parsed_annotations,
3491                                                  TRAPS) {
3492   assert(cfs != nullptr, "invariant");
3493   assert(cp != nullptr, "invariant");
3494   assert(parsed_annotations != nullptr, "invariant");
3495 
3496   // Set inner classes attribute to default sentinel
3497   _inner_classes = Universe::the_empty_short_array();
3498   // Set nest members attribute to default sentinel
3499   _nest_members = Universe::the_empty_short_array();
3500   // Set _permitted_subclasses attribute to default sentinel
3501   _permitted_subclasses = Universe::the_empty_short_array();
3502   // Set _loadable_descriptors attribute to default sentinel
3503   _loadable_descriptors = Universe::the_empty_short_array();
3504   cfs->guarantee_more(2, CHECK);  // attributes_count
3505   u2 attributes_count = cfs->get_u2_fast();
3506   bool parsed_sourcefile_attribute = false;
3507   bool parsed_innerclasses_attribute = false;
3508   bool parsed_nest_members_attribute = false;
3509   bool parsed_permitted_subclasses_attribute = false;
3510   bool parsed_loadable_descriptors_attribute = false;
3511   bool parsed_nest_host_attribute = false;
3512   bool parsed_record_attribute = false;
3513   bool parsed_enclosingmethod_attribute = false;
3514   bool parsed_bootstrap_methods_attribute = false;
3515   const u1* runtime_visible_annotations = nullptr;
3516   int runtime_visible_annotations_length = 0;
3517   const u1* runtime_visible_type_annotations = nullptr;
3518   int runtime_visible_type_annotations_length = 0;
3519   bool runtime_invisible_type_annotations_exists = false;
3520   bool runtime_invisible_annotations_exists = false;
3521   bool parsed_source_debug_ext_annotations_exist = false;
3522   const u1* inner_classes_attribute_start = nullptr;
3523   u4  inner_classes_attribute_length = 0;
3524   u2  enclosing_method_class_index = 0;
3525   u2  enclosing_method_method_index = 0;
3526   const u1* nest_members_attribute_start = nullptr;
3527   u4  nest_members_attribute_length = 0;
3528   const u1* record_attribute_start = nullptr;
3529   u4  record_attribute_length = 0;
3530   const u1* permitted_subclasses_attribute_start = nullptr;
3531   u4  permitted_subclasses_attribute_length = 0;
3532   const u1* loadable_descriptors_attribute_start = nullptr;
3533   u4  loadable_descriptors_attribute_length = 0;
3534 
3535   // Iterate over attributes
3536   while (attributes_count--) {
3537     cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
3538     const u2 attribute_name_index = cfs->get_u2_fast();
3539     const u4 attribute_length = cfs->get_u4_fast();
3540     guarantee_property(
3541       valid_symbol_at(attribute_name_index),
3542       "Attribute name has bad constant pool index %u in class file %s",
3543       attribute_name_index, CHECK);
3544     const Symbol* const tag = cp->symbol_at(attribute_name_index);
3545     if (tag == vmSymbols::tag_source_file()) {
3546       // Check for SourceFile tag
3547       if (_need_verify) {
3548         guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
3549       }
3550       if (parsed_sourcefile_attribute) {
3551         classfile_parse_error("Multiple SourceFile attributes in class file %s", THREAD);
3552         return;
3553       } else {

3729               return;
3730             }
3731             parsed_record_attribute = true;
3732             record_attribute_start = cfs->current();
3733             record_attribute_length = attribute_length;
3734           } else if (_major_version >= JAVA_17_VERSION) {
3735             if (tag == vmSymbols::tag_permitted_subclasses()) {
3736               if (parsed_permitted_subclasses_attribute) {
3737                 classfile_parse_error("Multiple PermittedSubclasses attributes in class file %s", CHECK);
3738                 return;
3739               }
3740               // Classes marked ACC_FINAL cannot have a PermittedSubclasses attribute.
3741               if (_access_flags.is_final()) {
3742                 classfile_parse_error("PermittedSubclasses attribute in final class file %s", CHECK);
3743                 return;
3744               }
3745               parsed_permitted_subclasses_attribute = true;
3746               permitted_subclasses_attribute_start = cfs->current();
3747               permitted_subclasses_attribute_length = attribute_length;
3748             }
3749             if (EnableValhalla && tag == vmSymbols::tag_loadable_descriptors()) {
3750               if (parsed_loadable_descriptors_attribute) {
3751                 classfile_parse_error("Multiple LoadableDescriptors attributes in class file %s", CHECK);
3752                 return;
3753               }
3754               parsed_loadable_descriptors_attribute = true;
3755               loadable_descriptors_attribute_start = cfs->current();
3756               loadable_descriptors_attribute_length = attribute_length;
3757             }
3758           }
3759           // Skip attribute_length for any attribute where major_verson >= JAVA_17_VERSION
3760           cfs->skip_u1(attribute_length, CHECK);
3761         } else {
3762           // Unknown attribute
3763           cfs->skip_u1(attribute_length, CHECK);
3764         }
3765       } else {
3766         // Unknown attribute
3767         cfs->skip_u1(attribute_length, CHECK);
3768       }
3769     } else {
3770       // Unknown attribute
3771       cfs->skip_u1(attribute_length, CHECK);
3772     }
3773   }
3774   _class_annotations = allocate_annotations(runtime_visible_annotations,
3775                                             runtime_visible_annotations_length,
3776                                             CHECK);
3777   _class_type_annotations = allocate_annotations(runtime_visible_type_annotations,

3814                             CHECK);
3815     if (_need_verify) {
3816       guarantee_property(record_attribute_length == calculated_attr_length,
3817                          "Record attribute has wrong length in class file %s",
3818                          CHECK);
3819     }
3820   }
3821 
3822   if (parsed_permitted_subclasses_attribute) {
3823     const u2 num_subclasses = parse_classfile_permitted_subclasses_attribute(
3824                             cfs,
3825                             permitted_subclasses_attribute_start,
3826                             CHECK);
3827     if (_need_verify) {
3828       guarantee_property(
3829         permitted_subclasses_attribute_length == sizeof(num_subclasses) + sizeof(u2) * num_subclasses,
3830         "Wrong PermittedSubclasses attribute length in class file %s", CHECK);
3831     }
3832   }
3833 
3834   if (parsed_loadable_descriptors_attribute) {
3835     const u2 num_classes = parse_classfile_loadable_descriptors_attribute(
3836                             cfs,
3837                             loadable_descriptors_attribute_start,
3838                             CHECK);
3839     if (_need_verify) {
3840       guarantee_property(
3841         loadable_descriptors_attribute_length == sizeof(num_classes) + sizeof(u2) * num_classes,
3842         "Wrong LoadableDescriptors attribute length in class file %s", CHECK);
3843     }
3844   }
3845 
3846   if (_max_bootstrap_specifier_index >= 0) {
3847     guarantee_property(parsed_bootstrap_methods_attribute,
3848                        "Missing BootstrapMethods attribute in class file %s", CHECK);
3849   }
3850 }
3851 
3852 void ClassFileParser::apply_parsed_class_attributes(InstanceKlass* k) {
3853   assert(k != nullptr, "invariant");
3854 
3855   if (_synthetic_flag)
3856     k->set_is_synthetic();
3857   if (_sourcefile_index != 0) {
3858     k->set_source_file_name_index(_sourcefile_index);
3859   }
3860   if (_generic_signature_index != 0) {
3861     k->set_generic_signature_index(_generic_signature_index);
3862   }
3863   if (_sde_buffer != nullptr) {
3864     k->set_source_debug_extension(_sde_buffer, _sde_length);
3865   }

3891     _class_annotations       = nullptr;
3892     _class_type_annotations  = nullptr;
3893     _fields_annotations      = nullptr;
3894     _fields_type_annotations = nullptr;
3895 }
3896 
3897 // Transfer ownership of metadata allocated to the InstanceKlass.
3898 void ClassFileParser::apply_parsed_class_metadata(
3899                                             InstanceKlass* this_klass,
3900                                             int java_fields_count) {
3901   assert(this_klass != nullptr, "invariant");
3902 
3903   _cp->set_pool_holder(this_klass);
3904   this_klass->set_constants(_cp);
3905   this_klass->set_fieldinfo_stream(_fieldinfo_stream);
3906   this_klass->set_fields_status(_fields_status);
3907   this_klass->set_methods(_methods);
3908   this_klass->set_inner_classes(_inner_classes);
3909   this_klass->set_nest_members(_nest_members);
3910   this_klass->set_nest_host_index(_nest_host);
3911   this_klass->set_loadable_descriptors(_loadable_descriptors);
3912   this_klass->set_annotations(_combined_annotations);
3913   this_klass->set_permitted_subclasses(_permitted_subclasses);
3914   this_klass->set_record_components(_record_components);
3915   this_klass->set_inline_layout_info_array(_inline_layout_info_array);
3916 
3917   // Delay the setting of _local_interfaces and _transitive_interfaces until after
3918   // initialize_supers() in fill_instance_klass(). It is because the _local_interfaces could
3919   // be shared with _transitive_interfaces and _transitive_interfaces may be shared with
3920   // its _super. If an OOM occurs while loading the current klass, its _super field
3921   // may not have been set. When GC tries to free the klass, the _transitive_interfaces
3922   // may be deallocated mistakenly in InstanceKlass::deallocate_interfaces(). Subsequent
3923   // dereferences to the deallocated _transitive_interfaces will result in a crash.
3924 
3925   // Clear out these fields so they don't get deallocated by the destructor
3926   clear_class_metadata();
3927 }
3928 
3929 AnnotationArray* ClassFileParser::allocate_annotations(const u1* const anno,
3930                                                        int anno_length,
3931                                                        TRAPS) {
3932   AnnotationArray* annotations = nullptr;
3933   if (anno != nullptr) {
3934     annotations = MetadataFactory::new_array<u1>(_loader_data,
3935                                                  anno_length,
3936                                                  CHECK_(annotations));
3937     for (int i = 0; i < anno_length; i++) {
3938       annotations->at_put(i, anno[i]);
3939     }
3940   }
3941   return annotations;
3942 }
3943 
3944 const InstanceKlass* ClassFileParser::parse_super_class(ConstantPool* const cp,
3945                                                         const int super_class_index,
3946                                                         const bool need_verify,
3947                                                         TRAPS) {
3948   assert(cp != nullptr, "invariant");
3949   const InstanceKlass* super_klass = nullptr;
3950 
3951   if (super_class_index == 0) {
3952     guarantee_property(_class_name == vmSymbols::java_lang_Object(),
3953                    "Invalid superclass index 0 in class file %s",
3954                    CHECK_NULL);

3955   } else {
3956     guarantee_property(valid_klass_reference_at(super_class_index),
3957                        "Invalid superclass index %u in class file %s",
3958                        super_class_index,
3959                        CHECK_NULL);
3960     // The class name should be legal because it is checked when parsing constant pool.
3961     // However, make sure it is not an array type.

3962     if (cp->tag_at(super_class_index).is_klass()) {
3963       super_klass = InstanceKlass::cast(cp->resolved_klass_at(super_class_index));




3964     }
3965     if (need_verify) {
3966       bool is_array = (cp->klass_name_at(super_class_index)->char_at(0) == JVM_SIGNATURE_ARRAY);
3967       guarantee_property(!is_array,
3968                         "Bad superclass name in class file %s", CHECK_NULL);
3969     }
3970   }
3971   return super_klass;
3972 }
3973 
3974 OopMapBlocksBuilder::OopMapBlocksBuilder(unsigned int max_blocks) {
3975   _max_nonstatic_oop_maps = max_blocks;
3976   _nonstatic_oop_map_count = 0;
3977   if (max_blocks == 0) {
3978     _nonstatic_oop_maps = nullptr;
3979   } else {
3980     _nonstatic_oop_maps =
3981         NEW_RESOURCE_ARRAY(OopMapBlock, _max_nonstatic_oop_maps);
3982     memset(_nonstatic_oop_maps, 0, sizeof(OopMapBlock) * max_blocks);
3983   }
3984 }
3985 
3986 OopMapBlock* OopMapBlocksBuilder::last_oop_map() const {

4120 
4121   // Check if this klass supports the java.lang.Cloneable interface
4122   if (vmClasses::Cloneable_klass_loaded()) {
4123     if (ik->is_subtype_of(vmClasses::Cloneable_klass())) {
4124       ik->set_is_cloneable();
4125     }
4126   }
4127 
4128   // If it cannot be fast-path allocated, set a bit in the layout helper.
4129   // See documentation of InstanceKlass::can_be_fastpath_allocated().
4130   assert(ik->size_helper() > 0, "layout_helper is initialized");
4131   if (ik->is_abstract() || ik->is_interface()
4132       || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == nullptr)
4133       || ik->size_helper() >= FastAllocateSizeLimit) {
4134     // Forbid fast-path allocation.
4135     const jint lh = Klass::instance_layout_helper(ik->size_helper(), true);
4136     ik->set_layout_helper(lh);
4137   }
4138 }
4139 
4140 bool ClassFileParser::supports_inline_types() const {
4141   // Inline types are only supported by class file version 69.65535 and later
4142   return _major_version > JAVA_25_VERSION ||
4143          (_major_version == JAVA_25_VERSION && _minor_version == JAVA_PREVIEW_MINOR_VERSION);
4144 }
4145 
4146 // utility methods for appending an array with check for duplicates
4147 
4148 static void append_interfaces(GrowableArray<InstanceKlass*>* result,
4149                               const Array<InstanceKlass*>* const ifs) {
4150   // iterate over new interfaces
4151   for (int i = 0; i < ifs->length(); i++) {
4152     InstanceKlass* const e = ifs->at(i);
4153     assert(e->is_klass() && e->is_interface(), "just checking");
4154     // add new interface
4155     result->append_if_missing(e);
4156   }
4157 }
4158 
4159 static Array<InstanceKlass*>* compute_transitive_interfaces(const InstanceKlass* super,
4160                                                             Array<InstanceKlass*>* local_ifs,
4161                                                             ClassLoaderData* loader_data,
4162                                                             TRAPS) {
4163   assert(local_ifs != nullptr, "invariant");
4164   assert(loader_data != nullptr, "invariant");
4165 

4169   // Add superclass transitive interfaces size
4170   if (super != nullptr) {
4171     super_size = super->transitive_interfaces()->length();
4172     max_transitive_size += super_size;
4173   }
4174   // Add local interfaces' super interfaces
4175   const int local_size = local_ifs->length();
4176   for (int i = 0; i < local_size; i++) {
4177     InstanceKlass* const l = local_ifs->at(i);
4178     max_transitive_size += l->transitive_interfaces()->length();
4179   }
4180   // Finally add local interfaces
4181   max_transitive_size += local_size;
4182   // Construct array
4183   if (max_transitive_size == 0) {
4184     // no interfaces, use canonicalized array
4185     return Universe::the_empty_instance_klass_array();
4186   } else if (max_transitive_size == super_size) {
4187     // no new local interfaces added, share superklass' transitive interface array
4188     return super->transitive_interfaces();
4189     // The three lines below are commented to work around bug JDK-8245487
4190 //  } else if (max_transitive_size == local_size) {
4191 //    // only local interfaces added, share local interface array
4192 //    return local_ifs;
4193   } else {
4194     ResourceMark rm;
4195     GrowableArray<InstanceKlass*>* const result = new GrowableArray<InstanceKlass*>(max_transitive_size);
4196 
4197     // Copy down from superclass
4198     if (super != nullptr) {
4199       append_interfaces(result, super->transitive_interfaces());
4200     }
4201 
4202     // Copy down from local interfaces' superinterfaces
4203     for (int i = 0; i < local_size; i++) {
4204       InstanceKlass* const l = local_ifs->at(i);
4205       append_interfaces(result, l->transitive_interfaces());
4206     }
4207     // Finally add local interfaces
4208     append_interfaces(result, local_ifs);
4209 
4210     // length will be less than the max_transitive_size if duplicates were removed
4211     const int length = result->length();
4212     assert(length <= max_transitive_size, "just checking");
4213 
4214     Array<InstanceKlass*>* const new_result =
4215       MetadataFactory::new_array<InstanceKlass*>(loader_data, length, CHECK_NULL);
4216     for (int i = 0; i < length; i++) {
4217       InstanceKlass* const e = result->at(i);
4218       assert(e != nullptr, "just checking");
4219       new_result->at_put(i, e);
4220     }
4221     return new_result;
4222   }
4223 }
4224 
4225 void ClassFileParser::check_super_class_access(const InstanceKlass* this_klass, TRAPS) {
4226   assert(this_klass != nullptr, "invariant");
4227   const Klass* const super = this_klass->super();
4228 
4229   if (super != nullptr) {
4230     const InstanceKlass* super_ik = InstanceKlass::cast(super);
4231 
4232     if (super->is_final()) {
4233       classfile_icce_error("class %s cannot inherit from final class %s", super_ik, THREAD);
4234       return;
4235     }
4236 
4237     if (super_ik->is_sealed()) {
4238       stringStream ss;
4239       ResourceMark rm(THREAD);
4240       if (!super_ik->has_as_permitted_subclass(this_klass, ss)) {
4241         classfile_icce_error(ss.as_string(), THREAD);
4242         return;
4243       }
4244     }
4245 
4246     // The JVMS says that super classes for value types must not have the ACC_IDENTITY
4247     // flag set. But, java.lang.Object must still be allowed to be a direct super class
4248     // for a value classes.  So, it is treated as a special case for now.
4249     if (!this_klass->access_flags().is_identity_class() &&
4250         super_ik->name() != vmSymbols::java_lang_Object() &&
4251         super_ik->is_identity_class()) {
4252       classfile_icce_error("value class %s cannot inherit from class %s", super_ik, THREAD);
4253       return;
4254     }
4255 
4256     Reflection::VerifyClassAccessResults vca_result =
4257       Reflection::verify_class_access(this_klass, InstanceKlass::cast(super), false);
4258     if (vca_result != Reflection::ACCESS_OK) {
4259       ResourceMark rm(THREAD);
4260       char* msg = Reflection::verify_class_access_msg(this_klass,
4261                                                       InstanceKlass::cast(super),
4262                                                       vca_result);
4263 
4264       // Names are all known to be < 64k so we know this formatted message is not excessively large.
4265       if (msg == nullptr) {
4266         bool same_module = (this_klass->module() == super->module());
4267         Exceptions::fthrow(
4268           THREAD_AND_LOCATION,
4269           vmSymbols::java_lang_IllegalAccessError(),
4270           "class %s cannot access its %ssuperclass %s (%s%s%s)",
4271           this_klass->external_name(),
4272           super->is_abstract() ? "abstract " : "",
4273           super->external_name(),
4274           (same_module) ? this_klass->joint_in_module_of_loader(super) : this_klass->class_in_module_of_loader(),
4275           (same_module) ? "" : "; ",

4408     const Method* const m = methods->at(index);
4409     // if m is static and not the init method, throw a verify error
4410     if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) {
4411       ResourceMark rm(THREAD);
4412 
4413       // Names are all known to be < 64k so we know this formatted message is not excessively large.
4414       Exceptions::fthrow(
4415         THREAD_AND_LOCATION,
4416         vmSymbols::java_lang_VerifyError(),
4417         "Illegal static method %s in interface %s",
4418         m->name()->as_C_string(),
4419         this_klass->external_name()
4420       );
4421       return;
4422     }
4423   }
4424 }
4425 
4426 // utility methods for format checking
4427 
4428 void ClassFileParser::verify_legal_class_modifiers(jint flags, const char* name, bool is_Object, TRAPS) const {
4429   const bool is_module = (flags & JVM_ACC_MODULE) != 0;
4430   const bool is_inner_class = name != nullptr;
4431   assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");
4432   if (is_module) {
4433     ResourceMark rm(THREAD);
4434     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4435     Exceptions::fthrow(
4436       THREAD_AND_LOCATION,
4437       vmSymbols::java_lang_NoClassDefFoundError(),
4438       "%s is not a class because access_flag ACC_MODULE is set",
4439       _class_name->as_C_string());
4440     return;
4441   }
4442 
4443   if (!_need_verify) { return; }
4444 
4445   const bool is_interface  = (flags & JVM_ACC_INTERFACE)  != 0;
4446   const bool is_abstract   = (flags & JVM_ACC_ABSTRACT)   != 0;
4447   const bool is_final      = (flags & JVM_ACC_FINAL)      != 0;
4448   const bool is_identity   = (flags & JVM_ACC_IDENTITY)   != 0;
4449   const bool is_enum       = (flags & JVM_ACC_ENUM)       != 0;
4450   const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4451   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4452   const bool valid_value_class = is_identity || is_interface ||
4453                                  (supports_inline_types() && (!is_identity && (is_abstract || is_final)));
4454 
4455   if ((is_abstract && is_final) ||
4456       (is_interface && !is_abstract) ||
4457       (is_interface && major_gte_1_5 && (is_identity || is_enum)) ||   //  ACC_SUPER (now ACC_IDENTITY) was illegal for interfaces
4458       (!is_interface && major_gte_1_5 && is_annotation) ||
4459       (!valid_value_class)) {
4460     ResourceMark rm(THREAD);
4461     const char* class_note = "";
4462     if (!valid_value_class) {
4463       class_note = " (a value class must be final or else abstract)";
4464     }
4465     if (name == nullptr) { // Not an inner class
4466       Exceptions::fthrow(
4467         THREAD_AND_LOCATION,
4468         vmSymbols::java_lang_ClassFormatError(),
4469         "Illegal class modifiers in class %s%s: 0x%X",
4470         _class_name->as_C_string(), class_note, flags
4471       );
4472       return;
4473     } else {
4474       // Names are all known to be < 64k so we know this formatted message is not excessively large.
4475       Exceptions::fthrow(
4476         THREAD_AND_LOCATION,
4477         vmSymbols::java_lang_ClassFormatError(),
4478         "Illegal class modifiers in declaration of inner class %s%s of class %s: 0x%X",
4479         name, class_note, _class_name->as_C_string(), flags
4480       );
4481       return;
4482     }
4483   }
4484 }
4485 
4486 static bool has_illegal_visibility(jint flags) {
4487   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4488   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4489   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4490 
4491   return ((is_public && is_protected) ||
4492           (is_public && is_private) ||
4493           (is_protected && is_private));
4494 }
4495 
4496 // A legal major_version.minor_version must be one of the following:
4497 //
4498 //  Major_version >= 45 and major_version < 56, any minor_version.
4499 //  Major_version >= 56 and major_version <= JVM_CLASSFILE_MAJOR_VERSION and minor_version = 0.
4500 //  Major_version = JVM_CLASSFILE_MAJOR_VERSION and minor_version = 65535 and --enable-preview is present.
4501 //
4502 void ClassFileParser::verify_class_version(u2 major, u2 minor, Symbol* class_name, TRAPS){

4530         THREAD_AND_LOCATION,
4531         vmSymbols::java_lang_UnsupportedClassVersionError(),
4532         "%s (class file version %u.%u) was compiled with preview features that are unsupported. "
4533         "This version of the Java Runtime only recognizes preview features for class file version %u.%u",
4534         class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION, JAVA_PREVIEW_MINOR_VERSION);
4535       return;
4536     }
4537 
4538     if (!Arguments::enable_preview()) {
4539       classfile_ucve_error("Preview features are not enabled for %s (class file version %u.%u). Try running with '--enable-preview'",
4540                            class_name, major, minor, THREAD);
4541       return;
4542     }
4543 
4544   } else { // minor != JAVA_PREVIEW_MINOR_VERSION
4545     classfile_ucve_error("%s (class file version %u.%u) was compiled with an invalid non-zero minor version",
4546                          class_name, major, minor, THREAD);
4547   }
4548 }
4549 
4550 void ClassFileParser:: verify_legal_field_modifiers(jint flags,
4551                                                    AccessFlags class_access_flags,
4552                                                    TRAPS) const {
4553   if (!_need_verify) { return; }
4554 
4555   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4556   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4557   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4558   const bool is_static    = (flags & JVM_ACC_STATIC)    != 0;
4559   const bool is_final     = (flags & JVM_ACC_FINAL)     != 0;
4560   const bool is_volatile  = (flags & JVM_ACC_VOLATILE)  != 0;
4561   const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
4562   const bool is_enum      = (flags & JVM_ACC_ENUM)      != 0;
4563   const bool is_strict    = (flags & JVM_ACC_STRICT)    != 0;
4564   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4565 
4566   const bool is_interface = class_access_flags.is_interface();
4567   const bool is_identity_class = class_access_flags.is_identity_class();
4568 
4569   bool is_illegal = false;
4570   const char* error_msg = "";
4571 
4572   // There is some overlap in the checks that apply, for example interface fields
4573   // must be static, static fields can't be strict, and therefore interfaces can't
4574   // have strict fields. So we don't have to check every possible invalid combination
4575   // individually as long as all are covered. Once we have found an illegal combination
4576   // we can stop checking.
4577 
4578   if (supports_inline_types()) {
4579     if (is_strict && is_static) {
4580       is_illegal = true;
4581       error_msg = "field cannot be strict and static";
4582     }
4583     else if (is_strict && !is_final) {

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

4753         if (type == ClassFileParser::LegalClass) {
4754           if (p == name || p+1 >= name+length ||
4755               *(p+1) == JVM_SIGNATURE_SLASH) {
4756             return false;
4757           }
4758         } else {
4759           return false;   // do not permit '/' unless it's class name
4760         }
4761         break;
4762       case JVM_SIGNATURE_SPECIAL:
4763       case JVM_SIGNATURE_ENDSPECIAL:
4764         // do not permit '<' or '>' in method names
4765         if (type == ClassFileParser::LegalMethod) {
4766           return false;
4767         }
4768     }
4769   }
4770   return true;
4771 }
4772 
4773 bool ClassFileParser::is_class_in_loadable_descriptors_attribute(Symbol *klass) {
4774   if (_loadable_descriptors == nullptr) return false;
4775   for (int i = 0; i < _loadable_descriptors->length(); i++) {
4776         Symbol* class_name = _cp->symbol_at(_loadable_descriptors->at(i));
4777         if (class_name == klass) return true;
4778   }
4779   return false;
4780 }
4781 
4782 // Take pointer to a UTF8 byte string (not NUL-terminated).
4783 // Skip over the longest part of the string that could
4784 // be taken as a fieldname. Allow non-trailing '/'s if slash_ok is true.
4785 // Return a pointer to just past the fieldname.
4786 // Return null if no fieldname at all was found, or in the case of slash_ok
4787 // being true, we saw consecutive slashes (meaning we were looking for a
4788 // qualified path but found something that was badly-formed).
4789 static const char* skip_over_field_name(const char* const name,
4790                                         bool slash_ok,
4791                                         unsigned int length) {
4792   const char* p;
4793   jboolean last_is_slash = false;
4794   jboolean not_first_ch = false;
4795 
4796   for (p = name; p != name + length; not_first_ch = true) {
4797     const char* old_p = p;
4798     jchar ch = *p;
4799     if (ch < 128) {
4800       p++;
4801       // quick check for ascii

4863 // be taken as a field signature. Allow "void" if void_ok.
4864 // Return a pointer to just past the signature.
4865 // Return null if no legal signature is found.
4866 const char* ClassFileParser::skip_over_field_signature(const char* signature,
4867                                                        bool void_ok,
4868                                                        unsigned int length,
4869                                                        TRAPS) const {
4870   unsigned int array_dim = 0;
4871   while (length > 0) {
4872     switch (signature[0]) {
4873     case JVM_SIGNATURE_VOID: if (!void_ok) { return nullptr; }
4874     case JVM_SIGNATURE_BOOLEAN:
4875     case JVM_SIGNATURE_BYTE:
4876     case JVM_SIGNATURE_CHAR:
4877     case JVM_SIGNATURE_SHORT:
4878     case JVM_SIGNATURE_INT:
4879     case JVM_SIGNATURE_FLOAT:
4880     case JVM_SIGNATURE_LONG:
4881     case JVM_SIGNATURE_DOUBLE:
4882       return signature + 1;
4883     case JVM_SIGNATURE_CLASS:
4884     {
4885       if (_major_version < JAVA_1_5_VERSION) {
4886         // Skip over the class name if one is there
4887         const char* const p = skip_over_field_name(signature + 1, true, --length);
4888 
4889         // The next character better be a semicolon
4890         if (p && (p - signature) > 1 && p[0] == JVM_SIGNATURE_ENDCLASS) {
4891           return p + 1;
4892         }
4893       }
4894       else {
4895         // Skip leading 'L' or 'Q' and ignore first appearance of ';'
4896         signature++;
4897         const char* c = (const char*) memchr(signature, JVM_SIGNATURE_ENDCLASS, length - 1);
4898         // Format check signature
4899         if (c != nullptr) {
4900           int newlen = pointer_delta_as_int(c, (char*) signature);
4901           bool legal = verify_unqualified_name(signature, newlen, LegalClass);
4902           if (!legal) {
4903             classfile_parse_error("Class name is empty or contains illegal character "
4904                                   "in descriptor in class file %s",
4905                                   THREAD);
4906             return nullptr;
4907           }
4908           return signature + newlen + 1;
4909         }
4910       }
4911       return nullptr;
4912     }
4913     case JVM_SIGNATURE_ARRAY:
4914       array_dim++;
4915       if (array_dim > 255) {

4931 
4932 // Checks if name is a legal class name.
4933 void ClassFileParser::verify_legal_class_name(const Symbol* name, TRAPS) const {
4934   if (!_need_verify) { return; }
4935 
4936   assert(name->refcount() > 0, "symbol must be kept alive");
4937   char* bytes = (char*)name->bytes();
4938   unsigned int length = name->utf8_length();
4939   bool legal = false;
4940 
4941   if (length > 0) {
4942     const char* p;
4943     if (bytes[0] == JVM_SIGNATURE_ARRAY) {
4944       p = skip_over_field_signature(bytes, false, length, CHECK);
4945       legal = (p != nullptr) && ((p - bytes) == (int)length);
4946     } else if (_major_version < JAVA_1_5_VERSION) {
4947       if (bytes[0] != JVM_SIGNATURE_SPECIAL) {
4948         p = skip_over_field_name(bytes, true, length);
4949         legal = (p != nullptr) && ((p - bytes) == (int)length);
4950       }
4951     } else if ((_major_version >= CONSTANT_CLASS_DESCRIPTORS || _class_name->starts_with("jdk/internal/reflect/"))
4952                    && bytes[length - 1] == ';' ) {
4953       // Support for L...; descriptors
4954       legal = verify_unqualified_name(bytes + 1, length - 2, LegalClass);
4955     } else {
4956       // 4900761: relax the constraints based on JSR202 spec
4957       // Class names may be drawn from the entire Unicode character set.
4958       // Identifiers between '/' must be unqualified names.
4959       // The utf8 string has been verified when parsing cpool entries.
4960       legal = verify_unqualified_name(bytes, length, LegalClass);
4961     }
4962   }
4963   if (!legal) {
4964     ResourceMark rm(THREAD);
4965     assert(_class_name != nullptr, "invariant");
4966     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4967     Exceptions::fthrow(
4968       THREAD_AND_LOCATION,
4969       vmSymbols::java_lang_ClassFormatError(),
4970       "Illegal class name \"%.*s\" in class file %s", length, bytes,
4971       _class_name->as_C_string()
4972     );
4973     return;
4974   }

5002       THREAD_AND_LOCATION,
5003       vmSymbols::java_lang_ClassFormatError(),
5004       "Illegal field name \"%.*s\" in class %s", length, bytes,
5005       _class_name->as_C_string()
5006     );
5007     return;
5008   }
5009 }
5010 
5011 // Checks if name is a legal method name.
5012 void ClassFileParser::verify_legal_method_name(const Symbol* name, TRAPS) const {
5013   if (!_need_verify) { return; }
5014 
5015   assert(name != nullptr, "method name is null");
5016   char* bytes = (char*)name->bytes();
5017   unsigned int length = name->utf8_length();
5018   bool legal = false;
5019 
5020   if (length > 0) {
5021     if (bytes[0] == JVM_SIGNATURE_SPECIAL) {
5022       if (name == vmSymbols::object_initializer_name() ||
5023           name == vmSymbols::class_initializer_name()) {
5024         legal = true;
5025       }
5026     } else if (_major_version < JAVA_1_5_VERSION) {
5027       const char* p;
5028       p = skip_over_field_name(bytes, false, length);
5029       legal = (p != nullptr) && ((p - bytes) == (int)length);
5030     } else {
5031       // 4881221: relax the constraints based on JSR202 spec
5032       legal = verify_unqualified_name(bytes, length, LegalMethod);
5033     }
5034   }
5035 
5036   if (!legal) {
5037     ResourceMark rm(THREAD);
5038     assert(_class_name != nullptr, "invariant");
5039     // Names are all known to be < 64k so we know this formatted message is not excessively large.
5040     Exceptions::fthrow(
5041       THREAD_AND_LOCATION,
5042       vmSymbols::java_lang_ClassFormatError(),
5043       "Illegal method name \"%.*s\" in class %s", length, bytes,
5044       _class_name->as_C_string()
5045     );
5046     return;
5047   }
5048 }
5049 
5050 bool ClassFileParser::legal_field_signature(const Symbol* signature, TRAPS) const {
5051   const char* const bytes = (const char*)signature->bytes();
5052   const unsigned int length = signature->utf8_length();
5053   const char* const p = skip_over_field_signature(bytes, false, length, CHECK_false);
5054 
5055   if (p == nullptr || (p - bytes) != (int)length) {
5056     return false;
5057   }
5058   return true;
5059 }
5060 
5061 // Checks if signature is a legal field signature.
5062 void ClassFileParser::verify_legal_field_signature(const Symbol* name,
5063                                                    const Symbol* signature,
5064                                                    TRAPS) const {
5065   if (!_need_verify) { return; }
5066 
5067   const char* const bytes = (const char*)signature->bytes();
5068   const unsigned int length = signature->utf8_length();
5069   const char* const p = skip_over_field_signature(bytes, false, length, CHECK);
5070 
5071   if (p == nullptr || (p - bytes) != (int)length) {
5072     throwIllegalSignature("Field", name, signature, CHECK);
5073   }
5074 }
5075 
5076 // Check that the signature is compatible with the method name.  For example,
5077 // check that <init> has a void signature.
5078 void ClassFileParser::verify_legal_name_with_signature(const Symbol* name,
5079                                                        const Symbol* signature,
5080                                                        TRAPS) const {
5081   if (!_need_verify) {
5082     return;
5083   }
5084 
5085   // Class initializers cannot have args for class format version >= 51.
5086   if (name == vmSymbols::class_initializer_name() &&
5087       signature != vmSymbols::void_method_signature() &&
5088       _major_version >= JAVA_7_VERSION) {
5089     throwIllegalSignature("Method", name, signature, THREAD);
5090     return;
5091   }
5092 
5093   int sig_length = signature->utf8_length();
5094   if (name->utf8_length() > 0 &&
5095     name->char_at(0) == JVM_SIGNATURE_SPECIAL &&
5096     sig_length > 0 &&
5097     signature->char_at(sig_length - 1) != JVM_SIGNATURE_VOID) {
5098     throwIllegalSignature("Method", name, signature, THREAD);
5099   }
5100 }
5101 
5102 // Checks if signature is a legal method signature.
5103 // Returns number of parameters
5104 int ClassFileParser::verify_legal_method_signature(const Symbol* name,
5105                                                    const Symbol* signature,
5106                                                    TRAPS) const {
5107   if (!_need_verify) {
5108     // make sure caller's args_size will be less than 0 even for non-static
5109     // method so it will be recomputed in compute_size_of_parameters().
5110     return -2;
5111   }
5112 
5113   unsigned int args_size = 0;
5114   const char* p = (const char*)signature->bytes();
5115   unsigned int length = signature->utf8_length();
5116   const char* nextp;
5117 

5128       length -= pointer_delta_as_int(nextp, p);
5129       p = nextp;
5130       nextp = skip_over_field_signature(p, false, length, CHECK_0);
5131     }
5132     // The first non-signature thing better be a ')'
5133     if ((length > 0) && (*p++ == JVM_SIGNATURE_ENDFUNC)) {
5134       length--;
5135       // Now we better just have a return value
5136       nextp = skip_over_field_signature(p, true, length, CHECK_0);
5137       if (nextp && ((int)length == (nextp - p))) {
5138         return args_size;
5139       }
5140     }
5141   }
5142   // Report error
5143   throwIllegalSignature("Method", name, signature, THREAD);
5144   return 0;
5145 }
5146 
5147 int ClassFileParser::static_field_size() const {
5148   assert(_layout_info != nullptr, "invariant");
5149   return _layout_info->_static_field_size;
5150 }
5151 
5152 int ClassFileParser::total_oop_map_count() const {
5153   assert(_layout_info != nullptr, "invariant");
5154   return _layout_info->oop_map_blocks->_nonstatic_oop_map_count;
5155 }
5156 
5157 jint ClassFileParser::layout_size() const {
5158   assert(_layout_info != nullptr, "invariant");
5159   return _layout_info->_instance_size;
5160 }
5161 
5162 static void check_methods_for_intrinsics(const InstanceKlass* ik,
5163                                          const Array<Method*>* methods) {
5164   assert(ik != nullptr, "invariant");
5165   assert(methods != nullptr, "invariant");
5166 
5167   // Set up Method*::intrinsic_id as soon as we know the names of methods.
5168   // (We used to do this lazily, but now we query it in Rewriter,
5169   // which is eagerly done for every method, so we might as well do it now,
5170   // when everything is fresh in memory.)
5171   const vmSymbolID klass_id = Method::klass_id_for_intrinsics(ik);
5172 
5173   if (klass_id != vmSymbolID::NO_SID) {
5174     for (int j = 0; j < methods->length(); ++j) {
5175       Method* method = methods->at(j);
5176       method->init_intrinsic_id(klass_id);
5177 
5178       if (CheckIntrinsics) {
5179         // Check if an intrinsic is defined for method 'method',

5254   }
5255 }
5256 
5257 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook,
5258                                                       const ClassInstanceInfo& cl_inst_info,
5259                                                       TRAPS) {
5260   if (_klass != nullptr) {
5261     return _klass;
5262   }
5263 
5264   InstanceKlass* const ik =
5265     InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
5266 
5267   if (is_hidden()) {
5268     mangle_hidden_class_name(ik);
5269   }
5270 
5271   fill_instance_klass(ik, changed_by_loadhook, cl_inst_info, CHECK_NULL);
5272 
5273   assert(_klass == ik, "invariant");

5274   return ik;
5275 }
5276 
5277 void ClassFileParser::fill_instance_klass(InstanceKlass* ik,
5278                                           bool changed_by_loadhook,
5279                                           const ClassInstanceInfo& cl_inst_info,
5280                                           TRAPS) {
5281   assert(ik != nullptr, "invariant");
5282 
5283   // Set name and CLD before adding to CLD
5284   ik->set_class_loader_data(_loader_data);
5285   ik->set_name(_class_name);
5286 
5287   // Add all classes to our internal class loader list here,
5288   // including classes in the bootstrap (null) class loader.
5289   const bool publicize = !is_internal();
5290 
5291   _loader_data->add_class(ik, publicize);
5292 
5293   set_klass_to_deallocate(ik);
5294 
5295   assert(_layout_info != nullptr, "invariant");
5296   assert(ik->static_field_size() == _layout_info->_static_field_size, "sanity");
5297   assert(ik->nonstatic_oop_map_count() == _layout_info->oop_map_blocks->_nonstatic_oop_map_count,
5298          "sanity");
5299 
5300   assert(ik->is_instance_klass(), "sanity");
5301   assert(ik->size_helper() == _layout_info->_instance_size, "sanity");
5302 
5303   // Fill in information already parsed
5304   ik->set_should_verify_class(_need_verify);
5305 
5306   // Not yet: supers are done below to support the new subtype-checking fields
5307   ik->set_nonstatic_field_size(_layout_info->_nonstatic_field_size);
5308   ik->set_has_nonstatic_fields(_layout_info->_has_nonstatic_fields);
5309 
5310   if (_layout_info->_is_naturally_atomic) {
5311     ik->set_is_naturally_atomic();
5312   }
5313 
5314   if (_layout_info->_must_be_atomic) {
5315     ik->set_must_be_atomic();
5316   }
5317   if (_is_implicitly_constructible) {
5318     ik->set_is_implicitly_constructible();
5319   }
5320 
5321   ik->set_static_oop_field_count(_static_oop_count);
5322 
5323   // this transfers ownership of a lot of arrays from
5324   // the parser onto the InstanceKlass*
5325   apply_parsed_class_metadata(ik, _java_fields_count);
5326   if (ik->is_inline_klass()) {
5327     InlineKlass::cast(ik)->init_fixed_block();
5328   }
5329 
5330   // can only set dynamic nest-host after static nest information is set
5331   if (cl_inst_info.dynamic_nest_host() != nullptr) {
5332     ik->set_nest_host(cl_inst_info.dynamic_nest_host());
5333   }
5334 
5335   // note that is not safe to use the fields in the parser from this point on
5336   assert(nullptr == _cp, "invariant");
5337   assert(nullptr == _fieldinfo_stream, "invariant");
5338   assert(nullptr == _fields_status, "invariant");
5339   assert(nullptr == _methods, "invariant");
5340   assert(nullptr == _inner_classes, "invariant");
5341   assert(nullptr == _nest_members, "invariant");
5342   assert(nullptr == _loadable_descriptors, "invariant");
5343   assert(nullptr == _combined_annotations, "invariant");
5344   assert(nullptr == _record_components, "invariant");
5345   assert(nullptr == _permitted_subclasses, "invariant");
5346   assert(nullptr == _inline_layout_info_array, "invariant");
5347 
5348   if (_has_localvariable_table) {
5349     ik->set_has_localvariable_table(true);
5350   }
5351 
5352   if (_has_final_method) {
5353     ik->set_has_final_method();
5354   }
5355 
5356   ik->copy_method_ordering(_method_ordering, CHECK);
5357   // The InstanceKlass::_methods_jmethod_ids cache
5358   // is managed on the assumption that the initial cache
5359   // size is equal to the number of methods in the class. If
5360   // that changes, then InstanceKlass::idnum_can_increment()
5361   // has to be changed accordingly.
5362   ik->set_initial_method_idnum(checked_cast<u2>(ik->methods()->length()));
5363 
5364   ik->set_this_class_index(_this_class_index);
5365 
5366   if (_is_hidden) {

5404   if ((_num_miranda_methods > 0) ||
5405       // if this class introduced new miranda methods or
5406       (_super_klass != nullptr && _super_klass->has_miranda_methods())
5407         // super class exists and this class inherited miranda methods
5408      ) {
5409        ik->set_has_miranda_methods(); // then set a flag
5410   }
5411 
5412   // Fill in information needed to compute superclasses.
5413   ik->initialize_supers(const_cast<InstanceKlass*>(_super_klass), _transitive_interfaces, CHECK);
5414   ik->set_transitive_interfaces(_transitive_interfaces);
5415   ik->set_local_interfaces(_local_interfaces);
5416   _transitive_interfaces = nullptr;
5417   _local_interfaces = nullptr;
5418 
5419   // Initialize itable offset tables
5420   klassItable::setup_itable_offset_table(ik);
5421 
5422   // Compute transitive closure of interfaces this class implements
5423   // Do final class setup
5424   OopMapBlocksBuilder* oop_map_blocks = _layout_info->oop_map_blocks;
5425   if (oop_map_blocks->_nonstatic_oop_map_count > 0) {
5426     oop_map_blocks->copy(ik->start_of_nonstatic_oop_maps());
5427   }
5428 
5429   if (_has_contended_fields || _parsed_annotations->is_contended() ||
5430       ( _super_klass != nullptr && _super_klass->has_contended_annotations())) {
5431     ik->set_has_contended_annotations(true);
5432   }
5433 
5434   // Fill in has_finalizer and layout_helper
5435   set_precomputed_flags(ik);
5436 
5437   // check if this class can access its super class
5438   check_super_class_access(ik, CHECK);
5439 
5440   // check if this class can access its superinterfaces
5441   check_super_interface_access(ik, CHECK);
5442 
5443   // check if this class overrides any final method
5444   check_final_method_override(ik, CHECK);

5465 
5466   assert(_all_mirandas != nullptr, "invariant");
5467 
5468   // Generate any default methods - default methods are public interface methods
5469   // that have a default implementation.  This is new with Java 8.
5470   if (_has_nonstatic_concrete_methods) {
5471     DefaultMethods::generate_default_methods(ik,
5472                                              _all_mirandas,
5473                                              CHECK);
5474   }
5475 
5476   // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5477   if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5478       !module_entry->has_default_read_edges()) {
5479     if (!module_entry->set_has_default_read_edges()) {
5480       // We won a potential race
5481       JvmtiExport::add_default_read_edges(module_handle, THREAD);
5482     }
5483   }
5484 
5485   if (is_inline_type()) {
5486     InlineKlass* vk = InlineKlass::cast(ik);
5487     vk->set_payload_alignment(_layout_info->_payload_alignment);
5488     vk->set_payload_offset(_layout_info->_payload_offset);
5489     vk->set_payload_size_in_bytes(_layout_info->_payload_size_in_bytes);
5490     vk->set_non_atomic_size_in_bytes(_layout_info->_non_atomic_size_in_bytes);
5491     vk->set_non_atomic_alignment(_layout_info->_non_atomic_alignment);
5492     vk->set_atomic_size_in_bytes(_layout_info->_atomic_layout_size_in_bytes);
5493     vk->set_nullable_size_in_bytes(_layout_info->_nullable_layout_size_in_bytes);
5494     vk->set_null_marker_offset(_layout_info->_null_marker_offset);
5495     vk->set_default_value_offset(_layout_info->_default_value_offset);
5496     vk->set_null_reset_value_offset(_layout_info->_null_reset_value_offset);
5497     if (_layout_info->_is_empty_inline_klass) vk->set_is_empty_inline_type();
5498     vk->initialize_calling_convention(CHECK);
5499   }
5500 
5501   ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5502 
5503   if (!is_internal()) {
5504     ik->print_class_load_logging(_loader_data, module_entry, _stream);
5505 
5506     if (ik->minor_version() == JAVA_PREVIEW_MINOR_VERSION &&
5507         ik->major_version() == JVM_CLASSFILE_MAJOR_VERSION &&
5508         log_is_enabled(Info, class, preview)) {
5509       ResourceMark rm;
5510       log_info(class, preview)("Loading class %s that depends on preview features (class file version %d.65535)",
5511                                ik->external_name(), JVM_CLASSFILE_MAJOR_VERSION);
5512     }
5513 
5514     if (log_is_enabled(Debug, class, resolve))  {
5515       ResourceMark rm;
5516       // print out the superclass.
5517       const char * from = ik->external_name();
5518       if (ik->java_super() != nullptr) {
5519         log_debug(class, resolve)("%s %s (super)",
5520                    from,

5562                                  ClassLoaderData* loader_data,
5563                                  const ClassLoadInfo* cl_info,
5564                                  Publicity pub_level,
5565                                  TRAPS) :
5566   _stream(stream),
5567   _class_name(nullptr),
5568   _loader_data(loader_data),
5569   _is_hidden(cl_info->is_hidden()),
5570   _can_access_vm_annotations(cl_info->can_access_vm_annotations()),
5571   _orig_cp_size(0),
5572   _static_oop_count(0),
5573   _super_klass(),
5574   _cp(nullptr),
5575   _fieldinfo_stream(nullptr),
5576   _fields_status(nullptr),
5577   _methods(nullptr),
5578   _inner_classes(nullptr),
5579   _nest_members(nullptr),
5580   _nest_host(0),
5581   _permitted_subclasses(nullptr),
5582   _loadable_descriptors(nullptr),
5583   _record_components(nullptr),
5584   _local_interfaces(nullptr),
5585   _local_interface_indexes(nullptr),
5586   _transitive_interfaces(nullptr),
5587   _combined_annotations(nullptr),
5588   _class_annotations(nullptr),
5589   _class_type_annotations(nullptr),
5590   _fields_annotations(nullptr),
5591   _fields_type_annotations(nullptr),
5592   _klass(nullptr),
5593   _klass_to_deallocate(nullptr),
5594   _parsed_annotations(nullptr),
5595   _layout_info(nullptr),
5596   _inline_layout_info_array(nullptr),
5597   _temp_field_info(nullptr),
5598   _method_ordering(nullptr),
5599   _all_mirandas(nullptr),
5600   _vtable_size(0),
5601   _itable_size(0),
5602   _num_miranda_methods(0),
5603   _protection_domain(cl_info->protection_domain()),
5604   _access_flags(),
5605   _pub_level(pub_level),
5606   _bad_constant_seen(0),
5607   _synthetic_flag(false),
5608   _sde_length(false),
5609   _sde_buffer(nullptr),
5610   _sourcefile_index(0),
5611   _generic_signature_index(0),
5612   _major_version(0),
5613   _minor_version(0),
5614   _this_class_index(0),
5615   _super_class_index(0),
5616   _itfs_len(0),
5617   _java_fields_count(0),
5618   _need_verify(false),
5619   _has_nonstatic_concrete_methods(false),
5620   _declares_nonstatic_concrete_methods(false),
5621   _has_localvariable_table(false),
5622   _has_final_method(false),
5623   _has_contended_fields(false),
5624   _has_inline_type_fields(false),
5625   _is_naturally_atomic(false),
5626   _must_be_atomic(true),
5627   _is_implicitly_constructible(false),
5628   _has_loosely_consistent_annotation(false),
5629   _has_implicitly_constructible_annotation(false),
5630   _has_finalizer(false),
5631   _has_empty_finalizer(false),
5632   _max_bootstrap_specifier_index(-1) {
5633 
5634   _class_name = name != nullptr ? name : vmSymbols::unknown_class_name();
5635   _class_name->increment_refcount();
5636 
5637   assert(_loader_data != nullptr, "invariant");
5638   assert(stream != nullptr, "invariant");
5639   assert(_stream != nullptr, "invariant");
5640   assert(_stream->buffer() == _stream->current(), "invariant");
5641   assert(_class_name != nullptr, "invariant");
5642   assert(0 == _access_flags.as_unsigned_short(), "invariant");
5643 
5644   // Figure out whether we can skip format checking (matching classic VM behavior)
5645   _need_verify = Verifier::should_verify_for(_loader_data->class_loader());
5646 
5647   // synch back verification state to stream to check for truncation.
5648   stream->set_need_verify(_need_verify);
5649 
5650   parse_stream(stream, CHECK);
5651 
5652   post_process_parsed_stream(stream, _cp, CHECK);
5653 }
5654 
5655 void ClassFileParser::clear_class_metadata() {
5656   // metadata created before the instance klass is created.  Must be
5657   // deallocated if classfile parsing returns an error.
5658   _cp = nullptr;
5659   _fieldinfo_stream = nullptr;
5660   _fields_status = nullptr;
5661   _methods = nullptr;
5662   _inner_classes = nullptr;
5663   _nest_members = nullptr;
5664   _permitted_subclasses = nullptr;
5665   _loadable_descriptors = nullptr;
5666   _combined_annotations = nullptr;
5667   _class_annotations = _class_type_annotations = nullptr;
5668   _fields_annotations = _fields_type_annotations = nullptr;
5669   _record_components = nullptr;
5670   _inline_layout_info_array = nullptr;
5671 }
5672 
5673 // Destructor to clean up
5674 ClassFileParser::~ClassFileParser() {
5675   _class_name->decrement_refcount();
5676 
5677   if (_cp != nullptr) {
5678     MetadataFactory::free_metadata(_loader_data, _cp);
5679   }
5680 
5681   if (_fieldinfo_stream != nullptr) {
5682     MetadataFactory::free_array<u1>(_loader_data, _fieldinfo_stream);
5683   }
5684 
5685   if (_fields_status != nullptr) {
5686     MetadataFactory::free_array<FieldStatus>(_loader_data, _fields_status);
5687   }
5688 
5689   if (_inline_layout_info_array != nullptr) {
5690     MetadataFactory::free_array<InlineLayoutInfo>(_loader_data, _inline_layout_info_array);
5691   }
5692 
5693   if (_methods != nullptr) {
5694     // Free methods
5695     InstanceKlass::deallocate_methods(_loader_data, _methods);
5696   }
5697 
5698   // beware of the Universe::empty_blah_array!!
5699   if (_inner_classes != nullptr && _inner_classes != Universe::the_empty_short_array()) {
5700     MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
5701   }
5702 
5703   if (_nest_members != nullptr && _nest_members != Universe::the_empty_short_array()) {
5704     MetadataFactory::free_array<u2>(_loader_data, _nest_members);
5705   }
5706 
5707   if (_record_components != nullptr) {
5708     InstanceKlass::deallocate_record_components(_loader_data, _record_components);
5709   }
5710 
5711   if (_permitted_subclasses != nullptr && _permitted_subclasses != Universe::the_empty_short_array()) {
5712     MetadataFactory::free_array<u2>(_loader_data, _permitted_subclasses);
5713   }
5714 
5715   if (_loadable_descriptors != nullptr && _loadable_descriptors != Universe::the_empty_short_array()) {
5716     MetadataFactory::free_array<u2>(_loader_data, _loadable_descriptors);
5717   }
5718 
5719   // Free interfaces
5720   InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
5721                                        _local_interfaces, _transitive_interfaces);
5722 
5723   if (_combined_annotations != nullptr) {
5724     // After all annotations arrays have been created, they are installed into the
5725     // Annotations object that will be assigned to the InstanceKlass being created.
5726 
5727     // Deallocate the Annotations object and the installed annotations arrays.
5728     _combined_annotations->deallocate_contents(_loader_data);
5729 
5730     // If the _combined_annotations pointer is non-null,
5731     // then the other annotations fields should have been cleared.
5732     assert(_class_annotations       == nullptr, "Should have been cleared");
5733     assert(_class_type_annotations  == nullptr, "Should have been cleared");
5734     assert(_fields_annotations      == nullptr, "Should have been cleared");
5735     assert(_fields_type_annotations == nullptr, "Should have been cleared");
5736   } else {
5737     // If the annotations arrays were not installed into the Annotations object,
5738     // then they have to be deallocated explicitly.

5783     cp_size, CHECK);
5784 
5785   _orig_cp_size = cp_size;
5786   if (is_hidden()) { // Add a slot for hidden class name.
5787     cp_size++;
5788   }
5789 
5790   _cp = ConstantPool::allocate(_loader_data,
5791                                cp_size,
5792                                CHECK);
5793 
5794   ConstantPool* const cp = _cp;
5795 
5796   parse_constant_pool(stream, cp, _orig_cp_size, CHECK);
5797 
5798   assert(cp_size == (u2)cp->length(), "invariant");
5799 
5800   // ACCESS FLAGS
5801   stream->guarantee_more(8, CHECK);  // flags, this_class, super_class, infs_len
5802 
5803   u2 recognized_modifiers = JVM_RECOGNIZED_CLASS_MODIFIERS;

5804   // JVM_ACC_MODULE is defined in JDK-9 and later.
5805   if (_major_version >= JAVA_9_VERSION) {
5806     recognized_modifiers |= JVM_ACC_MODULE;


5807   }
5808 
5809   // Access flags
5810   u2 flags = stream->get_u2_fast() & recognized_modifiers;
5811 
5812   if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
5813     // Set abstract bit for old class files for backward compatibility
5814     flags |= JVM_ACC_ABSTRACT;
5815   }
5816 
5817   // Fixing ACC_SUPER/ACC_IDENTITY for old class files
5818   if (!supports_inline_types()) {
5819     const bool is_module = (flags & JVM_ACC_MODULE) != 0;
5820     const bool is_interface = (flags & JVM_ACC_INTERFACE) != 0;
5821     if (!is_module && !is_interface) {
5822       flags |= JVM_ACC_IDENTITY;
5823     }

5824   }
5825 

5826 
5827   // This class and superclass
5828   _this_class_index = stream->get_u2_fast();
5829   guarantee_property(
5830     valid_cp_range(_this_class_index, cp_size) &&
5831       cp->tag_at(_this_class_index).is_unresolved_klass(),
5832     "Invalid this class index %u in constant pool in class file %s",
5833     _this_class_index, CHECK);
5834 
5835   Symbol* const class_name_in_cp = cp->klass_name_at(_this_class_index);
5836   assert(class_name_in_cp != nullptr, "class_name can't be null");
5837 
5838   bool is_java_lang_Object = class_name_in_cp == vmSymbols::java_lang_Object();
5839 
5840   verify_legal_class_modifiers(flags, nullptr, is_java_lang_Object, CHECK);
5841 
5842   _access_flags.set_flags(flags);
5843 
5844   short bad_constant = class_bad_constant_seen();
5845   if (bad_constant != 0) {
5846     // Do not throw CFE until after the access_flags are checked because if
5847     // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
5848     classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, THREAD);
5849     return;
5850   }
5851 
5852   // Don't need to check whether this class name is legal or not.
5853   // It has been checked when constant pool is parsed.
5854   // However, make sure it is not an array type.
5855   if (_need_verify) {
5856     guarantee_property(class_name_in_cp->char_at(0) != JVM_SIGNATURE_ARRAY,
5857                        "Bad class name in class file %s",
5858                        CHECK);
5859   }
5860 
5861 #ifdef ASSERT
5862   // Basic sanity checks
5863   if (_is_hidden) {
5864     assert(_class_name != vmSymbols::unknown_class_name(), "hidden classes should have a special name");
5865   }
5866 #endif
5867 
5868   // Update the _class_name as needed depending on whether this is a named, un-named, or hidden class.
5869 
5870   if (_is_hidden) {
5871     assert(_class_name != nullptr, "Unexpected null _class_name");

5912       }
5913       ls.cr();
5914     }
5915   }
5916 
5917   // SUPERKLASS
5918   _super_class_index = stream->get_u2_fast();
5919   _super_klass = parse_super_class(cp,
5920                                    _super_class_index,
5921                                    _need_verify,
5922                                    CHECK);
5923 
5924   // Interfaces
5925   _itfs_len = stream->get_u2_fast();
5926   parse_interfaces(stream,
5927                    _itfs_len,
5928                    cp,
5929                    &_has_nonstatic_concrete_methods,
5930                    CHECK);
5931 


5932   // Fields (offsets are filled in later)
5933   parse_fields(stream,
5934                _access_flags,
5935                cp,
5936                cp_size,
5937                &_java_fields_count,
5938                CHECK);
5939 
5940   assert(_temp_field_info != nullptr, "invariant");
5941 
5942   // Methods
5943   parse_methods(stream,
5944                 is_interface(),
5945                 !is_identity_class(),
5946                 is_abstract_class(),
5947                 &_has_localvariable_table,
5948                 &_has_final_method,
5949                 &_declares_nonstatic_concrete_methods,
5950                 CHECK);
5951 
5952   assert(_methods != nullptr, "invariant");
5953 
5954   if (_declares_nonstatic_concrete_methods) {
5955     _has_nonstatic_concrete_methods = true;
5956   }
5957 
5958   // Additional attributes/annotations
5959   _parsed_annotations = new ClassAnnotationCollector();
5960   parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK);
5961 
5962   assert(_inner_classes != nullptr, "invariant");
5963 
5964   // Finalize the Annotations metadata object,
5965   // now that all annotation arrays have been created.
5966   create_combined_annotations(CHECK);

6006   // Update this_class_index's slot in the constant pool with the new Utf8 entry.
6007   // We have to update the resolved_klass_index and the name_index together
6008   // so extract the existing resolved_klass_index first.
6009   CPKlassSlot cp_klass_slot = _cp->klass_slot_at(_this_class_index);
6010   int resolved_klass_index = cp_klass_slot.resolved_klass_index();
6011   _cp->unresolved_klass_at_put(_this_class_index, hidden_index, resolved_klass_index);
6012   assert(_cp->klass_slot_at(_this_class_index).name_index() == _orig_cp_size,
6013          "Bad name_index");
6014 }
6015 
6016 void ClassFileParser::post_process_parsed_stream(const ClassFileStream* const stream,
6017                                                  ConstantPool* cp,
6018                                                  TRAPS) {
6019   assert(stream != nullptr, "invariant");
6020   assert(stream->at_eos(), "invariant");
6021   assert(cp != nullptr, "invariant");
6022   assert(_loader_data != nullptr, "invariant");
6023 
6024   if (_class_name == vmSymbols::java_lang_Object()) {
6025     guarantee_property(_local_interfaces == Universe::the_empty_instance_klass_array(),
6026         "java.lang.Object cannot implement an interface in class file %s",
6027         CHECK);
6028   }
6029   // We check super class after class file is parsed and format is checked
6030   if (_super_class_index > 0 && nullptr == _super_klass) {
6031     Symbol* const super_class_name = cp->klass_name_at(_super_class_index);
6032     if (is_interface()) {
6033       // Before attempting to resolve the superclass, check for class format
6034       // errors not checked yet.
6035       guarantee_property(super_class_name == vmSymbols::java_lang_Object(),
6036         "Interfaces must have java.lang.Object as superclass in class file %s",
6037         CHECK);
6038     }
6039     Handle loader(THREAD, _loader_data->class_loader());
6040     if (loader.is_null() && super_class_name == vmSymbols::java_lang_Object()) {
6041       _super_klass = vmClasses::Object_klass();
6042     } else {
6043       _super_klass = (const InstanceKlass*)
6044                        SystemDictionary::resolve_with_circularity_detection_or_fail(_class_name,
6045                                                                super_class_name,
6046                                                                loader,
6047                                                                true,
6048                                                                CHECK);
6049     }
6050   }
6051 
6052   if (_super_klass != nullptr) {
6053     if (_super_klass->is_interface()) {
6054       classfile_icce_error("class %s has interface %s as super class", _super_klass, THREAD);
6055       return;
6056     }
6057 
6058     if (_super_klass->is_final()) {
6059       classfile_icce_error("class %s cannot inherit from final class %s", _super_klass, THREAD);
6060       return;
6061     }
6062 
6063     if (EnableValhalla) {
6064       check_identity_and_value_modifiers(this, _super_klass, CHECK);
6065     }
6066 
6067     if (_super_klass->has_nonstatic_concrete_methods()) {
6068       _has_nonstatic_concrete_methods = true;
6069     }
6070   }
6071 
6072   if (_parsed_annotations->has_annotation(AnnotationCollector::_jdk_internal_LooselyConsistentValue) && _access_flags.is_identity_class()) {
6073     THROW_MSG(vmSymbols::java_lang_ClassFormatError(),
6074           err_msg("class %s cannot have annotation jdk.internal.vm.annotation.LooselyConsistentValue, because it is not a value class",
6075                   _class_name->as_klass_external_name()));
6076   }
6077   if (_parsed_annotations->has_annotation(AnnotationCollector::_jdk_internal_ImplicitlyConstructible) && _access_flags.is_identity_class()) {
6078     THROW_MSG(vmSymbols::java_lang_ClassFormatError(),
6079           err_msg("class %s cannot have annotation jdk.internal.vm.annotation.ImplicitlyConstructible, because it is not a value class",
6080                   _class_name->as_klass_external_name()));
6081   }
6082 
6083   // Determining is the class allows tearing or not (default is not)
6084   if (EnableValhalla && !_access_flags.is_identity_class()) {
6085     if (_parsed_annotations->has_annotation(ClassAnnotationCollector::_jdk_internal_LooselyConsistentValue)
6086         && (_super_klass == vmClasses::Object_klass() || !_super_klass->must_be_atomic())) {
6087       // Conditions above are not sufficient to determine atomicity requirements,
6088       // the presence of fields with atomic requirements could force the current class to have atomicy requirements too
6089       // Marking as not needing atomicity for now, can be updated when computing the fields layout
6090       // The InstanceKlass must be filled with the value from the FieldLayoutInfo returned by
6091       // the FieldLayoutBuilder, not with this _must_be_atomic field.
6092       _must_be_atomic = false;
6093     }
6094     if (_parsed_annotations->has_annotation(ClassAnnotationCollector::_jdk_internal_ImplicitlyConstructible)
6095         && (_super_klass == vmClasses::Object_klass() || _super_klass == vmClasses::Record_klass()
6096         || _super_klass->is_implicitly_constructible())) {
6097       _is_implicitly_constructible = true;
6098     }
6099     // Apply VM options override
6100     if (*ForceNonTearable != '\0') {
6101       // Allow a command line switch to force the same atomicity property:
6102       const char* class_name_str = _class_name->as_C_string();
6103       if (StringUtils::class_list_match(ForceNonTearable, class_name_str)) {
6104         _must_be_atomic = true;
6105       }
6106     }
6107   }
6108 
6109   int itfs_len = _local_interface_indexes == nullptr ? 0 : _local_interface_indexes->length();
6110   _local_interfaces = MetadataFactory::new_array<InstanceKlass*>(_loader_data, itfs_len, nullptr, CHECK);
6111   if (_local_interface_indexes != nullptr) {
6112     for (int i = 0; i < _local_interface_indexes->length(); i++) {
6113       u2 interface_index = _local_interface_indexes->at(i);
6114       Klass* interf;
6115       if (cp->tag_at(interface_index).is_klass()) {
6116         interf = cp->resolved_klass_at(interface_index);
6117       } else {
6118         Symbol* const unresolved_klass  = cp->klass_name_at(interface_index);
6119 
6120         // Don't need to check legal name because it's checked when parsing constant pool.
6121         // But need to make sure it's not an array type.
6122         guarantee_property(unresolved_klass->char_at(0) != JVM_SIGNATURE_ARRAY,
6123                             "Bad interface name in class file %s", CHECK);
6124 
6125         // Call resolve on the interface class name with class circularity checking
6126         interf = SystemDictionary::resolve_with_circularity_detection_or_fail(
6127                                                   _class_name,
6128                                                   unresolved_klass,
6129                                                   Handle(THREAD, _loader_data->class_loader()),
6130                                                   false,
6131                                                   CHECK);
6132       }
6133 
6134       if (!interf->is_interface()) {
6135         THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
6136                   err_msg("class %s can not implement %s, because it is not an interface (%s)",
6137                           _class_name->as_klass_external_name(),
6138                           interf->external_name(),
6139                           interf->class_in_module_of_loader()));
6140       }
6141 
6142       if (EnableValhalla) {
6143         // Check modifiers and set carries_identity_modifier/carries_value_modifier flags
6144         check_identity_and_value_modifiers(this, InstanceKlass::cast(interf), CHECK);
6145       }
6146 
6147       if (InstanceKlass::cast(interf)->has_nonstatic_concrete_methods()) {
6148         _has_nonstatic_concrete_methods = true;
6149       }
6150       _local_interfaces->at_put(i, InstanceKlass::cast(interf));
6151     }
6152   }
6153   assert(_local_interfaces != nullptr, "invariant");
6154 
6155   // Compute the transitive list of all unique interfaces implemented by this class
6156   _transitive_interfaces =
6157     compute_transitive_interfaces(_super_klass,
6158                                   _local_interfaces,
6159                                   _loader_data,
6160                                   CHECK);
6161 
6162   assert(_transitive_interfaces != nullptr, "invariant");
6163 
6164   // sort methods
6165   _method_ordering = sort_methods(_methods);
6166 
6167   _all_mirandas = new GrowableArray<Method*>(20);
6168 
6169   Handle loader(THREAD, _loader_data->class_loader());
6170   klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
6171                                                     &_num_miranda_methods,
6172                                                     _all_mirandas,
6173                                                     _super_klass,
6174                                                     _methods,
6175                                                     _access_flags,
6176                                                     _major_version,
6177                                                     loader,
6178                                                     _class_name,
6179                                                     _local_interfaces);
6180 
6181   // Size of Java itable (in words)
6182   _itable_size = is_interface() ? 0 :
6183     klassItable::compute_itable_size(_transitive_interfaces);
6184 
6185   assert(_parsed_annotations != nullptr, "invariant");
6186 
6187   if (EnableValhalla) {
6188     _inline_layout_info_array = MetadataFactory::new_array<InlineLayoutInfo>(_loader_data,
6189                                                    java_fields_count(),
6190                                                    CHECK);
6191     for (GrowableArrayIterator<FieldInfo> it = _temp_field_info->begin(); it != _temp_field_info->end(); ++it) {
6192       FieldInfo fieldinfo = *it;
6193       if (fieldinfo.access_flags().is_static()) continue;  // Only non-static fields are processed at load time
6194       Symbol* sig = fieldinfo.signature(cp);
6195       if (fieldinfo.field_flags().is_null_free_inline_type()) {
6196         // Pre-load classes of null-free fields that are candidate for flattening
6197         TempNewSymbol s = Signature::strip_envelope(sig);
6198         if (s == _class_name) {
6199           THROW_MSG(vmSymbols::java_lang_ClassCircularityError(), err_msg("Class %s cannot have a null-free non-static field of its own type", _class_name->as_C_string()));
6200         }
6201         log_info(class, preload)("Preloading class %s during loading of class %s. Cause: a null-free non-static field is declared with this type", s->as_C_string(), _class_name->as_C_string());
6202         Klass* klass = SystemDictionary::resolve_with_circularity_detection_or_fail(_class_name, s, Handle(THREAD, _loader_data->class_loader()), false, THREAD);
6203         if (HAS_PENDING_EXCEPTION) {
6204           log_warning(class, preload)("Preloading of class %s during loading of class %s (cause: null-free non-static field) failed: %s",
6205                                       s->as_C_string(), _class_name->as_C_string(), PENDING_EXCEPTION->klass()->name()->as_C_string());
6206           return; // Exception is still pending
6207         }
6208         assert(klass != nullptr, "Sanity check");
6209         if (klass->access_flags().is_identity_class()) {
6210           assert(klass->is_instance_klass(), "Sanity check");
6211           ResourceMark rm(THREAD);
6212           THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
6213                     err_msg("Class %s expects class %s to be a value class, but it is an identity class",
6214                     _class_name->as_C_string(),
6215                     InstanceKlass::cast(klass)->external_name()));
6216         }
6217         if (klass->is_abstract()) {
6218           assert(klass->is_instance_klass(), "Sanity check");
6219           ResourceMark rm(THREAD);
6220           THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
6221                     err_msg("Class %s expects class %s to be concrete value type, but it is an abstract class",
6222                     _class_name->as_C_string(),
6223                     InstanceKlass::cast(klass)->external_name()));
6224         }
6225         InlineKlass* vk = InlineKlass::cast(klass);
6226         if (!vk->is_implicitly_constructible()) {
6227           THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
6228                     err_msg("class %s is not implicitly constructible and it is used in a null restricted non-static field (not supported)",
6229                     klass->name()->as_C_string()));
6230         }
6231         _inline_layout_info_array->adr_at(fieldinfo.index())->set_klass(vk);
6232         log_info(class, preload)("Preloading of class %s during loading of class %s (cause: null-free non-static field) succeeded", s->as_C_string(), _class_name->as_C_string());
6233       } else if (Signature::has_envelope(sig)) {
6234         // Preloading classes for nullable fields that are listed in the LoadableDescriptors attribute
6235         // Those classes would be required later for the flattening of nullable inline type fields
6236         TempNewSymbol name = Signature::strip_envelope(sig);
6237         if (name != _class_name && is_class_in_loadable_descriptors_attribute(sig)) {
6238           log_info(class, preload)("Preloading class %s during loading of class %s. Cause: field type in LoadableDescriptors attribute", name->as_C_string(), _class_name->as_C_string());
6239           oop loader = loader_data()->class_loader();
6240           Klass* klass = SystemDictionary::resolve_with_circularity_detection_or_fail(_class_name, name, Handle(THREAD, loader), false, THREAD);
6241           if (klass != nullptr) {
6242             if (klass->is_inline_klass()) {
6243               _inline_layout_info_array->adr_at(fieldinfo.index())->set_klass(InlineKlass::cast(klass));
6244               log_info(class, preload)("Preloading of class %s during loading of class %s (cause: field type in LoadableDescriptors attribute) succeeded", name->as_C_string(), _class_name->as_C_string());
6245             } else {
6246               // Non value class are allowed by the current spec, but it could be an indication of an issue so let's log a warning
6247               log_warning(class, preload)("Preloading class %s during loading of class %s (cause: field type in LoadableDescriptors attribute) but loaded class is not a value class", name->as_C_string(), _class_name->as_C_string());
6248             }
6249             } else {
6250             log_warning(class, preload)("Preloading of class %s during loading of class %s (cause: field type in LoadableDescriptors attribute) failed : %s",
6251                                           name->as_C_string(), _class_name->as_C_string(), PENDING_EXCEPTION->klass()->name()->as_C_string());
6252           }
6253           // Loads triggered by the LoadableDescriptors attribute are speculative, failures must not impact loading of current class
6254           if (HAS_PENDING_EXCEPTION) {
6255             CLEAR_PENDING_EXCEPTION;
6256           }
6257         }
6258       }
6259     }
6260   }
6261 
6262   _layout_info = new FieldLayoutInfo();
6263   FieldLayoutBuilder lb(class_name(), loader_data(), super_klass(), _cp, /*_fields*/ _temp_field_info,
6264       _parsed_annotations->is_contended(), is_inline_type(),
6265       access_flags().is_abstract() && !access_flags().is_identity_class() && !access_flags().is_interface(),
6266       _must_be_atomic, _layout_info, _inline_layout_info_array);
6267   lb.build_layout();
6268   _has_inline_type_fields = _layout_info->_has_inline_fields;
6269 
6270   int injected_fields_count = _temp_field_info->length() - _java_fields_count;
6271   _fieldinfo_stream =
6272     FieldInfoStream::create_FieldInfoStream(_temp_field_info, _java_fields_count,
6273                                             injected_fields_count, loader_data(), CHECK);
6274 
6275   _fields_status =
6276     MetadataFactory::new_array<FieldStatus>(_loader_data, _temp_field_info->length(),
6277                                             FieldStatus(0), CHECK);
6278 }
6279 
6280 void ClassFileParser::set_klass(InstanceKlass* klass) {
6281 
6282 #ifdef ASSERT
6283   if (klass != nullptr) {
6284     assert(nullptr == _klass, "leaking?");
6285   }
6286 #endif
6287 
6288   _klass = klass;
6289 }
6290 
6291 void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) {
6292 
6293 #ifdef ASSERT
6294   if (klass != nullptr) {
< prev index next >