< 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   // Always verify CFLH bytes from the user agents.
5337   _need_verify = stream->from_class_file_load_hook() ? true : Verifier::should_verify_for(_loader_data->class_loader());
5338 
5339   // synch back verification state to stream to check for truncation.
5340   stream->set_need_verify(_need_verify);
5341 
5342   parse_stream(stream, CHECK);
5343 
5344   post_process_parsed_stream(stream, _cp, CHECK);
5345 }
5346 
5347 void ClassFileParser::clear_class_metadata() {
5348   // metadata created before the instance klass is created.  Must be
5349   // deallocated if classfile parsing returns an error.
5350   _cp = nullptr;
5351   _fieldinfo_stream = nullptr;
5352   _fields_status = nullptr;
5353   _methods = nullptr;
5354   _inner_classes = nullptr;
5355   _nest_members = nullptr;
5356   _permitted_subclasses = nullptr;

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

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




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




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

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



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














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

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


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

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














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

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


































































5730     }
5731   }

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








































































5768   lb.build_layout();

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

5774   _fields_status =
5775     MetadataFactory::new_array<FieldStatus>(_loader_data, _temp_field_info->length(),
5776                                             FieldStatus(0), CHECK);





















5777 }
5778 
5779 void ClassFileParser::set_klass(InstanceKlass* klass) {
5780 
5781 #ifdef ASSERT
5782   if (klass != nullptr) {
5783     assert(nullptr == _klass, "leaking?");
5784   }
5785 #endif
5786 
5787   _klass = klass;
5788 }
5789 
5790 void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) {
5791 
5792 #ifdef ASSERT
5793   if (klass != nullptr) {
5794     assert(nullptr == _klass_to_deallocate, "leaking?");
5795   }
5796 #endif

   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "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_LooselyConsistentValue,
 944     _jdk_internal_NullRestricted,
 945     _java_lang_Deprecated,
 946     _java_lang_Deprecated_for_removal,
 947     _annotation_LIMIT
 948   };
 949   const Location _location;
 950   int _annotations_present;
 951   u2 _contended_group;
 952 
 953   AnnotationCollector(Location location)
 954     : _location(location), _annotations_present(0), _contended_group(0)
 955   {
 956     assert((int)_annotation_LIMIT <= (int)sizeof(_annotations_present) * BitsPerByte, "");
 957   }
 958   // If this annotation name has an ID, report it (or _none).
 959   ID annotation_index(const ClassLoaderData* loader_data, const Symbol* name, bool can_access_vm_annotations);
 960   // Set the annotation name:
 961   void set_annotation(ID id) {
 962     assert((int)id >= 0 && (int)id < (int)_annotation_LIMIT, "oob");
 963     _annotations_present |= (int)nth_bit((int)id);
 964   }

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


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

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

1553     }
1554   }
1555 
1556   if (is_inline_type) {
1557     // Inject static ".null_reset" field. This is an all-zero value with its null-channel set to zero.
1558     // IT should never be seen by user code, it is used when writing "null" to a nullable flat field
1559     // The all-zero value ensure that any embedded oop will be set to null, to avoid keeping dead objects
1560     // alive.
1561     FieldInfo::FieldFlags fflags2(0);
1562     fflags2.update_injected(true);
1563     AccessFlags aflags2(JVM_ACC_STATIC);
1564     FieldInfo fi2(aflags2,
1565                  (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(null_reset_value_name)),
1566                  (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(object_signature)),
1567                  0,
1568                  fflags2);
1569     int idx2 = _temp_field_info->append(fi2);
1570     _temp_field_info->adr_at(idx2)->set_index(idx2);
1571     _static_oop_count++;
1572   }
1573 
1574   if (_need_verify && length > 1) {
1575     // Check duplicated fields
1576     ResourceMark rm(THREAD);
1577     // Set containing name-signature pairs
1578     NameSigHashtable* names_and_sigs = new NameSigHashtable();
1579     for (int i = 0; i < _temp_field_info->length(); i++) {
1580       NameSigHash name_and_sig(_temp_field_info->adr_at(i)->name(_cp),
1581                                _temp_field_info->adr_at(i)->signature(_cp));
1582       // If no duplicates, add name/signature in hashtable names_and_sigs.
1583       if(!names_and_sigs->put(name_and_sig, 0)) {
1584         classfile_parse_error("Duplicate field name \"%s\" with signature \"%s\" in class file %s",
1585                                name_and_sig._name->as_C_string(), name_and_sig._sig->as_klass_external_name(), THREAD);
1586         return;
1587       }
1588     }
1589   }
1590 }
1591 
1592 

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

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

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

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

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


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

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

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

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

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

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

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

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




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

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

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

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

