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

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

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

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


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

 495         check_property(valid_symbol_at(name_ref_index),
 496           "Invalid constant pool index %u in class file %s",
 497           name_ref_index, CHECK);
 498         check_property(valid_symbol_at(signature_ref_index),
 499           "Invalid constant pool index %u in class file %s",
 500           signature_ref_index, CHECK);
 501         break;
 502       }
 503       case JVM_CONSTANT_Utf8:
 504         break;
 505       case JVM_CONSTANT_UnresolvedClass:         // fall-through
 506       case JVM_CONSTANT_UnresolvedClassInError: {
 507         ShouldNotReachHere();     // Only JVM_CONSTANT_ClassIndex should be present
 508         break;
 509       }
 510       case JVM_CONSTANT_ClassIndex: {
 511         const int class_index = cp->klass_index_at(index);
 512         check_property(valid_symbol_at(class_index),
 513           "Invalid constant pool index %u in class file %s",
 514           class_index, CHECK);



 515         cp->unresolved_klass_at_put(index, class_index, num_klasses++);
 516         break;
 517       }
 518       case JVM_CONSTANT_StringIndex: {
 519         const int string_index = cp->string_index_at(index);
 520         check_property(valid_symbol_at(string_index),
 521           "Invalid constant pool index %u in class file %s",
 522           string_index, CHECK);
 523         Symbol* const sym = cp->symbol_at(string_index);
 524         cp->unresolved_string_at_put(index, sym);
 525         break;
 526       }
 527       case JVM_CONSTANT_MethodHandle: {
 528         const int ref_index = cp->method_handle_index_at(index);
 529         check_property(valid_cp_range(ref_index, length),
 530           "Invalid constant pool index %u in class file %s",
 531           ref_index, CHECK);
 532         const constantTag tag = cp->tag_at(ref_index);
 533         const int ref_kind = cp->method_handle_ref_kind_at(index);
 534 

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

 746                 classfile_parse_error(
 747                   "Bad constructor name at constant pool index %u in class file %s",
 748                     name_ref_index, THREAD);
 749                 return;
 750               }
 751             } else {
 752               if (name == vmSymbols::object_initializer_name()) {








 753                 classfile_parse_error(
 754                   "Bad method name at constant pool index %u in class file %s",
 755                   name_ref_index, THREAD);
 756                 return;
 757               }
 758             }
 759             break;
 760           }
 761           // Other ref_kinds are already fully checked in previous pass.
 762         } // switch(ref_kind)
 763         break;
 764       }
 765       case JVM_CONSTANT_MethodType: {
 766         const Symbol* const no_name = vmSymbols::type_name(); // place holder
 767         const Symbol* const signature = cp->method_type_signature_at(index);
 768         verify_legal_method_signature(no_name, signature, CHECK);
 769         break;
 770       }
 771       case JVM_CONSTANT_Utf8: {
 772         assert(cp->symbol_at(index)->refcount() != 0, "count corrupted");

 784 
 785   NameSigHash(Symbol* name, Symbol* sig) :
 786     _name(name),
 787     _sig(sig) {}
 788 
 789   static unsigned int hash(NameSigHash const& namesig) {
 790     return namesig._name->identity_hash() ^ namesig._sig->identity_hash();
 791   }
 792 
 793   static bool equals(NameSigHash const& e0, NameSigHash const& e1) {
 794     return (e0._name == e1._name) &&
 795           (e0._sig  == e1._sig);
 796   }
 797 };
 798 
 799 using NameSigHashtable = ResourceHashtable<NameSigHash, int,
 800                                            NameSigHash::HASH_ROW_SIZE,
 801                                            AnyObj::RESOURCE_AREA, mtInternal,
 802                                            &NameSigHash::hash, &NameSigHash::equals>;
 803 
 804 // Side-effects: populates the _local_interfaces field
 805 void ClassFileParser::parse_interfaces(const ClassFileStream* const stream,
 806                                        const int itfs_len,
 807                                        ConstantPool* const cp,









 808                                        bool* const has_nonstatic_concrete_methods,






 809                                        TRAPS) {
 810   assert(stream != nullptr, "invariant");
 811   assert(cp != nullptr, "invariant");
 812   assert(has_nonstatic_concrete_methods != nullptr, "invariant");
 813 
 814   if (itfs_len == 0) {
 815     _local_interfaces = Universe::the_empty_instance_klass_array();

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

 936 
 937 class AnnotationCollector : public ResourceObj{
 938 public:
 939   enum Location { _in_field, _in_method, _in_class };
 940   enum ID {
 941     _unknown = 0,
 942     _method_CallerSensitive,
 943     _method_ForceInline,
 944     _method_DontInline,
 945     _method_ChangesCurrentThread,
 946     _method_JvmtiMountTransition,
 947     _method_InjectedProfile,
 948     _method_LambdaForm_Compiled,
 949     _method_Hidden,
 950     _method_Scoped,
 951     _method_IntrinsicCandidate,
 952     _jdk_internal_vm_annotation_Contended,
 953     _field_Stable,
 954     _jdk_internal_vm_annotation_ReservedStackAccess,
 955     _jdk_internal_ValueBased,



 956     _java_lang_Deprecated,
 957     _java_lang_Deprecated_for_removal,
 958     _annotation_LIMIT
 959   };
 960   const Location _location;
 961   int _annotations_present;
 962   u2 _contended_group;
 963 
 964   AnnotationCollector(Location location)
 965     : _location(location), _annotations_present(0), _contended_group(0)
 966   {
 967     assert((int)_annotation_LIMIT <= (int)sizeof(_annotations_present) * BitsPerByte, "");
 968   }
 969   // If this annotation name has an ID, report it (or _none).
 970   ID annotation_index(const ClassLoaderData* loader_data, const Symbol* name, bool can_access_vm_annotations);
 971   // Set the annotation name:
 972   void set_annotation(ID id) {
 973     assert((int)id >= 0 && (int)id < (int)_annotation_LIMIT, "oob");
 974     _annotations_present |= (int)nth_bit((int)id);
 975   }

1343   AnnotationArray* a = allocate_annotations(runtime_visible_annotations,
1344                                             runtime_visible_annotations_length,
1345                                             CHECK);
1346   parsed_annotations->set_field_annotations(a);
1347   a = allocate_annotations(runtime_visible_type_annotations,
1348                            runtime_visible_type_annotations_length,
1349                            CHECK);
1350   parsed_annotations->set_field_type_annotations(a);
1351   return;
1352 }
1353 
1354 
1355 // Field allocation types. Used for computing field offsets.
1356 
1357 enum FieldAllocationType {
1358   STATIC_OOP,           // Oops
1359   STATIC_BYTE,          // Boolean, Byte, char
1360   STATIC_SHORT,         // shorts
1361   STATIC_WORD,          // ints
1362   STATIC_DOUBLE,        // aligned long or double

1363   NONSTATIC_OOP,
1364   NONSTATIC_BYTE,
1365   NONSTATIC_SHORT,
1366   NONSTATIC_WORD,
1367   NONSTATIC_DOUBLE,

1368   MAX_FIELD_ALLOCATION_TYPE,
1369   BAD_ALLOCATION_TYPE = -1
1370 };
1371 
1372 static FieldAllocationType _basic_type_to_atype[2 * (T_CONFLICT + 1)] = {
1373   BAD_ALLOCATION_TYPE, // 0
1374   BAD_ALLOCATION_TYPE, // 1
1375   BAD_ALLOCATION_TYPE, // 2
1376   BAD_ALLOCATION_TYPE, // 3
1377   NONSTATIC_BYTE ,     // T_BOOLEAN     =  4,
1378   NONSTATIC_SHORT,     // T_CHAR        =  5,
1379   NONSTATIC_WORD,      // T_FLOAT       =  6,
1380   NONSTATIC_DOUBLE,    // T_DOUBLE      =  7,
1381   NONSTATIC_BYTE,      // T_BYTE        =  8,
1382   NONSTATIC_SHORT,     // T_SHORT       =  9,
1383   NONSTATIC_WORD,      // T_INT         = 10,
1384   NONSTATIC_DOUBLE,    // T_LONG        = 11,
1385   NONSTATIC_OOP,       // T_OBJECT      = 12,
1386   NONSTATIC_OOP,       // T_ARRAY       = 13,
1387   BAD_ALLOCATION_TYPE, // T_VOID        = 14,
1388   BAD_ALLOCATION_TYPE, // T_ADDRESS     = 15,
1389   BAD_ALLOCATION_TYPE, // T_NARROWOOP   = 16,
1390   BAD_ALLOCATION_TYPE, // T_METADATA    = 17,
1391   BAD_ALLOCATION_TYPE, // T_NARROWKLASS = 18,
1392   BAD_ALLOCATION_TYPE, // T_CONFLICT    = 19,

1393   BAD_ALLOCATION_TYPE, // 0
1394   BAD_ALLOCATION_TYPE, // 1
1395   BAD_ALLOCATION_TYPE, // 2
1396   BAD_ALLOCATION_TYPE, // 3
1397   STATIC_BYTE ,        // T_BOOLEAN     =  4,
1398   STATIC_SHORT,        // T_CHAR        =  5,
1399   STATIC_WORD,         // T_FLOAT       =  6,
1400   STATIC_DOUBLE,       // T_DOUBLE      =  7,
1401   STATIC_BYTE,         // T_BYTE        =  8,
1402   STATIC_SHORT,        // T_SHORT       =  9,
1403   STATIC_WORD,         // T_INT         = 10,
1404   STATIC_DOUBLE,       // T_LONG        = 11,
1405   STATIC_OOP,          // T_OBJECT      = 12,
1406   STATIC_OOP,          // T_ARRAY       = 13,
1407   BAD_ALLOCATION_TYPE, // T_VOID        = 14,
1408   BAD_ALLOCATION_TYPE, // T_ADDRESS     = 15,
1409   BAD_ALLOCATION_TYPE, // T_NARROWOOP   = 16,
1410   BAD_ALLOCATION_TYPE, // T_METADATA    = 17,
1411   BAD_ALLOCATION_TYPE, // T_NARROWKLASS = 18,
1412   BAD_ALLOCATION_TYPE, // T_CONFLICT    = 19,

1413 };
1414 
1415 static FieldAllocationType basic_type_to_atype(bool is_static, BasicType type) {
1416   assert(type >= T_BOOLEAN && type < T_VOID, "only allowable values");
1417   FieldAllocationType result = _basic_type_to_atype[type + (is_static ? (T_CONFLICT + 1) : 0)];
1418   assert(result != BAD_ALLOCATION_TYPE, "bad type");



1419   return result;
1420 }
1421 
1422 class ClassFileParser::FieldAllocationCount : public ResourceObj {
1423  public:
1424   u2 count[MAX_FIELD_ALLOCATION_TYPE];
1425 
1426   FieldAllocationCount() {
1427     for (int i = 0; i < MAX_FIELD_ALLOCATION_TYPE; i++) {
1428       count[i] = 0;
1429     }
1430   }
1431 
1432   void update(bool is_static, BasicType type) {
1433     FieldAllocationType atype = basic_type_to_atype(is_static, type);
1434     if (atype != BAD_ALLOCATION_TYPE) {
1435       // Make sure there is no overflow with injected fields.
1436       assert(count[atype] < 0xFFFF, "More than 65535 fields");
1437       count[atype]++;
1438     }
1439   }
1440 };
1441 
1442 // Side-effects: populates the _fields, _fields_annotations,
1443 // _fields_type_annotations fields
1444 void ClassFileParser::parse_fields(const ClassFileStream* const cfs,
1445                                    bool is_interface,
1446                                    FieldAllocationCount* const fac,
1447                                    ConstantPool* cp,
1448                                    const int cp_size,
1449                                    u2* const java_fields_count_ptr,
1450                                    TRAPS) {
1451 
1452   assert(cfs != nullptr, "invariant");
1453   assert(fac != nullptr, "invariant");
1454   assert(cp != nullptr, "invariant");
1455   assert(java_fields_count_ptr != nullptr, "invariant");
1456 
1457   assert(nullptr == _fields_annotations, "invariant");
1458   assert(nullptr == _fields_type_annotations, "invariant");
1459 

1460   cfs->guarantee_more(2, CHECK);  // length
1461   const u2 length = cfs->get_u2_fast();
1462   *java_fields_count_ptr = length;
1463 
1464   int num_injected = 0;
1465   const InjectedField* const injected = JavaClasses::get_injected(_class_name,
1466                                                                   &num_injected);
1467   const int total_fields = length + num_injected;




1468 
1469   // Allocate a temporary resource array to collect field data.
1470   // After parsing all fields, data are stored in a UNSIGNED5 compressed stream.
1471   _temp_field_info = new GrowableArray<FieldInfo>(total_fields);
1472 

1473   ResourceMark rm(THREAD);
1474   for (int n = 0; n < length; n++) {
1475     // access_flags, name_index, descriptor_index, attributes_count
1476     cfs->guarantee_more(8, CHECK);
1477 







1478     AccessFlags access_flags;
1479     const jint flags = cfs->get_u2_fast() & JVM_RECOGNIZED_FIELD_MODIFIERS;
1480     verify_legal_field_modifiers(flags, is_interface, CHECK);
1481     access_flags.set_flags(flags);
1482     FieldInfo::FieldFlags fieldFlags(0);
1483 
1484     const u2 name_index = cfs->get_u2_fast();
1485     check_property(valid_symbol_at(name_index),
1486       "Invalid constant pool index %u for field name in class file %s",
1487       name_index, CHECK);
1488     const Symbol* const name = cp->symbol_at(name_index);
1489     verify_legal_field_name(name, CHECK);
1490 
1491     const u2 signature_index = cfs->get_u2_fast();
1492     check_property(valid_symbol_at(signature_index),
1493       "Invalid constant pool index %u for field signature in class file %s",
1494       signature_index, CHECK);
1495     const Symbol* const sig = cp->symbol_at(signature_index);
1496     verify_legal_field_signature(name, sig, CHECK);

1497 
1498     u2 constantvalue_index = 0;
1499     bool is_synthetic = false;
1500     u2 generic_signature_index = 0;
1501     const bool is_static = access_flags.is_static();
1502     FieldAnnotationCollector parsed_annotations(_loader_data);
1503 


1504     const u2 attributes_count = cfs->get_u2_fast();
1505     if (attributes_count > 0) {
1506       parse_field_attributes(cfs,
1507                              attributes_count,
1508                              is_static,
1509                              signature_index,
1510                              &constantvalue_index,
1511                              &is_synthetic,
1512                              &generic_signature_index,
1513                              &parsed_annotations,
1514                              CHECK);
1515 
1516       if (parsed_annotations.field_annotations() != nullptr) {
1517         if (_fields_annotations == nullptr) {
1518           _fields_annotations = MetadataFactory::new_array<AnnotationArray*>(
1519                                              _loader_data, length, nullptr,
1520                                              CHECK);
1521         }
1522         _fields_annotations->at_put(n, parsed_annotations.field_annotations());










1523         parsed_annotations.set_field_annotations(nullptr);
1524       }
1525       if (parsed_annotations.field_type_annotations() != nullptr) {
1526         if (_fields_type_annotations == nullptr) {
1527           _fields_type_annotations =
1528             MetadataFactory::new_array<AnnotationArray*>(_loader_data,
1529                                                          length,
1530                                                          nullptr,
1531                                                          CHECK);
1532         }
1533         _fields_type_annotations->at_put(n, parsed_annotations.field_type_annotations());
1534         parsed_annotations.set_field_type_annotations(nullptr);
1535       }
1536 
1537       if (is_synthetic) {
1538         access_flags.set_is_synthetic();
1539       }
1540       if (generic_signature_index != 0) {
1541         fieldFlags.update_generic(true);
1542       }
1543     }
1544 
1545     const BasicType type = cp->basic_type_for_signature_at(signature_index);
1546 
1547     // Update FieldAllocationCount for this kind of field
1548     fac->update(is_static, type);



1549 
1550     FieldInfo fi(access_flags, name_index, signature_index, constantvalue_index, fieldFlags);
1551     fi.set_index(n);
1552     if (fieldFlags.is_generic()) {
1553       fi.set_generic_signature_index(generic_signature_index);
1554     }
1555     parsed_annotations.apply_to(&fi);
1556     if (fi.field_flags().is_contended()) {
1557       _has_contended_fields = true;
1558     }
1559     _temp_field_info->append(fi);
1560   }
1561   assert(_temp_field_info->length() == length, "Must be");
1562 
1563   int index = length;
1564   if (num_injected != 0) {
1565     for (int n = 0; n < num_injected; n++) {
1566       // Check for duplicates
1567       if (injected[n].may_be_java) {
1568         const Symbol* const name      = injected[n].name();

1576             duplicate = true;
1577             break;
1578           }
1579         }
1580         if (duplicate) {
1581           // These will be removed from the field array at the end
1582           continue;
1583         }
1584       }
1585 
1586       // Injected field
1587       FieldInfo::FieldFlags fflags(0);
1588       fflags.update_injected(true);
1589       AccessFlags aflags;
1590       FieldInfo fi(aflags, (u2)(injected[n].name_index), (u2)(injected[n].signature_index), 0, fflags);
1591       fi.set_index(index);
1592       _temp_field_info->append(fi);
1593 
1594       // Update FieldAllocationCount for this kind of field
1595       const BasicType type = Signature::basic_type(injected[n].signature());
1596       fac->update(false, type);
1597       index++;
1598     }
1599   }
1600 










































1601   assert(_temp_field_info->length() == index, "Must be");
1602 
1603   if (_need_verify && length > 1) {
1604     // Check duplicated fields
1605     ResourceMark rm(THREAD);
1606     // Set containing name-signature pairs
1607     NameSigHashtable* names_and_sigs = new NameSigHashtable();
1608     for (int i = 0; i < _temp_field_info->length(); i++) {
1609       NameSigHash name_and_sig(_temp_field_info->adr_at(i)->name(_cp),
1610                                _temp_field_info->adr_at(i)->signature(_cp));
1611       // If no duplicates, add name/signature in hashtable names_and_sigs.
1612       if(!names_and_sigs->put(name_and_sig, 0)) {
1613         classfile_parse_error("Duplicate field name \"%s\" with signature \"%s\" in class file %s",
1614                                name_and_sig._name->as_C_string(), name_and_sig._sig->as_klass_external_name(), THREAD);
1615         return;
1616       }
1617     }
1618   }
1619 }
1620 

1955     }
1956     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Contended_signature): {
1957       if (_location != _in_field && _location != _in_class) {
1958         break;  // only allow for fields and classes
1959       }
1960       if (!EnableContended || (RestrictContended && !privileged)) {
1961         break;  // honor privileges
1962       }
1963       return _jdk_internal_vm_annotation_Contended;
1964     }
1965     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ReservedStackAccess_signature): {
1966       if (_location != _in_method)  break;  // only allow for methods
1967       if (RestrictReservedStack && !privileged) break; // honor privileges
1968       return _jdk_internal_vm_annotation_ReservedStackAccess;
1969     }
1970     case VM_SYMBOL_ENUM_NAME(jdk_internal_ValueBased_signature): {
1971       if (_location != _in_class)   break;  // only allow for classes
1972       if (!privileged)              break;  // only allow in privileged code
1973       return _jdk_internal_ValueBased;
1974     }












1975     case VM_SYMBOL_ENUM_NAME(java_lang_Deprecated): {
1976       return _java_lang_Deprecated;
1977     }
1978     default: {
1979       break;
1980     }
1981   }
1982   return AnnotationCollector::_unknown;
1983 }
1984 
1985 void ClassFileParser::FieldAnnotationCollector::apply_to(FieldInfo* f) {
1986   if (is_contended())
1987     // Setting the contended group also sets the contended bit in field flags
1988     f->set_contended_group(contended_group());
1989   if (is_stable())
1990     (f->field_flags_addr())->update_stable(true);
1991 }
1992 
1993 ClassFileParser::FieldAnnotationCollector::~FieldAnnotationCollector() {
1994   // If there's an error deallocate metadata for field annotations

2176   }
2177 
2178   if (runtime_visible_type_annotations_length > 0) {
2179     a = allocate_annotations(runtime_visible_type_annotations,
2180                              runtime_visible_type_annotations_length,
2181                              CHECK);
2182     cm->set_type_annotations(a);
2183   }
2184 }
2185 
2186 
2187 // Note: the parse_method below is big and clunky because all parsing of the code and exceptions
2188 // attribute is inlined. This is cumbersome to avoid since we inline most of the parts in the
2189 // Method* to save footprint, so we only know the size of the resulting Method* when the
2190 // entire method attribute is parsed.
2191 //
2192 // The has_localvariable_table parameter is used to pass up the value to InstanceKlass.
2193 
2194 Method* ClassFileParser::parse_method(const ClassFileStream* const cfs,
2195                                       bool is_interface,


2196                                       const ConstantPool* cp,
2197                                       bool* const has_localvariable_table,
2198                                       TRAPS) {
2199   assert(cfs != nullptr, "invariant");
2200   assert(cp != nullptr, "invariant");
2201   assert(has_localvariable_table != nullptr, "invariant");
2202 
2203   ResourceMark rm(THREAD);
2204   // Parse fixed parts:
2205   // access_flags, name_index, descriptor_index, attributes_count
2206   cfs->guarantee_more(8, CHECK_NULL);
2207 
2208   int flags = cfs->get_u2_fast();
2209   const u2 name_index = cfs->get_u2_fast();
2210   const int cp_size = cp->length();
2211   check_property(
2212     valid_symbol_at(name_index),
2213     "Illegal constant pool index %u for method name in class file %s",
2214     name_index, CHECK_NULL);
2215   const Symbol* const name = cp->symbol_at(name_index);

2217 
2218   const u2 signature_index = cfs->get_u2_fast();
2219   guarantee_property(
2220     valid_symbol_at(signature_index),
2221     "Illegal constant pool index %u for method signature in class file %s",
2222     signature_index, CHECK_NULL);
2223   const Symbol* const signature = cp->symbol_at(signature_index);
2224 
2225   if (name == vmSymbols::class_initializer_name()) {
2226     // We ignore the other access flags for a valid class initializer.
2227     // (JVM Spec 2nd ed., chapter 4.6)
2228     if (_major_version < 51) { // backward compatibility
2229       flags = JVM_ACC_STATIC;
2230     } else if ((flags & JVM_ACC_STATIC) == JVM_ACC_STATIC) {
2231       flags &= JVM_ACC_STATIC | (_major_version <= JAVA_16_VERSION ? JVM_ACC_STRICT : 0);
2232     } else {
2233       classfile_parse_error("Method <clinit> is not static in class file %s", THREAD);
2234       return nullptr;
2235     }
2236   } else {
2237     verify_legal_method_modifiers(flags, is_interface, name, CHECK_NULL);
2238   }
2239 
2240   if (name == vmSymbols::object_initializer_name() && is_interface) {
2241     classfile_parse_error("Interface cannot have a method named <init>, class file %s", THREAD);
2242     return nullptr;
2243   }
2244 









2245   int args_size = -1;  // only used when _need_verify is true
2246   if (_need_verify) {
2247     verify_legal_name_with_signature(name, signature, CHECK_NULL);
2248     args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) +
2249                  verify_legal_method_signature(name, signature, CHECK_NULL);
2250     if (args_size > MAX_ARGS_SIZE) {
2251       classfile_parse_error("Too many arguments in method signature in class file %s", THREAD);
2252       return nullptr;
2253     }
2254   }
2255 
2256   AccessFlags access_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS);
2257 
2258   // Default values for code and exceptions attribute elements
2259   u2 max_stack = 0;
2260   u2 max_locals = 0;
2261   u4 code_length = 0;
2262   const u1* code_start = nullptr;
2263   u2 exception_table_length = 0;
2264   const unsafe_u2* exception_table_start = nullptr; // (potentially unaligned) pointer to array of u2 elements

2752                           CHECK_NULL);
2753 
2754   if (InstanceKlass::is_finalization_enabled() &&
2755       name == vmSymbols::finalize_method_name() &&
2756       signature == vmSymbols::void_method_signature()) {
2757     if (m->is_empty_method()) {
2758       _has_empty_finalizer = true;
2759     } else {
2760       _has_finalizer = true;
2761     }
2762   }
2763 
2764   NOT_PRODUCT(m->verify());
2765   return m;
2766 }
2767 
2768 
2769 // Side-effects: populates the _methods field in the parser
2770 void ClassFileParser::parse_methods(const ClassFileStream* const cfs,
2771                                     bool is_interface,


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                                     _cp,
2797                                     has_localvariable_table,
2798                                     CHECK);
2799 
2800       if (method->is_final()) {
2801         *has_final_method = true;
2802       }
2803       // declares_nonstatic_concrete_methods: declares concrete instance methods, any access flags
2804       // used for interface initialization, and default method inheritance analysis
2805       if (is_interface && !(*declares_nonstatic_concrete_methods)
2806         && !method->is_abstract() && !method->is_static()) {
2807         *declares_nonstatic_concrete_methods = true;
2808       }
2809       _methods->at_put(index, method);
2810     }
2811 
2812     if (_need_verify && length > 1) {
2813       // Check duplicated methods
2814       ResourceMark rm(THREAD);
2815       // Set containing name-signature pairs

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




3069     if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
3070       // Set abstract bit for old class files for backward compatibility
3071       flags |= JVM_ACC_ABSTRACT;
3072     }
3073     verify_legal_class_modifiers(flags, CHECK_0);