4527         THREAD_AND_LOCATION,
4528         vmSymbols::java_lang_UnsupportedClassVersionError(),
4529         "%s (class file version %u.%u) was compiled with preview features that are unsupported. "
4530         "This version of the Java Runtime only recognizes preview features for class file version %u.%u",
4531         class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION, JAVA_PREVIEW_MINOR_VERSION);
4532       return;
4533     }
4534 
4535     if (!Arguments::enable_preview()) {
4536       classfile_ucve_error("Preview features are not enabled for %s (class file version %u.%u). Try running with '--enable-preview'",
4537                            class_name, major, minor, THREAD);
4538       return;
4539     }
4540 
4541   } else { // minor != JAVA_PREVIEW_MINOR_VERSION
4542     classfile_ucve_error("%s (class file version %u.%u) was compiled with an invalid non-zero minor version",
4543                          class_name, major, minor, THREAD);
4544   }
4545 }
4546 
4547 void ClassFileParser:: verify_legal_field_modifiers(jint flags,
4548                                                    AccessFlags class_access_flags,
4549                                                    TRAPS) const {
4550   if (!_need_verify) { return; }
4551 
4552   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4553   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4554   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4555   const bool is_static    = (flags & JVM_ACC_STATIC)    != 0;
4556   const bool is_final     = (flags & JVM_ACC_FINAL)     != 0;
4557   const bool is_volatile  = (flags & JVM_ACC_VOLATILE)  != 0;
4558   const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
4559   const bool is_enum      = (flags & JVM_ACC_ENUM)      != 0;
4560   const bool is_strict    = (flags & JVM_ACC_STRICT)    != 0;
4561   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4562 
4563   const bool is_interface = class_access_flags.is_interface();
4564   const bool is_identity_class = class_access_flags.is_identity_class();
4565 
4566   bool is_illegal = false;
4567   const char* error_msg = "";
4568 
4569   // There is some overlap in the checks that apply, for example interface fields
4570   // must be static, static fields can't be strict, and therefore interfaces can't
4571   // have strict fields. So we don't have to check every possible invalid combination
4572   // individually as long as all are covered. Once we have found an illegal combination
4573   // we can stop checking.
4574 
4575   if (!is_illegal) {
4576     if (is_interface) {
4577       if (!is_public || !is_static || !is_final || is_private ||
4578           is_protected || is_volatile || is_transient ||
4579           (major_gte_1_5 && is_enum)) {
4580         is_illegal = true;
4581         error_msg = "interface fields must be public, static and final, and may be synthetic";
4582       }
4583     } else { // not interface
4584       if (has_illegal_visibility(flags)) {
4585         is_illegal = true;
4586         error_msg = "invalid visibility flags for class field";
4587       } else if (is_final && is_volatile) {
4588         is_illegal = true;
4589         error_msg = "fields cannot be final and volatile";
4590       } else if (supports_inline_types()) {
4591         if (!is_identity_class && !is_static && (!is_strict || !is_final)) {
4592           is_illegal = true;
4593           error_msg = "value class fields must be either non-static final and strict, or static";
4594         }
4595       }
4596     }
4597   }
4598 
4599   if (is_illegal) {
4600     ResourceMark rm(THREAD);
4601     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4602     Exceptions::fthrow(
4603       THREAD_AND_LOCATION,
4604       vmSymbols::java_lang_ClassFormatError(),
4605       "Illegal field modifiers (%s) in class %s: 0x%X",
4606       error_msg, _class_name->as_C_string(), flags);
4607     return;
4608   }
4609 }
4610 
4611 void ClassFileParser::verify_legal_method_modifiers(jint flags,
4612                                                     AccessFlags class_access_flags,
4613                                                     const Symbol* name,
4614                                                     TRAPS) const {
4615   if (!_need_verify) { return; }
4616 
4617   const bool is_public       = (flags & JVM_ACC_PUBLIC)       != 0;
4618   const bool is_private      = (flags & JVM_ACC_PRIVATE)      != 0;
4619   const bool is_static       = (flags & JVM_ACC_STATIC)       != 0;
4620   const bool is_final        = (flags & JVM_ACC_FINAL)        != 0;
4621   const bool is_native       = (flags & JVM_ACC_NATIVE)       != 0;
4622   const bool is_abstract     = (flags & JVM_ACC_ABSTRACT)     != 0;
4623   const bool is_bridge       = (flags & JVM_ACC_BRIDGE)       != 0;
4624   const bool is_strict       = (flags & JVM_ACC_STRICT)       != 0;
4625   const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
4626   const bool is_protected    = (flags & JVM_ACC_PROTECTED)    != 0;
4627   const bool major_gte_1_5   = _major_version >= JAVA_1_5_VERSION;
4628   const bool major_gte_8     = _major_version >= JAVA_8_VERSION;
4629   const bool major_gte_17    = _major_version >= JAVA_17_VERSION;
4630   const bool is_initializer  = (name == vmSymbols::object_initializer_name());
4631   // LW401 CR required: removal of value factories support
4632   const bool is_interface    = class_access_flags.is_interface();
4633   const bool is_identity_class = class_access_flags.is_identity_class();
4634   const bool is_abstract_class = class_access_flags.is_abstract();
4635 
4636   bool is_illegal = false;
4637 
4638   const char* class_note = "";
4639   if (is_interface) {
4640     if (major_gte_8) {
4641       // Class file version is JAVA_8_VERSION or later Methods of
4642       // interfaces may set any of the flags except ACC_PROTECTED,
4643       // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must
4644       // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.
4645       if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
4646           (is_native || is_protected || is_final || is_synchronized) ||
4647           // If a specific method of a class or interface has its
4648           // ACC_ABSTRACT flag set, it must not have any of its
4649           // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,
4650           // ACC_STRICT, or ACC_SYNCHRONIZED flags set.  No need to
4651           // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as
4652           // those flags are illegal irrespective of ACC_ABSTRACT being set or not.
4653           (is_abstract && (is_private || is_static || (!major_gte_17 && is_strict)))) {
4654         is_illegal = true;
4655       }
4656     } else if (major_gte_1_5) {
4657       // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)
4658       if (!is_public || is_private || is_protected || is_static || is_final ||
4659           is_synchronized || is_native || !is_abstract || is_strict) {
4660         is_illegal = true;
4661       }
4662     } else {
4663       // Class file version is pre-JAVA_1_5_VERSION
4664       if (!is_public || is_static || is_final || is_native || !is_abstract) {
4665         is_illegal = true;
4666       }
4667     }
4668   } else { // not interface
4669     if (has_illegal_visibility(flags)) {
4670       is_illegal = true;
4671     } else {
4672       if (is_initializer) {
4673         if (is_static || is_final || is_synchronized || is_native ||
4674             is_abstract || (major_gte_1_5 && is_bridge)) {
4675           is_illegal = true;
4676         }
4677       } else { // not initializer
4678         if (!is_identity_class && is_synchronized && !is_static) {
4679           is_illegal = true;
4680           class_note = " (not an identity class)";
4681         } else {
4682           if (is_abstract) {
4683             if ((is_final || is_native || is_private || is_static ||
4684                 (major_gte_1_5 && (is_synchronized || (!major_gte_17 && is_strict))))) {
4685               is_illegal = true;
4686             }
4687           }
4688         }
4689       }
4690     }
4691   }
4692 
4693   if (is_illegal) {
4694     ResourceMark rm(THREAD);
4695     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4696     Exceptions::fthrow(
4697       THREAD_AND_LOCATION,
4698       vmSymbols::java_lang_ClassFormatError(),
4699       "Method %s in class %s%s has illegal modifiers: 0x%X",
4700       name->as_C_string(), _class_name->as_C_string(),
4701       class_note, flags);
4702     return;
4703   }
4704 }
4705 
4706 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer,
4707                                         int length,
4708                                         TRAPS) const {
4709   assert(_need_verify, "only called when _need_verify is true");
4710   // Note: 0 <= length < 64K, as it comes from a u2 entry in the CP.
4711   if (!UTF8::is_legal_utf8(buffer, static_cast<size_t>(length), _major_version <= 47)) {
4712     classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", THREAD);
4713   }
4714 }
4715 
4716 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
4717 // In class names, '/' separates unqualified names.  This is verified in this function also.
4718 // Method names also may not contain the characters '<' or '>', unless <init>
4719 // or <clinit>.  Note that method names may not be <init> or <clinit> in this
4720 // method.  Because these names have been checked as special cases before
4721 // calling this method in verify_legal_method_name.

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

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

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

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

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