3074     AccessFlags inner_access_flags(flags);
3075 
3076     inner_classes->at_put(index++, inner_class_info_index);
3077     inner_classes->at_put(index++, outer_class_info_index);
3078     inner_classes->at_put(index++, inner_name_index);
3079     inner_classes->at_put(index++, inner_access_flags.as_short());
3080   }
3081 
3082   // Check for circular and duplicate entries.
3083   bool has_circularity = false;
3084   if (_need_verify) {
3085     has_circularity = check_inner_classes_circularity(cp, length * 4, CHECK_0);
3086     if (has_circularity) {
3087       // If circularity check failed then ignore InnerClasses attribute.
3088       MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
3089       index = 0;
3090       if (parsed_enclosingmethod_attribute) {
3091         inner_classes = MetadataFactory::new_array<u2>(_loader_data, 2, CHECK_0);
3092         _inner_classes = inner_classes;
3093       } else {

3157   if (length > 0) {
3158     int index = 0;
3159     cfs->guarantee_more(2 * length, CHECK_0);
3160     for (int n = 0; n < length; n++) {
3161       const u2 class_info_index = cfs->get_u2_fast();
3162       check_property(
3163         valid_klass_reference_at(class_info_index),
3164         "Permitted subclass class_info_index %u has bad constant type in class file %s",
3165         class_info_index, CHECK_0);
3166       permitted_subclasses->at_put(index++, class_info_index);
3167     }
3168     assert(index == size, "wrong size");
3169   }
3170 
3171   // Restore buffer's current position.
3172   cfs->set_current(current_mark);
3173 
3174   return length;
3175 }
3176 











































3177 //  Record {
3178 //    u2 attribute_name_index;
3179 //    u4 attribute_length;
3180 //    u2 components_count;
3181 //    component_info components[components_count];
3182 //  }
3183 //  component_info {
3184 //    u2 name_index;
3185 //    u2 descriptor_index
3186 //    u2 attributes_count;
3187 //    attribute_info_attributes[attributes_count];
3188 //  }
3189 u4 ClassFileParser::parse_classfile_record_attribute(const ClassFileStream* const cfs,
3190                                                      const ConstantPool* cp,
3191                                                      const u1* const record_attribute_start,
3192                                                      TRAPS) {
3193   const u1* const current_mark = cfs->current();
3194   int components_count = 0;
3195   unsigned int calculate_attr_size = 0;
3196   if (record_attribute_start != nullptr) {

3422   }
3423   guarantee_property(current_start + attribute_byte_length == cfs->current(),
3424                      "Bad length on BootstrapMethods in class file %s",
3425                      CHECK);
3426 }
3427 
3428 void ClassFileParser::parse_classfile_attributes(const ClassFileStream* const cfs,
3429                                                  ConstantPool* cp,
3430                  ClassFileParser::ClassAnnotationCollector* parsed_annotations,
3431                                                  TRAPS) {
3432   assert(cfs != nullptr, "invariant");
3433   assert(cp != nullptr, "invariant");
3434   assert(parsed_annotations != nullptr, "invariant");
3435 
3436   // Set inner classes attribute to default sentinel
3437   _inner_classes = Universe::the_empty_short_array();
3438   // Set nest members attribute to default sentinel
3439   _nest_members = Universe::the_empty_short_array();
3440   // Set _permitted_subclasses attribute to default sentinel
3441   _permitted_subclasses = Universe::the_empty_short_array();


3442   cfs->guarantee_more(2, CHECK);  // attributes_count
3443   u2 attributes_count = cfs->get_u2_fast();
3444   bool parsed_sourcefile_attribute = false;
3445   bool parsed_innerclasses_attribute = false;
3446   bool parsed_nest_members_attribute = false;
3447   bool parsed_permitted_subclasses_attribute = false;

3448   bool parsed_nest_host_attribute = false;
3449   bool parsed_record_attribute = false;
3450   bool parsed_enclosingmethod_attribute = false;
3451   bool parsed_bootstrap_methods_attribute = false;
3452   const u1* runtime_visible_annotations = nullptr;
3453   int runtime_visible_annotations_length = 0;
3454   const u1* runtime_visible_type_annotations = nullptr;
3455   int runtime_visible_type_annotations_length = 0;
3456   bool runtime_invisible_type_annotations_exists = false;
3457   bool runtime_invisible_annotations_exists = false;
3458   bool parsed_source_debug_ext_annotations_exist = false;
3459   const u1* inner_classes_attribute_start = nullptr;
3460   u4  inner_classes_attribute_length = 0;
3461   u2  enclosing_method_class_index = 0;
3462   u2  enclosing_method_method_index = 0;
3463   const u1* nest_members_attribute_start = nullptr;
3464   u4  nest_members_attribute_length = 0;
3465   const u1* record_attribute_start = nullptr;
3466   u4  record_attribute_length = 0;
3467   const u1* permitted_subclasses_attribute_start = nullptr;
3468   u4  permitted_subclasses_attribute_length = 0;


3469 
3470   // Iterate over attributes
3471   while (attributes_count--) {
3472     cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
3473     const u2 attribute_name_index = cfs->get_u2_fast();
3474     const u4 attribute_length = cfs->get_u4_fast();
3475     check_property(
3476       valid_symbol_at(attribute_name_index),
3477       "Attribute name has bad constant pool index %u in class file %s",
3478       attribute_name_index, CHECK);
3479     const Symbol* const tag = cp->symbol_at(attribute_name_index);
3480     if (tag == vmSymbols::tag_source_file()) {
3481       // Check for SourceFile tag
3482       if (_need_verify) {
3483         guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
3484       }
3485       if (parsed_sourcefile_attribute) {
3486         classfile_parse_error("Multiple SourceFile attributes in class file %s", THREAD);
3487         return;
3488       } else {

3664               return;
3665             }
3666             parsed_record_attribute = true;
3667             record_attribute_start = cfs->current();
3668             record_attribute_length = attribute_length;
3669           } else if (_major_version >= JAVA_17_VERSION) {
3670             if (tag == vmSymbols::tag_permitted_subclasses()) {
3671               if (parsed_permitted_subclasses_attribute) {
3672                 classfile_parse_error("Multiple PermittedSubclasses attributes in class file %s", CHECK);
3673                 return;
3674               }
3675               // Classes marked ACC_FINAL cannot have a PermittedSubclasses attribute.
3676               if (_access_flags.is_final()) {
3677                 classfile_parse_error("PermittedSubclasses attribute in final class file %s", CHECK);
3678                 return;
3679               }
3680               parsed_permitted_subclasses_attribute = true;
3681               permitted_subclasses_attribute_start = cfs->current();
3682               permitted_subclasses_attribute_length = attribute_length;
3683             }









3684           }
3685           // Skip attribute_length for any attribute where major_verson >= JAVA_17_VERSION
3686           cfs->skip_u1(attribute_length, CHECK);
3687         } else {
3688           // Unknown attribute
3689           cfs->skip_u1(attribute_length, CHECK);
3690         }
3691       } else {
3692         // Unknown attribute
3693         cfs->skip_u1(attribute_length, CHECK);
3694       }
3695     } else {
3696       // Unknown attribute
3697       cfs->skip_u1(attribute_length, CHECK);
3698     }
3699   }
3700   _class_annotations = allocate_annotations(runtime_visible_annotations,
3701                                             runtime_visible_annotations_length,
3702                                             CHECK);
3703   _class_type_annotations = allocate_annotations(runtime_visible_type_annotations,

3740                             CHECK);
3741     if (_need_verify) {
3742       guarantee_property(record_attribute_length == calculated_attr_length,
3743                          "Record attribute has wrong length in class file %s",
3744                          CHECK);
3745     }
3746   }
3747 
3748   if (parsed_permitted_subclasses_attribute) {
3749     const u2 num_subclasses = parse_classfile_permitted_subclasses_attribute(
3750                             cfs,
3751                             permitted_subclasses_attribute_start,
3752                             CHECK);
3753     if (_need_verify) {
3754       guarantee_property(
3755         permitted_subclasses_attribute_length == sizeof(num_subclasses) + sizeof(u2) * num_subclasses,
3756         "Wrong PermittedSubclasses attribute length in class file %s", CHECK);
3757     }
3758   }
3759 












3760   if (_max_bootstrap_specifier_index >= 0) {
3761     guarantee_property(parsed_bootstrap_methods_attribute,
3762                        "Missing BootstrapMethods attribute in class file %s", CHECK);
3763   }
3764 }
3765 
3766 void ClassFileParser::apply_parsed_class_attributes(InstanceKlass* k) {
3767   assert(k != nullptr, "invariant");
3768 
3769   if (_synthetic_flag)
3770     k->set_is_synthetic();
3771   if (_sourcefile_index != 0) {
3772     k->set_source_file_name_index(_sourcefile_index);
3773   }
3774   if (_generic_signature_index != 0) {
3775     k->set_generic_signature_index(_generic_signature_index);
3776   }
3777   if (_sde_buffer != nullptr) {
3778     k->set_source_debug_extension(_sde_buffer, _sde_length);
3779   }

3805     _class_annotations       = nullptr;
3806     _class_type_annotations  = nullptr;
3807     _fields_annotations      = nullptr;
3808     _fields_type_annotations = nullptr;
3809 }
3810 
3811 // Transfer ownership of metadata allocated to the InstanceKlass.
3812 void ClassFileParser::apply_parsed_class_metadata(
3813                                             InstanceKlass* this_klass,
3814                                             int java_fields_count) {
3815   assert(this_klass != nullptr, "invariant");
3816 
3817   _cp->set_pool_holder(this_klass);
3818   this_klass->set_constants(_cp);
3819   this_klass->set_fieldinfo_stream(_fieldinfo_stream);
3820   this_klass->set_fields_status(_fields_status);
3821   this_klass->set_methods(_methods);
3822   this_klass->set_inner_classes(_inner_classes);
3823   this_klass->set_nest_members(_nest_members);
3824   this_klass->set_nest_host_index(_nest_host);

3825   this_klass->set_annotations(_combined_annotations);
3826   this_klass->set_permitted_subclasses(_permitted_subclasses);
3827   this_klass->set_record_components(_record_components);


3828   // Delay the setting of _local_interfaces and _transitive_interfaces until after
3829   // initialize_supers() in fill_instance_klass(). It is because the _local_interfaces could
3830   // be shared with _transitive_interfaces and _transitive_interfaces may be shared with
3831   // its _super. If an OOM occurs while loading the current klass, its _super field
3832   // may not have been set. When GC tries to free the klass, the _transitive_interfaces
3833   // may be deallocated mistakenly in InstanceKlass::deallocate_interfaces(). Subsequent
3834   // dereferences to the deallocated _transitive_interfaces will result in a crash.
3835 
3836   // Clear out these fields so they don't get deallocated by the destructor
3837   clear_class_metadata();
3838 }
3839 
3840 AnnotationArray* ClassFileParser::allocate_annotations(const u1* const anno,
3841                                                        int anno_length,
3842                                                        TRAPS) {
3843   AnnotationArray* annotations = nullptr;
3844   if (anno != nullptr) {
3845     annotations = MetadataFactory::new_array<u1>(_loader_data,
3846                                                  anno_length,
3847                                                  CHECK_(annotations));
3848     for (int i = 0; i < anno_length; i++) {
3849       annotations->at_put(i, anno[i]);
3850     }
3851   }
3852   return annotations;
3853 }
3854 
3855 const InstanceKlass* ClassFileParser::parse_super_class(ConstantPool* const cp,
3856                                                         const int super_class_index,
3857                                                         const bool need_verify,
3858                                                         TRAPS) {
3859   assert(cp != nullptr, "invariant");
3860   const InstanceKlass* super_klass = nullptr;
3861 
3862   if (super_class_index == 0) {
3863     check_property(_class_name == vmSymbols::java_lang_Object(),
3864                    "Invalid superclass index %u in class file %s",
3865                    super_class_index,
3866                    CHECK_NULL);
3867   } else {
3868     check_property(valid_klass_reference_at(super_class_index),
3869                    "Invalid superclass index %u in class file %s",
3870                    super_class_index,
3871                    CHECK_NULL);
3872     // The class name should be legal because it is checked when parsing constant pool.
3873     // However, make sure it is not an array type.
3874     bool is_array = false;
3875     if (cp->tag_at(super_class_index).is_klass()) {
3876       super_klass = InstanceKlass::cast(cp->resolved_klass_at(super_class_index));
3877       if (need_verify)
3878         is_array = super_klass->is_array_klass();
3879     } else if (need_verify) {
3880       is_array = (cp->klass_name_at(super_class_index)->char_at(0) == JVM_SIGNATURE_ARRAY);
3881     }
3882     if (need_verify) {

3883       guarantee_property(!is_array,
3884                         "Bad superclass name in class file %s", CHECK_NULL);
3885     }
3886   }
3887   return super_klass;
3888 }
3889 
3890 OopMapBlocksBuilder::OopMapBlocksBuilder(unsigned int max_blocks) {
3891   _max_nonstatic_oop_maps = max_blocks;
3892   _nonstatic_oop_map_count = 0;
3893   if (max_blocks == 0) {
3894     _nonstatic_oop_maps = nullptr;
3895   } else {
3896     _nonstatic_oop_maps =
3897         NEW_RESOURCE_ARRAY(OopMapBlock, _max_nonstatic_oop_maps);
3898     memset(_nonstatic_oop_maps, 0, sizeof(OopMapBlock) * max_blocks);
3899   }
3900 }
3901 
3902 OopMapBlock* OopMapBlocksBuilder::last_oop_map() const {

4036 
4037   // Check if this klass supports the java.lang.Cloneable interface
4038   if (vmClasses::Cloneable_klass_loaded()) {
4039     if (ik->is_subtype_of(vmClasses::Cloneable_klass())) {
4040       ik->set_is_cloneable();
4041     }
4042   }
4043 
4044   // If it cannot be fast-path allocated, set a bit in the layout helper.
4045   // See documentation of InstanceKlass::can_be_fastpath_allocated().
4046   assert(ik->size_helper() > 0, "layout_helper is initialized");
4047   if (ik->is_abstract() || ik->is_interface()
4048       || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == nullptr)
4049       || ik->size_helper() >= FastAllocateSizeLimit) {
4050     // Forbid fast-path allocation.
4051     const jint lh = Klass::instance_layout_helper(ik->size_helper(), true);
4052     ik->set_layout_helper(lh);
4053   }
4054 }
4055 






4056 // utility methods for appending an array with check for duplicates
4057 
4058 static void append_interfaces(GrowableArray<InstanceKlass*>* result,
4059                               const Array<InstanceKlass*>* const ifs) {
4060   // iterate over new interfaces
4061   for (int i = 0; i < ifs->length(); i++) {
4062     InstanceKlass* const e = ifs->at(i);
4063     assert(e->is_klass() && e->is_interface(), "just checking");
4064     // add new interface
4065     result->append_if_missing(e);
4066   }
4067 }
4068 
4069 static Array<InstanceKlass*>* compute_transitive_interfaces(const InstanceKlass* super,
4070                                                             Array<InstanceKlass*>* local_ifs,
4071                                                             ClassLoaderData* loader_data,
4072                                                             TRAPS) {
4073   assert(local_ifs != nullptr, "invariant");
4074   assert(loader_data != nullptr, "invariant");
4075 

4079   // Add superclass transitive interfaces size
4080   if (super != nullptr) {
4081     super_size = super->transitive_interfaces()->length();
4082     max_transitive_size += super_size;
4083   }
4084   // Add local interfaces' super interfaces
4085   const int local_size = local_ifs->length();
4086   for (int i = 0; i < local_size; i++) {
4087     InstanceKlass* const l = local_ifs->at(i);
4088     max_transitive_size += l->transitive_interfaces()->length();
4089   }
4090   // Finally add local interfaces
4091   max_transitive_size += local_size;
4092   // Construct array
4093   if (max_transitive_size == 0) {
4094     // no interfaces, use canonicalized array
4095     return Universe::the_empty_instance_klass_array();
4096   } else if (max_transitive_size == super_size) {
4097     // no new local interfaces added, share superklass' transitive interface array
4098     return super->transitive_interfaces();
4099   } else if (max_transitive_size == local_size) {
4100     // only local interfaces added, share local interface array
4101     return local_ifs;

4102   } else {
4103     ResourceMark rm;
4104     GrowableArray<InstanceKlass*>* const result = new GrowableArray<InstanceKlass*>(max_transitive_size);
4105 
4106     // Copy down from superclass
4107     if (super != nullptr) {
4108       append_interfaces(result, super->transitive_interfaces());
4109     }
4110 
4111     // Copy down from local interfaces' superinterfaces
4112     for (int i = 0; i < local_size; i++) {
4113       InstanceKlass* const l = local_ifs->at(i);
4114       append_interfaces(result, l->transitive_interfaces());
4115     }
4116     // Finally add local interfaces
4117     append_interfaces(result, local_ifs);
4118 
4119     // length will be less than the max_transitive_size if duplicates were removed
4120     const int length = result->length();
4121     assert(length <= max_transitive_size, "just checking");

4122     Array<InstanceKlass*>* const new_result =
4123       MetadataFactory::new_array<InstanceKlass*>(loader_data, length, CHECK_NULL);
4124     for (int i = 0; i < length; i++) {
4125       InstanceKlass* const e = result->at(i);
4126       assert(e != nullptr, "just checking");
4127       new_result->at_put(i, e);
4128     }
4129     return new_result;
4130   }
4131 }
4132 
4133 void ClassFileParser::check_super_class_access(const InstanceKlass* this_klass, TRAPS) {
4134   assert(this_klass != nullptr, "invariant");
4135   const Klass* const super = this_klass->super();
4136 
4137   if (super != nullptr) {
4138     const InstanceKlass* super_ik = InstanceKlass::cast(super);
4139 
4140     if (super->is_final()) {
4141       classfile_icce_error("class %s cannot inherit from final class %s", super_ik, THREAD);
4142       return;
4143     }
4144 
4145     if (super_ik->is_sealed() && !super_ik->has_as_permitted_subclass(this_klass)) {
4146       classfile_icce_error("class %s cannot inherit from sealed class %s", super_ik, THREAD);
4147       return;
4148     }
4149 










4150     // If the loader is not the boot loader then throw an exception if its
4151     // superclass is in package jdk.internal.reflect and its loader is not a
4152     // special reflection class loader
4153     if (!this_klass->class_loader_data()->is_the_null_class_loader_data()) {
4154       PackageEntry* super_package = super->package();
4155       if (super_package != nullptr &&
4156           super_package->name()->fast_compare(vmSymbols::jdk_internal_reflect()) == 0 &&
4157           !java_lang_ClassLoader::is_reflection_class_loader(this_klass->class_loader())) {
4158         ResourceMark rm(THREAD);
4159         Exceptions::fthrow(
4160           THREAD_AND_LOCATION,
4161           vmSymbols::java_lang_IllegalAccessError(),
4162           "class %s loaded by %s cannot access jdk/internal/reflect superclass %s",
4163           this_klass->external_name(),
4164           this_klass->class_loader_data()->loader_name_and_id(),
4165           super->external_name());
4166         return;
4167       }
4168     }
4169 

4315 
4316   for (int index = 0; index < num_methods; index++) {
4317     const Method* const m = methods->at(index);
4318     // if m is static and not the init method, throw a verify error
4319     if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) {
4320       ResourceMark rm(THREAD);
4321       Exceptions::fthrow(
4322         THREAD_AND_LOCATION,
4323         vmSymbols::java_lang_VerifyError(),
4324         "Illegal static method %s in interface %s",
4325         m->name()->as_C_string(),
4326         this_klass->external_name()
4327       );
4328       return;
4329     }
4330   }
4331 }
4332 
4333 // utility methods for format checking
4334 
4335 void ClassFileParser::verify_legal_class_modifiers(jint flags, TRAPS) const {
4336   const bool is_module = (flags & JVM_ACC_MODULE) != 0;

4337   assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");
4338   if (is_module) {
4339     ResourceMark rm(THREAD);
4340     Exceptions::fthrow(
4341       THREAD_AND_LOCATION,
4342       vmSymbols::java_lang_NoClassDefFoundError(),
4343       "%s is not a class because access_flag ACC_MODULE is set",
4344       _class_name->as_C_string());
4345     return;
4346   }
4347 
4348   if (!_need_verify) { return; }
4349 
4350   const bool is_interface  = (flags & JVM_ACC_INTERFACE)  != 0;
4351   const bool is_abstract   = (flags & JVM_ACC_ABSTRACT)   != 0;
4352   const bool is_final      = (flags & JVM_ACC_FINAL)      != 0;
4353   const bool is_super      = (flags & JVM_ACC_SUPER)      != 0;
4354   const bool is_enum       = (flags & JVM_ACC_ENUM)       != 0;
4355   const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4356   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;


4357 
4358   if ((is_abstract && is_final) ||
4359       (is_interface && !is_abstract) ||
4360       (is_interface && major_gte_1_5 && (is_super || is_enum)) ||
4361       (!is_interface && major_gte_1_5 && is_annotation)) {

4362     ResourceMark rm(THREAD);
4363     Exceptions::fthrow(
4364       THREAD_AND_LOCATION,
4365       vmSymbols::java_lang_ClassFormatError(),
4366       "Illegal class modifiers in class %s: 0x%X",
4367       _class_name->as_C_string(), flags
4368     );
4369     return;














4370   }
4371 }
4372 
4373 static bool has_illegal_visibility(jint flags) {
4374   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4375   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4376   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4377 
4378   return ((is_public && is_protected) ||
4379           (is_public && is_private) ||
4380           (is_protected && is_private));
4381 }
4382 
4383 // A legal major_version.minor_version must be one of the following:
4384 //
4385 //  Major_version >= 45 and major_version < 56, any minor_version.
4386 //  Major_version >= 56 and major_version <= JVM_CLASSFILE_MAJOR_VERSION and minor_version = 0.
4387 //  Major_version = JVM_CLASSFILE_MAJOR_VERSION and minor_version = 65535 and --enable-preview is present.
4388 //
4389 void ClassFileParser::verify_class_version(u2 major, u2 minor, Symbol* class_name, TRAPS){

4415         THREAD_AND_LOCATION,
4416         vmSymbols::java_lang_UnsupportedClassVersionError(),
4417         "%s (class file version %u.%u) was compiled with preview features that are unsupported. "
4418         "This version of the Java Runtime only recognizes preview features for class file version %u.%u",
4419         class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION, JAVA_PREVIEW_MINOR_VERSION);
4420       return;
4421     }
4422 
4423     if (!Arguments::enable_preview()) {
4424       classfile_ucve_error("Preview features are not enabled for %s (class file version %u.%u). Try running with '--enable-preview'",
4425                            class_name, major, minor, THREAD);
4426       return;
4427     }
4428 
4429   } else { // minor != JAVA_PREVIEW_MINOR_VERSION
4430     classfile_ucve_error("%s (class file version %u.%u) was compiled with an invalid non-zero minor version",
4431                          class_name, major, minor, THREAD);
4432   }
4433 }
4434 
4435 void ClassFileParser::verify_legal_field_modifiers(jint flags,
4436                                                    bool is_interface,
4437                                                    TRAPS) const {
4438   if (!_need_verify) { return; }
4439 
4440   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4441   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4442   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4443   const bool is_static    = (flags & JVM_ACC_STATIC)    != 0;
4444   const bool is_final     = (flags & JVM_ACC_FINAL)     != 0;
4445   const bool is_volatile  = (flags & JVM_ACC_VOLATILE)  != 0;
4446   const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
4447   const bool is_enum      = (flags & JVM_ACC_ENUM)      != 0;

4448   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4449 



4450   bool is_illegal = false;

4451 
4452   if (is_interface) {
4453     if (!is_public || !is_static || !is_final || is_private ||
4454         is_protected || is_volatile || is_transient ||
4455         (major_gte_1_5 && is_enum)) {




4456       is_illegal = true;

4457     }
4458   } else { // not interface
4459     if (has_illegal_visibility(flags) || (is_final && is_volatile)) {
4460       is_illegal = true;

























4461     }
4462   }
4463 
4464   if (is_illegal) {
4465     ResourceMark rm(THREAD);
4466     Exceptions::fthrow(
4467       THREAD_AND_LOCATION,
4468       vmSymbols::java_lang_ClassFormatError(),
4469       "Illegal field modifiers in class %s: 0x%X",
4470       _class_name->as_C_string(), flags);
4471     return;
4472   }
4473 }
4474 
4475 void ClassFileParser::verify_legal_method_modifiers(jint flags,
4476                                                     bool is_interface,
4477                                                     const Symbol* name,
4478                                                     TRAPS) const {
4479   if (!_need_verify) { return; }
4480 
4481   const bool is_public       = (flags & JVM_ACC_PUBLIC)       != 0;
4482   const bool is_private      = (flags & JVM_ACC_PRIVATE)      != 0;
4483   const bool is_static       = (flags & JVM_ACC_STATIC)       != 0;
4484   const bool is_final        = (flags & JVM_ACC_FINAL)        != 0;
4485   const bool is_native       = (flags & JVM_ACC_NATIVE)       != 0;
4486   const bool is_abstract     = (flags & JVM_ACC_ABSTRACT)     != 0;
4487   const bool is_bridge       = (flags & JVM_ACC_BRIDGE)       != 0;
4488   const bool is_strict       = (flags & JVM_ACC_STRICT)       != 0;
4489   const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
4490   const bool is_protected    = (flags & JVM_ACC_PROTECTED)    != 0;
4491   const bool major_gte_1_5   = _major_version >= JAVA_1_5_VERSION;
4492   const bool major_gte_8     = _major_version >= JAVA_8_VERSION;
4493   const bool major_gte_17    = _major_version >= JAVA_17_VERSION;
4494   const bool is_initializer  = (name == vmSymbols::object_initializer_name());




4495 
4496   bool is_illegal = false;
4497 

4498   if (is_interface) {
4499     if (major_gte_8) {
4500       // Class file version is JAVA_8_VERSION or later Methods of
4501       // interfaces may set any of the flags except ACC_PROTECTED,
4502       // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must
4503       // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.
4504       if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
4505           (is_native || is_protected || is_final || is_synchronized) ||
4506           // If a specific method of a class or interface has its
4507           // ACC_ABSTRACT flag set, it must not have any of its
4508           // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,
4509           // ACC_STRICT, or ACC_SYNCHRONIZED flags set.  No need to
4510           // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as
4511           // those flags are illegal irrespective of ACC_ABSTRACT being set or not.
4512           (is_abstract && (is_private || is_static || (!major_gte_17 && is_strict)))) {
4513         is_illegal = true;
4514       }
4515     } else if (major_gte_1_5) {
4516       // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)
4517       if (!is_public || is_private || is_protected || is_static || is_final ||
4518           is_synchronized || is_native || !is_abstract || is_strict) {
4519         is_illegal = true;
4520       }
4521     } else {
4522       // Class file version is pre-JAVA_1_5_VERSION
4523       if (!is_public || is_static || is_final || is_native || !is_abstract) {
4524         is_illegal = true;
4525       }
4526     }
4527   } else { // not interface
4528     if (has_illegal_visibility(flags)) {
4529       is_illegal = true;
4530     } else {
4531       if (is_initializer) {
4532         if (is_static || is_final || is_synchronized || is_native ||
4533             is_abstract || (major_gte_1_5 && is_bridge)) {
4534           is_illegal = true;
4535         }
4536       } else { // not initializer
4537         if (is_abstract) {
4538           if ((is_final || is_native || is_private || is_static ||
4539               (major_gte_1_5 && (is_synchronized || (!major_gte_17 && is_strict))))) {
4540             is_illegal = true;





4541           }
4542         }
4543       }
4544     }
4545   }
4546 
4547   if (is_illegal) {
4548     ResourceMark rm(THREAD);
4549     Exceptions::fthrow(
4550       THREAD_AND_LOCATION,
4551       vmSymbols::java_lang_ClassFormatError(),
4552       "Method %s in class %s has illegal modifiers: 0x%X",
4553       name->as_C_string(), _class_name->as_C_string(), flags);

4554     return;
4555   }
4556 }
4557 
4558 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer,
4559                                         int length,
4560                                         TRAPS) const {
4561   assert(_need_verify, "only called when _need_verify is true");
4562   // Note: 0 <= length < 64K, as it comes from a u2 entry in the CP.
4563   if (!UTF8::is_legal_utf8(buffer, static_cast<size_t>(length), _major_version <= 47)) {
4564     classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", THREAD);
4565   }
4566 }
4567 
4568 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
4569 // In class names, '/' separates unqualified names.  This is verified in this function also.
4570 // Method names also may not contain the characters '<' or '>', unless <init>
4571 // or <clinit>.  Note that method names may not be <init> or <clinit> in this
4572 // method.  Because these names have been checked as special cases before
4573 // calling this method in verify_legal_method_name.

4591         if (type == ClassFileParser::LegalClass) {
4592           if (p == name || p+1 >= name+length ||
4593               *(p+1) == JVM_SIGNATURE_SLASH) {
4594             return false;
4595           }
4596         } else {
4597           return false;   // do not permit '/' unless it's class name
4598         }
4599         break;
4600       case JVM_SIGNATURE_SPECIAL:
4601       case JVM_SIGNATURE_ENDSPECIAL:
4602         // do not permit '<' or '>' in method names
4603         if (type == ClassFileParser::LegalMethod) {
4604           return false;
4605         }
4606     }
4607   }
4608   return true;
4609 }
4610 









4611 // Take pointer to a UTF8 byte string (not NUL-terminated).
4612 // Skip over the longest part of the string that could
4613 // be taken as a fieldname. Allow non-trailing '/'s if slash_ok is true.
4614 // Return a pointer to just past the fieldname.
4615 // Return null if no fieldname at all was found, or in the case of slash_ok
4616 // being true, we saw consecutive slashes (meaning we were looking for a
4617 // qualified path but found something that was badly-formed).
4618 static const char* skip_over_field_name(const char* const name,
4619                                         bool slash_ok,
4620                                         unsigned int length) {
4621   const char* p;
4622   jboolean last_is_slash = false;
4623   jboolean not_first_ch = false;
4624 
4625   for (p = name; p != name + length; not_first_ch = true) {
4626     const char* old_p = p;
4627     jchar ch = *p;
4628     if (ch < 128) {
4629       p++;
4630       // quick check for ascii

4692 // be taken as a field signature. Allow "void" if void_ok.
4693 // Return a pointer to just past the signature.
4694 // Return null if no legal signature is found.
4695 const char* ClassFileParser::skip_over_field_signature(const char* signature,
4696                                                        bool void_ok,
4697                                                        unsigned int length,
4698                                                        TRAPS) const {
4699   unsigned int array_dim = 0;
4700   while (length > 0) {
4701     switch (signature[0]) {
4702     case JVM_SIGNATURE_VOID: if (!void_ok) { return nullptr; }
4703     case JVM_SIGNATURE_BOOLEAN:
4704     case JVM_SIGNATURE_BYTE:
4705     case JVM_SIGNATURE_CHAR:
4706     case JVM_SIGNATURE_SHORT:
4707     case JVM_SIGNATURE_INT:
4708     case JVM_SIGNATURE_FLOAT:
4709     case JVM_SIGNATURE_LONG:
4710     case JVM_SIGNATURE_DOUBLE:
4711       return signature + 1;
4712     case JVM_SIGNATURE_CLASS: {

4713       if (_major_version < JAVA_1_5_VERSION) {
4714         // Skip over the class name if one is there
4715         const char* const p = skip_over_field_name(signature + 1, true, --length);
4716 
4717         // The next character better be a semicolon
4718         if (p && (p - signature) > 1 && p[0] == JVM_SIGNATURE_ENDCLASS) {
4719           return p + 1;
4720         }
4721       }
4722       else {
4723         // Skip leading 'L' and ignore first appearance of ';'
4724         signature++;
4725         const char* c = (const char*) memchr(signature, JVM_SIGNATURE_ENDCLASS, length - 1);
4726         // Format check signature
4727         if (c != nullptr) {
4728           int newlen = pointer_delta_as_int(c, (char*) signature);
4729           bool legal = verify_unqualified_name(signature, newlen, LegalClass);
4730           if (!legal) {
4731             classfile_parse_error("Class name is empty or contains illegal character "
4732                                   "in descriptor in class file %s",
4733                                   THREAD);
4734             return nullptr;
4735           }
4736           return signature + newlen + 1;
4737         }
4738       }
4739       return nullptr;
4740     }
4741     case JVM_SIGNATURE_ARRAY:
4742       array_dim++;
4743       if (array_dim > 255) {

4759 
4760 // Checks if name is a legal class name.
4761 void ClassFileParser::verify_legal_class_name(const Symbol* name, TRAPS) const {
4762   if (!_need_verify || _relax_verify) { return; }
4763 
4764   assert(name->refcount() > 0, "symbol must be kept alive");
4765   char* bytes = (char*)name->bytes();
4766   unsigned int length = name->utf8_length();
4767   bool legal = false;
4768 
4769   if (length > 0) {
4770     const char* p;
4771     if (bytes[0] == JVM_SIGNATURE_ARRAY) {
4772       p = skip_over_field_signature(bytes, false, length, CHECK);
4773       legal = (p != nullptr) && ((p - bytes) == (int)length);
4774     } else if (_major_version < JAVA_1_5_VERSION) {
4775       if (bytes[0] != JVM_SIGNATURE_SPECIAL) {
4776         p = skip_over_field_name(bytes, true, length);
4777         legal = (p != nullptr) && ((p - bytes) == (int)length);
4778       }




4779     } else {
4780       // 4900761: relax the constraints based on JSR202 spec
4781       // Class names may be drawn from the entire Unicode character set.
4782       // Identifiers between '/' must be unqualified names.
4783       // The utf8 string has been verified when parsing cpool entries.
4784       legal = verify_unqualified_name(bytes, length, LegalClass);
4785     }
4786   }
4787   if (!legal) {
4788     ResourceMark rm(THREAD);
4789     assert(_class_name != nullptr, "invariant");
4790     Exceptions::fthrow(
4791       THREAD_AND_LOCATION,
4792       vmSymbols::java_lang_ClassFormatError(),
4793       "Illegal class name \"%.*s\" in class file %s", length, bytes,
4794       _class_name->as_C_string()
4795     );
4796     return;
4797   }
4798 }

4824       THREAD_AND_LOCATION,
4825       vmSymbols::java_lang_ClassFormatError(),
4826       "Illegal field name \"%.*s\" in class %s", length, bytes,
4827       _class_name->as_C_string()
4828     );
4829     return;
4830   }
4831 }
4832 
4833 // Checks if name is a legal method name.
4834 void ClassFileParser::verify_legal_method_name(const Symbol* name, TRAPS) const {
4835   if (!_need_verify || _relax_verify) { return; }
4836 
4837   assert(name != nullptr, "method name is null");
4838   char* bytes = (char*)name->bytes();
4839   unsigned int length = name->utf8_length();
4840   bool legal = false;
4841 
4842   if (length > 0) {
4843     if (bytes[0] == JVM_SIGNATURE_SPECIAL) {
4844       if (name == vmSymbols::object_initializer_name() || name == vmSymbols::class_initializer_name()) {

4845         legal = true;
4846       }
4847     } else if (_major_version < JAVA_1_5_VERSION) {
4848       const char* p;
4849       p = skip_over_field_name(bytes, false, length);
4850       legal = (p != nullptr) && ((p - bytes) == (int)length);
4851     } else {
4852       // 4881221: relax the constraints based on JSR202 spec
4853       legal = verify_unqualified_name(bytes, length, LegalMethod);
4854     }
4855   }
4856 
4857   if (!legal) {
4858     ResourceMark rm(THREAD);
4859     assert(_class_name != nullptr, "invariant");
4860     Exceptions::fthrow(
4861       THREAD_AND_LOCATION,
4862       vmSymbols::java_lang_ClassFormatError(),
4863       "Illegal method name \"%.*s\" in class %s", length, bytes,
4864       _class_name->as_C_string()
4865     );
4866     return;
4867   }
4868 }
4869 










4870 
4871 // Checks if signature is a legal field signature.
4872 void ClassFileParser::verify_legal_field_signature(const Symbol* name,
4873                                                    const Symbol* signature,
4874                                                    TRAPS) const {
4875   if (!_need_verify) { return; }
4876 
4877   const char* const bytes = (const char*)signature->bytes();
4878   const unsigned int length = signature->utf8_length();
4879   const char* const p = skip_over_field_signature(bytes, false, length, CHECK);
4880 
4881   if (p == nullptr || (p - bytes) != (int)length) {
4882     throwIllegalSignature("Field", name, signature, CHECK);
4883   }
4884 }
4885 
4886 // Check that the signature is compatible with the method name.  For example,
4887 // check that <init> has a void signature.
4888 void ClassFileParser::verify_legal_name_with_signature(const Symbol* name,
4889                                                        const Symbol* signature,
4890                                                        TRAPS) const {
4891   if (!_need_verify) {
4892     return;
4893   }
4894 
4895   // Class initializers cannot have args for class format version >= 51.
4896   if (name == vmSymbols::class_initializer_name() &&
4897       signature != vmSymbols::void_method_signature() &&
4898       _major_version >= JAVA_7_VERSION) {
4899     throwIllegalSignature("Method", name, signature, THREAD);
4900     return;
4901   }
4902 
4903   int sig_length = signature->utf8_length();
4904   if (name->utf8_length() > 0 &&
4905       name->char_at(0) == JVM_SIGNATURE_SPECIAL &&
4906       sig_length > 0 &&
4907       signature->char_at(sig_length - 1) != JVM_SIGNATURE_VOID) {
4908     throwIllegalSignature("Method", name, signature, THREAD);
4909   }
4910 }
4911 
4912 // Checks if signature is a legal method signature.
4913 // Returns number of parameters
4914 int ClassFileParser::verify_legal_method_signature(const Symbol* name,
4915                                                    const Symbol* signature,
4916                                                    TRAPS) const {
4917   if (!_need_verify) {
4918     // make sure caller's args_size will be less than 0 even for non-static
4919     // method so it will be recomputed in compute_size_of_parameters().
4920     return -2;
4921   }
4922 
4923   unsigned int args_size = 0;
4924   const char* p = (const char*)signature->bytes();
4925   unsigned int length = signature->utf8_length();
4926   const char* nextp;
4927 

5064   }
5065 }
5066 
5067 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook,
5068                                                       const ClassInstanceInfo& cl_inst_info,
5069                                                       TRAPS) {
5070   if (_klass != nullptr) {
5071     return _klass;
5072   }
5073 
5074   InstanceKlass* const ik =
5075     InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
5076 
5077   if (is_hidden()) {
5078     mangle_hidden_class_name(ik);
5079   }
5080 
5081   fill_instance_klass(ik, changed_by_loadhook, cl_inst_info, CHECK_NULL);
5082 
5083   assert(_klass == ik, "invariant");
5084 
5085   return ik;
5086 }
5087 
5088 void ClassFileParser::fill_instance_klass(InstanceKlass* ik,
5089                                           bool changed_by_loadhook,
5090                                           const ClassInstanceInfo& cl_inst_info,
5091                                           TRAPS) {
5092   assert(ik != nullptr, "invariant");
5093 
5094   // Set name and CLD before adding to CLD
5095   ik->set_class_loader_data(_loader_data);
5096   ik->set_name(_class_name);
5097 
5098   // Add all classes to our internal class loader list here,
5099   // including classes in the bootstrap (null) class loader.
5100   const bool publicize = !is_internal();
5101 
5102   _loader_data->add_class(ik, publicize);
5103 
5104   set_klass_to_deallocate(ik);
5105 
5106   assert(_field_info != nullptr, "invariant");
5107   assert(ik->static_field_size() == _field_info->_static_field_size, "sanity");
5108   assert(ik->nonstatic_oop_map_count() == _field_info->oop_map_blocks->_nonstatic_oop_map_count,
5109          "sanity");
5110 
5111   assert(ik->is_instance_klass(), "sanity");
5112   assert(ik->size_helper() == _field_info->_instance_size, "sanity");
5113 
5114   // Fill in information already parsed
5115   ik->set_should_verify_class(_need_verify);
5116 
5117   // Not yet: supers are done below to support the new subtype-checking fields
5118   ik->set_nonstatic_field_size(_field_info->_nonstatic_field_size);
5119   ik->set_has_nonstatic_fields(_field_info->_has_nonstatic_fields);




5120   assert(_fac != nullptr, "invariant");
5121   ik->set_static_oop_field_count(_fac->count[STATIC_OOP]);
5122 
5123   // this transfers ownership of a lot of arrays from
5124   // the parser onto the InstanceKlass*
5125   apply_parsed_class_metadata(ik, _java_fields_count);



5126 
5127   // can only set dynamic nest-host after static nest information is set
5128   if (cl_inst_info.dynamic_nest_host() != nullptr) {
5129     ik->set_nest_host(cl_inst_info.dynamic_nest_host());
5130   }
5131 
5132   // note that is not safe to use the fields in the parser from this point on
5133   assert(nullptr == _cp, "invariant");
5134   assert(nullptr == _fieldinfo_stream, "invariant");
5135   assert(nullptr == _fields_status, "invariant");
5136   assert(nullptr == _methods, "invariant");
5137   assert(nullptr == _inner_classes, "invariant");
5138   assert(nullptr == _nest_members, "invariant");

5139   assert(nullptr == _combined_annotations, "invariant");
5140   assert(nullptr == _record_components, "invariant");
5141   assert(nullptr == _permitted_subclasses, "invariant");

5142 
5143   if (_has_localvariable_table) {
5144     ik->set_has_localvariable_table(true);
5145   }
5146 
5147   if (_has_final_method) {
5148     ik->set_has_final_method();
5149   }
5150 
5151   ik->copy_method_ordering(_method_ordering, CHECK);
5152   // The InstanceKlass::_methods_jmethod_ids cache
5153   // is managed on the assumption that the initial cache
5154   // size is equal to the number of methods in the class. If
5155   // that changes, then InstanceKlass::idnum_can_increment()
5156   // has to be changed accordingly.
5157   ik->set_initial_method_idnum(checked_cast<u2>(ik->methods()->length()));
5158 
5159   ik->set_this_class_index(_this_class_index);
5160 
5161   if (_is_hidden) {
5162     // _this_class_index is a CONSTANT_Class entry that refers to this
5163     // hidden class itself. If this class needs to refer to its own methods
5164     // or fields, it would use a CONSTANT_MethodRef, etc, which would reference
5165     // _this_class_index. However, because this class is hidden (it's
5166     // not stored in SystemDictionary), _this_class_index cannot be resolved
5167     // with ConstantPool::klass_at_impl, which does a SystemDictionary lookup.
5168     // Therefore, we must eagerly resolve _this_class_index now.
5169     ik->constants()->klass_at_put(_this_class_index, ik);
5170   }
5171 
5172   ik->set_minor_version(_minor_version);
5173   ik->set_major_version(_major_version);
5174   ik->set_has_nonstatic_concrete_methods(_has_nonstatic_concrete_methods);
5175   ik->set_declares_nonstatic_concrete_methods(_declares_nonstatic_concrete_methods);
5176 






5177   assert(!_is_hidden || ik->is_hidden(), "must be set already");
5178 
5179   // Set PackageEntry for this_klass
5180   oop cl = ik->class_loader();
5181   Handle clh = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(cl));
5182   ClassLoaderData* cld = ClassLoaderData::class_loader_data_or_null(clh());
5183   ik->set_package(cld, nullptr, CHECK);
5184 
5185   const Array<Method*>* const methods = ik->methods();
5186   assert(methods != nullptr, "invariant");
5187   const int methods_len = methods->length();
5188 
5189   check_methods_for_intrinsics(ik, methods);
5190 
5191   // Fill in field values obtained by parse_classfile_attributes
5192   if (_parsed_annotations->has_any_annotations()) {
5193     _parsed_annotations->apply_to(ik);
5194   }
5195 
5196   apply_parsed_class_attributes(ik);

5261 
5262   assert(_all_mirandas != nullptr, "invariant");
5263 
5264   // Generate any default methods - default methods are public interface methods
5265   // that have a default implementation.  This is new with Java 8.
5266   if (_has_nonstatic_concrete_methods) {
5267     DefaultMethods::generate_default_methods(ik,
5268                                              _all_mirandas,
5269                                              CHECK);
5270   }
5271 
5272   // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5273   if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5274       !module_entry->has_default_read_edges()) {
5275     if (!module_entry->set_has_default_read_edges()) {
5276       // We won a potential race
5277       JvmtiExport::add_default_read_edges(module_handle, THREAD);
5278     }
5279   }
5280 




























5281   ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5282 
5283   if (!is_internal()) {
5284     ik->print_class_load_logging(_loader_data, module_entry, _stream);
5285 
5286     if (ik->minor_version() == JAVA_PREVIEW_MINOR_VERSION &&
5287         ik->major_version() == JVM_CLASSFILE_MAJOR_VERSION &&
5288         log_is_enabled(Info, class, preview)) {
5289       ResourceMark rm;
5290       log_info(class, preview)("Loading class %s that depends on preview features (class file version %d.65535)",
5291                                ik->external_name(), JVM_CLASSFILE_MAJOR_VERSION);
5292     }
5293 
5294     if (log_is_enabled(Debug, class, resolve))  {
5295       ResourceMark rm;
5296       // print out the superclass.
5297       const char * from = ik->external_name();
5298       if (ik->java_super() != nullptr) {
5299         log_debug(class, resolve)("%s %s (super)",
5300                    from,

5352                                  Symbol* name,
5353                                  ClassLoaderData* loader_data,
5354                                  const ClassLoadInfo* cl_info,
5355                                  Publicity pub_level,
5356                                  TRAPS) :
5357   _stream(stream),
5358   _class_name(nullptr),
5359   _loader_data(loader_data),
5360   _is_hidden(cl_info->is_hidden()),
5361   _can_access_vm_annotations(cl_info->can_access_vm_annotations()),
5362   _orig_cp_size(0),
5363   _super_klass(),
5364   _cp(nullptr),
5365   _fieldinfo_stream(nullptr),
5366   _fields_status(nullptr),
5367   _methods(nullptr),
5368   _inner_classes(nullptr),
5369   _nest_members(nullptr),
5370   _nest_host(0),
5371   _permitted_subclasses(nullptr),

5372   _record_components(nullptr),
5373   _local_interfaces(nullptr),

5374   _transitive_interfaces(nullptr),
5375   _combined_annotations(nullptr),
5376   _class_annotations(nullptr),
5377   _class_type_annotations(nullptr),
5378   _fields_annotations(nullptr),
5379   _fields_type_annotations(nullptr),
5380   _klass(nullptr),
5381   _klass_to_deallocate(nullptr),
5382   _parsed_annotations(nullptr),
5383   _fac(nullptr),
5384   _field_info(nullptr),


5385   _temp_field_info(nullptr),
5386   _method_ordering(nullptr),
5387   _all_mirandas(nullptr),
5388   _vtable_size(0),
5389   _itable_size(0),
5390   _num_miranda_methods(0),
5391   _protection_domain(cl_info->protection_domain()),
5392   _access_flags(),
5393   _pub_level(pub_level),
5394   _bad_constant_seen(0),
5395   _synthetic_flag(false),
5396   _sde_length(false),
5397   _sde_buffer(nullptr),
5398   _sourcefile_index(0),
5399   _generic_signature_index(0),
5400   _major_version(0),
5401   _minor_version(0),
5402   _this_class_index(0),
5403   _super_class_index(0),
5404   _itfs_len(0),
5405   _java_fields_count(0),
5406   _need_verify(false),
5407   _relax_verify(false),
5408   _has_nonstatic_concrete_methods(false),
5409   _declares_nonstatic_concrete_methods(false),
5410   _has_localvariable_table(false),
5411   _has_final_method(false),
5412   _has_contended_fields(false),








5413   _has_finalizer(false),
5414   _has_empty_finalizer(false),
5415   _max_bootstrap_specifier_index(-1) {
5416 
5417   _class_name = name != nullptr ? name : vmSymbols::unknown_class_name();
5418   _class_name->increment_refcount();
5419 
5420   assert(_loader_data != nullptr, "invariant");
5421   assert(stream != nullptr, "invariant");
5422   assert(_stream != nullptr, "invariant");
5423   assert(_stream->buffer() == _stream->current(), "invariant");
5424   assert(_class_name != nullptr, "invariant");
5425   assert(0 == _access_flags.as_int(), "invariant");
5426 
5427   // Figure out whether we can skip format checking (matching classic VM behavior)
5428   if (CDSConfig::is_dumping_static_archive()) {
5429     // verify == true means it's a 'remote' class (i.e., non-boot class)
5430     // Verification decision is based on BytecodeVerificationRemote flag
5431     // for those classes.
5432     _need_verify = (stream->need_verify()) ? BytecodeVerificationRemote :

5442 
5443   // Check if verification needs to be relaxed for this class file
5444   // Do not restrict it to jdk1.0 or jdk1.1 to maintain backward compatibility (4982376)
5445   _relax_verify = relax_format_check_for(_loader_data);
5446 
5447   parse_stream(stream, CHECK);
5448 
5449   post_process_parsed_stream(stream, _cp, CHECK);
5450 }
5451 
5452 void ClassFileParser::clear_class_metadata() {
5453   // metadata created before the instance klass is created.  Must be
5454   // deallocated if classfile parsing returns an error.
5455   _cp = nullptr;
5456   _fieldinfo_stream = nullptr;
5457   _fields_status = nullptr;
5458   _methods = nullptr;
5459   _inner_classes = nullptr;
5460   _nest_members = nullptr;
5461   _permitted_subclasses = nullptr;

5462   _combined_annotations = nullptr;
5463   _class_annotations = _class_type_annotations = nullptr;
5464   _fields_annotations = _fields_type_annotations = nullptr;
5465   _record_components = nullptr;


5466 }
5467 
5468 // Destructor to clean up
5469 ClassFileParser::~ClassFileParser() {
5470   _class_name->decrement_refcount();
5471 
5472   if (_cp != nullptr) {
5473     MetadataFactory::free_metadata(_loader_data, _cp);
5474   }
5475 
5476   if (_fieldinfo_stream != nullptr) {
5477     MetadataFactory::free_array<u1>(_loader_data, _fieldinfo_stream);
5478   }
5479 
5480   if (_fields_status != nullptr) {
5481     MetadataFactory::free_array<FieldStatus>(_loader_data, _fields_status);
5482   }
5483 








5484   if (_methods != nullptr) {
5485     // Free methods
5486     InstanceKlass::deallocate_methods(_loader_data, _methods);
5487   }
5488 
5489   // beware of the Universe::empty_blah_array!!
5490   if (_inner_classes != nullptr && _inner_classes != Universe::the_empty_short_array()) {
5491     MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
5492   }
5493 
5494   if (_nest_members != nullptr && _nest_members != Universe::the_empty_short_array()) {
5495     MetadataFactory::free_array<u2>(_loader_data, _nest_members);
5496   }
5497 
5498   if (_record_components != nullptr) {
5499     InstanceKlass::deallocate_record_components(_loader_data, _record_components);
5500   }
5501 
5502   if (_permitted_subclasses != nullptr && _permitted_subclasses != Universe::the_empty_short_array()) {
5503     MetadataFactory::free_array<u2>(_loader_data, _permitted_subclasses);
5504   }
5505 




5506   // Free interfaces
5507   InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
5508                                        _local_interfaces, _transitive_interfaces);
5509 
5510   if (_combined_annotations != nullptr) {
5511     // After all annotations arrays have been created, they are installed into the
5512     // Annotations object that will be assigned to the InstanceKlass being created.
5513 
5514     // Deallocate the Annotations object and the installed annotations arrays.
5515     _combined_annotations->deallocate_contents(_loader_data);
5516 
5517     // If the _combined_annotations pointer is non-null,
5518     // then the other annotations fields should have been cleared.
5519     assert(_class_annotations       == nullptr, "Should have been cleared");
5520     assert(_class_type_annotations  == nullptr, "Should have been cleared");
5521     assert(_fields_annotations      == nullptr, "Should have been cleared");
5522     assert(_fields_type_annotations == nullptr, "Should have been cleared");
5523   } else {
5524     // If the annotations arrays were not installed into the Annotations object,
5525     // then they have to be deallocated explicitly.

5570     cp_size, CHECK);
5571 
5572   _orig_cp_size = cp_size;
5573   if (is_hidden()) { // Add a slot for hidden class name.
5574     cp_size++;
5575   }
5576 
5577   _cp = ConstantPool::allocate(_loader_data,
5578                                cp_size,
5579                                CHECK);
5580 
5581   ConstantPool* const cp = _cp;
5582 
5583   parse_constant_pool(stream, cp, _orig_cp_size, CHECK);
5584 
5585   assert(cp_size == (u2)cp->length(), "invariant");
5586 
5587   // ACCESS FLAGS
5588   stream->guarantee_more(8, CHECK);  // flags, this_class, super_class, infs_len
5589 
5590   // Access flags
5591   jint flags;
5592   // JVM_ACC_MODULE is defined in JDK-9 and later.
5593   if (_major_version >= JAVA_9_VERSION) {
5594     flags = stream->get_u2_fast() & (JVM_RECOGNIZED_CLASS_MODIFIERS | JVM_ACC_MODULE);
5595   } else {
5596     flags = stream->get_u2_fast() & JVM_RECOGNIZED_CLASS_MODIFIERS;
5597   }
5598 



5599   if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
5600     // Set abstract bit for old class files for backward compatibility
5601     flags |= JVM_ACC_ABSTRACT;
5602   }
5603 
5604   verify_legal_class_modifiers(flags, CHECK);
5605 
5606   short bad_constant = class_bad_constant_seen();
5607   if (bad_constant != 0) {
5608     // Do not throw CFE until after the access_flags are checked because if
5609     // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
5610     classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, THREAD);
5611     return;
5612   }
5613 
5614   _access_flags.set_flags(flags);
5615 
5616   // This class and superclass
5617   _this_class_index = stream->get_u2_fast();
5618   check_property(
5619     valid_cp_range(_this_class_index, cp_size) &&
5620       cp->tag_at(_this_class_index).is_unresolved_klass(),
5621     "Invalid this class index %u in constant pool in class file %s",
5622     _this_class_index, CHECK);
5623 
5624   Symbol* const class_name_in_cp = cp->klass_name_at(_this_class_index);
5625   assert(class_name_in_cp != nullptr, "class_name can't be null");
5626 














5627   // Don't need to check whether this class name is legal or not.
5628   // It has been checked when constant pool is parsed.
5629   // However, make sure it is not an array type.
5630   if (_need_verify) {
5631     guarantee_property(class_name_in_cp->char_at(0) != JVM_SIGNATURE_ARRAY,
5632                        "Bad class name in class file %s",
5633                        CHECK);
5634   }
5635 
5636 #ifdef ASSERT
5637   // Basic sanity checks
5638   if (_is_hidden) {
5639     assert(_class_name != vmSymbols::unknown_class_name(), "hidden classes should have a special name");
5640   }
5641 #endif
5642 
5643   // Update the _class_name as needed depending on whether this is a named, un-named, or hidden class.
5644 
5645   if (_is_hidden) {
5646     assert(_class_name != nullptr, "Unexpected null _class_name");

5686       }
5687       ls.cr();
5688     }
5689   }
5690 
5691   // SUPERKLASS
5692   _super_class_index = stream->get_u2_fast();
5693   _super_klass = parse_super_class(cp,
5694                                    _super_class_index,
5695                                    _need_verify,
5696                                    CHECK);
5697 
5698   // Interfaces
5699   _itfs_len = stream->get_u2_fast();
5700   parse_interfaces(stream,
5701                    _itfs_len,
5702                    cp,
5703                    &_has_nonstatic_concrete_methods,
5704                    CHECK);
5705 
5706   assert(_local_interfaces != nullptr, "invariant");
5707 
5708   // Fields (offsets are filled in later)
5709   _fac = new FieldAllocationCount();
5710   parse_fields(stream,
5711                _access_flags.is_interface(),
5712                _fac,
5713                cp,
5714                cp_size,
5715                &_java_fields_count,
5716                CHECK);
5717 
5718   assert(_temp_field_info != nullptr, "invariant");
5719 
5720   // Methods
5721   parse_methods(stream,
5722                 _access_flags.is_interface(),


5723                 &_has_localvariable_table,
5724                 &_has_final_method,
5725                 &_declares_nonstatic_concrete_methods,
5726                 CHECK);
5727 
5728   assert(_methods != nullptr, "invariant");
5729 
5730   if (_declares_nonstatic_concrete_methods) {
5731     _has_nonstatic_concrete_methods = true;
5732   }
5733 
5734   // Additional attributes/annotations
5735   _parsed_annotations = new ClassAnnotationCollector();
5736   parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK);
5737 
5738   assert(_inner_classes != nullptr, "invariant");
5739 
5740   // Finalize the Annotations metadata object,
5741   // now that all annotation arrays have been created.
5742   create_combined_annotations(CHECK);