5240   }
5241 }
5242 
5243 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook,
5244                                                       const ClassInstanceInfo& cl_inst_info,
5245                                                       TRAPS) {
5246   if (_klass != nullptr) {
5247     return _klass;
5248   }
5249 
5250   InstanceKlass* const ik =
5251     InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
5252 
5253   if (is_hidden()) {
5254     mangle_hidden_class_name(ik);
5255   }
5256 
5257   fill_instance_klass(ik, changed_by_loadhook, cl_inst_info, CHECK_NULL);
5258 
5259   assert(_klass == ik, "invariant");

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

5388   if ((_num_miranda_methods > 0) ||
5389       // if this class introduced new miranda methods or
5390       (_super_klass != nullptr && _super_klass->has_miranda_methods())
5391         // super class exists and this class inherited miranda methods
5392      ) {
5393        ik->set_has_miranda_methods(); // then set a flag
5394   }
5395 
5396   // Fill in information needed to compute superclasses.
5397   ik->initialize_supers(const_cast<InstanceKlass*>(_super_klass), _transitive_interfaces, CHECK);
5398   ik->set_transitive_interfaces(_transitive_interfaces);
5399   ik->set_local_interfaces(_local_interfaces);
5400   _transitive_interfaces = nullptr;
5401   _local_interfaces = nullptr;
5402 
5403   // Initialize itable offset tables
5404   klassItable::setup_itable_offset_table(ik);
5405 
5406   // Compute transitive closure of interfaces this class implements
5407   // Do final class setup
5408   OopMapBlocksBuilder* oop_map_blocks = _layout_info->oop_map_blocks;
5409   if (oop_map_blocks->_nonstatic_oop_map_count > 0) {
5410     oop_map_blocks->copy(ik->start_of_nonstatic_oop_maps());
5411   }
5412 
5413   if (_has_contended_fields || _parsed_annotations->is_contended() ||
5414       ( _super_klass != nullptr && _super_klass->has_contended_annotations())) {
5415     ik->set_has_contended_annotations(true);
5416   }
5417 
5418   // Fill in has_finalizer and layout_helper
5419   set_precomputed_flags(ik);
5420 
5421   // check if this class can access its super class
5422   check_super_class_access(ik, CHECK);
5423 
5424   // check if this class can access its superinterfaces
5425   check_super_interface_access(ik, CHECK);
5426 
5427   // check if this class overrides any final method
5428   check_final_method_override(ik, CHECK);

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

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

5766     cp_size, CHECK);
5767 
5768   _orig_cp_size = cp_size;
5769   if (is_hidden()) { // Add a slot for hidden class name.
5770     cp_size++;
5771   }
5772 
5773   _cp = ConstantPool::allocate(_loader_data,
5774                                cp_size,
5775                                CHECK);
5776 
5777   ConstantPool* const cp = _cp;
5778 
5779   parse_constant_pool(stream, cp, _orig_cp_size, CHECK);
5780 
5781   assert(cp_size == (u2)cp->length(), "invariant");
5782 
5783   // ACCESS FLAGS
5784   stream->guarantee_more(8, CHECK);  // flags, this_class, super_class, infs_len
5785 
5786   u2 recognized_modifiers = JVM_RECOGNIZED_CLASS_MODIFIERS;