5782   // Update this_class_index's slot in the constant pool with the new Utf8 entry.
5783   // We have to update the resolved_klass_index and the name_index together
5784   // so extract the existing resolved_klass_index first.
5785   CPKlassSlot cp_klass_slot = _cp->klass_slot_at(_this_class_index);
5786   int resolved_klass_index = cp_klass_slot.resolved_klass_index();
5787   _cp->unresolved_klass_at_put(_this_class_index, hidden_index, resolved_klass_index);
5788   assert(_cp->klass_slot_at(_this_class_index).name_index() == _orig_cp_size,
5789          "Bad name_index");
5790 }
5791 
5792 void ClassFileParser::post_process_parsed_stream(const ClassFileStream* const stream,
5793                                                  ConstantPool* cp,
5794                                                  TRAPS) {
5795   assert(stream != nullptr, "invariant");
5796   assert(stream->at_eos(), "invariant");
5797   assert(cp != nullptr, "invariant");
5798   assert(_loader_data != nullptr, "invariant");
5799 
5800   if (_class_name == vmSymbols::java_lang_Object()) {
5801     check_property(_local_interfaces == Universe::the_empty_instance_klass_array(),
5802                    "java.lang.Object cannot implement an interface in class file %s",
5803                    CHECK);
5804   }
5805   // We check super class after class file is parsed and format is checked
5806   if (_super_class_index > 0 && nullptr == _super_klass) {
5807     Symbol* const super_class_name = cp->klass_name_at(_super_class_index);
5808     if (_access_flags.is_interface()) {
5809       // Before attempting to resolve the superclass, check for class format
5810       // errors not checked yet.
5811       guarantee_property(super_class_name == vmSymbols::java_lang_Object(),
5812         "Interfaces must have java.lang.Object as superclass in class file %s",
5813         CHECK);
5814     }
5815     Handle loader(THREAD, _loader_data->class_loader());
5816     if (loader.is_null() && super_class_name == vmSymbols::java_lang_Object()) {
5817       _super_klass = vmClasses::Object_klass();
5818     } else {
5819       _super_klass = (const InstanceKlass*)
5820                        SystemDictionary::resolve_super_or_fail(_class_name,
5821                                                                super_class_name,
5822                                                                loader,
5823                                                                _protection_domain,
5824                                                                true,
5825                                                                CHECK);
5826     }
5827   }
5828 
5829   if (_super_klass != nullptr) {














5830     if (_super_klass->has_nonstatic_concrete_methods()) {
5831       _has_nonstatic_concrete_methods = true;
5832     }

5833 
5834     if (_super_klass->is_interface()) {
5835       classfile_icce_error("class %s has interface %s as super class", _super_klass, THREAD);
5836       return;








































































5837     }
5838   }

5839 
5840   // Compute the transitive list of all unique interfaces implemented by this class
5841   _transitive_interfaces =
5842     compute_transitive_interfaces(_super_klass,
5843                                   _local_interfaces,
5844                                   _loader_data,
5845                                   CHECK);
5846 
5847   assert(_transitive_interfaces != nullptr, "invariant");
5848 
5849   // sort methods
5850   _method_ordering = sort_methods(_methods);
5851 
5852   _all_mirandas = new GrowableArray<Method*>(20);
5853 
5854   Handle loader(THREAD, _loader_data->class_loader());
5855   klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
5856                                                     &_num_miranda_methods,
5857                                                     _all_mirandas,
5858                                                     _super_klass,
5859                                                     _methods,
5860                                                     _access_flags,
5861                                                     _major_version,
5862                                                     loader,
5863                                                     _class_name,
5864                                                     _local_interfaces);
5865 
5866   // Size of Java itable (in words)
5867   _itable_size = _access_flags.is_interface() ? 0 :
5868     klassItable::compute_itable_size(_transitive_interfaces);
5869 
5870   assert(_fac != nullptr, "invariant");
5871   assert(_parsed_annotations != nullptr, "invariant");
5872 












































































5873   _field_info = new FieldLayoutInfo();
5874   FieldLayoutBuilder lb(class_name(), super_klass(), _cp, /*_fields*/ _temp_field_info,
5875                         _parsed_annotations->is_contended(), _field_info);


5876   lb.build_layout();







5877 
5878   int injected_fields_count = _temp_field_info->length() - _java_fields_count;
5879   _fieldinfo_stream =
5880     FieldInfoStream::create_FieldInfoStream(_temp_field_info, _java_fields_count,
5881                                             injected_fields_count, loader_data(), CHECK);

5882   _fields_status =
5883     MetadataFactory::new_array<FieldStatus>(_loader_data, _temp_field_info->length(),
5884                                             FieldStatus(0), CHECK);











5885 }
5886 
5887 void ClassFileParser::set_klass(InstanceKlass* klass) {
5888 
5889 #ifdef ASSERT
5890   if (klass != nullptr) {
5891     assert(nullptr == _klass, "leaking?");
5892   }
5893 #endif
5894 
5895   _klass = klass;
5896 }
5897 
5898 void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) {
5899 
5900 #ifdef ASSERT
5901   if (klass != nullptr) {
5902     assert(nullptr == _klass_to_deallocate, "leaking?");
5903   }
5904 #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 "precompiled.hpp"
  27 #include "cds/cdsConfig.hpp"
  28 #include "classfile/classFileParser.hpp"
  29 #include "classfile/classFileStream.hpp"
  30 #include "classfile/classLoader.hpp"
  31 #include "classfile/classLoaderData.inline.hpp"
  32 #include "classfile/classLoadInfo.hpp"
  33 #include "classfile/defaultMethods.hpp"
  34 #include "classfile/fieldLayoutBuilder.hpp"
  35 #include "classfile/javaClasses.inline.hpp"
  36 #include "classfile/moduleEntry.hpp"
  37 #include "classfile/packageEntry.hpp"
  38 #include "classfile/symbolTable.hpp"
  39 #include "classfile/systemDictionary.hpp"
  40 #include "classfile/verificationType.hpp"
  41 #include "classfile/verifier.hpp"
  42 #include "classfile/vmClasses.hpp"
  43 #include "classfile/vmSymbols.hpp"
  44 #include "jvm.h"
  45 #include "logging/log.hpp"
  46 #include "logging/logStream.hpp"
  47 #include "memory/allocation.hpp"
  48 #include "memory/metadataFactory.hpp"
  49 #include "memory/oopFactory.hpp"
  50 #include "memory/resourceArea.hpp"
  51 #include "memory/universe.hpp"
  52 #include "oops/annotations.hpp"
  53 #include "oops/constantPool.inline.hpp"
  54 #include "oops/fieldInfo.hpp"
  55 #include "oops/fieldStreams.inline.hpp"
  56 #include "oops/inlineKlass.inline.hpp"
  57 #include "oops/instanceKlass.inline.hpp"
  58 #include "oops/instanceMirrorKlass.hpp"
  59 #include "oops/klass.inline.hpp"
  60 #include "oops/klassVtable.hpp"
  61 #include "oops/metadata.hpp"
  62 #include "oops/method.inline.hpp"
  63 #include "oops/oop.inline.hpp"
  64 #include "oops/recordComponent.hpp"
  65 #include "oops/symbol.hpp"
  66 #include "prims/jvmtiExport.hpp"
  67 #include "prims/jvmtiThreadState.hpp"
  68 #include "runtime/arguments.hpp"
  69 #include "runtime/fieldDescriptor.inline.hpp"
  70 #include "runtime/handles.inline.hpp"
  71 #include "runtime/javaCalls.hpp"
  72 #include "runtime/os.hpp"
  73 #include "runtime/perfData.hpp"
  74 #include "runtime/reflection.hpp"
  75 #include "runtime/safepointVerifiers.hpp"
  76 #include "runtime/signature.hpp"
  77 #include "runtime/timer.hpp"
  78 #include "services/classLoadingService.hpp"
  79 #include "services/threadService.hpp"
  80 #include "utilities/align.hpp"
  81 #include "utilities/bitMap.inline.hpp"
  82 #include "utilities/checkedCast.hpp"
  83 #include "utilities/copy.hpp"
  84 #include "utilities/formatBuffer.hpp"
  85 #include "utilities/exceptions.hpp"
  86 #include "utilities/globalDefinitions.hpp"
  87 #include "utilities/growableArray.hpp"
  88 #include "utilities/macros.hpp"
  89 #include "utilities/ostream.hpp"
  90 #include "utilities/resourceHash.hpp"
  91 #include "utilities/stringUtils.hpp"
  92 #include "utilities/utf8.hpp"
  93 #if INCLUDE_CDS
  94 #include "classfile/systemDictionaryShared.hpp"
  95 #endif
  96 #if INCLUDE_JFR
  97 #include "jfr/support/jfrTraceIdExtension.hpp"
  98 #endif
  99 
 100 // We generally try to create the oops directly when parsing, rather than
 101 // allocating temporary data structures and copying the bytes twice. A
 102 // temporary area is only needed when parsing utf8 entries in the constant
 103 // pool and when parsing line number tables.
 104 
 105 // We add assert in debug mode when class format is not checked.
 106 
 107 #define JAVA_CLASSFILE_MAGIC              0xCAFEBABE
 108 #define JAVA_MIN_SUPPORTED_VERSION        45
 109 #define JAVA_PREVIEW_MINOR_VERSION        65535
 110 
 111 // Used for two backward compatibility reasons:

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

 501         check_property(valid_symbol_at(name_ref_index),
 502           "Invalid constant pool index %u in class file %s",
 503           name_ref_index, CHECK);
 504         check_property(valid_symbol_at(signature_ref_index),
 505           "Invalid constant pool index %u in class file %s",
 506           signature_ref_index, CHECK);
 507         break;
 508       }
 509       case JVM_CONSTANT_Utf8:
 510         break;
 511       case JVM_CONSTANT_UnresolvedClass:         // fall-through
 512       case JVM_CONSTANT_UnresolvedClassInError: {
 513         ShouldNotReachHere();     // Only JVM_CONSTANT_ClassIndex should be present
 514         break;
 515       }
 516       case JVM_CONSTANT_ClassIndex: {
 517         const int class_index = cp->klass_index_at(index);
 518         check_property(valid_symbol_at(class_index),
 519           "Invalid constant pool index %u in class file %s",
 520           class_index, CHECK);
 521 
 522         Symbol* const name = cp->symbol_at(class_index);
 523         const unsigned int name_len = name->utf8_length();
 524         cp->unresolved_klass_at_put(index, class_index, num_klasses++);
 525         break;
 526       }
 527       case JVM_CONSTANT_StringIndex: {
 528         const int string_index = cp->string_index_at(index);
 529         check_property(valid_symbol_at(string_index),
 530           "Invalid constant pool index %u in class file %s",
 531           string_index, CHECK);
 532         Symbol* const sym = cp->symbol_at(string_index);
 533         cp->unresolved_string_at_put(index, sym);
 534         break;
 535       }
 536       case JVM_CONSTANT_MethodHandle: {
 537         const int ref_index = cp->method_handle_index_at(index);
 538         check_property(valid_cp_range(ref_index, length),
 539           "Invalid constant pool index %u in class file %s",
 540           ref_index, CHECK);
 541         const constantTag tag = cp->tag_at(ref_index);
 542         const int ref_kind = cp->method_handle_ref_kind_at(index);
 543 

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

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

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

 856       check_property(
 857         valid_klass_reference_at(interface_index),
 858         "Interface name has bad constant pool index %u in class file %s",
 859         interface_index, CHECK);
 860       _local_interface_indexes->at_put_grow(index, interface_index);





























 861     }
 862 
 863     if (!_need_verify || itfs_len <= 1) {
 864       return;
 865     }
 866 
 867     // Check if there's any duplicates in interfaces
 868     ResourceMark rm(THREAD);
 869     // Set containing interface names
 870     ResourceHashtable<Symbol*, int>* interface_names = new ResourceHashtable<Symbol*, int>();
 871     for (index = 0; index < itfs_len; index++) {
 872       Symbol* interface_name = cp->klass_name_at(_local_interface_indexes->at(index));

 873       // If no duplicates, add (name, nullptr) in hashtable interface_names.
 874       if (!interface_names->put(interface_name, 0)) {
 875         classfile_parse_error("Duplicate interface name \"%s\" in class file %s",
 876                                interface_name->as_C_string(), THREAD);
 877         return;
 878       }
 879     }
 880   }
 881 }
 882 
 883 void ClassFileParser::verify_constantvalue(const ConstantPool* const cp,
 884                                            int constantvalue_index,
 885                                            int signature_index,
 886                                            TRAPS) const {
 887   // Make sure the constant pool entry is of a type appropriate to this field
 888   guarantee_property(
 889     (constantvalue_index > 0 &&
 890       constantvalue_index < cp->length()),
 891     "Bad initial value index %u in ConstantValue attribute in class file %s",
 892     constantvalue_index, CHECK);

 938 
 939 class AnnotationCollector : public ResourceObj{
 940 public:
 941   enum Location { _in_field, _in_method, _in_class };
 942   enum ID {
 943     _unknown = 0,
 944     _method_CallerSensitive,
 945     _method_ForceInline,
 946     _method_DontInline,
 947     _method_ChangesCurrentThread,
 948     _method_JvmtiMountTransition,
 949     _method_InjectedProfile,
 950     _method_LambdaForm_Compiled,
 951     _method_Hidden,
 952     _method_Scoped,
 953     _method_IntrinsicCandidate,
 954     _jdk_internal_vm_annotation_Contended,
 955     _field_Stable,
 956     _jdk_internal_vm_annotation_ReservedStackAccess,
 957     _jdk_internal_ValueBased,
 958     _jdk_internal_ImplicitlyConstructible,
 959     _jdk_internal_LooselyConsistentValue,
 960     _jdk_internal_NullRestricted,
 961     _java_lang_Deprecated,
 962     _java_lang_Deprecated_for_removal,
 963     _annotation_LIMIT
 964   };
 965   const Location _location;
 966   int _annotations_present;
 967   u2 _contended_group;
 968 
 969   AnnotationCollector(Location location)
 970     : _location(location), _annotations_present(0), _contended_group(0)
 971   {
 972     assert((int)_annotation_LIMIT <= (int)sizeof(_annotations_present) * BitsPerByte, "");
 973   }
 974   // If this annotation name has an ID, report it (or _none).
 975   ID annotation_index(const ClassLoaderData* loader_data, const Symbol* name, bool can_access_vm_annotations);
 976   // Set the annotation name:
 977   void set_annotation(ID id) {
 978     assert((int)id >= 0 && (int)id < (int)_annotation_LIMIT, "oob");
 979     _annotations_present |= (int)nth_bit((int)id);
 980   }

1348   AnnotationArray* a = allocate_annotations(runtime_visible_annotations,
1349                                             runtime_visible_annotations_length,
1350                                             CHECK);
1351   parsed_annotations->set_field_annotations(a);
1352   a = allocate_annotations(runtime_visible_type_annotations,
1353                            runtime_visible_type_annotations_length,
1354                            CHECK);
1355   parsed_annotations->set_field_type_annotations(a);
1356   return;
1357 }
1358 
1359 
1360 // Field allocation types. Used for computing field offsets.
1361 
1362 enum FieldAllocationType {
1363   STATIC_OOP,           // Oops
1364   STATIC_BYTE,          // Boolean, Byte, char
1365   STATIC_SHORT,         // shorts
1366   STATIC_WORD,          // ints
1367   STATIC_DOUBLE,        // aligned long or double
1368   STATIC_INLINE,        // inline type field
1369   NONSTATIC_OOP,
1370   NONSTATIC_BYTE,
1371   NONSTATIC_SHORT,
1372   NONSTATIC_WORD,
1373   NONSTATIC_DOUBLE,
1374   NONSTATIC_INLINE,
1375   MAX_FIELD_ALLOCATION_TYPE,
1376   BAD_ALLOCATION_TYPE = -1
1377 };
1378 
1379 static FieldAllocationType _basic_type_to_atype[2 * (T_CONFLICT + 1)] = {
1380   BAD_ALLOCATION_TYPE, // 0
1381   BAD_ALLOCATION_TYPE, // 1
1382   BAD_ALLOCATION_TYPE, // 2
1383   BAD_ALLOCATION_TYPE, // 3
1384   NONSTATIC_BYTE ,     // T_BOOLEAN     =  4,
1385   NONSTATIC_SHORT,     // T_CHAR        =  5,
1386   NONSTATIC_WORD,      // T_FLOAT       =  6,
1387   NONSTATIC_DOUBLE,    // T_DOUBLE      =  7,
1388   NONSTATIC_BYTE,      // T_BYTE        =  8,
1389   NONSTATIC_SHORT,     // T_SHORT       =  9,
1390   NONSTATIC_WORD,      // T_INT         = 10,
1391   NONSTATIC_DOUBLE,    // T_LONG        = 11,
1392   NONSTATIC_OOP,       // T_OBJECT      = 12,
1393   NONSTATIC_OOP,       // T_ARRAY       = 13,
1394   NONSTATIC_OOP,       // T_PRIMITIVE_OBJECT = 14,
1395   BAD_ALLOCATION_TYPE, // T_VOID        = 15,
1396   BAD_ALLOCATION_TYPE, // T_ADDRESS     = 16,
1397   BAD_ALLOCATION_TYPE, // T_NARROWOOP   = 17,
1398   BAD_ALLOCATION_TYPE, // T_METADATA    = 18,
1399   BAD_ALLOCATION_TYPE, // T_NARROWKLASS = 19,
1400   BAD_ALLOCATION_TYPE, // T_CONFLICT    = 20,
1401   BAD_ALLOCATION_TYPE, // 0
1402   BAD_ALLOCATION_TYPE, // 1
1403   BAD_ALLOCATION_TYPE, // 2
1404   BAD_ALLOCATION_TYPE, // 3
1405   STATIC_BYTE ,        // T_BOOLEAN     =  4,
1406   STATIC_SHORT,        // T_CHAR        =  5,
1407   STATIC_WORD,         // T_FLOAT       =  6,
1408   STATIC_DOUBLE,       // T_DOUBLE      =  7,
1409   STATIC_BYTE,         // T_BYTE        =  8,
1410   STATIC_SHORT,        // T_SHORT       =  9,
1411   STATIC_WORD,         // T_INT         = 10,
1412   STATIC_DOUBLE,       // T_LONG        = 11,
1413   STATIC_OOP,          // T_OBJECT      = 12,
1414   STATIC_OOP,          // T_ARRAY       = 13,
1415   STATIC_OOP,          // T_PRIMITIVE_OBJECT = 14,
1416   BAD_ALLOCATION_TYPE, // T_VOID        = 15,
1417   BAD_ALLOCATION_TYPE, // T_ADDRESS     = 16,
1418   BAD_ALLOCATION_TYPE, // T_NARROWOOP   = 17,
1419   BAD_ALLOCATION_TYPE, // T_METADATA    = 18,
1420   BAD_ALLOCATION_TYPE, // T_NARROWKLASS = 19,
1421   BAD_ALLOCATION_TYPE, // T_CONFLICT    = 20
1422 };
1423 
1424 static FieldAllocationType basic_type_to_atype(bool is_static, BasicType type, bool is_inline_type) {
1425   assert(type >= T_BOOLEAN && type < T_VOID, "only allowable values");
1426   FieldAllocationType result = _basic_type_to_atype[type + (is_static ? (T_CONFLICT + 1) : 0)];
1427   assert(result != BAD_ALLOCATION_TYPE, "bad type");
1428   if (is_inline_type) {
1429     result = is_static ? STATIC_INLINE : NONSTATIC_INLINE;
1430   }
1431   return result;
1432 }
1433 
1434 class ClassFileParser::FieldAllocationCount : public ResourceObj {
1435  public:
1436   u2 count[MAX_FIELD_ALLOCATION_TYPE];
1437 
1438   FieldAllocationCount() {
1439     for (int i = 0; i < MAX_FIELD_ALLOCATION_TYPE; i++) {
1440       count[i] = 0;
1441     }
1442   }
1443 
1444   void update(bool is_static, BasicType type, bool is_inline_type) {
1445     FieldAllocationType atype = basic_type_to_atype(is_static, type, is_inline_type);
1446     if (atype != BAD_ALLOCATION_TYPE) {
1447       // Make sure there is no overflow with injected fields.
1448       assert(count[atype] < 0xFFFF, "More than 65535 fields");
1449       count[atype]++;
1450     }
1451   }
1452 };
1453 
1454 // Side-effects: populates the _fields, _fields_annotations,
1455 // _fields_type_annotations fields
1456 void ClassFileParser::parse_fields(const ClassFileStream* const cfs,
1457                                    AccessFlags class_access_flags,
1458                                    FieldAllocationCount* const fac,
1459                                    ConstantPool* cp,
1460                                    const int cp_size,
1461                                    u2* const java_fields_count_ptr,
1462                                    TRAPS) {
1463 
1464   assert(cfs != nullptr, "invariant");
1465   assert(fac != nullptr, "invariant");
1466   assert(cp != nullptr, "invariant");
1467   assert(java_fields_count_ptr != nullptr, "invariant");
1468 
1469   assert(nullptr == _fields_annotations, "invariant");
1470   assert(nullptr == _fields_type_annotations, "invariant");
1471 
1472   bool is_inline_type = !class_access_flags.is_identity_class() && !class_access_flags.is_abstract();
1473   cfs->guarantee_more(2, CHECK);  // length
1474   const u2 length = cfs->get_u2_fast();
1475   *java_fields_count_ptr = length;
1476 
1477   int num_injected = 0;
1478   const InjectedField* const injected = JavaClasses::get_injected(_class_name,
1479                                                                   &num_injected);
1480 
1481   // two more slots are required for inline classes:
1482   // one for the static field with a reference to the pre-allocated default value
1483   // one for the field the JVM injects when detecting an empty inline class
1484   const int total_fields = length + num_injected + (is_inline_type ? 2 : 0);
1485 
1486   // Allocate a temporary resource array to collect field data.
1487   // After parsing all fields, data are stored in a UNSIGNED5 compressed stream.
1488   _temp_field_info = new GrowableArray<FieldInfo>(total_fields);
1489 
1490   int instance_fields_count = 0;
1491   ResourceMark rm(THREAD);
1492   for (int n = 0; n < length; n++) {
1493     // access_flags, name_index, descriptor_index, attributes_count
1494     cfs->guarantee_more(8, CHECK);
1495 
1496     jint recognized_modifiers = JVM_RECOGNIZED_FIELD_MODIFIERS;
1497     if (!supports_inline_types()) {
1498       recognized_modifiers &= ~JVM_ACC_STRICT;
1499     }
1500 
1501     const jint flags = cfs->get_u2_fast() & recognized_modifiers;
1502     verify_legal_field_modifiers(flags, class_access_flags, CHECK);
1503     AccessFlags access_flags;


1504     access_flags.set_flags(flags);
1505     FieldInfo::FieldFlags fieldFlags(0);
1506 
1507     const u2 name_index = cfs->get_u2_fast();
1508     check_property(valid_symbol_at(name_index),
1509       "Invalid constant pool index %u for field name in class file %s",
1510       name_index, CHECK);
1511     const Symbol* const name = cp->symbol_at(name_index);
1512     verify_legal_field_name(name, CHECK);
1513 
1514     const u2 signature_index = cfs->get_u2_fast();
1515     check_property(valid_symbol_at(signature_index),
1516       "Invalid constant pool index %u for field signature in class file %s",
1517       signature_index, CHECK);
1518     const Symbol* const sig = cp->symbol_at(signature_index);
1519     verify_legal_field_signature(name, sig, CHECK);
1520     if (!access_flags.is_static()) instance_fields_count++;
1521 
1522     u2 constantvalue_index = 0;
1523     bool is_synthetic = false;
1524     u2 generic_signature_index = 0;
1525     const bool is_static = access_flags.is_static();
1526     FieldAnnotationCollector parsed_annotations(_loader_data);
1527 
1528     bool is_null_restricted = false;
1529 
1530     const u2 attributes_count = cfs->get_u2_fast();
1531     if (attributes_count > 0) {
1532       parse_field_attributes(cfs,
1533                              attributes_count,
1534                              is_static,
1535                              signature_index,
1536                              &constantvalue_index,
1537                              &is_synthetic,
1538                              &generic_signature_index,
1539                              &parsed_annotations,
1540                              CHECK);
1541 
1542       if (parsed_annotations.field_annotations() != nullptr) {
1543         if (_fields_annotations == nullptr) {
1544           _fields_annotations = MetadataFactory::new_array<AnnotationArray*>(
1545                                              _loader_data, length, nullptr,
1546                                              CHECK);
1547         }
1548         _fields_annotations->at_put(n, parsed_annotations.field_annotations());
1549         if (parsed_annotations.has_annotation(AnnotationCollector::_jdk_internal_NullRestricted)) {
1550           if (!Signature::has_envelope(sig)) {
1551             Exceptions::fthrow(
1552               THREAD_AND_LOCATION,
1553               vmSymbols::java_lang_ClassFormatError(),
1554               "Illegal use of @jdk.internal.vm.annotation.NullRestricted annotation on field %s with signature %s (primitive types can never be null)",
1555               name->as_C_string(), sig->as_C_string());
1556           }
1557           is_null_restricted = true;
1558         }
1559         parsed_annotations.set_field_annotations(nullptr);
1560       }
1561       if (parsed_annotations.field_type_annotations() != nullptr) {
1562         if (_fields_type_annotations == nullptr) {
1563           _fields_type_annotations =
1564             MetadataFactory::new_array<AnnotationArray*>(_loader_data,
1565                                                          length,
1566                                                          nullptr,
1567                                                          CHECK);
1568         }
1569         _fields_type_annotations->at_put(n, parsed_annotations.field_type_annotations());
1570         parsed_annotations.set_field_type_annotations(nullptr);
1571       }
1572 
1573       if (is_synthetic) {
1574         access_flags.set_is_synthetic();
1575       }
1576       if (generic_signature_index != 0) {
1577         fieldFlags.update_generic(true);
1578       }
1579     }
1580 
1581     const BasicType type = cp->basic_type_for_signature_at(signature_index);
1582 
1583     // Update FieldAllocationCount for this kind of field
1584     // This use of T_PRIMITIVE_OBJECT is not valid anymore => FIXME (relate to cleanup (removal?) of FiedAllocationCount
1585     fac->update(is_static, type, type == T_PRIMITIVE_OBJECT);
1586 
1587     if (is_null_restricted) fieldFlags.update_null_free_inline_type(true);
1588 
1589     FieldInfo fi(access_flags, name_index, signature_index, constantvalue_index, fieldFlags);
1590     fi.set_index(n);
1591     if (fieldFlags.is_generic()) {
1592       fi.set_generic_signature_index(generic_signature_index);
1593     }
1594     parsed_annotations.apply_to(&fi);
1595     if (fi.field_flags().is_contended()) {
1596       _has_contended_fields = true;
1597     }
1598     _temp_field_info->append(fi);
1599   }
1600   assert(_temp_field_info->length() == length, "Must be");
1601 
1602   int index = length;
1603   if (num_injected != 0) {
1604     for (int n = 0; n < num_injected; n++) {
1605       // Check for duplicates
1606       if (injected[n].may_be_java) {
1607         const Symbol* const name      = injected[n].name();

1615             duplicate = true;
1616             break;
1617           }
1618         }
1619         if (duplicate) {
1620           // These will be removed from the field array at the end
1621           continue;
1622         }
1623       }
1624 
1625       // Injected field
1626       FieldInfo::FieldFlags fflags(0);
1627       fflags.update_injected(true);
1628       AccessFlags aflags;
1629       FieldInfo fi(aflags, (u2)(injected[n].name_index), (u2)(injected[n].signature_index), 0, fflags);
1630       fi.set_index(index);
1631       _temp_field_info->append(fi);
1632 
1633       // Update FieldAllocationCount for this kind of field
1634       const BasicType type = Signature::basic_type(injected[n].signature());
1635       fac->update(false, type, false);
1636       index++;
1637     }
1638   }
1639 
1640   if (is_inline_type) {
1641     // Inject static ".default" field
1642     FieldInfo::FieldFlags fflags(0);
1643     fflags.update_injected(true);
1644     AccessFlags aflags(JVM_ACC_STATIC);
1645     FieldInfo fi(aflags,
1646                  (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(default_value_name)),
1647                  (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(object_signature)),
1648                  0,
1649                  fflags);
1650       fi.set_index(index);
1651       _temp_field_info->append(fi);
1652 
1653     const BasicType type = Signature::basic_type(vmSymbols::object_signature());
1654     fac->update(true, type, false);
1655     index++;
1656   }
1657 
1658   if (is_inline_type && instance_fields_count == 0) {
1659     // Inject ".empty" dummy field
1660     _is_empty_inline_type = true;
1661 
1662     FieldInfo::FieldFlags fflags(0);
1663     fflags.update_injected(true);
1664     AccessFlags aflags;
1665     FieldInfo fi(aflags,
1666                  (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(empty_marker_name)),
1667                  (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(byte_signature)),
1668                  0,
1669                  fflags);
1670     fi.set_index(index);
1671     _temp_field_info->append(fi);
1672 
1673     const BasicType type = Signature::basic_type(vmSymbols::byte_signature());
1674     fac->update(false, type, false);
1675     index++;
1676   }
1677 
1678   if (instance_fields_count > 0) {
1679     _has_nonstatic_fields = true;
1680   }
1681 
1682   assert(_temp_field_info->length() == index, "Must be");
1683 
1684   if (_need_verify && length > 1) {
1685     // Check duplicated fields
1686     ResourceMark rm(THREAD);
1687     // Set containing name-signature pairs
1688     NameSigHashtable* names_and_sigs = new NameSigHashtable();
1689     for (int i = 0; i < _temp_field_info->length(); i++) {
1690       NameSigHash name_and_sig(_temp_field_info->adr_at(i)->name(_cp),
1691                                _temp_field_info->adr_at(i)->signature(_cp));
1692       // If no duplicates, add name/signature in hashtable names_and_sigs.
1693       if(!names_and_sigs->put(name_and_sig, 0)) {
1694         classfile_parse_error("Duplicate field name \"%s\" with signature \"%s\" in class file %s",
1695                                name_and_sig._name->as_C_string(), name_and_sig._sig->as_klass_external_name(), THREAD);
1696         return;
1697       }
1698     }
1699   }
1700 }
1701 

2036     }
2037     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Contended_signature): {
2038       if (_location != _in_field && _location != _in_class) {
2039         break;  // only allow for fields and classes
2040       }
2041       if (!EnableContended || (RestrictContended && !privileged)) {
2042         break;  // honor privileges
2043       }
2044       return _jdk_internal_vm_annotation_Contended;
2045     }
2046     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ReservedStackAccess_signature): {
2047       if (_location != _in_method)  break;  // only allow for methods
2048       if (RestrictReservedStack && !privileged) break; // honor privileges
2049       return _jdk_internal_vm_annotation_ReservedStackAccess;
2050     }
2051     case VM_SYMBOL_ENUM_NAME(jdk_internal_ValueBased_signature): {
2052       if (_location != _in_class)   break;  // only allow for classes
2053       if (!privileged)              break;  // only allow in privileged code
2054       return _jdk_internal_ValueBased;
2055     }
2056     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ImplicitlyConstructible_signature): {
2057       if (_location != _in_class)   break; // only allow for classes
2058       return _jdk_internal_ImplicitlyConstructible;
2059     }
2060     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_LooselyConsistentValue_signature): {
2061       if (_location != _in_class)   break; // only allow for classes
2062       return _jdk_internal_LooselyConsistentValue;
2063     }
2064     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_NullRestricted_signature): {
2065       if (_location != _in_field)   break; // only allow for fields
2066       return _jdk_internal_NullRestricted;
2067     }
2068     case VM_SYMBOL_ENUM_NAME(java_lang_Deprecated): {
2069       return _java_lang_Deprecated;
2070     }
2071     default: {
2072       break;
2073     }
2074   }
2075   return AnnotationCollector::_unknown;
2076 }
2077 
2078 void ClassFileParser::FieldAnnotationCollector::apply_to(FieldInfo* f) {
2079   if (is_contended())
2080     // Setting the contended group also sets the contended bit in field flags
2081     f->set_contended_group(contended_group());
2082   if (is_stable())
2083     (f->field_flags_addr())->update_stable(true);
2084 }
2085 
2086 ClassFileParser::FieldAnnotationCollector::~FieldAnnotationCollector() {
2087   // If there's an error deallocate metadata for field annotations

2269   }
2270 
2271   if (runtime_visible_type_annotations_length > 0) {
2272     a = allocate_annotations(runtime_visible_type_annotations,
2273                              runtime_visible_type_annotations_length,
2274                              CHECK);
2275     cm->set_type_annotations(a);
2276   }
2277 }
2278 
2279 
2280 // Note: the parse_method below is big and clunky because all parsing of the code and exceptions
2281 // attribute is inlined. This is cumbersome to avoid since we inline most of the parts in the
2282 // Method* to save footprint, so we only know the size of the resulting Method* when the
2283 // entire method attribute is parsed.
2284 //
2285 // The has_localvariable_table parameter is used to pass up the value to InstanceKlass.
2286 
2287 Method* ClassFileParser::parse_method(const ClassFileStream* const cfs,
2288                                       bool is_interface,
2289                                       bool is_value_class,
2290                                       bool is_abstract_class,
2291                                       const ConstantPool* cp,
2292                                       bool* const has_localvariable_table,
2293                                       TRAPS) {
2294   assert(cfs != nullptr, "invariant");
2295   assert(cp != nullptr, "invariant");
2296   assert(has_localvariable_table != nullptr, "invariant");
2297 
2298   ResourceMark rm(THREAD);
2299   // Parse fixed parts:
2300   // access_flags, name_index, descriptor_index, attributes_count
2301   cfs->guarantee_more(8, CHECK_NULL);
2302 
2303   int flags = cfs->get_u2_fast();
2304   const u2 name_index = cfs->get_u2_fast();
2305   const int cp_size = cp->length();
2306   check_property(
2307     valid_symbol_at(name_index),
2308     "Illegal constant pool index %u for method name in class file %s",
2309     name_index, CHECK_NULL);
2310   const Symbol* const name = cp->symbol_at(name_index);

2312 
2313   const u2 signature_index = cfs->get_u2_fast();
2314   guarantee_property(
2315     valid_symbol_at(signature_index),
2316     "Illegal constant pool index %u for method signature in class file %s",
2317     signature_index, CHECK_NULL);
2318   const Symbol* const signature = cp->symbol_at(signature_index);
2319 
2320   if (name == vmSymbols::class_initializer_name()) {
2321     // We ignore the other access flags for a valid class initializer.
2322     // (JVM Spec 2nd ed., chapter 4.6)
2323     if (_major_version < 51) { // backward compatibility
2324       flags = JVM_ACC_STATIC;
2325     } else if ((flags & JVM_ACC_STATIC) == JVM_ACC_STATIC) {
2326       flags &= JVM_ACC_STATIC | (_major_version <= JAVA_16_VERSION ? JVM_ACC_STRICT : 0);
2327     } else {
2328       classfile_parse_error("Method <clinit> is not static in class file %s", THREAD);
2329       return nullptr;
2330     }
2331   } else {
2332     verify_legal_method_modifiers(flags, access_flags() , name, CHECK_NULL);
2333   }
2334 
2335   if (name == vmSymbols::object_initializer_name() && is_interface) {
2336     classfile_parse_error("Interface cannot have a method named <init>, class file %s", THREAD);
2337     return nullptr;
2338   }
2339 
2340   if (EnableValhalla) {
2341     if (((flags & JVM_ACC_SYNCHRONIZED) == JVM_ACC_SYNCHRONIZED)
2342         && ((flags & JVM_ACC_STATIC) == 0 )
2343         && !_access_flags.is_identity_class()) {
2344       classfile_parse_error("Invalid synchronized method in non-identity class %s", THREAD);
2345         return nullptr;
2346     }
2347   }
2348 
2349   int args_size = -1;  // only used when _need_verify is true
2350   if (_need_verify) {
2351     verify_legal_name_with_signature(name, signature, CHECK_NULL);
2352     args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) +
2353                  verify_legal_method_signature(name, signature, CHECK_NULL);
2354     if (args_size > MAX_ARGS_SIZE) {
2355       classfile_parse_error("Too many arguments in method signature in class file %s", THREAD);
2356       return nullptr;
2357     }
2358   }
2359 
2360   AccessFlags access_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS);
2361 
2362   // Default values for code and exceptions attribute elements
2363   u2 max_stack = 0;
2364   u2 max_locals = 0;
2365   u4 code_length = 0;
2366   const u1* code_start = nullptr;
2367   u2 exception_table_length = 0;
2368   const unsafe_u2* exception_table_start = nullptr; // (potentially unaligned) pointer to array of u2 elements