5787   // JVM_ACC_MODULE is defined in JDK-9 and later.
5788   if (_major_version >= JAVA_9_VERSION) {
5789     recognized_modifiers |= JVM_ACC_MODULE;


5790   }
5791 
5792   // Access flags
5793   u2 flags = stream->get_u2_fast() & recognized_modifiers;
5794 
5795   if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
5796     // Set abstract bit for old class files for backward compatibility
5797     flags |= JVM_ACC_ABSTRACT;
5798   }
5799 
5800   // Fixing ACC_SUPER/ACC_IDENTITY for old class files
5801   if (!supports_inline_types()) {
5802     const bool is_module = (flags & JVM_ACC_MODULE) != 0;
5803     const bool is_interface = (flags & JVM_ACC_INTERFACE) != 0;
5804     if (!is_module && !is_interface) {
5805       flags |= JVM_ACC_IDENTITY;
5806     }

5807   }
5808 

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

5895       }
5896       ls.cr();
5897     }
5898   }
5899 
5900   // SUPERKLASS
5901   _super_class_index = stream->get_u2_fast();
5902   _super_klass = parse_super_class(cp,
5903                                    _super_class_index,
5904                                    _need_verify,
5905                                    CHECK);
5906 
5907   // Interfaces
5908   _itfs_len = stream->get_u2_fast();
5909   parse_interfaces(stream,
5910                    _itfs_len,
5911                    cp,
5912                    &_has_nonstatic_concrete_methods,
5913                    CHECK);
5914 


5915   // Fields (offsets are filled in later)
5916   parse_fields(stream,
5917                _access_flags,
5918                cp,
5919                cp_size,
5920                &_java_fields_count,
5921                CHECK);
5922 
5923   assert(_temp_field_info != nullptr, "invariant");
5924 
5925   // Methods
5926   parse_methods(stream,
5927                 is_interface(),
5928                 !is_identity_class(),
5929                 is_abstract_class(),
5930                 &_has_localvariable_table,
5931                 &_has_final_method,
5932                 &_declares_nonstatic_concrete_methods,
5933                 CHECK);
5934 
5935   assert(_methods != nullptr, "invariant");
5936 
5937   if (_declares_nonstatic_concrete_methods) {
5938     _has_nonstatic_concrete_methods = true;
5939   }
5940 
5941   // Additional attributes/annotations
5942   _parsed_annotations = new ClassAnnotationCollector();
5943   parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK);
5944 
5945   assert(_inner_classes != nullptr, "invariant");
5946 
5947   // Finalize the Annotations metadata object,
5948   // now that all annotation arrays have been created.
5949   create_combined_annotations(CHECK);

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