2856                           CHECK_NULL);
2857 
2858   if (InstanceKlass::is_finalization_enabled() &&
2859       name == vmSymbols::finalize_method_name() &&
2860       signature == vmSymbols::void_method_signature()) {
2861     if (m->is_empty_method()) {
2862       _has_empty_finalizer = true;
2863     } else {
2864       _has_finalizer = true;
2865     }
2866   }
2867 
2868   NOT_PRODUCT(m->verify());
2869   return m;
2870 }
2871 
2872 
2873 // Side-effects: populates the _methods field in the parser
2874 void ClassFileParser::parse_methods(const ClassFileStream* const cfs,
2875                                     bool is_interface,
2876                                     bool is_value_class,
2877                                     bool is_abstract_type,
2878                                     bool* const has_localvariable_table,
2879                                     bool* has_final_method,
2880                                     bool* declares_nonstatic_concrete_methods,
2881                                     TRAPS) {
2882   assert(cfs != nullptr, "invariant");
2883   assert(has_localvariable_table != nullptr, "invariant");
2884   assert(has_final_method != nullptr, "invariant");
2885   assert(declares_nonstatic_concrete_methods != nullptr, "invariant");
2886 
2887   assert(nullptr == _methods, "invariant");
2888 
2889   cfs->guarantee_more(2, CHECK);  // length
2890   const u2 length = cfs->get_u2_fast();
2891   if (length == 0) {
2892     _methods = Universe::the_empty_method_array();
2893   } else {
2894     _methods = MetadataFactory::new_array<Method*>(_loader_data,
2895                                                    length,
2896                                                    nullptr,
2897                                                    CHECK);
2898 
2899     for (int index = 0; index < length; index++) {
2900       Method* method = parse_method(cfs,
2901                                     is_interface,
2902                                     is_value_class,
2903                                     is_abstract_type,
2904                                     _cp,
2905                                     has_localvariable_table,
2906                                     CHECK);
2907 
2908       if (method->is_final()) {
2909         *has_final_method = true;
2910       }
2911       // declares_nonstatic_concrete_methods: declares concrete instance methods, any access flags
2912       // used for interface initialization, and default method inheritance analysis
2913       if (is_interface && !(*declares_nonstatic_concrete_methods)
2914         && !method->is_abstract() && !method->is_static()) {
2915         *declares_nonstatic_concrete_methods = true;
2916       }
2917       _methods->at_put(index, method);
2918     }
2919 
2920     if (_need_verify && length > 1) {
2921       // Check duplicated methods
2922       ResourceMark rm(THREAD);
2923       // Set containing name-signature pairs

3149         valid_klass_reference_at(outer_class_info_index),
3150       "outer_class_info_index %u has bad constant type in class file %s",
3151       outer_class_info_index, CHECK_0);
3152 
3153     if (outer_class_info_index != 0) {
3154       const Symbol* const outer_class_name = cp->klass_name_at(outer_class_info_index);
3155       char* bytes = (char*)outer_class_name->bytes();
3156       guarantee_property(bytes[0] != JVM_SIGNATURE_ARRAY,
3157                          "Outer class is an array class in class file %s", CHECK_0);
3158     }
3159     // Inner class name
3160     const u2 inner_name_index = cfs->get_u2_fast();
3161     check_property(
3162       inner_name_index == 0 || valid_symbol_at(inner_name_index),
3163       "inner_name_index %u has bad constant type in class file %s",
3164       inner_name_index, CHECK_0);
3165     if (_need_verify) {
3166       guarantee_property(inner_class_info_index != outer_class_info_index,
3167                          "Class is both outer and inner class in class file %s", CHECK_0);
3168     }
3169 
3170     jint recognized_modifiers = RECOGNIZED_INNER_CLASS_MODIFIERS;
3171     // JVM_ACC_MODULE is defined in JDK-9 and later.
3172     if (_major_version >= JAVA_9_VERSION) {
3173       recognized_modifiers |= JVM_ACC_MODULE;


3174     }
3175 
3176     // Access flags
3177     jint flags = cfs->get_u2_fast() & recognized_modifiers;
3178 
3179     if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
3180       // Set abstract bit for old class files for backward compatibility
3181       flags |= JVM_ACC_ABSTRACT;
3182     }
3183 
3184     if (!supports_inline_types()) {
3185       const bool is_module = (flags & JVM_ACC_MODULE) != 0;
3186       const bool is_interface = (flags & JVM_ACC_INTERFACE) != 0;
3187       if (!is_module && !is_interface) {
3188         flags |= JVM_ACC_IDENTITY;
3189       }
3190     }
3191 
3192     const char* name = inner_name_index == 0 ? "unnamed" : cp->symbol_at(inner_name_index)->as_utf8();
3193     verify_legal_class_modifiers(flags, name, false, CHECK_0);
3194     AccessFlags inner_access_flags(flags);
3195 
3196     inner_classes->at_put(index++, inner_class_info_index);
3197     inner_classes->at_put(index++, outer_class_info_index);
3198     inner_classes->at_put(index++, inner_name_index);
3199     inner_classes->at_put(index++, inner_access_flags.as_short());
3200   }
3201 
3202   // Check for circular and duplicate entries.
3203   bool has_circularity = false;
3204   if (_need_verify) {
3205     has_circularity = check_inner_classes_circularity(cp, length * 4, CHECK_0);
3206     if (has_circularity) {
3207       // If circularity check failed then ignore InnerClasses attribute.
3208       MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
3209       index = 0;
3210       if (parsed_enclosingmethod_attribute) {
3211         inner_classes = MetadataFactory::new_array<u2>(_loader_data, 2, CHECK_0);
3212         _inner_classes = inner_classes;
3213       } else {

3277   if (length > 0) {
3278     int index = 0;
3279     cfs->guarantee_more(2 * length, CHECK_0);
3280     for (int n = 0; n < length; n++) {
3281       const u2 class_info_index = cfs->get_u2_fast();
3282       check_property(
3283         valid_klass_reference_at(class_info_index),
3284         "Permitted subclass class_info_index %u has bad constant type in class file %s",
3285         class_info_index, CHECK_0);
3286       permitted_subclasses->at_put(index++, class_info_index);
3287     }
3288     assert(index == size, "wrong size");
3289   }
3290 
3291   // Restore buffer's current position.
3292   cfs->set_current(current_mark);
3293 
3294   return length;
3295 }
3296 
3297 u2 ClassFileParser::parse_classfile_loadable_descriptors_attribute(const ClassFileStream* const cfs,
3298                                                                    const u1* const loadable_descriptors_attribute_start,
3299                                                                    TRAPS) {
3300   const u1* const current_mark = cfs->current();
3301   u2 length = 0;
3302   if (loadable_descriptors_attribute_start != nullptr) {
3303     cfs->set_current(loadable_descriptors_attribute_start);
3304     cfs->guarantee_more(2, CHECK_0);  // length
3305     length = cfs->get_u2_fast();
3306   }
3307   const int size = length;
3308   Array<u2>* const loadable_descriptors = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
3309   _loadable_descriptors = loadable_descriptors;
3310   if (length > 0) {
3311     int index = 0;
3312     cfs->guarantee_more(2 * length, CHECK_0);
3313     for (int n = 0; n < length; n++) {
3314       const u2 descriptor_index = cfs->get_u2_fast();
3315       check_property(
3316         valid_symbol_at(descriptor_index),
3317         "LoadableDescriptors descriptor_index %u has bad constant type in class file %s",
3318         descriptor_index, CHECK_0);
3319       Symbol* descriptor = _cp->symbol_at(descriptor_index);
3320       bool valid = legal_field_signature(descriptor, CHECK_0);
3321       if(!valid) {
3322         ResourceMark rm(THREAD);
3323         Exceptions::fthrow(THREAD_AND_LOCATION,
3324           vmSymbols::java_lang_ClassFormatError(),
3325           "Descriptor from LoadableDescriptors attribute at index \"%d\" in class %s has illegal signature \"%s\"",
3326           descriptor_index, _class_name->as_C_string(), descriptor->as_C_string());
3327         return 0;
3328       }
3329       loadable_descriptors->at_put(index++, descriptor_index);
3330     }
3331     assert(index == size, "wrong size");
3332   }
3333 
3334   // Restore buffer's current position.
3335   cfs->set_current(current_mark);
3336 
3337   return length;
3338 }
3339 
3340 //  Record {
3341 //    u2 attribute_name_index;
3342 //    u4 attribute_length;
3343 //    u2 components_count;
3344 //    component_info components[components_count];
3345 //  }
3346 //  component_info {
3347 //    u2 name_index;
3348 //    u2 descriptor_index
3349 //    u2 attributes_count;
3350 //    attribute_info_attributes[attributes_count];
3351 //  }
3352 u4 ClassFileParser::parse_classfile_record_attribute(const ClassFileStream* const cfs,
3353                                                      const ConstantPool* cp,
3354                                                      const u1* const record_attribute_start,
3355                                                      TRAPS) {
3356   const u1* const current_mark = cfs->current();
3357   int components_count = 0;
3358   unsigned int calculate_attr_size = 0;
3359   if (record_attribute_start != nullptr) {

3585   }
3586   guarantee_property(current_start + attribute_byte_length == cfs->current(),
3587                      "Bad length on BootstrapMethods in class file %s",
3588                      CHECK);
3589 }
3590 
3591 void ClassFileParser::parse_classfile_attributes(const ClassFileStream* const cfs,
3592                                                  ConstantPool* cp,
3593                  ClassFileParser::ClassAnnotationCollector* parsed_annotations,
3594                                                  TRAPS) {
3595   assert(cfs != nullptr, "invariant");
3596   assert(cp != nullptr, "invariant");
3597   assert(parsed_annotations != nullptr, "invariant");
3598 
3599   // Set inner classes attribute to default sentinel
3600   _inner_classes = Universe::the_empty_short_array();
3601   // Set nest members attribute to default sentinel
3602   _nest_members = Universe::the_empty_short_array();
3603   // Set _permitted_subclasses attribute to default sentinel
3604   _permitted_subclasses = Universe::the_empty_short_array();
3605   // Set _loadable_descriptors attribute to default sentinel
3606   _loadable_descriptors = Universe::the_empty_short_array();
3607   cfs->guarantee_more(2, CHECK);  // attributes_count
3608   u2 attributes_count = cfs->get_u2_fast();
3609   bool parsed_sourcefile_attribute = false;
3610   bool parsed_innerclasses_attribute = false;
3611   bool parsed_nest_members_attribute = false;
3612   bool parsed_permitted_subclasses_attribute = false;
3613   bool parsed_loadable_descriptors_attribute = false;
3614   bool parsed_nest_host_attribute = false;
3615   bool parsed_record_attribute = false;
3616   bool parsed_enclosingmethod_attribute = false;
3617   bool parsed_bootstrap_methods_attribute = false;
3618   const u1* runtime_visible_annotations = nullptr;
3619   int runtime_visible_annotations_length = 0;
3620   const u1* runtime_visible_type_annotations = nullptr;
3621   int runtime_visible_type_annotations_length = 0;
3622   bool runtime_invisible_type_annotations_exists = false;
3623   bool runtime_invisible_annotations_exists = false;
3624   bool parsed_source_debug_ext_annotations_exist = false;
3625   const u1* inner_classes_attribute_start = nullptr;
3626   u4  inner_classes_attribute_length = 0;
3627   u2  enclosing_method_class_index = 0;
3628   u2  enclosing_method_method_index = 0;
3629   const u1* nest_members_attribute_start = nullptr;
3630   u4  nest_members_attribute_length = 0;
3631   const u1* record_attribute_start = nullptr;
3632   u4  record_attribute_length = 0;
3633   const u1* permitted_subclasses_attribute_start = nullptr;
3634   u4  permitted_subclasses_attribute_length = 0;
3635   const u1* loadable_descriptors_attribute_start = nullptr;
3636   u4  loadable_descriptors_attribute_length = 0;
3637 
3638   // Iterate over attributes
3639   while (attributes_count--) {
3640     cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
3641     const u2 attribute_name_index = cfs->get_u2_fast();
3642     const u4 attribute_length = cfs->get_u4_fast();
3643     check_property(
3644       valid_symbol_at(attribute_name_index),
3645       "Attribute name has bad constant pool index %u in class file %s",
3646       attribute_name_index, CHECK);
3647     const Symbol* const tag = cp->symbol_at(attribute_name_index);
3648     if (tag == vmSymbols::tag_source_file()) {
3649       // Check for SourceFile tag
3650       if (_need_verify) {
3651         guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
3652       }
3653       if (parsed_sourcefile_attribute) {
3654         classfile_parse_error("Multiple SourceFile attributes in class file %s", THREAD);
3655         return;
3656       } else {

3832               return;
3833             }
3834             parsed_record_attribute = true;
3835             record_attribute_start = cfs->current();
3836             record_attribute_length = attribute_length;
3837           } else if (_major_version >= JAVA_17_VERSION) {
3838             if (tag == vmSymbols::tag_permitted_subclasses()) {
3839               if (parsed_permitted_subclasses_attribute) {
3840                 classfile_parse_error("Multiple PermittedSubclasses attributes in class file %s", CHECK);
3841                 return;
3842               }
3843               // Classes marked ACC_FINAL cannot have a PermittedSubclasses attribute.
3844               if (_access_flags.is_final()) {
3845                 classfile_parse_error("PermittedSubclasses attribute in final class file %s", CHECK);
3846                 return;
3847               }
3848               parsed_permitted_subclasses_attribute = true;
3849               permitted_subclasses_attribute_start = cfs->current();
3850               permitted_subclasses_attribute_length = attribute_length;
3851             }
3852             if (EnableValhalla && tag == vmSymbols::tag_loadable_descriptors()) {
3853               if (parsed_loadable_descriptors_attribute) {
3854                 classfile_parse_error("Multiple LoadableDescriptors attributes in class file %s", CHECK);
3855                 return;
3856               }
3857               parsed_loadable_descriptors_attribute = true;
3858               loadable_descriptors_attribute_start = cfs->current();
3859               loadable_descriptors_attribute_length = attribute_length;
3860             }
3861           }
3862           // Skip attribute_length for any attribute where major_verson >= JAVA_17_VERSION
3863           cfs->skip_u1(attribute_length, CHECK);
3864         } else {
3865           // Unknown attribute
3866           cfs->skip_u1(attribute_length, CHECK);
3867         }
3868       } else {
3869         // Unknown attribute
3870         cfs->skip_u1(attribute_length, CHECK);
3871       }
3872     } else {
3873       // Unknown attribute
3874       cfs->skip_u1(attribute_length, CHECK);
3875     }
3876   }
3877   _class_annotations = allocate_annotations(runtime_visible_annotations,
3878                                             runtime_visible_annotations_length,
3879                                             CHECK);
3880   _class_type_annotations = allocate_annotations(runtime_visible_type_annotations,

3917                             CHECK);
3918     if (_need_verify) {
3919       guarantee_property(record_attribute_length == calculated_attr_length,
3920                          "Record attribute has wrong length in class file %s",
3921                          CHECK);
3922     }
3923   }
3924 
3925   if (parsed_permitted_subclasses_attribute) {
3926     const u2 num_subclasses = parse_classfile_permitted_subclasses_attribute(
3927                             cfs,
3928                             permitted_subclasses_attribute_start,
3929                             CHECK);
3930     if (_need_verify) {
3931       guarantee_property(
3932         permitted_subclasses_attribute_length == sizeof(num_subclasses) + sizeof(u2) * num_subclasses,
3933         "Wrong PermittedSubclasses attribute length in class file %s", CHECK);
3934     }
3935   }
3936 
3937   if (parsed_loadable_descriptors_attribute) {
3938     const u2 num_classes = parse_classfile_loadable_descriptors_attribute(
3939                             cfs,
3940                             loadable_descriptors_attribute_start,
3941                             CHECK);
3942     if (_need_verify) {
3943       guarantee_property(
3944         loadable_descriptors_attribute_length == sizeof(num_classes) + sizeof(u2) * num_classes,
3945         "Wrong LoadableDescriptors attribute length in class file %s", CHECK);
3946     }
3947   }
3948 
3949   if (_max_bootstrap_specifier_index >= 0) {
3950     guarantee_property(parsed_bootstrap_methods_attribute,
3951                        "Missing BootstrapMethods attribute in class file %s", CHECK);
3952   }
3953 }
3954 
3955 void ClassFileParser::apply_parsed_class_attributes(InstanceKlass* k) {
3956   assert(k != nullptr, "invariant");
3957 
3958   if (_synthetic_flag)
3959     k->set_is_synthetic();
3960   if (_sourcefile_index != 0) {
3961     k->set_source_file_name_index(_sourcefile_index);
3962   }
3963   if (_generic_signature_index != 0) {
3964     k->set_generic_signature_index(_generic_signature_index);
3965   }
3966   if (_sde_buffer != nullptr) {
3967     k->set_source_debug_extension(_sde_buffer, _sde_length);
3968   }

3994     _class_annotations       = nullptr;
3995     _class_type_annotations  = nullptr;
3996     _fields_annotations      = nullptr;
3997     _fields_type_annotations = nullptr;
3998 }
3999 
4000 // Transfer ownership of metadata allocated to the InstanceKlass.
4001 void ClassFileParser::apply_parsed_class_metadata(
4002                                             InstanceKlass* this_klass,
4003                                             int java_fields_count) {
4004   assert(this_klass != nullptr, "invariant");
4005 
4006   _cp->set_pool_holder(this_klass);
4007   this_klass->set_constants(_cp);
4008   this_klass->set_fieldinfo_stream(_fieldinfo_stream);
4009   this_klass->set_fields_status(_fields_status);
4010   this_klass->set_methods(_methods);
4011   this_klass->set_inner_classes(_inner_classes);
4012   this_klass->set_nest_members(_nest_members);
4013   this_klass->set_nest_host_index(_nest_host);
4014   this_klass->set_loadable_descriptors(_loadable_descriptors);
4015   this_klass->set_annotations(_combined_annotations);
4016   this_klass->set_permitted_subclasses(_permitted_subclasses);
4017   this_klass->set_record_components(_record_components);
4018   this_klass->set_inline_type_field_klasses_array(_inline_type_field_klasses);
4019   this_klass->set_null_marker_offsets_array(_null_marker_offsets);
4020   // Delay the setting of _local_interfaces and _transitive_interfaces until after
4021   // initialize_supers() in fill_instance_klass(). It is because the _local_interfaces could
4022   // be shared with _transitive_interfaces and _transitive_interfaces may be shared with
4023   // its _super. If an OOM occurs while loading the current klass, its _super field
4024   // may not have been set. When GC tries to free the klass, the _transitive_interfaces
4025   // may be deallocated mistakenly in InstanceKlass::deallocate_interfaces(). Subsequent
4026   // dereferences to the deallocated _transitive_interfaces will result in a crash.
4027 
4028   // Clear out these fields so they don't get deallocated by the destructor
4029   clear_class_metadata();
4030 }
4031 
4032 AnnotationArray* ClassFileParser::allocate_annotations(const u1* const anno,
4033                                                        int anno_length,
4034                                                        TRAPS) {
4035   AnnotationArray* annotations = nullptr;
4036   if (anno != nullptr) {
4037     annotations = MetadataFactory::new_array<u1>(_loader_data,
4038                                                  anno_length,
4039                                                  CHECK_(annotations));
4040     for (int i = 0; i < anno_length; i++) {
4041       annotations->at_put(i, anno[i]);
4042     }
4043   }
4044   return annotations;
4045 }
4046 
4047 const InstanceKlass* ClassFileParser::parse_super_class(ConstantPool* const cp,
4048                                                         const int super_class_index,
4049                                                         const bool need_verify,
4050                                                         TRAPS) {
4051   assert(cp != nullptr, "invariant");
4052   const InstanceKlass* super_klass = nullptr;
4053 
4054   if (super_class_index == 0) {
4055     check_property(_class_name == vmSymbols::java_lang_Object(),
4056                    "Invalid superclass index 0 in class file %s",

4057                    CHECK_NULL);
4058   } else {
4059     check_property(valid_klass_reference_at(super_class_index),
4060                    "Invalid superclass index %u in class file %s",
4061                    super_class_index,
4062                    CHECK_NULL);
4063     // The class name should be legal because it is checked when parsing constant pool.
4064     // However, make sure it is not an array type.

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




4067     }
4068     if (need_verify) {
4069       bool is_array = (cp->klass_name_at(super_class_index)->char_at(0) == JVM_SIGNATURE_ARRAY);
4070       guarantee_property(!is_array,
4071                         "Bad superclass name in class file %s", CHECK_NULL);
4072     }
4073   }
4074   return super_klass;
4075 }
4076 
4077 OopMapBlocksBuilder::OopMapBlocksBuilder(unsigned int max_blocks) {
4078   _max_nonstatic_oop_maps = max_blocks;
4079   _nonstatic_oop_map_count = 0;
4080   if (max_blocks == 0) {
4081     _nonstatic_oop_maps = nullptr;
4082   } else {
4083     _nonstatic_oop_maps =
4084         NEW_RESOURCE_ARRAY(OopMapBlock, _max_nonstatic_oop_maps);
4085     memset(_nonstatic_oop_maps, 0, sizeof(OopMapBlock) * max_blocks);
4086   }
4087 }
4088 
4089 OopMapBlock* OopMapBlocksBuilder::last_oop_map() const {

4223 
4224   // Check if this klass supports the java.lang.Cloneable interface
4225   if (vmClasses::Cloneable_klass_loaded()) {
4226     if (ik->is_subtype_of(vmClasses::Cloneable_klass())) {
4227       ik->set_is_cloneable();
4228     }
4229   }
4230 
4231   // If it cannot be fast-path allocated, set a bit in the layout helper.
4232   // See documentation of InstanceKlass::can_be_fastpath_allocated().
4233   assert(ik->size_helper() > 0, "layout_helper is initialized");
4234   if (ik->is_abstract() || ik->is_interface()
4235       || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == nullptr)
4236       || ik->size_helper() >= FastAllocateSizeLimit) {
4237     // Forbid fast-path allocation.
4238     const jint lh = Klass::instance_layout_helper(ik->size_helper(), true);
4239     ik->set_layout_helper(lh);
4240   }
4241 }
4242 
4243 bool ClassFileParser::supports_inline_types() const {
4244   // Inline types are only supported by class file version 68.65535 and later
4245   return _major_version > JAVA_24_VERSION ||
4246          (_major_version == JAVA_24_VERSION && _minor_version == JAVA_PREVIEW_MINOR_VERSION);
4247 }
4248 
4249 // utility methods for appending an array with check for duplicates
4250 
4251 static void append_interfaces(GrowableArray<InstanceKlass*>* result,
4252                               const Array<InstanceKlass*>* const ifs) {
4253   // iterate over new interfaces
4254   for (int i = 0; i < ifs->length(); i++) {
4255     InstanceKlass* const e = ifs->at(i);
4256     assert(e->is_klass() && e->is_interface(), "just checking");
4257     // add new interface
4258     result->append_if_missing(e);
4259   }
4260 }
4261 
4262 static Array<InstanceKlass*>* compute_transitive_interfaces(const InstanceKlass* super,
4263                                                             Array<InstanceKlass*>* local_ifs,
4264                                                             ClassLoaderData* loader_data,
4265                                                             TRAPS) {
4266   assert(local_ifs != nullptr, "invariant");
4267   assert(loader_data != nullptr, "invariant");
4268 

4272   // Add superclass transitive interfaces size
4273   if (super != nullptr) {
4274     super_size = super->transitive_interfaces()->length();
4275     max_transitive_size += super_size;
4276   }
4277   // Add local interfaces' super interfaces
4278   const int local_size = local_ifs->length();
4279   for (int i = 0; i < local_size; i++) {
4280     InstanceKlass* const l = local_ifs->at(i);
4281     max_transitive_size += l->transitive_interfaces()->length();
4282   }
4283   // Finally add local interfaces
4284   max_transitive_size += local_size;
4285   // Construct array
4286   if (max_transitive_size == 0) {
4287     // no interfaces, use canonicalized array
4288     return Universe::the_empty_instance_klass_array();
4289   } else if (max_transitive_size == super_size) {
4290     // no new local interfaces added, share superklass' transitive interface array
4291     return super->transitive_interfaces();
4292     // The three lines below are commented to work around bug JDK-8245487
4293 //  } else if (max_transitive_size == local_size) {
4294 //    // only local interfaces added, share local interface array
4295 //    return local_ifs;
4296   } else {
4297     ResourceMark rm;
4298     GrowableArray<InstanceKlass*>* const result = new GrowableArray<InstanceKlass*>(max_transitive_size);
4299 
4300     // Copy down from superclass
4301     if (super != nullptr) {
4302       append_interfaces(result, super->transitive_interfaces());
4303     }
4304 
4305     // Copy down from local interfaces' superinterfaces
4306     for (int i = 0; i < local_size; i++) {
4307       InstanceKlass* const l = local_ifs->at(i);
4308       append_interfaces(result, l->transitive_interfaces());
4309     }
4310     // Finally add local interfaces
4311     append_interfaces(result, local_ifs);
4312 
4313     // length will be less than the max_transitive_size if duplicates were removed
4314     const int length = result->length();
4315     assert(length <= max_transitive_size, "just checking");
4316 
4317     Array<InstanceKlass*>* const new_result =
4318       MetadataFactory::new_array<InstanceKlass*>(loader_data, length, CHECK_NULL);
4319     for (int i = 0; i < length; i++) {
4320       InstanceKlass* const e = result->at(i);
4321       assert(e != nullptr, "just checking");
4322       new_result->at_put(i, e);
4323     }
4324     return new_result;
4325   }
4326 }
4327 
4328 void ClassFileParser::check_super_class_access(const InstanceKlass* this_klass, TRAPS) {
4329   assert(this_klass != nullptr, "invariant");
4330   const Klass* const super = this_klass->super();
4331 
4332   if (super != nullptr) {
4333     const InstanceKlass* super_ik = InstanceKlass::cast(super);
4334 
4335     if (super->is_final()) {
4336       classfile_icce_error("class %s cannot inherit from final class %s", super_ik, THREAD);
4337       return;
4338     }
4339 
4340     if (super_ik->is_sealed() && !super_ik->has_as_permitted_subclass(this_klass)) {
4341       classfile_icce_error("class %s cannot inherit from sealed class %s", super_ik, THREAD);
4342       return;
4343     }
4344 
4345     // The JVMS says that super classes for value types must not have the ACC_IDENTITY
4346     // flag set. But, java.lang.Object must still be allowed to be a direct super class
4347     // for a value classes.  So, it is treated as a special case for now.
4348     if (!this_klass->access_flags().is_identity_class() &&
4349         super_ik->name() != vmSymbols::java_lang_Object() &&
4350         super_ik->is_identity_class()) {
4351       classfile_icce_error("value class %s cannot inherit from class %s", super_ik, THREAD);
4352       return;
4353     }
4354 
4355     // If the loader is not the boot loader then throw an exception if its
4356     // superclass is in package jdk.internal.reflect and its loader is not a
4357     // special reflection class loader
4358     if (!this_klass->class_loader_data()->is_the_null_class_loader_data()) {
4359       PackageEntry* super_package = super->package();
4360       if (super_package != nullptr &&
4361           super_package->name()->fast_compare(vmSymbols::jdk_internal_reflect()) == 0 &&
4362           !java_lang_ClassLoader::is_reflection_class_loader(this_klass->class_loader())) {
4363         ResourceMark rm(THREAD);
4364         Exceptions::fthrow(
4365           THREAD_AND_LOCATION,
4366           vmSymbols::java_lang_IllegalAccessError(),
4367           "class %s loaded by %s cannot access jdk/internal/reflect superclass %s",
4368           this_klass->external_name(),
4369           this_klass->class_loader_data()->loader_name_and_id(),
4370           super->external_name());
4371         return;
4372       }
4373     }
4374 

4520 
4521   for (int index = 0; index < num_methods; index++) {
4522     const Method* const m = methods->at(index);
4523     // if m is static and not the init method, throw a verify error
4524     if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) {
4525       ResourceMark rm(THREAD);
4526       Exceptions::fthrow(
4527         THREAD_AND_LOCATION,
4528         vmSymbols::java_lang_VerifyError(),
4529         "Illegal static method %s in interface %s",
4530         m->name()->as_C_string(),
4531         this_klass->external_name()
4532       );
4533       return;
4534     }
4535   }
4536 }
4537 
4538 // utility methods for format checking
4539 
4540 void ClassFileParser::verify_legal_class_modifiers(jint flags, const char* name, bool is_Object, TRAPS) const {
4541   const bool is_module = (flags & JVM_ACC_MODULE) != 0;
4542   const bool is_inner_class = name != nullptr;
4543   assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");
4544   if (is_module) {
4545     ResourceMark rm(THREAD);
4546     Exceptions::fthrow(
4547       THREAD_AND_LOCATION,
4548       vmSymbols::java_lang_NoClassDefFoundError(),
4549       "%s is not a class because access_flag ACC_MODULE is set",
4550       _class_name->as_C_string());
4551     return;
4552   }
4553 
4554   if (!_need_verify) { return; }
4555 
4556   const bool is_interface  = (flags & JVM_ACC_INTERFACE)  != 0;
4557   const bool is_abstract   = (flags & JVM_ACC_ABSTRACT)   != 0;
4558   const bool is_final      = (flags & JVM_ACC_FINAL)      != 0;
4559   const bool is_identity   = (flags & JVM_ACC_IDENTITY)   != 0;
4560   const bool is_enum       = (flags & JVM_ACC_ENUM)       != 0;
4561   const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4562   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4563   const bool valid_value_class = is_identity || is_interface ||
4564                                  (supports_inline_types() && (!is_identity && (is_abstract || is_final)));
4565 
4566   if ((is_abstract && is_final) ||
4567       (is_interface && !is_abstract) ||
4568       (is_interface && major_gte_1_5 && (is_identity || is_enum)) ||   //  ACC_SUPER (now ACC_IDENTITY) was illegal for interfaces
4569       (!is_interface && major_gte_1_5 && is_annotation) ||
4570       (!valid_value_class)) {
4571     ResourceMark rm(THREAD);
4572     const char* class_note = "";
4573     if (!valid_value_class) {
4574       class_note = " (a value class must be final or else abstract)";
4575     }
4576     if (name == nullptr) { // Not an inner class
4577       Exceptions::fthrow(
4578         THREAD_AND_LOCATION,
4579         vmSymbols::java_lang_ClassFormatError(),
4580         "Illegal class modifiers in class %s%s: 0x%X",
4581         _class_name->as_C_string(), class_note, flags
4582       );
4583       return;
4584     } else {
4585       Exceptions::fthrow(
4586         THREAD_AND_LOCATION,
4587         vmSymbols::java_lang_ClassFormatError(),
4588         "Illegal class modifiers in declaration of inner class %s%s of class %s: 0x%X",
4589         name, class_note, _class_name->as_C_string(), flags
4590       );
4591       return;
4592     }
4593   }
4594 }
4595 
4596 static bool has_illegal_visibility(jint flags) {
4597   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4598   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4599   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4600 
4601   return ((is_public && is_protected) ||
4602           (is_public && is_private) ||
4603           (is_protected && is_private));
4604 }
4605 
4606 // A legal major_version.minor_version must be one of the following:
4607 //
4608 //  Major_version >= 45 and major_version < 56, any minor_version.
4609 //  Major_version >= 56 and major_version <= JVM_CLASSFILE_MAJOR_VERSION and minor_version = 0.
4610 //  Major_version = JVM_CLASSFILE_MAJOR_VERSION and minor_version = 65535 and --enable-preview is present.
4611 //
4612 void ClassFileParser::verify_class_version(u2 major, u2 minor, Symbol* class_name, TRAPS){

4638         THREAD_AND_LOCATION,
4639         vmSymbols::java_lang_UnsupportedClassVersionError(),
4640         "%s (class file version %u.%u) was compiled with preview features that are unsupported. "
4641         "This version of the Java Runtime only recognizes preview features for class file version %u.%u",
4642         class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION, JAVA_PREVIEW_MINOR_VERSION);
4643       return;
4644     }
4645 
4646     if (!Arguments::enable_preview()) {
4647       classfile_ucve_error("Preview features are not enabled for %s (class file version %u.%u). Try running with '--enable-preview'",
4648                            class_name, major, minor, THREAD);
4649       return;
4650     }
4651 
4652   } else { // minor != JAVA_PREVIEW_MINOR_VERSION
4653     classfile_ucve_error("%s (class file version %u.%u) was compiled with an invalid non-zero minor version",
4654                          class_name, major, minor, THREAD);
4655   }
4656 }
4657 
4658 void ClassFileParser:: verify_legal_field_modifiers(jint flags,
4659                                                    AccessFlags class_access_flags,
4660                                                    TRAPS) const {
4661   if (!_need_verify) { return; }
4662 
4663   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4664   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4665   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4666   const bool is_static    = (flags & JVM_ACC_STATIC)    != 0;
4667   const bool is_final     = (flags & JVM_ACC_FINAL)     != 0;
4668   const bool is_volatile  = (flags & JVM_ACC_VOLATILE)  != 0;
4669   const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
4670   const bool is_enum      = (flags & JVM_ACC_ENUM)      != 0;
4671   const bool is_strict    = (flags & JVM_ACC_STRICT)    != 0;
4672   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4673 
4674   const bool is_interface = class_access_flags.is_interface();
4675   const bool is_identity_class = class_access_flags.is_identity_class();
4676 
4677   bool is_illegal = false;
4678   const char* error_msg = "";
4679 
4680   // There is some overlap in the checks that apply, for example interface fields
4681   // must be static, static fields can't be strict, and therefore interfaces can't
4682   // have strict fields. So we don't have to check every possible invalid combination
4683   // individually as long as all are covered. Once we have found an illegal combination
4684   // we can stop checking.
4685 
4686   if (supports_inline_types()) {
4687     if (is_strict && is_static) {
4688       is_illegal = true;
4689       error_msg = "field cannot be strict and static";
4690     }
4691     else if (is_strict && !is_final) {

4692       is_illegal = true;
4693       error_msg = "strict field must be final";
4694     }
4695   }
4696 
4697   if (!is_illegal) {
4698     if (is_interface) {
4699       if (!is_public || !is_static || !is_final || is_private ||
4700           is_protected || is_volatile || is_transient ||
4701           (major_gte_1_5 && is_enum)) {
4702         is_illegal = true;
4703         error_msg = "interface fields must be public, static and final, and may be synthetic";
4704       }
4705     } else { // not interface
4706       if (has_illegal_visibility(flags)) {
4707         is_illegal = true;
4708         error_msg = "invalid visibility flags for class field";
4709       } else if (is_final && is_volatile) {
4710         is_illegal = true;
4711         error_msg = "fields cannot be final and volatile";
4712       } else if (supports_inline_types()) {
4713         if (!is_identity_class && !is_static && !is_strict) {
4714           is_illegal = true;
4715           error_msg = "value class fields must be either strict or static";
4716         }
4717       }
4718     }
4719   }
4720 
4721   if (is_illegal) {
4722     ResourceMark rm(THREAD);
4723     Exceptions::fthrow(
4724       THREAD_AND_LOCATION,
4725       vmSymbols::java_lang_ClassFormatError(),
4726       "Illegal field modifiers (%s) in class %s: 0x%X",
4727       error_msg, _class_name->as_C_string(), flags);
4728     return;
4729   }
4730 }
4731 
4732 void ClassFileParser::verify_legal_method_modifiers(jint flags,
4733                                                     AccessFlags class_access_flags,
4734                                                     const Symbol* name,
4735                                                     TRAPS) const {
4736   if (!_need_verify) { return; }
4737 
4738   const bool is_public       = (flags & JVM_ACC_PUBLIC)       != 0;
4739   const bool is_private      = (flags & JVM_ACC_PRIVATE)      != 0;
4740   const bool is_static       = (flags & JVM_ACC_STATIC)       != 0;
4741   const bool is_final        = (flags & JVM_ACC_FINAL)        != 0;
4742   const bool is_native       = (flags & JVM_ACC_NATIVE)       != 0;
4743   const bool is_abstract     = (flags & JVM_ACC_ABSTRACT)     != 0;
4744   const bool is_bridge       = (flags & JVM_ACC_BRIDGE)       != 0;
4745   const bool is_strict       = (flags & JVM_ACC_STRICT)       != 0;
4746   const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
4747   const bool is_protected    = (flags & JVM_ACC_PROTECTED)    != 0;
4748   const bool major_gte_1_5   = _major_version >= JAVA_1_5_VERSION;
4749   const bool major_gte_8     = _major_version >= JAVA_8_VERSION;
4750   const bool major_gte_17    = _major_version >= JAVA_17_VERSION;
4751   const bool is_initializer  = (name == vmSymbols::object_initializer_name());
4752   // LW401 CR required: removal of value factories support
4753   const bool is_interface    = class_access_flags.is_interface();
4754   const bool is_identity_class = class_access_flags.is_identity_class();
4755   const bool is_abstract_class = class_access_flags.is_abstract();
4756 
4757   bool is_illegal = false;
4758 
4759   const char* class_note = "";
4760   if (is_interface) {
4761     if (major_gte_8) {
4762       // Class file version is JAVA_8_VERSION or later Methods of
4763       // interfaces may set any of the flags except ACC_PROTECTED,
4764       // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must
4765       // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.
4766       if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
4767           (is_native || is_protected || is_final || is_synchronized) ||
4768           // If a specific method of a class or interface has its
4769           // ACC_ABSTRACT flag set, it must not have any of its
4770           // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,
4771           // ACC_STRICT, or ACC_SYNCHRONIZED flags set.  No need to
4772           // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as
4773           // those flags are illegal irrespective of ACC_ABSTRACT being set or not.
4774           (is_abstract && (is_private || is_static || (!major_gte_17 && is_strict)))) {
4775         is_illegal = true;
4776       }
4777     } else if (major_gte_1_5) {
4778       // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)
4779       if (!is_public || is_private || is_protected || is_static || is_final ||
4780           is_synchronized || is_native || !is_abstract || is_strict) {
4781         is_illegal = true;
4782       }
4783     } else {
4784       // Class file version is pre-JAVA_1_5_VERSION
4785       if (!is_public || is_static || is_final || is_native || !is_abstract) {
4786         is_illegal = true;
4787       }
4788     }
4789   } else { // not interface
4790     if (has_illegal_visibility(flags)) {
4791       is_illegal = true;
4792     } else {
4793       if (is_initializer) {
4794         if (is_static || is_final || is_synchronized || is_native ||
4795             is_abstract || (major_gte_1_5 && is_bridge)) {
4796           is_illegal = true;
4797         }
4798       } else { // not initializer
4799         if (!is_identity_class && is_synchronized && !is_static) {
4800           is_illegal = true;
4801           class_note = " (not an identity class)";
4802         } else {
4803           if (is_abstract) {
4804             if ((is_final || is_native || is_private || is_static ||
4805                 (major_gte_1_5 && (is_synchronized || (!major_gte_17 && is_strict))))) {
4806               is_illegal = true;
4807             }
4808           }
4809         }
4810       }
4811     }
4812   }
4813 
4814   if (is_illegal) {
4815     ResourceMark rm(THREAD);
4816     Exceptions::fthrow(
4817       THREAD_AND_LOCATION,
4818       vmSymbols::java_lang_ClassFormatError(),
4819       "Method %s in class %s%s has illegal modifiers: 0x%X",
4820       name->as_C_string(), _class_name->as_C_string(),
4821       class_note, flags);
4822     return;
4823   }
4824 }
4825 
4826 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer,
4827                                         int length,
4828                                         TRAPS) const {
4829   assert(_need_verify, "only called when _need_verify is true");
4830   // Note: 0 <= length < 64K, as it comes from a u2 entry in the CP.
4831   if (!UTF8::is_legal_utf8(buffer, static_cast<size_t>(length), _major_version <= 47)) {
4832     classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", THREAD);
4833   }
4834 }
4835 
4836 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
4837 // In class names, '/' separates unqualified names.  This is verified in this function also.
4838 // Method names also may not contain the characters '<' or '>', unless <init>
4839 // or <clinit>.  Note that method names may not be <init> or <clinit> in this
4840 // method.  Because these names have been checked as special cases before
4841 // calling this method in verify_legal_method_name.

4859         if (type == ClassFileParser::LegalClass) {
4860           if (p == name || p+1 >= name+length ||
4861               *(p+1) == JVM_SIGNATURE_SLASH) {
4862             return false;
4863           }
4864         } else {
4865           return false;   // do not permit '/' unless it's class name
4866         }
4867         break;
4868       case JVM_SIGNATURE_SPECIAL:
4869       case JVM_SIGNATURE_ENDSPECIAL:
4870         // do not permit '<' or '>' in method names
4871         if (type == ClassFileParser::LegalMethod) {
4872           return false;
4873         }
4874     }
4875   }
4876   return true;
4877 }
4878 
4879 bool ClassFileParser::is_class_in_loadable_descriptors_attribute(Symbol *klass) {
4880   if (_loadable_descriptors == nullptr) return false;
4881   for (int i = 0; i < _loadable_descriptors->length(); i++) {
4882         Symbol* class_name = _cp->symbol_at(_loadable_descriptors->at(i));
4883         if (class_name == klass) return true;
4884   }
4885   return false;
4886 }
4887 
4888 // Take pointer to a UTF8 byte string (not NUL-terminated).
4889 // Skip over the longest part of the string that could
4890 // be taken as a fieldname. Allow non-trailing '/'s if slash_ok is true.
4891 // Return a pointer to just past the fieldname.
4892 // Return null if no fieldname at all was found, or in the case of slash_ok
4893 // being true, we saw consecutive slashes (meaning we were looking for a
4894 // qualified path but found something that was badly-formed).
4895 static const char* skip_over_field_name(const char* const name,
4896                                         bool slash_ok,
4897                                         unsigned int length) {
4898   const char* p;
4899   jboolean last_is_slash = false;
4900   jboolean not_first_ch = false;
4901 
4902   for (p = name; p != name + length; not_first_ch = true) {
4903     const char* old_p = p;
4904     jchar ch = *p;
4905     if (ch < 128) {
4906       p++;
4907       // quick check for ascii

4969 // be taken as a field signature. Allow "void" if void_ok.
4970 // Return a pointer to just past the signature.
4971 // Return null if no legal signature is found.
4972 const char* ClassFileParser::skip_over_field_signature(const char* signature,
4973                                                        bool void_ok,
4974                                                        unsigned int length,
4975                                                        TRAPS) const {
4976   unsigned int array_dim = 0;
4977   while (length > 0) {
4978     switch (signature[0]) {
4979     case JVM_SIGNATURE_VOID: if (!void_ok) { return nullptr; }
4980     case JVM_SIGNATURE_BOOLEAN:
4981     case JVM_SIGNATURE_BYTE:
4982     case JVM_SIGNATURE_CHAR:
4983     case JVM_SIGNATURE_SHORT:
4984     case JVM_SIGNATURE_INT:
4985     case JVM_SIGNATURE_FLOAT:
4986     case JVM_SIGNATURE_LONG:
4987     case JVM_SIGNATURE_DOUBLE:
4988       return signature + 1;
4989     case JVM_SIGNATURE_CLASS:
4990     {
4991       if (_major_version < JAVA_1_5_VERSION) {
4992         // Skip over the class name if one is there
4993         const char* const p = skip_over_field_name(signature + 1, true, --length);
4994 
4995         // The next character better be a semicolon
4996         if (p && (p - signature) > 1 && p[0] == JVM_SIGNATURE_ENDCLASS) {
4997           return p + 1;
4998         }
4999       }
5000       else {
5001         // Skip leading 'L' or 'Q' and ignore first appearance of ';'
5002         signature++;
5003         const char* c = (const char*) memchr(signature, JVM_SIGNATURE_ENDCLASS, length - 1);
5004         // Format check signature
5005         if (c != nullptr) {
5006           int newlen = pointer_delta_as_int(c, (char*) signature);
5007           bool legal = verify_unqualified_name(signature, newlen, LegalClass);
5008           if (!legal) {
5009             classfile_parse_error("Class name is empty or contains illegal character "
5010                                   "in descriptor in class file %s",
5011                                   THREAD);
5012             return nullptr;
5013           }
5014           return signature + newlen + 1;
5015         }
5016       }
5017       return nullptr;
5018     }
5019     case JVM_SIGNATURE_ARRAY:
5020       array_dim++;
5021       if (array_dim > 255) {

5037 
5038 // Checks if name is a legal class name.
5039 void ClassFileParser::verify_legal_class_name(const Symbol* name, TRAPS) const {
5040   if (!_need_verify || _relax_verify) { return; }
5041 
5042   assert(name->refcount() > 0, "symbol must be kept alive");
5043   char* bytes = (char*)name->bytes();
5044   unsigned int length = name->utf8_length();
5045   bool legal = false;
5046 
5047   if (length > 0) {
5048     const char* p;
5049     if (bytes[0] == JVM_SIGNATURE_ARRAY) {
5050       p = skip_over_field_signature(bytes, false, length, CHECK);
5051       legal = (p != nullptr) && ((p - bytes) == (int)length);
5052     } else if (_major_version < JAVA_1_5_VERSION) {
5053       if (bytes[0] != JVM_SIGNATURE_SPECIAL) {
5054         p = skip_over_field_name(bytes, true, length);
5055         legal = (p != nullptr) && ((p - bytes) == (int)length);
5056       }
5057     } else if ((_major_version >= CONSTANT_CLASS_DESCRIPTORS || _class_name->starts_with("jdk/internal/reflect/"))
5058                    && bytes[length - 1] == ';' ) {
5059       // Support for L...; descriptors
5060       legal = verify_unqualified_name(bytes + 1, length - 2, LegalClass);
5061     } else {
5062       // 4900761: relax the constraints based on JSR202 spec
5063       // Class names may be drawn from the entire Unicode character set.
5064       // Identifiers between '/' must be unqualified names.
5065       // The utf8 string has been verified when parsing cpool entries.
5066       legal = verify_unqualified_name(bytes, length, LegalClass);
5067     }
5068   }
5069   if (!legal) {
5070     ResourceMark rm(THREAD);
5071     assert(_class_name != nullptr, "invariant");
5072     Exceptions::fthrow(
5073       THREAD_AND_LOCATION,
5074       vmSymbols::java_lang_ClassFormatError(),
5075       "Illegal class name \"%.*s\" in class file %s", length, bytes,
5076       _class_name->as_C_string()
5077     );
5078     return;
5079   }
5080 }

5106       THREAD_AND_LOCATION,
5107       vmSymbols::java_lang_ClassFormatError(),
5108       "Illegal field name \"%.*s\" in class %s", length, bytes,
5109       _class_name->as_C_string()
5110     );
5111     return;
5112   }
5113 }
5114 
5115 // Checks if name is a legal method name.
5116 void ClassFileParser::verify_legal_method_name(const Symbol* name, TRAPS) const {
5117   if (!_need_verify || _relax_verify) { return; }
5118 
5119   assert(name != nullptr, "method name is null");
5120   char* bytes = (char*)name->bytes();
5121   unsigned int length = name->utf8_length();
5122   bool legal = false;
5123 
5124   if (length > 0) {
5125     if (bytes[0] == JVM_SIGNATURE_SPECIAL) {
5126       if (name == vmSymbols::object_initializer_name() ||
5127           name == vmSymbols::class_initializer_name()) {
5128         legal = true;
5129       }
5130     } else if (_major_version < JAVA_1_5_VERSION) {
5131       const char* p;
5132       p = skip_over_field_name(bytes, false, length);
5133       legal = (p != nullptr) && ((p - bytes) == (int)length);
5134     } else {
5135       // 4881221: relax the constraints based on JSR202 spec
5136       legal = verify_unqualified_name(bytes, length, LegalMethod);
5137     }
5138   }
5139 
5140   if (!legal) {
5141     ResourceMark rm(THREAD);
5142     assert(_class_name != nullptr, "invariant");
5143     Exceptions::fthrow(
5144       THREAD_AND_LOCATION,
5145       vmSymbols::java_lang_ClassFormatError(),
5146       "Illegal method name \"%.*s\" in class %s", length, bytes,
5147       _class_name->as_C_string()
5148     );
5149     return;
5150   }
5151 }
5152 
5153 bool ClassFileParser::legal_field_signature(const Symbol* signature, TRAPS) const {
5154   const char* const bytes = (const char*)signature->bytes();
5155   const unsigned int length = signature->utf8_length();
5156   const char* const p = skip_over_field_signature(bytes, false, length, CHECK_false);
5157 
5158   if (p == nullptr || (p - bytes) != (int)length) {
5159     return false;
5160   }
5161   return true;
5162 }
5163 
5164 // Checks if signature is a legal field signature.
5165 void ClassFileParser::verify_legal_field_signature(const Symbol* name,
5166                                                    const Symbol* signature,
5167                                                    TRAPS) const {
5168   if (!_need_verify) { return; }
5169 
5170   const char* const bytes = (const char*)signature->bytes();
5171   const unsigned int length = signature->utf8_length();
5172   const char* const p = skip_over_field_signature(bytes, false, length, CHECK);
5173 
5174   if (p == nullptr || (p - bytes) != (int)length) {
5175     throwIllegalSignature("Field", name, signature, CHECK);
5176   }
5177 }
5178 
5179 // Check that the signature is compatible with the method name.  For example,
5180 // check that <init> has a void signature.
5181 void ClassFileParser::verify_legal_name_with_signature(const Symbol* name,
5182                                                        const Symbol* signature,
5183                                                        TRAPS) const {
5184   if (!_need_verify) {
5185     return;
5186   }
5187 
5188   // Class initializers cannot have args for class format version >= 51.
5189   if (name == vmSymbols::class_initializer_name() &&
5190       signature != vmSymbols::void_method_signature() &&
5191       _major_version >= JAVA_7_VERSION) {
5192     throwIllegalSignature("Method", name, signature, THREAD);
5193     return;
5194   }
5195 
5196   int sig_length = signature->utf8_length();
5197   if (name->utf8_length() > 0 &&
5198     name->char_at(0) == JVM_SIGNATURE_SPECIAL &&
5199     sig_length > 0 &&
5200     signature->char_at(sig_length - 1) != JVM_SIGNATURE_VOID) {
5201     throwIllegalSignature("Method", name, signature, THREAD);
5202   }
5203 }
5204 
5205 // Checks if signature is a legal method signature.
5206 // Returns number of parameters
5207 int ClassFileParser::verify_legal_method_signature(const Symbol* name,
5208                                                    const Symbol* signature,
5209                                                    TRAPS) const {
5210   if (!_need_verify) {
5211     // make sure caller's args_size will be less than 0 even for non-static
5212     // method so it will be recomputed in compute_size_of_parameters().
5213     return -2;
5214   }
5215 
5216   unsigned int args_size = 0;
5217   const char* p = (const char*)signature->bytes();
5218   unsigned int length = signature->utf8_length();
5219   const char* nextp;
5220 

5357   }
5358 }
5359 
5360 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook,
5361                                                       const ClassInstanceInfo& cl_inst_info,
5362                                                       TRAPS) {
5363   if (_klass != nullptr) {
5364     return _klass;
5365   }
5366 
5367   InstanceKlass* const ik =
5368     InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
5369 
5370   if (is_hidden()) {
5371     mangle_hidden_class_name(ik);
5372   }
5373 
5374   fill_instance_klass(ik, changed_by_loadhook, cl_inst_info, CHECK_NULL);
5375 
5376   assert(_klass == ik, "invariant");

5377   return ik;
5378 }
5379 
5380 void ClassFileParser::fill_instance_klass(InstanceKlass* ik,
5381                                           bool changed_by_loadhook,
5382                                           const ClassInstanceInfo& cl_inst_info,
5383                                           TRAPS) {
5384   assert(ik != nullptr, "invariant");
5385 
5386   // Set name and CLD before adding to CLD
5387   ik->set_class_loader_data(_loader_data);
5388   ik->set_name(_class_name);
5389 
5390   // Add all classes to our internal class loader list here,
5391   // including classes in the bootstrap (null) class loader.
5392   const bool publicize = !is_internal();
5393 
5394   _loader_data->add_class(ik, publicize);
5395 
5396   set_klass_to_deallocate(ik);
5397 
5398   assert(_field_info != nullptr, "invariant");
5399   assert(ik->static_field_size() == _field_info->_static_field_size, "sanity");
5400   assert(ik->nonstatic_oop_map_count() == _field_info->oop_map_blocks->_nonstatic_oop_map_count,
5401          "sanity");
5402 
5403   assert(ik->is_instance_klass(), "sanity");
5404   assert(ik->size_helper() == _field_info->_instance_size, "sanity");
5405 
5406   // Fill in information already parsed
5407   ik->set_should_verify_class(_need_verify);
5408 
5409   // Not yet: supers are done below to support the new subtype-checking fields
5410   ik->set_nonstatic_field_size(_field_info->_nonstatic_field_size);
5411   ik->set_has_nonstatic_fields(_field_info->_has_nonstatic_fields);
5412   if (_field_info->_is_naturally_atomic && ik->is_inline_klass()) {
5413     ik->set_is_naturally_atomic();
5414   }
5415 
5416   assert(_fac != nullptr, "invariant");
5417   ik->set_static_oop_field_count(_fac->count[STATIC_OOP] + _fac->count[STATIC_INLINE]);
5418 
5419   // this transfers ownership of a lot of arrays from
5420   // the parser onto the InstanceKlass*
5421   apply_parsed_class_metadata(ik, _java_fields_count);
5422   if (ik->is_inline_klass()) {
5423     InlineKlass::cast(ik)->init_fixed_block();
5424   }
5425 
5426   // can only set dynamic nest-host after static nest information is set
5427   if (cl_inst_info.dynamic_nest_host() != nullptr) {
5428     ik->set_nest_host(cl_inst_info.dynamic_nest_host());
5429   }
5430 
5431   // note that is not safe to use the fields in the parser from this point on
5432   assert(nullptr == _cp, "invariant");
5433   assert(nullptr == _fieldinfo_stream, "invariant");
5434   assert(nullptr == _fields_status, "invariant");
5435   assert(nullptr == _methods, "invariant");
5436   assert(nullptr == _inner_classes, "invariant");
5437   assert(nullptr == _nest_members, "invariant");
5438   assert(nullptr == _loadable_descriptors, "invariant");
5439   assert(nullptr == _combined_annotations, "invariant");
5440   assert(nullptr == _record_components, "invariant");
5441   assert(nullptr == _permitted_subclasses, "invariant");
5442   assert(nullptr == _inline_type_field_klasses, "invariant");
5443 
5444   if (_has_localvariable_table) {
5445     ik->set_has_localvariable_table(true);
5446   }
5447 
5448   if (_has_final_method) {
5449     ik->set_has_final_method();
5450   }
5451 
5452   ik->copy_method_ordering(_method_ordering, CHECK);
5453   // The InstanceKlass::_methods_jmethod_ids cache
5454   // is managed on the assumption that the initial cache
5455   // size is equal to the number of methods in the class. If
5456   // that changes, then InstanceKlass::idnum_can_increment()
5457   // has to be changed accordingly.
5458   ik->set_initial_method_idnum(checked_cast<u2>(ik->methods()->length()));
5459 
5460   ik->set_this_class_index(_this_class_index);
5461 
5462   if (_is_hidden) {
5463     // _this_class_index is a CONSTANT_Class entry that refers to this
5464     // hidden class itself. If this class needs to refer to its own methods
5465     // or fields, it would use a CONSTANT_MethodRef, etc, which would reference
5466     // _this_class_index. However, because this class is hidden (it's
5467     // not stored in SystemDictionary), _this_class_index cannot be resolved
5468     // with ConstantPool::klass_at_impl, which does a SystemDictionary lookup.
5469     // Therefore, we must eagerly resolve _this_class_index now.
5470     ik->constants()->klass_at_put(_this_class_index, ik);
5471   }
5472 
5473   ik->set_minor_version(_minor_version);
5474   ik->set_major_version(_major_version);
5475   ik->set_has_nonstatic_concrete_methods(_has_nonstatic_concrete_methods);
5476   ik->set_declares_nonstatic_concrete_methods(_declares_nonstatic_concrete_methods);
5477 
5478   if (_must_be_atomic) {
5479     ik->set_must_be_atomic();
5480   }
5481   if (_is_implicitly_constructible) {
5482     ik->set_is_implicitly_constructible();
5483   }
5484   assert(!_is_hidden || ik->is_hidden(), "must be set already");
5485 
5486   // Set PackageEntry for this_klass
5487   oop cl = ik->class_loader();
5488   Handle clh = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(cl));
5489   ClassLoaderData* cld = ClassLoaderData::class_loader_data_or_null(clh());
5490   ik->set_package(cld, nullptr, CHECK);
5491 
5492   const Array<Method*>* const methods = ik->methods();
5493   assert(methods != nullptr, "invariant");
5494   const int methods_len = methods->length();
5495 
5496   check_methods_for_intrinsics(ik, methods);
5497 
5498   // Fill in field values obtained by parse_classfile_attributes
5499   if (_parsed_annotations->has_any_annotations()) {
5500     _parsed_annotations->apply_to(ik);
5501   }
5502 
5503   apply_parsed_class_attributes(ik);

5568 
5569   assert(_all_mirandas != nullptr, "invariant");
5570 
5571   // Generate any default methods - default methods are public interface methods
5572   // that have a default implementation.  This is new with Java 8.
5573   if (_has_nonstatic_concrete_methods) {
5574     DefaultMethods::generate_default_methods(ik,
5575                                              _all_mirandas,
5576                                              CHECK);
5577   }
5578 
5579   // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5580   if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5581       !module_entry->has_default_read_edges()) {
5582     if (!module_entry->set_has_default_read_edges()) {
5583       // We won a potential race
5584       JvmtiExport::add_default_read_edges(module_handle, THREAD);
5585     }
5586   }
5587 
5588   bool all_fields_empty = true;
5589   for (AllFieldStream fs(ik); !fs.done(); fs.next()) {
5590     if (!fs.access_flags().is_static()) {
5591       if (fs.field_descriptor().is_null_free_inline_type()) {
5592         Klass* k = ik->inline_type_field_klasses_array()->at(fs.index());
5593         assert(k->is_inline_klass(), "must be");
5594         if (!InlineKlass::cast(k)->is_empty_inline_type()) { all_fields_empty = false; }
5595       } else {
5596         all_fields_empty = false;
5597       }
5598     } else if (is_inline_type() && (fs.name() == vmSymbols::default_value_name())) {
5599       InlineKlass::cast(ik)->set_default_value_offset(ik->field_offset(fs.index()));
5600     }
5601   }
5602 
5603   if (_is_empty_inline_type || (is_inline_type() && all_fields_empty)) {
5604     ik->set_is_empty_inline_type();
5605   }
5606 
5607   if (is_inline_type()) {
5608     InlineKlass* vk = InlineKlass::cast(ik);
5609     vk->set_alignment(_alignment);
5610     vk->set_first_field_offset(_first_field_offset);
5611     vk->set_payload_size_in_bytes(_payload_size_in_bytes);
5612     vk->set_internal_null_marker_offset(_internal_null_marker_offset);
5613     InlineKlass::cast(ik)->initialize_calling_convention(CHECK);
5614   }
5615 
5616   ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5617 
5618   if (!is_internal()) {
5619     ik->print_class_load_logging(_loader_data, module_entry, _stream);
5620 
5621     if (ik->minor_version() == JAVA_PREVIEW_MINOR_VERSION &&
5622         ik->major_version() == JVM_CLASSFILE_MAJOR_VERSION &&
5623         log_is_enabled(Info, class, preview)) {
5624       ResourceMark rm;
5625       log_info(class, preview)("Loading class %s that depends on preview features (class file version %d.65535)",
5626                                ik->external_name(), JVM_CLASSFILE_MAJOR_VERSION);
5627     }
5628 
5629     if (log_is_enabled(Debug, class, resolve))  {
5630       ResourceMark rm;
5631       // print out the superclass.
5632       const char * from = ik->external_name();
5633       if (ik->java_super() != nullptr) {
5634         log_debug(class, resolve)("%s %s (super)",
5635                    from,

5687                                  Symbol* name,
5688                                  ClassLoaderData* loader_data,
5689                                  const ClassLoadInfo* cl_info,
5690                                  Publicity pub_level,
5691                                  TRAPS) :
5692   _stream(stream),
5693   _class_name(nullptr),
5694   _loader_data(loader_data),
5695   _is_hidden(cl_info->is_hidden()),
5696   _can_access_vm_annotations(cl_info->can_access_vm_annotations()),
5697   _orig_cp_size(0),
5698   _super_klass(),
5699   _cp(nullptr),
5700   _fieldinfo_stream(nullptr),
5701   _fields_status(nullptr),
5702   _methods(nullptr),
5703   _inner_classes(nullptr),
5704   _nest_members(nullptr),
5705   _nest_host(0),
5706   _permitted_subclasses(nullptr),
5707   _loadable_descriptors(nullptr),
5708   _record_components(nullptr),
5709   _local_interfaces(nullptr),
5710   _local_interface_indexes(nullptr),
5711   _transitive_interfaces(nullptr),
5712   _combined_annotations(nullptr),
5713   _class_annotations(nullptr),
5714   _class_type_annotations(nullptr),
5715   _fields_annotations(nullptr),
5716   _fields_type_annotations(nullptr),
5717   _klass(nullptr),
5718   _klass_to_deallocate(nullptr),
5719   _parsed_annotations(nullptr),
5720   _fac(nullptr),
5721   _field_info(nullptr),
5722   _inline_type_field_klasses(nullptr),
5723   _null_marker_offsets(nullptr),
5724   _temp_field_info(nullptr),
5725   _method_ordering(nullptr),
5726   _all_mirandas(nullptr),
5727   _vtable_size(0),
5728   _itable_size(0),
5729   _num_miranda_methods(0),
5730   _protection_domain(cl_info->protection_domain()),
5731   _access_flags(),
5732   _pub_level(pub_level),
5733   _bad_constant_seen(0),
5734   _synthetic_flag(false),
5735   _sde_length(false),
5736   _sde_buffer(nullptr),
5737   _sourcefile_index(0),
5738   _generic_signature_index(0),
5739   _major_version(0),
5740   _minor_version(0),
5741   _this_class_index(0),
5742   _super_class_index(0),
5743   _itfs_len(0),
5744   _java_fields_count(0),
5745   _need_verify(false),
5746   _relax_verify(false),
5747   _has_nonstatic_concrete_methods(false),
5748   _declares_nonstatic_concrete_methods(false),
5749   _has_localvariable_table(false),
5750   _has_final_method(false),
5751   _has_contended_fields(false),
5752   _has_inline_type_fields(false),
5753   _has_nonstatic_fields(false),
5754   _is_empty_inline_type(false),
5755   _is_naturally_atomic(false),
5756   _must_be_atomic(true),
5757   _is_implicitly_constructible(false),
5758   _has_loosely_consistent_annotation(false),
5759   _has_implicitly_constructible_annotation(false),
5760   _has_finalizer(false),
5761   _has_empty_finalizer(false),
5762   _max_bootstrap_specifier_index(-1) {
5763 
5764   _class_name = name != nullptr ? name : vmSymbols::unknown_class_name();
5765   _class_name->increment_refcount();
5766 
5767   assert(_loader_data != nullptr, "invariant");
5768   assert(stream != nullptr, "invariant");
5769   assert(_stream != nullptr, "invariant");
5770   assert(_stream->buffer() == _stream->current(), "invariant");
5771   assert(_class_name != nullptr, "invariant");
5772   assert(0 == _access_flags.as_int(), "invariant");
5773 
5774   // Figure out whether we can skip format checking (matching classic VM behavior)
5775   if (CDSConfig::is_dumping_static_archive()) {
5776     // verify == true means it's a 'remote' class (i.e., non-boot class)
5777     // Verification decision is based on BytecodeVerificationRemote flag
5778     // for those classes.
5779     _need_verify = (stream->need_verify()) ? BytecodeVerificationRemote :

5789 
5790   // Check if verification needs to be relaxed for this class file
5791   // Do not restrict it to jdk1.0 or jdk1.1 to maintain backward compatibility (4982376)
5792   _relax_verify = relax_format_check_for(_loader_data);
5793 
5794   parse_stream(stream, CHECK);
5795 
5796   post_process_parsed_stream(stream, _cp, CHECK);
5797 }
5798 
5799 void ClassFileParser::clear_class_metadata() {
5800   // metadata created before the instance klass is created.  Must be
5801   // deallocated if classfile parsing returns an error.
5802   _cp = nullptr;
5803   _fieldinfo_stream = nullptr;
5804   _fields_status = nullptr;
5805   _methods = nullptr;
5806   _inner_classes = nullptr;
5807   _nest_members = nullptr;
5808   _permitted_subclasses = nullptr;
5809   _loadable_descriptors = nullptr;
5810   _combined_annotations = nullptr;
5811   _class_annotations = _class_type_annotations = nullptr;
5812   _fields_annotations = _fields_type_annotations = nullptr;
5813   _record_components = nullptr;
5814   _inline_type_field_klasses = nullptr;
5815   _null_marker_offsets = nullptr;
5816 }
5817 
5818 // Destructor to clean up
5819 ClassFileParser::~ClassFileParser() {
5820   _class_name->decrement_refcount();
5821 
5822   if (_cp != nullptr) {
5823     MetadataFactory::free_metadata(_loader_data, _cp);
5824   }
5825 
5826   if (_fieldinfo_stream != nullptr) {
5827     MetadataFactory::free_array<u1>(_loader_data, _fieldinfo_stream);
5828   }
5829 
5830   if (_fields_status != nullptr) {
5831     MetadataFactory::free_array<FieldStatus>(_loader_data, _fields_status);
5832   }
5833 
5834   if (_inline_type_field_klasses != nullptr) {
5835      MetadataFactory::free_array<InlineKlass*>(_loader_data, _inline_type_field_klasses);
5836   }
5837 
5838   if (_null_marker_offsets != nullptr) {
5839      MetadataFactory::free_array<int>(_loader_data, _null_marker_offsets);
5840   }
5841 
5842   if (_methods != nullptr) {
5843     // Free methods
5844     InstanceKlass::deallocate_methods(_loader_data, _methods);
5845   }
5846 
5847   // beware of the Universe::empty_blah_array!!
5848   if (_inner_classes != nullptr && _inner_classes != Universe::the_empty_short_array()) {
5849     MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
5850   }
5851 
5852   if (_nest_members != nullptr && _nest_members != Universe::the_empty_short_array()) {
5853     MetadataFactory::free_array<u2>(_loader_data, _nest_members);
5854   }
5855 
5856   if (_record_components != nullptr) {
5857     InstanceKlass::deallocate_record_components(_loader_data, _record_components);
5858   }
5859 
5860   if (_permitted_subclasses != nullptr && _permitted_subclasses != Universe::the_empty_short_array()) {
5861     MetadataFactory::free_array<u2>(_loader_data, _permitted_subclasses);
5862   }
5863 
5864   if (_loadable_descriptors != nullptr && _loadable_descriptors != Universe::the_empty_short_array()) {
5865     MetadataFactory::free_array<u2>(_loader_data, _loadable_descriptors);
5866   }
5867 
5868   // Free interfaces
5869   InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
5870                                        _local_interfaces, _transitive_interfaces);
5871 
5872   if (_combined_annotations != nullptr) {
5873     // After all annotations arrays have been created, they are installed into the
5874     // Annotations object that will be assigned to the InstanceKlass being created.
5875 
5876     // Deallocate the Annotations object and the installed annotations arrays.
5877     _combined_annotations->deallocate_contents(_loader_data);
5878 
5879     // If the _combined_annotations pointer is non-null,
5880     // then the other annotations fields should have been cleared.
5881     assert(_class_annotations       == nullptr, "Should have been cleared");
5882     assert(_class_type_annotations  == nullptr, "Should have been cleared");
5883     assert(_fields_annotations      == nullptr, "Should have been cleared");
5884     assert(_fields_type_annotations == nullptr, "Should have been cleared");
5885   } else {
5886     // If the annotations arrays were not installed into the Annotations object,
5887     // then they have to be deallocated explicitly.

5932     cp_size, CHECK);
5933 
5934   _orig_cp_size = cp_size;
5935   if (is_hidden()) { // Add a slot for hidden class name.
5936     cp_size++;
5937   }
5938 
5939   _cp = ConstantPool::allocate(_loader_data,
5940                                cp_size,
5941                                CHECK);
5942 
5943   ConstantPool* const cp = _cp;
5944 
5945   parse_constant_pool(stream, cp, _orig_cp_size, CHECK);
5946 
5947   assert(cp_size == (u2)cp->length(), "invariant");
5948 
5949   // ACCESS FLAGS
5950   stream->guarantee_more(8, CHECK);  // flags, this_class, super_class, infs_len
5951 
5952   jint recognized_modifiers = JVM_RECOGNIZED_CLASS_MODIFIERS;

5953   // JVM_ACC_MODULE is defined in JDK-9 and later.
5954   if (_major_version >= JAVA_9_VERSION) {
5955     recognized_modifiers |= JVM_ACC_MODULE;


5956   }
5957 
5958   // Access flags
5959   jint flags = stream->get_u2_fast() & recognized_modifiers;
5960 
5961   if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
5962     // Set abstract bit for old class files for backward compatibility
5963     flags |= JVM_ACC_ABSTRACT;
5964   }
5965 
5966   // Fixing ACC_SUPER/ACC_IDENTITY for old class files
5967   if (!supports_inline_types()) {
5968     const bool is_module = (flags & JVM_ACC_MODULE) != 0;
5969     const bool is_interface = (flags & JVM_ACC_INTERFACE) != 0;
5970     if (!is_module && !is_interface) {
5971       flags |= JVM_ACC_IDENTITY;
5972     }

5973   }
5974 

5975 
5976   // This class and superclass
5977   _this_class_index = stream->get_u2_fast();
5978   check_property(
5979     valid_cp_range(_this_class_index, cp_size) &&
5980       cp->tag_at(_this_class_index).is_unresolved_klass(),
5981     "Invalid this class index %u in constant pool in class file %s",
5982     _this_class_index, CHECK);
5983 
5984   Symbol* const class_name_in_cp = cp->klass_name_at(_this_class_index);
5985   assert(class_name_in_cp != nullptr, "class_name can't be null");
5986 
5987   bool is_java_lang_Object = class_name_in_cp == vmSymbols::java_lang_Object();
5988 
5989   verify_legal_class_modifiers(flags, nullptr, is_java_lang_Object, CHECK);
5990 
5991   _access_flags.set_flags(flags);
5992 
5993   short bad_constant = class_bad_constant_seen();
5994   if (bad_constant != 0) {
5995     // Do not throw CFE until after the access_flags are checked because if
5996     // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
5997     classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, THREAD);
5998     return;
5999   }
6000 
6001   // Don't need to check whether this class name is legal or not.
6002   // It has been checked when constant pool is parsed.
6003   // However, make sure it is not an array type.
6004   if (_need_verify) {
6005     guarantee_property(class_name_in_cp->char_at(0) != JVM_SIGNATURE_ARRAY,
6006                        "Bad class name in class file %s",
6007                        CHECK);
6008   }
6009 
6010 #ifdef ASSERT
6011   // Basic sanity checks
6012   if (_is_hidden) {
6013     assert(_class_name != vmSymbols::unknown_class_name(), "hidden classes should have a special name");
6014   }
6015 #endif
6016 
6017   // Update the _class_name as needed depending on whether this is a named, un-named, or hidden class.
6018 
6019   if (_is_hidden) {
6020     assert(_class_name != nullptr, "Unexpected null _class_name");

6060       }
6061       ls.cr();
6062     }
6063   }
6064 
6065   // SUPERKLASS
6066   _super_class_index = stream->get_u2_fast();
6067   _super_klass = parse_super_class(cp,
6068                                    _super_class_index,
6069                                    _need_verify,
6070                                    CHECK);
6071 
6072   // Interfaces
6073   _itfs_len = stream->get_u2_fast();
6074   parse_interfaces(stream,
6075                    _itfs_len,
6076                    cp,
6077                    &_has_nonstatic_concrete_methods,
6078                    CHECK);
6079 


6080   // Fields (offsets are filled in later)
6081   _fac = new FieldAllocationCount();
6082   parse_fields(stream,
6083                _access_flags,
6084                _fac,
6085                cp,
6086                cp_size,
6087                &_java_fields_count,
6088                CHECK);
6089 
6090   assert(_temp_field_info != nullptr, "invariant");
6091 
6092   // Methods
6093   parse_methods(stream,
6094                 is_interface(),
6095                 !is_identity_class(),
6096                 is_abstract_class(),
6097                 &_has_localvariable_table,
6098                 &_has_final_method,
6099                 &_declares_nonstatic_concrete_methods,
6100                 CHECK);
6101 
6102   assert(_methods != nullptr, "invariant");
6103 
6104   if (_declares_nonstatic_concrete_methods) {
6105     _has_nonstatic_concrete_methods = true;
6106   }
6107 
6108   // Additional attributes/annotations
6109   _parsed_annotations = new ClassAnnotationCollector();
6110   parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK);
6111 
6112   assert(_inner_classes != nullptr, "invariant");
6113 
6114   // Finalize the Annotations metadata object,
6115   // now that all annotation arrays have been created.
6116   create_combined_annotations(CHECK);

6156   // Update this_class_index's slot in the constant pool with the new Utf8 entry.
6157   // We have to update the resolved_klass_index and the name_index together
6158   // so extract the existing resolved_klass_index first.
6159   CPKlassSlot cp_klass_slot = _cp->klass_slot_at(_this_class_index);
6160   int resolved_klass_index = cp_klass_slot.resolved_klass_index();
6161   _cp->unresolved_klass_at_put(_this_class_index, hidden_index, resolved_klass_index);
6162   assert(_cp->klass_slot_at(_this_class_index).name_index() == _orig_cp_size,
6163          "Bad name_index");
6164 }
6165 
6166 void ClassFileParser::post_process_parsed_stream(const ClassFileStream* const stream,
6167                                                  ConstantPool* cp,
6168                                                  TRAPS) {
6169   assert(stream != nullptr, "invariant");
6170   assert(stream->at_eos(), "invariant");
6171   assert(cp != nullptr, "invariant");
6172   assert(_loader_data != nullptr, "invariant");
6173 
6174   if (_class_name == vmSymbols::java_lang_Object()) {
6175     check_property(_local_interfaces == Universe::the_empty_instance_klass_array(),
6176         "java.lang.Object cannot implement an interface in class file %s",
6177         CHECK);
6178   }
6179   // We check super class after class file is parsed and format is checked
6180   if (_super_class_index > 0 && nullptr == _super_klass) {
6181     Symbol* const super_class_name = cp->klass_name_at(_super_class_index);
6182     if (is_interface()) {
6183       // Before attempting to resolve the superclass, check for class format
6184       // errors not checked yet.
6185       guarantee_property(super_class_name == vmSymbols::java_lang_Object(),
6186         "Interfaces must have java.lang.Object as superclass in class file %s",
6187         CHECK);
6188     }
6189     Handle loader(THREAD, _loader_data->class_loader());
6190     if (loader.is_null() && super_class_name == vmSymbols::java_lang_Object()) {
6191       _super_klass = vmClasses::Object_klass();
6192     } else {
6193       _super_klass = (const InstanceKlass*)
6194                        SystemDictionary::resolve_with_circularity_detection_or_fail(_class_name,
6195                                                                super_class_name,
6196                                                                loader,
6197                                                                _protection_domain,
6198                                                                true,
6199                                                                CHECK);
6200     }
6201   }
6202 
6203   if (_super_klass != nullptr) {
6204     if (_super_klass->is_interface()) {
6205       classfile_icce_error("class %s has interface %s as super class", _super_klass, THREAD);
6206       return;
6207     }
6208 
6209     if (_super_klass->is_final()) {
6210       classfile_icce_error("class %s cannot inherit from final class %s", _super_klass, THREAD);
6211       return;
6212     }
6213 
6214     if (EnableValhalla) {
6215       check_identity_and_value_modifiers(this, _super_klass, CHECK);
6216     }
6217 
6218     if (_super_klass->has_nonstatic_concrete_methods()) {
6219       _has_nonstatic_concrete_methods = true;
6220     }
6221   }
6222 
6223   if (_parsed_annotations->has_annotation(AnnotationCollector::_jdk_internal_LooselyConsistentValue) && _access_flags.is_identity_class()) {
6224     THROW_MSG(vmSymbols::java_lang_ClassFormatError(),
6225           err_msg("class %s cannot have annotation jdk.internal.vm.annotation.LooselyConsistentValue, because it is not a value class",
6226                   _class_name->as_klass_external_name()));
6227   }
6228   if (_parsed_annotations->has_annotation(AnnotationCollector::_jdk_internal_ImplicitlyConstructible) && _access_flags.is_identity_class()) {
6229     THROW_MSG(vmSymbols::java_lang_ClassFormatError(),
6230           err_msg("class %s cannot have annotation jdk.internal.vm.annotation.ImplicitlyConstructible, because it is not a value class",
6231                   _class_name->as_klass_external_name()));
6232   }
6233 
6234   // Determining is the class allows tearing or not (default is not)
6235   // Test might need extensions when field inheritance is added for value classes
6236   if (EnableValhalla && !_access_flags.is_identity_class()) {
6237     if (_parsed_annotations->has_annotation(ClassAnnotationCollector::_jdk_internal_LooselyConsistentValue)
6238         && (_super_klass == vmClasses::Object_klass() || !_super_klass->must_be_atomic())) {
6239       _must_be_atomic = false;
6240     }
6241     if (_parsed_annotations->has_annotation(ClassAnnotationCollector::_jdk_internal_ImplicitlyConstructible)
6242         && (_super_klass == vmClasses::Object_klass() || _super_klass->is_implicitly_constructible())) {
6243       _is_implicitly_constructible = true;
6244     }
6245     // Apply VM options override
6246     if (*ForceNonTearable != '\0') {
6247       // Allow a command line switch to force the same atomicity property:
6248       const char* class_name_str = _class_name->as_C_string();
6249       if (StringUtils::class_list_match(ForceNonTearable, class_name_str)) {
6250         _must_be_atomic = true;
6251       }
6252     }
6253   }
6254 
6255   int itfs_len = _local_interface_indexes == nullptr ? 0 : _local_interface_indexes->length();
6256   _local_interfaces = MetadataFactory::new_array<InstanceKlass*>(_loader_data, itfs_len, nullptr, CHECK);
6257   if (_local_interface_indexes != nullptr) {
6258     for (int i = 0; i < _local_interface_indexes->length(); i++) {
6259       u2 interface_index = _local_interface_indexes->at(i);
6260       Klass* interf;
6261       if (cp->tag_at(interface_index).is_klass()) {
6262         interf = cp->resolved_klass_at(interface_index);
6263       } else {
6264         Symbol* const unresolved_klass  = cp->klass_name_at(interface_index);
6265 
6266         // Don't need to check legal name because it's checked when parsing constant pool.
6267         // But need to make sure it's not an array type.
6268         guarantee_property(unresolved_klass->char_at(0) != JVM_SIGNATURE_ARRAY,
6269                             "Bad interface name in class file %s", CHECK);
6270 
6271         // Call resolve on the interface class name with class circularity checking
6272         interf = SystemDictionary::resolve_with_circularity_detection_or_fail(
6273                                                   _class_name,
6274                                                   unresolved_klass,
6275                                                   Handle(THREAD, _loader_data->class_loader()),
6276                                                   _protection_domain,
6277                                                   false,
6278                                                   CHECK);
6279       }
6280 
6281       if (!interf->is_interface()) {
6282         THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
6283                   err_msg("class %s can not implement %s, because it is not an interface (%s)",
6284                           _class_name->as_klass_external_name(),
6285                           interf->external_name(),
6286                           interf->class_in_module_of_loader()));
6287       }
6288 
6289       if (EnableValhalla) {
6290         // Check modifiers and set carries_identity_modifier/carries_value_modifier flags
6291         check_identity_and_value_modifiers(this, InstanceKlass::cast(interf), CHECK);
6292       }
6293 
6294       if (InstanceKlass::cast(interf)->has_nonstatic_concrete_methods()) {
6295         _has_nonstatic_concrete_methods = true;
6296       }
6297       _local_interfaces->at_put(i, InstanceKlass::cast(interf));
6298     }
6299   }
6300   assert(_local_interfaces != nullptr, "invariant");
6301 
6302   // Compute the transitive list of all unique interfaces implemented by this class
6303   _transitive_interfaces =
6304     compute_transitive_interfaces(_super_klass,
6305                                   _local_interfaces,
6306                                   _loader_data,
6307                                   CHECK);
6308 
6309   assert(_transitive_interfaces != nullptr, "invariant");
6310 
6311   // sort methods
6312   _method_ordering = sort_methods(_methods);
6313 
6314   _all_mirandas = new GrowableArray<Method*>(20);
6315 
6316   Handle loader(THREAD, _loader_data->class_loader());
6317   klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
6318                                                     &_num_miranda_methods,
6319                                                     _all_mirandas,
6320                                                     _super_klass,
6321                                                     _methods,
6322                                                     _access_flags,
6323                                                     _major_version,
6324                                                     loader,
6325                                                     _class_name,
6326                                                     _local_interfaces);
6327 
6328   // Size of Java itable (in words)
6329   _itable_size = is_interface() ? 0 :
6330     klassItable::compute_itable_size(_transitive_interfaces);
6331 
6332   assert(_fac != nullptr, "invariant");
6333   assert(_parsed_annotations != nullptr, "invariant");
6334 
6335   if (EnableValhalla) {
6336     _inline_type_field_klasses = MetadataFactory::new_array<InlineKlass*>(_loader_data,
6337                                                    java_fields_count(),
6338                                                    nullptr,
6339                                                    CHECK);
6340     for (GrowableArrayIterator<FieldInfo> it = _temp_field_info->begin(); it != _temp_field_info->end(); ++it) {
6341       FieldInfo fieldinfo = *it;
6342       if (fieldinfo.access_flags().is_static()) continue;  // Only non-static fields are processed at load time
6343       Symbol* sig = fieldinfo.signature(cp);
6344       if (fieldinfo.field_flags().is_null_free_inline_type()) {
6345         // Pre-load classes of null-free fields that are candidate for flattening
6346         TempNewSymbol s = Signature::strip_envelope(sig);
6347         if (s == _class_name) {
6348           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()));
6349         }
6350         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());
6351         Klass* klass = SystemDictionary::resolve_with_circularity_detection_or_fail(_class_name, s, Handle(THREAD, _loader_data->class_loader()), _protection_domain, false, THREAD);
6352         if (HAS_PENDING_EXCEPTION) {
6353           log_warning(class, preload)("Preloading of class %s during loading of class %s (cause: null-free non-static field) failed: %s",
6354                                       s->as_C_string(), _class_name->as_C_string(), PENDING_EXCEPTION->klass()->name()->as_C_string());
6355           return; // Exception is still pending
6356         }
6357         assert(klass != nullptr, "Sanity check");
6358         if (klass->access_flags().is_identity_class()) {
6359           assert(klass->is_instance_klass(), "Sanity check");
6360           ResourceMark rm(THREAD);
6361           THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
6362                     err_msg("Class %s expects class %s to be a value class, but it is an identity class",
6363                     _class_name->as_C_string(),
6364                     InstanceKlass::cast(klass)->external_name()));
6365         }
6366         if (klass->is_abstract()) {
6367           assert(klass->is_instance_klass(), "Sanity check");
6368           ResourceMark rm(THREAD);
6369           THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
6370                     err_msg("Class %s expects class %s to be concrete value type, but it is an abstract class",
6371                     _class_name->as_C_string(),
6372                     InstanceKlass::cast(klass)->external_name()));
6373         }
6374         InlineKlass* vk = InlineKlass::cast(klass);
6375         if (!vk->is_implicitly_constructible()) {
6376           THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
6377                     err_msg("class %s is not implicitly constructible and it is used in a null restricted non-static field (not supported)",
6378                     klass->name()->as_C_string()));
6379         }
6380         _inline_type_field_klasses->at_put(fieldinfo.index(), vk);
6381         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());
6382       } else if (Signature::has_envelope(sig)) {
6383         // Preloading classes for nullable fields that are listed in the LoadableDescriptors attribute
6384         // Those classes would be required later for the flattening of nullable inline type fields
6385         TempNewSymbol name = Signature::strip_envelope(sig);
6386         if (name != _class_name && is_class_in_loadable_descriptors_attribute(sig)) {
6387           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());
6388           oop loader = loader_data()->class_loader();
6389           Klass* klass = SystemDictionary::resolve_with_circularity_detection_or_fail(_class_name, name, Handle(THREAD, loader), _protection_domain, false, THREAD);
6390           if (klass != nullptr) {
6391             if (klass->is_inline_klass()) {
6392               _inline_type_field_klasses->at_put(fieldinfo.index(), InlineKlass::cast(klass));
6393               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());
6394             } else {
6395               // Non value class are allowed by the current spec, but it could be an indication of an issue so let's log a warning
6396               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());
6397             }
6398             } else {
6399             log_warning(class, preload)("Preloading of class %s during loading of class %s (cause: field type in LoadableDescriptors attribute) failed : %s",
6400                                           name->as_C_string(), _class_name->as_C_string(), PENDING_EXCEPTION->klass()->name()->as_C_string());
6401           }
6402           // Loads triggered by the LoadableDescriptors attribute are speculative, failures must not impact loading of current class
6403           if (HAS_PENDING_EXCEPTION) {
6404             CLEAR_PENDING_EXCEPTION;
6405           }
6406         }
6407       }
6408     }
6409   }
6410 
6411   _field_info = new FieldLayoutInfo();
6412   FieldLayoutBuilder lb(class_name(), loader_data(), super_klass(), _cp, /*_fields*/ _temp_field_info,
6413       _parsed_annotations->is_contended(), is_inline_type(),
6414       access_flags().is_abstract() && !access_flags().is_identity_class() && !access_flags().is_interface(),
6415       _field_info, _inline_type_field_klasses);
6416   lb.build_layout();
6417   if (is_inline_type()) {
6418     _alignment = lb.get_alignment();
6419     _first_field_offset = lb.get_first_field_offset();
6420     _payload_size_in_bytes = lb.get_payload_size_in_byte();
6421     _internal_null_marker_offset = lb.get_internal_null_marker_offset();
6422   }
6423   _has_inline_type_fields = _field_info->_has_inline_fields;
6424 
6425   int injected_fields_count = _temp_field_info->length() - _java_fields_count;
6426   _fieldinfo_stream =
6427     FieldInfoStream::create_FieldInfoStream(_temp_field_info, _java_fields_count,
6428                                             injected_fields_count, loader_data(), CHECK);
6429 
6430   _fields_status =
6431     MetadataFactory::new_array<FieldStatus>(_loader_data, _temp_field_info->length(),
6432                                             FieldStatus(0), CHECK);
6433   if (_field_info->_has_null_marker_offsets) {
6434     int idx = 0;
6435     _null_marker_offsets = MetadataFactory::new_array<int>(_loader_data, _temp_field_info->length(), 0, CHECK);
6436     for (GrowableArrayIterator<FieldInfo> it = _temp_field_info->begin(); it != _temp_field_info->end(); ++it, ++idx) {
6437       FieldInfo fieldinfo = *it;
6438       if (fieldinfo.field_flags().has_null_marker()) {
6439         assert(fieldinfo.null_marker_offset() != 0, "Invalid value");
6440         _null_marker_offsets->at_put(idx, fieldinfo.null_marker_offset());
6441       }
6442     }
6443   }
6444 }
6445 
6446 void ClassFileParser::set_klass(InstanceKlass* klass) {
6447 
6448 #ifdef ASSERT
6449   if (klass != nullptr) {
6450     assert(nullptr == _klass, "leaking?");
6451   }
6452 #endif
6453 
6454   _klass = klass;
6455 }
6456 
6457 void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) {
6458 
6459 #ifdef ASSERT
6460   if (klass != nullptr) {
6461     assert(nullptr == _klass_to_deallocate, "leaking?");
6462   }
6463 #endif
< prev index next >