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

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

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

 130 #define JAVA_13_VERSION                   57
 131 
 132 #define JAVA_14_VERSION                   58
 133 
 134 #define JAVA_15_VERSION                   59
 135 
 136 #define JAVA_16_VERSION                   60
 137 
 138 #define JAVA_17_VERSION                   61
 139 
 140 #define JAVA_18_VERSION                   62
 141 
 142 #define JAVA_19_VERSION                   63
 143 
 144 #define JAVA_20_VERSION                   64
 145 
 146 #define JAVA_21_VERSION                   65
 147 
 148 #define JAVA_22_VERSION                   66
 149 


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

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







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

 689           cp->signature_ref_index_at(name_and_type_ref_index);
 690         const Symbol* const name = cp->symbol_at(name_ref_index);
 691         const Symbol* const signature = cp->symbol_at(signature_ref_index);
 692         if (tag == JVM_CONSTANT_Fieldref) {
 693           if (_need_verify) {
 694             // Field name and signature are verified above, when iterating NameAndType_info.
 695             // Need only to be sure signature is non-zero length and the right type.
 696             if (Signature::is_method(signature)) {
 697               throwIllegalSignature("Field", name, signature, CHECK);
 698             }
 699           }
 700         } else {
 701           if (_need_verify) {
 702             // Method name and signature are individually verified above, when iterating
 703             // NameAndType_info.  Need to check here that signature is non-zero length and
 704             // the right type.
 705             if (!Signature::is_method(signature)) {
 706               throwIllegalSignature("Method", name, signature, CHECK);
 707             }
 708           }
 709           // If a class method name begins with '<', it must be "<init>" and have void signature.

 710           const unsigned int name_len = name->utf8_length();
 711           if (tag == JVM_CONSTANT_Methodref && name_len != 0 &&
 712               name->char_at(0) == JVM_SIGNATURE_SPECIAL) {
 713             if (name != vmSymbols::object_initializer_name()) {

 714               classfile_parse_error(
 715                 "Bad method name at constant pool index %u in class file %s",
 716                 name_ref_index, THREAD);
 717               return;
 718             } else if (!Signature::is_void_method(signature)) { // must have void signature.
 719               throwIllegalSignature("Method", name, signature, CHECK);





 720             }
 721           }
 722         }
 723         break;
 724       }
 725       case JVM_CONSTANT_MethodHandle: {
 726         const int ref_index = cp->method_handle_index_at(index);
 727         const int ref_kind = cp->method_handle_ref_kind_at(index);
 728         switch (ref_kind) {
 729           case JVM_REF_invokeVirtual:
 730           case JVM_REF_invokeStatic:
 731           case JVM_REF_invokeSpecial:
 732           case JVM_REF_newInvokeSpecial: {
 733             const int name_and_type_ref_index =
 734               cp->uncached_name_and_type_ref_index_at(ref_index);
 735             const int name_ref_index =
 736               cp->name_ref_index_at(name_and_type_ref_index);
 737             const Symbol* const name = cp->symbol_at(name_ref_index);
 738             if (ref_kind == JVM_REF_newInvokeSpecial) {
 739               if (name != vmSymbols::object_initializer_name()) {











 740                 classfile_parse_error(
 741                   "Bad constructor name at constant pool index %u in class file %s",
 742                     name_ref_index, THREAD);
 743                 return;
 744               }
 745             } else {
 746               if (name == vmSymbols::object_initializer_name()) {








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

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



























 802                                        bool* const has_nonstatic_concrete_methods,







 803                                        TRAPS) {
 804   assert(stream != nullptr, "invariant");
 805   assert(cp != nullptr, "invariant");
 806   assert(has_nonstatic_concrete_methods != nullptr, "invariant");
 807 
 808   if (itfs_len == 0) {
 809     _local_interfaces = Universe::the_empty_instance_klass_array();

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

1328                                             CHECK);
1329   parsed_annotations->set_field_annotations(a);
1330   a = assemble_annotations(runtime_visible_type_annotations,
1331                            runtime_visible_type_annotations_length,
1332                            runtime_invisible_type_annotations,
1333                            runtime_invisible_type_annotations_length,
1334                            CHECK);
1335   parsed_annotations->set_field_type_annotations(a);
1336   return;
1337 }
1338 
1339 
1340 // Field allocation types. Used for computing field offsets.
1341 
1342 enum FieldAllocationType {
1343   STATIC_OOP,           // Oops
1344   STATIC_BYTE,          // Boolean, Byte, char
1345   STATIC_SHORT,         // shorts
1346   STATIC_WORD,          // ints
1347   STATIC_DOUBLE,        // aligned long or double

1348   NONSTATIC_OOP,
1349   NONSTATIC_BYTE,
1350   NONSTATIC_SHORT,
1351   NONSTATIC_WORD,
1352   NONSTATIC_DOUBLE,

1353   MAX_FIELD_ALLOCATION_TYPE,
1354   BAD_ALLOCATION_TYPE = -1
1355 };
1356 
1357 static FieldAllocationType _basic_type_to_atype[2 * (T_CONFLICT + 1)] = {
1358   BAD_ALLOCATION_TYPE, // 0
1359   BAD_ALLOCATION_TYPE, // 1
1360   BAD_ALLOCATION_TYPE, // 2
1361   BAD_ALLOCATION_TYPE, // 3
1362   NONSTATIC_BYTE ,     // T_BOOLEAN     =  4,
1363   NONSTATIC_SHORT,     // T_CHAR        =  5,
1364   NONSTATIC_WORD,      // T_FLOAT       =  6,
1365   NONSTATIC_DOUBLE,    // T_DOUBLE      =  7,
1366   NONSTATIC_BYTE,      // T_BYTE        =  8,
1367   NONSTATIC_SHORT,     // T_SHORT       =  9,
1368   NONSTATIC_WORD,      // T_INT         = 10,
1369   NONSTATIC_DOUBLE,    // T_LONG        = 11,
1370   NONSTATIC_OOP,       // T_OBJECT      = 12,
1371   NONSTATIC_OOP,       // T_ARRAY       = 13,
1372   BAD_ALLOCATION_TYPE, // T_VOID        = 14,
1373   BAD_ALLOCATION_TYPE, // T_ADDRESS     = 15,
1374   BAD_ALLOCATION_TYPE, // T_NARROWOOP   = 16,
1375   BAD_ALLOCATION_TYPE, // T_METADATA    = 17,
1376   BAD_ALLOCATION_TYPE, // T_NARROWKLASS = 18,
1377   BAD_ALLOCATION_TYPE, // T_CONFLICT    = 19,

1378   BAD_ALLOCATION_TYPE, // 0
1379   BAD_ALLOCATION_TYPE, // 1
1380   BAD_ALLOCATION_TYPE, // 2
1381   BAD_ALLOCATION_TYPE, // 3
1382   STATIC_BYTE ,        // T_BOOLEAN     =  4,
1383   STATIC_SHORT,        // T_CHAR        =  5,
1384   STATIC_WORD,         // T_FLOAT       =  6,
1385   STATIC_DOUBLE,       // T_DOUBLE      =  7,
1386   STATIC_BYTE,         // T_BYTE        =  8,
1387   STATIC_SHORT,        // T_SHORT       =  9,
1388   STATIC_WORD,         // T_INT         = 10,
1389   STATIC_DOUBLE,       // T_LONG        = 11,
1390   STATIC_OOP,          // T_OBJECT      = 12,
1391   STATIC_OOP,          // T_ARRAY       = 13,
1392   BAD_ALLOCATION_TYPE, // T_VOID        = 14,
1393   BAD_ALLOCATION_TYPE, // T_ADDRESS     = 15,
1394   BAD_ALLOCATION_TYPE, // T_NARROWOOP   = 16,
1395   BAD_ALLOCATION_TYPE, // T_METADATA    = 17,
1396   BAD_ALLOCATION_TYPE, // T_NARROWKLASS = 18,
1397   BAD_ALLOCATION_TYPE, // T_CONFLICT    = 19,

1398 };
1399 
1400 static FieldAllocationType basic_type_to_atype(bool is_static, BasicType type) {
1401   assert(type >= T_BOOLEAN && type < T_VOID, "only allowable values");
1402   FieldAllocationType result = _basic_type_to_atype[type + (is_static ? (T_CONFLICT + 1) : 0)];
1403   assert(result != BAD_ALLOCATION_TYPE, "bad type");



1404   return result;
1405 }
1406 
1407 class ClassFileParser::FieldAllocationCount : public ResourceObj {
1408  public:
1409   u2 count[MAX_FIELD_ALLOCATION_TYPE];
1410 
1411   FieldAllocationCount() {
1412     for (int i = 0; i < MAX_FIELD_ALLOCATION_TYPE; i++) {
1413       count[i] = 0;
1414     }
1415   }
1416 
1417   void update(bool is_static, BasicType type) {
1418     FieldAllocationType atype = basic_type_to_atype(is_static, type);
1419     if (atype != BAD_ALLOCATION_TYPE) {
1420       // Make sure there is no overflow with injected fields.
1421       assert(count[atype] < 0xFFFF, "More than 65535 fields");
1422       count[atype]++;
1423     }
1424   }
1425 };
1426 
1427 // Side-effects: populates the _fields, _fields_annotations,
1428 // _fields_type_annotations fields
1429 void ClassFileParser::parse_fields(const ClassFileStream* const cfs,
1430                                    bool is_interface,
1431                                    FieldAllocationCount* const fac,
1432                                    ConstantPool* cp,
1433                                    const int cp_size,
1434                                    u2* const java_fields_count_ptr,
1435                                    TRAPS) {
1436 
1437   assert(cfs != nullptr, "invariant");
1438   assert(fac != nullptr, "invariant");
1439   assert(cp != nullptr, "invariant");
1440   assert(java_fields_count_ptr != nullptr, "invariant");
1441 
1442   assert(nullptr == _fields_annotations, "invariant");
1443   assert(nullptr == _fields_type_annotations, "invariant");
1444 

1445   cfs->guarantee_more(2, CHECK);  // length
1446   const u2 length = cfs->get_u2_fast();
1447   *java_fields_count_ptr = length;
1448 
1449   int num_injected = 0;
1450   const InjectedField* const injected = JavaClasses::get_injected(_class_name,
1451                                                                   &num_injected);
1452   const int total_fields = length + num_injected;




1453 
1454   // Allocate a temporary resource array to collect field data.
1455   // After parsing all fields, data are stored in a UNSIGNED5 compressed stream.
1456   _temp_field_info = new GrowableArray<FieldInfo>(total_fields);
1457 

1458   ResourceMark rm(THREAD);
1459   for (int n = 0; n < length; n++) {
1460     // access_flags, name_index, descriptor_index, attributes_count
1461     cfs->guarantee_more(8, CHECK);
1462 




1463     AccessFlags access_flags;
1464     const jint flags = cfs->get_u2_fast() & JVM_RECOGNIZED_FIELD_MODIFIERS;
1465     verify_legal_field_modifiers(flags, is_interface, CHECK);
1466     access_flags.set_flags(flags);
1467     FieldInfo::FieldFlags fieldFlags(0);
1468 
1469     const u2 name_index = cfs->get_u2_fast();
1470     check_property(valid_symbol_at(name_index),
1471       "Invalid constant pool index %u for field name in class file %s",
1472       name_index, CHECK);
1473     const Symbol* const name = cp->symbol_at(name_index);
1474     verify_legal_field_name(name, CHECK);
1475 
1476     const u2 signature_index = cfs->get_u2_fast();
1477     check_property(valid_symbol_at(signature_index),
1478       "Invalid constant pool index %u for field signature in class file %s",
1479       signature_index, CHECK);
1480     const Symbol* const sig = cp->symbol_at(signature_index);
1481     verify_legal_field_signature(name, sig, CHECK);

1482 
1483     u2 constantvalue_index = 0;
1484     bool is_synthetic = false;
1485     u2 generic_signature_index = 0;
1486     const bool is_static = access_flags.is_static();
1487     FieldAnnotationCollector parsed_annotations(_loader_data);
1488 
1489     const u2 attributes_count = cfs->get_u2_fast();
1490     if (attributes_count > 0) {
1491       parse_field_attributes(cfs,
1492                              attributes_count,
1493                              is_static,
1494                              signature_index,
1495                              &constantvalue_index,
1496                              &is_synthetic,
1497                              &generic_signature_index,
1498                              &parsed_annotations,
1499                              CHECK);
1500 
1501       if (parsed_annotations.field_annotations() != nullptr) {

1513             MetadataFactory::new_array<AnnotationArray*>(_loader_data,
1514                                                          length,
1515                                                          nullptr,
1516                                                          CHECK);
1517         }
1518         _fields_type_annotations->at_put(n, parsed_annotations.field_type_annotations());
1519         parsed_annotations.set_field_type_annotations(nullptr);
1520       }
1521 
1522       if (is_synthetic) {
1523         access_flags.set_is_synthetic();
1524       }
1525       if (generic_signature_index != 0) {
1526         fieldFlags.update_generic(true);
1527       }
1528     }
1529 
1530     const BasicType type = cp->basic_type_for_signature_at(signature_index);
1531 
1532     // Update FieldAllocationCount for this kind of field
1533     fac->update(is_static, type);






1534 
1535     FieldInfo fi(access_flags, name_index, signature_index, constantvalue_index, fieldFlags);
1536     fi.set_index(n);
1537     if (fieldFlags.is_generic()) {
1538       fi.set_generic_signature_index(generic_signature_index);
1539     }
1540     parsed_annotations.apply_to(&fi);
1541     if (fi.field_flags().is_contended()) {
1542       _has_contended_fields = true;
1543     }
1544     _temp_field_info->append(fi);
1545   }
1546   assert(_temp_field_info->length() == length, "Must be");
1547 
1548   int index = length;
1549   if (num_injected != 0) {
1550     for (int n = 0; n < num_injected; n++) {
1551       // Check for duplicates
1552       if (injected[n].may_be_java) {
1553         const Symbol* const name      = injected[n].name();

1561             duplicate = true;
1562             break;
1563           }
1564         }
1565         if (duplicate) {
1566           // These will be removed from the field array at the end
1567           continue;
1568         }
1569       }
1570 
1571       // Injected field
1572       FieldInfo::FieldFlags fflags(0);
1573       fflags.update_injected(true);
1574       AccessFlags aflags;
1575       FieldInfo fi(aflags, (u2)(injected[n].name_index), (u2)(injected[n].signature_index), 0, fflags);
1576       fi.set_index(index);
1577       _temp_field_info->append(fi);
1578 
1579       // Update FieldAllocationCount for this kind of field
1580       const BasicType type = Signature::basic_type(injected[n].signature());
1581       fac->update(false, type);
1582       index++;
1583     }
1584   }
1585 










































1586   assert(_temp_field_info->length() == index, "Must be");
1587 
1588   if (_need_verify && length > 1) {
1589     // Check duplicated fields
1590     ResourceMark rm(THREAD);
1591     // Set containing name-signature pairs
1592     NameSigHashtable* names_and_sigs = new NameSigHashtable();
1593     for (int i = 0; i < _temp_field_info->length(); i++) {
1594       NameSigHash name_and_sig(_temp_field_info->adr_at(i)->name(_cp),
1595                                _temp_field_info->adr_at(i)->signature(_cp));
1596       // If no duplicates, add name/signature in hashtable names_and_sigs.
1597       if(!names_and_sigs->put(name_and_sig, 0)) {
1598         classfile_parse_error("Duplicate field name \"%s\" with signature \"%s\" in class file %s",
1599                                name_and_sig._name->as_C_string(), name_and_sig._sig->as_klass_external_name(), THREAD);
1600         return;
1601       }
1602     }
1603   }
1604 }
1605 

1849         "Exception name has bad type at constant pool %u in class file %s",
1850         checked_exception, CHECK_NULL);
1851     }
1852   }
1853   // check exceptions attribute length
1854   if (_need_verify) {
1855     guarantee_property(method_attribute_length == (sizeof(*checked_exceptions_length) +
1856                                                    sizeof(u2) * size),
1857                       "Exceptions attribute has wrong length in class file %s", CHECK_NULL);
1858   }
1859   return checked_exceptions_start;
1860 }
1861 
1862 void ClassFileParser::throwIllegalSignature(const char* type,
1863                                             const Symbol* name,
1864                                             const Symbol* sig,
1865                                             TRAPS) const {
1866   assert(name != nullptr, "invariant");
1867   assert(sig != nullptr, "invariant");
1868 





1869   ResourceMark rm(THREAD);
1870   Exceptions::fthrow(THREAD_AND_LOCATION,
1871       vmSymbols::java_lang_ClassFormatError(),
1872       "%s \"%s\" in class %s has illegal signature \"%s\"", type,
1873       name->as_C_string(), _class_name->as_C_string(), sig->as_C_string());
1874 }
1875 
1876 AnnotationCollector::ID
1877 AnnotationCollector::annotation_index(const ClassLoaderData* loader_data,
1878                                       const Symbol* name,
1879                                       const bool can_access_vm_annotations) {
1880   const vmSymbolID sid = vmSymbols::find_sid(name);
1881   // Privileged code can use all annotations.  Other code silently drops some.
1882   const bool privileged = loader_data->is_boot_class_loader_data() ||
1883                           loader_data->is_platform_class_loader_data() ||
1884                           can_access_vm_annotations;
1885   switch (sid) {
1886     case VM_SYMBOL_ENUM_NAME(reflect_CallerSensitive_signature): {
1887       if (_location != _in_method)  break;  // only allow for methods
1888       if (!privileged)              break;  // only allow in privileged code
1889       return _method_CallerSensitive;
1890     }
1891     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ForceInline_signature): {
1892       if (_location != _in_method)  break;  // only allow for methods
1893       if (!privileged)              break;  // only allow in privileged code

2155       runtime_invisible_type_annotations_length > 0) {
2156     a = assemble_annotations(runtime_visible_type_annotations,
2157                              runtime_visible_type_annotations_length,
2158                              runtime_invisible_type_annotations,
2159                              runtime_invisible_type_annotations_length,
2160                              CHECK);
2161     cm->set_type_annotations(a);
2162   }
2163 }
2164 
2165 
2166 // Note: the parse_method below is big and clunky because all parsing of the code and exceptions
2167 // attribute is inlined. This is cumbersome to avoid since we inline most of the parts in the
2168 // Method* to save footprint, so we only know the size of the resulting Method* when the
2169 // entire method attribute is parsed.
2170 //
2171 // The has_localvariable_table parameter is used to pass up the value to InstanceKlass.
2172 
2173 Method* ClassFileParser::parse_method(const ClassFileStream* const cfs,
2174                                       bool is_interface,


2175                                       const ConstantPool* cp,
2176                                       bool* const has_localvariable_table,
2177                                       TRAPS) {
2178   assert(cfs != nullptr, "invariant");
2179   assert(cp != nullptr, "invariant");
2180   assert(has_localvariable_table != nullptr, "invariant");
2181 
2182   ResourceMark rm(THREAD);
2183   // Parse fixed parts:
2184   // access_flags, name_index, descriptor_index, attributes_count
2185   cfs->guarantee_more(8, CHECK_NULL);
2186 
2187   int flags = cfs->get_u2_fast();
2188   const u2 name_index = cfs->get_u2_fast();
2189   const int cp_size = cp->length();
2190   check_property(
2191     valid_symbol_at(name_index),
2192     "Illegal constant pool index %u for method name in class file %s",
2193     name_index, CHECK_NULL);
2194   const Symbol* const name = cp->symbol_at(name_index);

2196 
2197   const u2 signature_index = cfs->get_u2_fast();
2198   guarantee_property(
2199     valid_symbol_at(signature_index),
2200     "Illegal constant pool index %u for method signature in class file %s",
2201     signature_index, CHECK_NULL);
2202   const Symbol* const signature = cp->symbol_at(signature_index);
2203 
2204   if (name == vmSymbols::class_initializer_name()) {
2205     // We ignore the other access flags for a valid class initializer.
2206     // (JVM Spec 2nd ed., chapter 4.6)
2207     if (_major_version < 51) { // backward compatibility
2208       flags = JVM_ACC_STATIC;
2209     } else if ((flags & JVM_ACC_STATIC) == JVM_ACC_STATIC) {
2210       flags &= JVM_ACC_STATIC | (_major_version <= JAVA_16_VERSION ? JVM_ACC_STRICT : 0);
2211     } else {
2212       classfile_parse_error("Method <clinit> is not static in class file %s", THREAD);
2213       return nullptr;
2214     }
2215   } else {
2216     verify_legal_method_modifiers(flags, is_interface, name, CHECK_NULL);

































2217   }
2218 
2219   if (name == vmSymbols::object_initializer_name() && is_interface) {
2220     classfile_parse_error("Interface cannot have a method named <init>, class file %s", THREAD);
2221     return nullptr;





















2222   }
2223 
2224   int args_size = -1;  // only used when _need_verify is true
2225   if (_need_verify) {
2226     verify_legal_name_with_signature(name, signature, CHECK_NULL);
2227     args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) +
2228                  verify_legal_method_signature(name, signature, CHECK_NULL);
2229     if (args_size > MAX_ARGS_SIZE) {
2230       classfile_parse_error("Too many arguments in method signature in class file %s", THREAD);
2231       return nullptr;
2232     }
2233   }
2234 
2235   AccessFlags access_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS);
2236 
2237   // Default values for code and exceptions attribute elements
2238   u2 max_stack = 0;
2239   u2 max_locals = 0;
2240   u4 code_length = 0;
2241   const u1* code_start = 0;

2768     if (m->is_empty_method()) {
2769       _has_empty_finalizer = true;
2770     } else {
2771       _has_finalizer = true;
2772     }
2773   }
2774   if (name == vmSymbols::object_initializer_name() &&
2775       signature == vmSymbols::void_method_signature() &&
2776       m->is_vanilla_constructor()) {
2777     _has_vanilla_constructor = true;
2778   }
2779 
2780   NOT_PRODUCT(m->verify());
2781   return m;
2782 }
2783 
2784 
2785 // Side-effects: populates the _methods field in the parser
2786 void ClassFileParser::parse_methods(const ClassFileStream* const cfs,
2787                                     bool is_interface,


2788                                     bool* const has_localvariable_table,
2789                                     bool* has_final_method,
2790                                     bool* declares_nonstatic_concrete_methods,
2791                                     TRAPS) {
2792   assert(cfs != nullptr, "invariant");
2793   assert(has_localvariable_table != nullptr, "invariant");
2794   assert(has_final_method != nullptr, "invariant");
2795   assert(declares_nonstatic_concrete_methods != nullptr, "invariant");
2796 
2797   assert(nullptr == _methods, "invariant");
2798 
2799   cfs->guarantee_more(2, CHECK);  // length
2800   const u2 length = cfs->get_u2_fast();
2801   if (length == 0) {
2802     _methods = Universe::the_empty_method_array();
2803   } else {
2804     _methods = MetadataFactory::new_array<Method*>(_loader_data,
2805                                                    length,
2806                                                    nullptr,
2807                                                    CHECK);
2808 
2809     for (int index = 0; index < length; index++) {
2810       Method* method = parse_method(cfs,
2811                                     is_interface,


2812                                     _cp,
2813                                     has_localvariable_table,
2814                                     CHECK);
2815 
2816       if (method->is_final()) {
2817         *has_final_method = true;
2818       }
2819       // declares_nonstatic_concrete_methods: declares concrete instance methods, any access flags
2820       // used for interface initialization, and default method inheritance analysis
2821       if (is_interface && !(*declares_nonstatic_concrete_methods)
2822         && !method->is_abstract() && !method->is_static()) {
2823         *declares_nonstatic_concrete_methods = true;
2824       }
2825       _methods->at_put(index, method);
2826     }
2827 
2828     if (_need_verify && length > 1) {
2829       // Check duplicated methods
2830       ResourceMark rm(THREAD);
2831       // Set containing name-signature pairs

3057         valid_klass_reference_at(outer_class_info_index),
3058       "outer_class_info_index %u has bad constant type in class file %s",
3059       outer_class_info_index, CHECK_0);
3060 
3061     if (outer_class_info_index != 0) {
3062       const Symbol* const outer_class_name = cp->klass_name_at(outer_class_info_index);
3063       char* bytes = (char*)outer_class_name->bytes();
3064       guarantee_property(bytes[0] != JVM_SIGNATURE_ARRAY,
3065                          "Outer class is an array class in class file %s", CHECK_0);
3066     }
3067     // Inner class name
3068     const u2 inner_name_index = cfs->get_u2_fast();
3069     check_property(
3070       inner_name_index == 0 || valid_symbol_at(inner_name_index),
3071       "inner_name_index %u has bad constant type in class file %s",
3072       inner_name_index, CHECK_0);
3073     if (_need_verify) {
3074       guarantee_property(inner_class_info_index != outer_class_info_index,
3075                          "Class is both outer and inner class in class file %s", CHECK_0);
3076     }
3077     // Access flags
3078     jint flags;
3079     // JVM_ACC_MODULE is defined in JDK-9 and later.
3080     if (_major_version >= JAVA_9_VERSION) {
3081       flags = cfs->get_u2_fast() & (RECOGNIZED_INNER_CLASS_MODIFIERS | JVM_ACC_MODULE);
3082     } else {
3083       flags = cfs->get_u2_fast() & RECOGNIZED_INNER_CLASS_MODIFIERS;
3084     }







3085     if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
3086       // Set abstract bit for old class files for backward compatibility
3087       flags |= JVM_ACC_ABSTRACT;
3088     }
3089     verify_legal_class_modifiers(flags, CHECK_0);












3090     AccessFlags inner_access_flags(flags);
3091 
3092     inner_classes->at_put(index++, inner_class_info_index);
3093     inner_classes->at_put(index++, outer_class_info_index);
3094     inner_classes->at_put(index++, inner_name_index);
3095     inner_classes->at_put(index++, inner_access_flags.as_short());
3096   }
3097 
3098   // Check for circular and duplicate entries.
3099   bool has_circularity = false;
3100   if (_need_verify) {
3101     has_circularity = check_inner_classes_circularity(cp, length * 4, CHECK_0);
3102     if (has_circularity) {
3103       // If circularity check failed then ignore InnerClasses attribute.
3104       MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
3105       index = 0;
3106       if (parsed_enclosingmethod_attribute) {
3107         inner_classes = MetadataFactory::new_array<u2>(_loader_data, 2, CHECK_0);
3108         _inner_classes = inner_classes;
3109       } else {

3173   if (length > 0) {
3174     int index = 0;
3175     cfs->guarantee_more(2 * length, CHECK_0);
3176     for (int n = 0; n < length; n++) {
3177       const u2 class_info_index = cfs->get_u2_fast();
3178       check_property(
3179         valid_klass_reference_at(class_info_index),
3180         "Permitted subclass class_info_index %u has bad constant type in class file %s",
3181         class_info_index, CHECK_0);
3182       permitted_subclasses->at_put(index++, class_info_index);
3183     }
3184     assert(index == size, "wrong size");
3185   }
3186 
3187   // Restore buffer's current position.
3188   cfs->set_current(current_mark);
3189 
3190   return length;
3191 }
3192 

































3193 //  Record {
3194 //    u2 attribute_name_index;
3195 //    u4 attribute_length;
3196 //    u2 components_count;
3197 //    component_info components[components_count];
3198 //  }
3199 //  component_info {
3200 //    u2 name_index;
3201 //    u2 descriptor_index
3202 //    u2 attributes_count;
3203 //    attribute_info_attributes[attributes_count];
3204 //  }
3205 u2 ClassFileParser::parse_classfile_record_attribute(const ClassFileStream* const cfs,
3206                                                      const ConstantPool* cp,
3207                                                      const u1* const record_attribute_start,
3208                                                      TRAPS) {
3209   const u1* const current_mark = cfs->current();
3210   int components_count = 0;
3211   unsigned int calculate_attr_size = 0;
3212   if (record_attribute_start != nullptr) {

3457   }
3458   guarantee_property(current_start + attribute_byte_length == cfs->current(),
3459                      "Bad length on BootstrapMethods in class file %s",
3460                      CHECK);
3461 }
3462 
3463 void ClassFileParser::parse_classfile_attributes(const ClassFileStream* const cfs,
3464                                                  ConstantPool* cp,
3465                  ClassFileParser::ClassAnnotationCollector* parsed_annotations,
3466                                                  TRAPS) {
3467   assert(cfs != nullptr, "invariant");
3468   assert(cp != nullptr, "invariant");
3469   assert(parsed_annotations != nullptr, "invariant");
3470 
3471   // Set inner classes attribute to default sentinel
3472   _inner_classes = Universe::the_empty_short_array();
3473   // Set nest members attribute to default sentinel
3474   _nest_members = Universe::the_empty_short_array();
3475   // Set _permitted_subclasses attribute to default sentinel
3476   _permitted_subclasses = Universe::the_empty_short_array();


3477   cfs->guarantee_more(2, CHECK);  // attributes_count
3478   u2 attributes_count = cfs->get_u2_fast();
3479   bool parsed_sourcefile_attribute = false;
3480   bool parsed_innerclasses_attribute = false;
3481   bool parsed_nest_members_attribute = false;
3482   bool parsed_permitted_subclasses_attribute = false;

3483   bool parsed_nest_host_attribute = false;
3484   bool parsed_record_attribute = false;
3485   bool parsed_enclosingmethod_attribute = false;
3486   bool parsed_bootstrap_methods_attribute = false;
3487   const u1* runtime_visible_annotations = nullptr;
3488   int runtime_visible_annotations_length = 0;
3489   const u1* runtime_invisible_annotations = nullptr;
3490   int runtime_invisible_annotations_length = 0;
3491   const u1* runtime_visible_type_annotations = nullptr;
3492   int runtime_visible_type_annotations_length = 0;
3493   const u1* runtime_invisible_type_annotations = nullptr;
3494   int runtime_invisible_type_annotations_length = 0;
3495   bool runtime_invisible_type_annotations_exists = false;
3496   bool runtime_invisible_annotations_exists = false;
3497   bool parsed_source_debug_ext_annotations_exist = false;
3498   const u1* inner_classes_attribute_start = nullptr;
3499   u4  inner_classes_attribute_length = 0;
3500   u2  enclosing_method_class_index = 0;
3501   u2  enclosing_method_method_index = 0;
3502   const u1* nest_members_attribute_start = nullptr;
3503   u4  nest_members_attribute_length = 0;
3504   const u1* record_attribute_start = nullptr;
3505   u4  record_attribute_length = 0;
3506   const u1* permitted_subclasses_attribute_start = nullptr;
3507   u4  permitted_subclasses_attribute_length = 0;


3508 
3509   // Iterate over attributes
3510   while (attributes_count--) {
3511     cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
3512     const u2 attribute_name_index = cfs->get_u2_fast();
3513     const u4 attribute_length = cfs->get_u4_fast();
3514     check_property(
3515       valid_symbol_at(attribute_name_index),
3516       "Attribute name has bad constant pool index %u in class file %s",
3517       attribute_name_index, CHECK);
3518     const Symbol* const tag = cp->symbol_at(attribute_name_index);
3519     if (tag == vmSymbols::tag_source_file()) {
3520       // Check for SourceFile tag
3521       if (_need_verify) {
3522         guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
3523       }
3524       if (parsed_sourcefile_attribute) {
3525         classfile_parse_error("Multiple SourceFile attributes in class file %s", THREAD);
3526         return;
3527       } else {

3714               return;
3715             }
3716             parsed_record_attribute = true;
3717             record_attribute_start = cfs->current();
3718             record_attribute_length = attribute_length;
3719           } else if (_major_version >= JAVA_17_VERSION) {
3720             if (tag == vmSymbols::tag_permitted_subclasses()) {
3721               if (parsed_permitted_subclasses_attribute) {
3722                 classfile_parse_error("Multiple PermittedSubclasses attributes in class file %s", CHECK);
3723                 return;
3724               }
3725               // Classes marked ACC_FINAL cannot have a PermittedSubclasses attribute.
3726               if (_access_flags.is_final()) {
3727                 classfile_parse_error("PermittedSubclasses attribute in final class file %s", CHECK);
3728                 return;
3729               }
3730               parsed_permitted_subclasses_attribute = true;
3731               permitted_subclasses_attribute_start = cfs->current();
3732               permitted_subclasses_attribute_length = attribute_length;
3733             }









3734           }
3735           // Skip attribute_length for any attribute where major_verson >= JAVA_17_VERSION
3736           cfs->skip_u1(attribute_length, CHECK);
3737         } else {
3738           // Unknown attribute
3739           cfs->skip_u1(attribute_length, CHECK);
3740         }
3741       } else {
3742         // Unknown attribute
3743         cfs->skip_u1(attribute_length, CHECK);
3744       }
3745     } else {
3746       // Unknown attribute
3747       cfs->skip_u1(attribute_length, CHECK);
3748     }
3749   }
3750   _class_annotations = assemble_annotations(runtime_visible_annotations,
3751                                             runtime_visible_annotations_length,
3752                                             runtime_invisible_annotations,
3753                                             runtime_invisible_annotations_length,

3794                             CHECK);
3795     if (_need_verify) {
3796       guarantee_property(record_attribute_length == calculated_attr_length,
3797                          "Record attribute has wrong length in class file %s",
3798                          CHECK);
3799     }
3800   }
3801 
3802   if (parsed_permitted_subclasses_attribute) {
3803     const u2 num_subclasses = parse_classfile_permitted_subclasses_attribute(
3804                             cfs,
3805                             permitted_subclasses_attribute_start,
3806                             CHECK);
3807     if (_need_verify) {
3808       guarantee_property(
3809         permitted_subclasses_attribute_length == sizeof(num_subclasses) + sizeof(u2) * num_subclasses,
3810         "Wrong PermittedSubclasses attribute length in class file %s", CHECK);
3811     }
3812   }
3813 












3814   if (_max_bootstrap_specifier_index >= 0) {
3815     guarantee_property(parsed_bootstrap_methods_attribute,
3816                        "Missing BootstrapMethods attribute in class file %s", CHECK);
3817   }
3818 }
3819 
3820 void ClassFileParser::apply_parsed_class_attributes(InstanceKlass* k) {
3821   assert(k != nullptr, "invariant");
3822 
3823   if (_synthetic_flag)
3824     k->set_is_synthetic();
3825   if (_sourcefile_index != 0) {
3826     k->set_source_file_name_index(_sourcefile_index);
3827   }
3828   if (_generic_signature_index != 0) {
3829     k->set_generic_signature_index(_generic_signature_index);
3830   }
3831   if (_sde_buffer != nullptr) {
3832     k->set_source_debug_extension(_sde_buffer, _sde_length);
3833   }

3859     _class_annotations       = nullptr;
3860     _class_type_annotations  = nullptr;
3861     _fields_annotations      = nullptr;
3862     _fields_type_annotations = nullptr;
3863 }
3864 
3865 // Transfer ownership of metadata allocated to the InstanceKlass.
3866 void ClassFileParser::apply_parsed_class_metadata(
3867                                             InstanceKlass* this_klass,
3868                                             int java_fields_count) {
3869   assert(this_klass != nullptr, "invariant");
3870 
3871   _cp->set_pool_holder(this_klass);
3872   this_klass->set_constants(_cp);
3873   this_klass->set_fieldinfo_stream(_fieldinfo_stream);
3874   this_klass->set_fields_status(_fields_status);
3875   this_klass->set_methods(_methods);
3876   this_klass->set_inner_classes(_inner_classes);
3877   this_klass->set_nest_members(_nest_members);
3878   this_klass->set_nest_host_index(_nest_host);

3879   this_klass->set_annotations(_combined_annotations);
3880   this_klass->set_permitted_subclasses(_permitted_subclasses);
3881   this_klass->set_record_components(_record_components);
3882   // Delay the setting of _local_interfaces and _transitive_interfaces until after
3883   // initialize_supers() in fill_instance_klass(). It is because the _local_interfaces could
3884   // be shared with _transitive_interfaces and _transitive_interfaces may be shared with
3885   // its _super. If an OOM occurs while loading the current klass, its _super field
3886   // may not have been set. When GC tries to free the klass, the _transitive_interfaces
3887   // may be deallocated mistakenly in InstanceKlass::deallocate_interfaces(). Subsequent
3888   // dereferences to the deallocated _transitive_interfaces will result in a crash.
3889 
3890   // Clear out these fields so they don't get deallocated by the destructor
3891   clear_class_metadata();
3892 }
3893 
3894 AnnotationArray* ClassFileParser::assemble_annotations(const u1* const runtime_visible_annotations,
3895                                                        int runtime_visible_annotations_length,
3896                                                        const u1* const runtime_invisible_annotations,
3897                                                        int runtime_invisible_annotations_length,
3898                                                        TRAPS) {

3910     }
3911     if (runtime_invisible_annotations != nullptr) {
3912       for (int i = 0; i < runtime_invisible_annotations_length; i++) {
3913         int append = runtime_visible_annotations_length+i;
3914         annotations->at_put(append, runtime_invisible_annotations[i]);
3915       }
3916     }
3917   }
3918   return annotations;
3919 }
3920 
3921 const InstanceKlass* ClassFileParser::parse_super_class(ConstantPool* const cp,
3922                                                         const int super_class_index,
3923                                                         const bool need_verify,
3924                                                         TRAPS) {
3925   assert(cp != nullptr, "invariant");
3926   const InstanceKlass* super_klass = nullptr;
3927 
3928   if (super_class_index == 0) {
3929     check_property(_class_name == vmSymbols::java_lang_Object(),
3930                    "Invalid superclass index %u in class file %s",
3931                    super_class_index,
3932                    CHECK_NULL);
3933   } else {
3934     check_property(valid_klass_reference_at(super_class_index),
3935                    "Invalid superclass index %u in class file %s",
3936                    super_class_index,
3937                    CHECK_NULL);
3938     // The class name should be legal because it is checked when parsing constant pool.
3939     // However, make sure it is not an array type.
3940     bool is_array = false;
3941     if (cp->tag_at(super_class_index).is_klass()) {
3942       super_klass = InstanceKlass::cast(cp->resolved_klass_at(super_class_index));
3943       if (need_verify)
3944         is_array = super_klass->is_array_klass();
3945     } else if (need_verify) {
3946       is_array = (cp->klass_name_at(super_class_index)->char_at(0) == JVM_SIGNATURE_ARRAY);
3947     }
3948     if (need_verify) {

3949       guarantee_property(!is_array,
3950                         "Bad superclass name in class file %s", CHECK_NULL);
3951     }
3952   }
3953   return super_klass;
3954 }
3955 
3956 OopMapBlocksBuilder::OopMapBlocksBuilder(unsigned int max_blocks) {
3957   _max_nonstatic_oop_maps = max_blocks;
3958   _nonstatic_oop_map_count = 0;
3959   if (max_blocks == 0) {
3960     _nonstatic_oop_maps = nullptr;
3961   } else {
3962     _nonstatic_oop_maps =
3963         NEW_RESOURCE_ARRAY(OopMapBlock, _max_nonstatic_oop_maps);
3964     memset(_nonstatic_oop_maps, 0, sizeof(OopMapBlock) * max_blocks);
3965   }
3966 }
3967 
3968 OopMapBlock* OopMapBlocksBuilder::last_oop_map() const {

4052 }
4053 
4054 void OopMapBlocksBuilder::print_on(outputStream* st) const {
4055   st->print_cr("  OopMapBlocks: %3d  /%3d", _nonstatic_oop_map_count, _max_nonstatic_oop_maps);
4056   if (_nonstatic_oop_map_count > 0) {
4057     OopMapBlock* map = _nonstatic_oop_maps;
4058     OopMapBlock* last_map = last_oop_map();
4059     assert(map <= last_map, "Last less than first");
4060     while (map <= last_map) {
4061       st->print_cr("    Offset: %3d  -%3d Count: %3d", map->offset(),
4062                    map->offset() + map->offset_span() - heapOopSize, map->count());
4063       map++;
4064     }
4065   }
4066 }
4067 
4068 void OopMapBlocksBuilder::print_value_on(outputStream* st) const {
4069   print_on(st);
4070 }
4071 



















4072 void ClassFileParser::set_precomputed_flags(InstanceKlass* ik) {
4073   assert(ik != nullptr, "invariant");
4074 
4075   const InstanceKlass* const super = ik->java_super();
4076 
4077   // Check if this klass has an empty finalize method (i.e. one with return bytecode only),
4078   // in which case we don't have to register objects as finalizable
4079   if (!_has_empty_finalizer) {
4080     if (_has_finalizer ||
4081         (super != nullptr && super->has_finalizer())) {
4082       ik->set_has_finalizer();
4083     }
4084   }
4085 
4086 #ifdef ASSERT
4087   bool f = false;
4088   const Method* const m = ik->lookup_method(vmSymbols::finalize_method_name(),
4089                                            vmSymbols::void_method_signature());
4090   if (InstanceKlass::is_finalization_enabled() &&
4091       (m != nullptr) && !m->is_empty_method()) {
4092       f = true;
4093   }
4094 
4095   // Spec doesn't prevent agent from redefinition of empty finalizer.
4096   // Despite the fact that it's generally bad idea and redefined finalizer
4097   // will not work as expected we shouldn't abort vm in this case
4098   if (!ik->has_redefined_this_or_super()) {
4099     assert(ik->has_finalizer() == f, "inconsistent has_finalizer");
4100   }
4101 #endif
4102 
4103   // Check if this klass supports the java.lang.Cloneable interface
4104   if (vmClasses::Cloneable_klass_loaded()) {
4105     if (ik->is_subtype_of(vmClasses::Cloneable_klass())) {





4106       ik->set_is_cloneable();
4107     }
4108   }
4109 
4110   // Check if this klass has a vanilla default constructor
4111   if (super == nullptr) {
4112     // java.lang.Object has empty default constructor
4113     ik->set_has_vanilla_constructor();
4114   } else {
4115     if (super->has_vanilla_constructor() &&
4116         _has_vanilla_constructor) {
4117       ik->set_has_vanilla_constructor();
4118     }
4119 #ifdef ASSERT
4120     bool v = false;
4121     if (super->has_vanilla_constructor()) {
4122       const Method* const constructor =
4123         ik->find_method(vmSymbols::object_initializer_name(),
4124                        vmSymbols::void_method_signature());
4125       if (constructor != nullptr && constructor->is_vanilla_constructor()) {
4126         v = true;
4127       }
4128     }
4129     assert(v == ik->has_vanilla_constructor(), "inconsistent has_vanilla_constructor");
4130 #endif
4131   }
4132 
4133   // If it cannot be fast-path allocated, set a bit in the layout helper.
4134   // See documentation of InstanceKlass::can_be_fastpath_allocated().
4135   assert(ik->size_helper() > 0, "layout_helper is initialized");
4136   if ((!RegisterFinalizersAtInit && ik->has_finalizer())
4137       || ik->is_abstract() || ik->is_interface()
4138       || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == nullptr)
4139       || ik->size_helper() >= FastAllocateSizeLimit) {
4140     // Forbid fast-path allocation.
4141     const jint lh = Klass::instance_layout_helper(ik->size_helper(), true);
4142     ik->set_layout_helper(lh);
4143   }
4144 }
4145 






4146 // utility methods for appending an array with check for duplicates
4147 
4148 static void append_interfaces(GrowableArray<InstanceKlass*>* result,
4149                               const Array<InstanceKlass*>* const ifs) {
4150   // iterate over new interfaces
4151   for (int i = 0; i < ifs->length(); i++) {
4152     InstanceKlass* const e = ifs->at(i);
4153     assert(e->is_klass() && e->is_interface(), "just checking");
4154     // add new interface
4155     result->append_if_missing(e);
4156   }
4157 }
4158 
4159 static Array<InstanceKlass*>* compute_transitive_interfaces(const InstanceKlass* super,
4160                                                             Array<InstanceKlass*>* local_ifs,
4161                                                             ClassLoaderData* loader_data,
4162                                                             TRAPS) {
4163   assert(local_ifs != nullptr, "invariant");
4164   assert(loader_data != nullptr, "invariant");
4165 

4169   // Add superclass transitive interfaces size
4170   if (super != nullptr) {
4171     super_size = super->transitive_interfaces()->length();
4172     max_transitive_size += super_size;
4173   }
4174   // Add local interfaces' super interfaces
4175   const int local_size = local_ifs->length();
4176   for (int i = 0; i < local_size; i++) {
4177     InstanceKlass* const l = local_ifs->at(i);
4178     max_transitive_size += l->transitive_interfaces()->length();
4179   }
4180   // Finally add local interfaces
4181   max_transitive_size += local_size;
4182   // Construct array
4183   if (max_transitive_size == 0) {
4184     // no interfaces, use canonicalized array
4185     return Universe::the_empty_instance_klass_array();
4186   } else if (max_transitive_size == super_size) {
4187     // no new local interfaces added, share superklass' transitive interface array
4188     return super->transitive_interfaces();
4189   } else if (max_transitive_size == local_size) {
4190     // only local interfaces added, share local interface array
4191     return local_ifs;

4192   } else {
4193     ResourceMark rm;
4194     GrowableArray<InstanceKlass*>* const result = new GrowableArray<InstanceKlass*>(max_transitive_size);
4195 
4196     // Copy down from superclass
4197     if (super != nullptr) {
4198       append_interfaces(result, super->transitive_interfaces());
4199     }
4200 
4201     // Copy down from local interfaces' superinterfaces
4202     for (int i = 0; i < local_size; i++) {
4203       InstanceKlass* const l = local_ifs->at(i);
4204       append_interfaces(result, l->transitive_interfaces());
4205     }
4206     // Finally add local interfaces
4207     append_interfaces(result, local_ifs);
4208 
4209     // length will be less than the max_transitive_size if duplicates were removed
4210     const int length = result->length();
4211     assert(length <= max_transitive_size, "just checking");

4212     Array<InstanceKlass*>* const new_result =
4213       MetadataFactory::new_array<InstanceKlass*>(loader_data, length, CHECK_NULL);
4214     for (int i = 0; i < length; i++) {
4215       InstanceKlass* const e = result->at(i);
4216       assert(e != nullptr, "just checking");
4217       new_result->at_put(i, e);
4218     }
4219     return new_result;
4220   }
4221 }
4222 
4223 void ClassFileParser::check_super_class_access(const InstanceKlass* this_klass, TRAPS) {
4224   assert(this_klass != nullptr, "invariant");
4225   const Klass* const super = this_klass->super();
4226 
4227   if (super != nullptr) {
4228     const InstanceKlass* super_ik = InstanceKlass::cast(super);
4229 
4230     if (super->is_final()) {
4231       classfile_icce_error("class %s cannot inherit from final class %s", super_ik, THREAD);
4232       return;
4233     }
4234 
4235     if (super_ik->is_sealed() && !super_ik->has_as_permitted_subclass(this_klass)) {
4236       classfile_icce_error("class %s cannot inherit from sealed class %s", super_ik, THREAD);
4237       return;
4238     }
4239 










4240     // If the loader is not the boot loader then throw an exception if its
4241     // superclass is in package jdk.internal.reflect and its loader is not a
4242     // special reflection class loader
4243     if (!this_klass->class_loader_data()->is_the_null_class_loader_data()) {
4244       PackageEntry* super_package = super->package();
4245       if (super_package != nullptr &&
4246           super_package->name()->fast_compare(vmSymbols::jdk_internal_reflect()) == 0 &&
4247           !java_lang_ClassLoader::is_reflection_class_loader(this_klass->class_loader())) {
4248         ResourceMark rm(THREAD);
4249         Exceptions::fthrow(
4250           THREAD_AND_LOCATION,
4251           vmSymbols::java_lang_IllegalAccessError(),
4252           "class %s loaded by %s cannot access jdk/internal/reflect superclass %s",
4253           this_klass->external_name(),
4254           this_klass->class_loader_data()->loader_name_and_id(),
4255           super->external_name());
4256         return;
4257       }
4258     }
4259 

4403 
4404   for (int index = 0; index < num_methods; index++) {
4405     const Method* const m = methods->at(index);
4406     // if m is static and not the init method, throw a verify error
4407     if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) {
4408       ResourceMark rm(THREAD);
4409       Exceptions::fthrow(
4410         THREAD_AND_LOCATION,
4411         vmSymbols::java_lang_VerifyError(),
4412         "Illegal static method %s in interface %s",
4413         m->name()->as_C_string(),
4414         this_klass->external_name()
4415       );
4416       return;
4417     }
4418   }
4419 }
4420 
4421 // utility methods for format checking
4422 
4423 void ClassFileParser::verify_legal_class_modifiers(jint flags, TRAPS) const {
4424   const bool is_module = (flags & JVM_ACC_MODULE) != 0;




4425   assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");
4426   if (is_module) {
4427     ResourceMark rm(THREAD);
4428     Exceptions::fthrow(
4429       THREAD_AND_LOCATION,
4430       vmSymbols::java_lang_NoClassDefFoundError(),
4431       "%s is not a class because access_flag ACC_MODULE is set",
4432       _class_name->as_C_string());
4433     return;
4434   }
4435 
4436   if (!_need_verify) { return; }






















4437 
4438   const bool is_interface  = (flags & JVM_ACC_INTERFACE)  != 0;
4439   const bool is_abstract   = (flags & JVM_ACC_ABSTRACT)   != 0;
4440   const bool is_final      = (flags & JVM_ACC_FINAL)      != 0;
4441   const bool is_super      = (flags & JVM_ACC_SUPER)      != 0;
4442   const bool is_enum       = (flags & JVM_ACC_ENUM)       != 0;
4443   const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4444   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4445 
4446   if ((is_abstract && is_final) ||
4447       (is_interface && !is_abstract) ||
4448       (is_interface && major_gte_1_5 && (is_super || is_enum)) ||
4449       (!is_interface && major_gte_1_5 && is_annotation)) {




4450     ResourceMark rm(THREAD);
4451     Exceptions::fthrow(
4452       THREAD_AND_LOCATION,
4453       vmSymbols::java_lang_ClassFormatError(),
4454       "Illegal class modifiers in class %s: 0x%X",
4455       _class_name->as_C_string(), flags
4456     );
4457     return;














4458   }
4459 }
4460 
4461 static bool has_illegal_visibility(jint flags) {
4462   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4463   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4464   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4465 
4466   return ((is_public && is_protected) ||
4467           (is_public && is_private) ||
4468           (is_protected && is_private));
4469 }
4470 
4471 // A legal major_version.minor_version must be one of the following:
4472 //
4473 //  Major_version >= 45 and major_version < 56, any minor_version.
4474 //  Major_version >= 56 and major_version <= JVM_CLASSFILE_MAJOR_VERSION and minor_version = 0.
4475 //  Major_version = JVM_CLASSFILE_MAJOR_VERSION and minor_version = 65535 and --enable-preview is present.
4476 //
4477 void ClassFileParser::verify_class_version(u2 major, u2 minor, Symbol* class_name, TRAPS){

4503         THREAD_AND_LOCATION,
4504         vmSymbols::java_lang_UnsupportedClassVersionError(),
4505         "%s (class file version %u.%u) was compiled with preview features that are unsupported. "
4506         "This version of the Java Runtime only recognizes preview features for class file version %u.%u",
4507         class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION, JAVA_PREVIEW_MINOR_VERSION);
4508       return;
4509     }
4510 
4511     if (!Arguments::enable_preview()) {
4512       classfile_ucve_error("Preview features are not enabled for %s (class file version %u.%u). Try running with '--enable-preview'",
4513                            class_name, major, minor, THREAD);
4514       return;
4515     }
4516 
4517   } else { // minor != JAVA_PREVIEW_MINOR_VERSION
4518     classfile_ucve_error("%s (class file version %u.%u) was compiled with an invalid non-zero minor version",
4519                          class_name, major, minor, THREAD);
4520   }
4521 }
4522 
4523 void ClassFileParser::verify_legal_field_modifiers(jint flags,
4524                                                    bool is_interface,
4525                                                    TRAPS) const {
4526   if (!_need_verify) { return; }
4527 
4528   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4529   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4530   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4531   const bool is_static    = (flags & JVM_ACC_STATIC)    != 0;
4532   const bool is_final     = (flags & JVM_ACC_FINAL)     != 0;
4533   const bool is_volatile  = (flags & JVM_ACC_VOLATILE)  != 0;
4534   const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
4535   const bool is_enum      = (flags & JVM_ACC_ENUM)      != 0;
4536   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4537 





4538   bool is_illegal = false;
4539 
4540   if (is_interface) {
4541     if (!is_public || !is_static || !is_final || is_private ||
4542         is_protected || is_volatile || is_transient ||
4543         (major_gte_1_5 && is_enum)) {
4544       is_illegal = true;
4545     }
4546   } else { // not interface
4547     if (has_illegal_visibility(flags) || (is_final && is_volatile)) {
4548       is_illegal = true;






4549     }
4550   }
4551 
4552   if (is_illegal) {
4553     ResourceMark rm(THREAD);
4554     Exceptions::fthrow(
4555       THREAD_AND_LOCATION,
4556       vmSymbols::java_lang_ClassFormatError(),
4557       "Illegal field modifiers in class %s: 0x%X",
4558       _class_name->as_C_string(), flags);
4559     return;
4560   }
4561 }
4562 
4563 void ClassFileParser::verify_legal_method_modifiers(jint flags,
4564                                                     bool is_interface,
4565                                                     const Symbol* name,
4566                                                     TRAPS) const {
4567   if (!_need_verify) { return; }
4568 
4569   const bool is_public       = (flags & JVM_ACC_PUBLIC)       != 0;
4570   const bool is_private      = (flags & JVM_ACC_PRIVATE)      != 0;
4571   const bool is_static       = (flags & JVM_ACC_STATIC)       != 0;
4572   const bool is_final        = (flags & JVM_ACC_FINAL)        != 0;
4573   const bool is_native       = (flags & JVM_ACC_NATIVE)       != 0;
4574   const bool is_abstract     = (flags & JVM_ACC_ABSTRACT)     != 0;
4575   const bool is_bridge       = (flags & JVM_ACC_BRIDGE)       != 0;
4576   const bool is_strict       = (flags & JVM_ACC_STRICT)       != 0;
4577   const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
4578   const bool is_protected    = (flags & JVM_ACC_PROTECTED)    != 0;
4579   const bool major_gte_1_5   = _major_version >= JAVA_1_5_VERSION;
4580   const bool major_gte_8     = _major_version >= JAVA_8_VERSION;
4581   const bool major_gte_17    = _major_version >= JAVA_17_VERSION;
4582   const bool is_initializer  = (name == vmSymbols::object_initializer_name());





4583 
4584   bool is_illegal = false;
4585 

4586   if (is_interface) {
4587     if (major_gte_8) {
4588       // Class file version is JAVA_8_VERSION or later Methods of
4589       // interfaces may set any of the flags except ACC_PROTECTED,
4590       // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must
4591       // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.
4592       if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
4593           (is_native || is_protected || is_final || is_synchronized) ||
4594           // If a specific method of a class or interface has its
4595           // ACC_ABSTRACT flag set, it must not have any of its
4596           // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,
4597           // ACC_STRICT, or ACC_SYNCHRONIZED flags set.  No need to
4598           // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as
4599           // those flags are illegal irrespective of ACC_ABSTRACT being set or not.
4600           (is_abstract && (is_private || is_static || (!major_gte_17 && is_strict)))) {
4601         is_illegal = true;
4602       }
4603     } else if (major_gte_1_5) {
4604       // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)
4605       if (!is_public || is_private || is_protected || is_static || is_final ||
4606           is_synchronized || is_native || !is_abstract || is_strict) {
4607         is_illegal = true;
4608       }
4609     } else {
4610       // Class file version is pre-JAVA_1_5_VERSION
4611       if (!is_public || is_static || is_final || is_native || !is_abstract) {
4612         is_illegal = true;
4613       }
4614     }
4615   } else { // not interface
4616     if (has_illegal_visibility(flags)) {
4617       is_illegal = true;
4618     } else {
4619       if (is_initializer) {






4620         if (is_static || is_final || is_synchronized || is_native ||
4621             is_abstract || (major_gte_1_5 && is_bridge)) {
4622           is_illegal = true;
4623         }
4624       } else { // not initializer
4625         if (is_abstract) {
4626           if ((is_final || is_native || is_private || is_static ||
4627               (major_gte_1_5 && (is_synchronized || (!major_gte_17 && is_strict))))) {
4628             is_illegal = true;





4629           }
4630         }
4631       }
4632     }
4633   }
4634 
4635   if (is_illegal) {
4636     ResourceMark rm(THREAD);
4637     Exceptions::fthrow(
4638       THREAD_AND_LOCATION,
4639       vmSymbols::java_lang_ClassFormatError(),
4640       "Method %s in class %s has illegal modifiers: 0x%X",
4641       name->as_C_string(), _class_name->as_C_string(), flags);









4642     return;
4643   }
4644 }
4645 
4646 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer,
4647                                         int length,
4648                                         TRAPS) const {
4649   assert(_need_verify, "only called when _need_verify is true");
4650   if (!UTF8::is_legal_utf8(buffer, length, _major_version <= 47)) {
4651     classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", THREAD);
4652   }
4653 }
4654 
4655 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
4656 // In class names, '/' separates unqualified names.  This is verified in this function also.
4657 // Method names also may not contain the characters '<' or '>', unless <init>
4658 // or <clinit>.  Note that method names may not be <init> or <clinit> in this
4659 // method.  Because these names have been checked as special cases before
4660 // calling this method in verify_legal_method_name.
4661 //

4779 // be taken as a field signature. Allow "void" if void_ok.
4780 // Return a pointer to just past the signature.
4781 // Return null if no legal signature is found.
4782 const char* ClassFileParser::skip_over_field_signature(const char* signature,
4783                                                        bool void_ok,
4784                                                        unsigned int length,
4785                                                        TRAPS) const {
4786   unsigned int array_dim = 0;
4787   while (length > 0) {
4788     switch (signature[0]) {
4789     case JVM_SIGNATURE_VOID: if (!void_ok) { return nullptr; }
4790     case JVM_SIGNATURE_BOOLEAN:
4791     case JVM_SIGNATURE_BYTE:
4792     case JVM_SIGNATURE_CHAR:
4793     case JVM_SIGNATURE_SHORT:
4794     case JVM_SIGNATURE_INT:
4795     case JVM_SIGNATURE_FLOAT:
4796     case JVM_SIGNATURE_LONG:
4797     case JVM_SIGNATURE_DOUBLE:
4798       return signature + 1;
4799     case JVM_SIGNATURE_CLASS: {











4800       if (_major_version < JAVA_1_5_VERSION) {
4801         // Skip over the class name if one is there
4802         const char* const p = skip_over_field_name(signature + 1, true, --length);
4803 
4804         // The next character better be a semicolon
4805         if (p && (p - signature) > 1 && p[0] == JVM_SIGNATURE_ENDCLASS) {
4806           return p + 1;
4807         }
4808       }
4809       else {
4810         // Skip leading 'L' and ignore first appearance of ';'
4811         signature++;
4812         const char* c = (const char*) memchr(signature, JVM_SIGNATURE_ENDCLASS, length - 1);
4813         // Format check signature
4814         if (c != nullptr) {
4815           int newlen = c - (char*) signature;
4816           bool legal = verify_unqualified_name(signature, newlen, LegalClass);
4817           if (!legal) {
4818             classfile_parse_error("Class name is empty or contains illegal character "
4819                                   "in descriptor in class file %s",
4820                                   THREAD);
4821             return nullptr;
4822           }
4823           return signature + newlen + 1;
4824         }
4825       }
4826       return nullptr;
4827     }
4828     case JVM_SIGNATURE_ARRAY:
4829       array_dim++;
4830       if (array_dim > 255) {

4846 
4847 // Checks if name is a legal class name.
4848 void ClassFileParser::verify_legal_class_name(const Symbol* name, TRAPS) const {
4849   if (!_need_verify || _relax_verify) { return; }
4850 
4851   assert(name->refcount() > 0, "symbol must be kept alive");
4852   char* bytes = (char*)name->bytes();
4853   unsigned int length = name->utf8_length();
4854   bool legal = false;
4855 
4856   if (length > 0) {
4857     const char* p;
4858     if (bytes[0] == JVM_SIGNATURE_ARRAY) {
4859       p = skip_over_field_signature(bytes, false, length, CHECK);
4860       legal = (p != nullptr) && ((p - bytes) == (int)length);
4861     } else if (_major_version < JAVA_1_5_VERSION) {
4862       if (bytes[0] != JVM_SIGNATURE_SPECIAL) {
4863         p = skip_over_field_name(bytes, true, length);
4864         legal = (p != nullptr) && ((p - bytes) == (int)length);
4865       }




4866     } else {
4867       // 4900761: relax the constraints based on JSR202 spec
4868       // Class names may be drawn from the entire Unicode character set.
4869       // Identifiers between '/' must be unqualified names.
4870       // The utf8 string has been verified when parsing cpool entries.
4871       legal = verify_unqualified_name(bytes, length, LegalClass);
4872     }
4873   }
4874   if (!legal) {
4875     ResourceMark rm(THREAD);
4876     assert(_class_name != nullptr, "invariant");
4877     Exceptions::fthrow(
4878       THREAD_AND_LOCATION,
4879       vmSymbols::java_lang_ClassFormatError(),
4880       "Illegal class name \"%.*s\" in class file %s", length, bytes,
4881       _class_name->as_C_string()
4882     );
4883     return;
4884   }
4885 }

4911       THREAD_AND_LOCATION,
4912       vmSymbols::java_lang_ClassFormatError(),
4913       "Illegal field name \"%.*s\" in class %s", length, bytes,
4914       _class_name->as_C_string()
4915     );
4916     return;
4917   }
4918 }
4919 
4920 // Checks if name is a legal method name.
4921 void ClassFileParser::verify_legal_method_name(const Symbol* name, TRAPS) const {
4922   if (!_need_verify || _relax_verify) { return; }
4923 
4924   assert(name != nullptr, "method name is null");
4925   char* bytes = (char*)name->bytes();
4926   unsigned int length = name->utf8_length();
4927   bool legal = false;
4928 
4929   if (length > 0) {
4930     if (bytes[0] == JVM_SIGNATURE_SPECIAL) {
4931       if (name == vmSymbols::object_initializer_name() || name == vmSymbols::class_initializer_name()) {



4932         legal = true;
4933       }
4934     } else if (_major_version < JAVA_1_5_VERSION) {
4935       const char* p;
4936       p = skip_over_field_name(bytes, false, length);
4937       legal = (p != nullptr) && ((p - bytes) == (int)length);
4938     } else {
4939       // 4881221: relax the constraints based on JSR202 spec
4940       legal = verify_unqualified_name(bytes, length, LegalMethod);
4941     }
4942   }
4943 
4944   if (!legal) {
4945     ResourceMark rm(THREAD);
4946     assert(_class_name != nullptr, "invariant");
4947     Exceptions::fthrow(
4948       THREAD_AND_LOCATION,
4949       vmSymbols::java_lang_ClassFormatError(),
4950       "Illegal method name \"%.*s\" in class %s", length, bytes,
4951       _class_name->as_C_string()
4952     );
4953     return;
4954   }
4955 }
4956 
4957 
4958 // Checks if signature is a legal field signature.
4959 void ClassFileParser::verify_legal_field_signature(const Symbol* name,
4960                                                    const Symbol* signature,
4961                                                    TRAPS) const {
4962   if (!_need_verify) { return; }



4963 
4964   const char* const bytes = (const char*)signature->bytes();
4965   const unsigned int length = signature->utf8_length();
4966   const char* const p = skip_over_field_signature(bytes, false, length, CHECK);
4967 
4968   if (p == nullptr || (p - bytes) != (int)length) {
4969     throwIllegalSignature("Field", name, signature, CHECK);
4970   }
4971 }
4972 
4973 // Check that the signature is compatible with the method name.  For example,
4974 // check that <init> has a void signature.
4975 void ClassFileParser::verify_legal_name_with_signature(const Symbol* name,
4976                                                        const Symbol* signature,
4977                                                        TRAPS) const {
4978   if (!_need_verify) {
4979     return;
4980   }
4981 
4982   // Class initializers cannot have args for class format version >= 51.
4983   if (name == vmSymbols::class_initializer_name() &&
4984       signature != vmSymbols::void_method_signature() &&
4985       _major_version >= JAVA_7_VERSION) {
4986     throwIllegalSignature("Method", name, signature, THREAD);
4987     return;
4988   }
4989 
4990   int sig_length = signature->utf8_length();
4991   if (name->utf8_length() > 0 &&

4992       name->char_at(0) == JVM_SIGNATURE_SPECIAL &&
4993       sig_length > 0 &&
4994       signature->char_at(sig_length - 1) != JVM_SIGNATURE_VOID) {
4995     throwIllegalSignature("Method", name, signature, THREAD);

4996   }
4997 }
4998 
4999 // Checks if signature is a legal method signature.
5000 // Returns number of parameters
5001 int ClassFileParser::verify_legal_method_signature(const Symbol* name,
5002                                                    const Symbol* signature,
5003                                                    TRAPS) const {
5004   if (!_need_verify) {
5005     // make sure caller's args_size will be less than 0 even for non-static
5006     // method so it will be recomputed in compute_size_of_parameters().
5007     return -2;
5008   }
5009 
5010   unsigned int args_size = 0;
5011   const char* p = (const char*)signature->bytes();
5012   unsigned int length = signature->utf8_length();
5013   const char* nextp;
5014 
5015   // The first character must be a '('

5151   }
5152 }
5153 
5154 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook,
5155                                                       const ClassInstanceInfo& cl_inst_info,
5156                                                       TRAPS) {
5157   if (_klass != nullptr) {
5158     return _klass;
5159   }
5160 
5161   InstanceKlass* const ik =
5162     InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
5163 
5164   if (is_hidden()) {
5165     mangle_hidden_class_name(ik);
5166   }
5167 
5168   fill_instance_klass(ik, changed_by_loadhook, cl_inst_info, CHECK_NULL);
5169 
5170   assert(_klass == ik, "invariant");
5171 
5172   return ik;
5173 }
5174 
5175 void ClassFileParser::fill_instance_klass(InstanceKlass* ik,
5176                                           bool changed_by_loadhook,
5177                                           const ClassInstanceInfo& cl_inst_info,
5178                                           TRAPS) {
5179   assert(ik != nullptr, "invariant");
5180 
5181   // Set name and CLD before adding to CLD
5182   ik->set_class_loader_data(_loader_data);
5183   ik->set_name(_class_name);
5184 
5185   // Add all classes to our internal class loader list here,
5186   // including classes in the bootstrap (null) class loader.
5187   const bool publicize = !is_internal();
5188 
5189   _loader_data->add_class(ik, publicize);
5190 
5191   set_klass_to_deallocate(ik);
5192 
5193   assert(_field_info != nullptr, "invariant");
5194   assert(ik->static_field_size() == _field_info->_static_field_size, "sanity");
5195   assert(ik->nonstatic_oop_map_count() == _field_info->oop_map_blocks->_nonstatic_oop_map_count,
5196          "sanity");
5197 
5198   assert(ik->is_instance_klass(), "sanity");
5199   assert(ik->size_helper() == _field_info->_instance_size, "sanity");
5200 
5201   // Fill in information already parsed
5202   ik->set_should_verify_class(_need_verify);
5203 
5204   // Not yet: supers are done below to support the new subtype-checking fields
5205   ik->set_nonstatic_field_size(_field_info->_nonstatic_field_size);
5206   ik->set_has_nonstatic_fields(_field_info->_has_nonstatic_fields);










5207   assert(_fac != nullptr, "invariant");
5208   ik->set_static_oop_field_count(_fac->count[STATIC_OOP]);
5209 
5210   // this transfers ownership of a lot of arrays from
5211   // the parser onto the InstanceKlass*
5212   apply_parsed_class_metadata(ik, _java_fields_count);



5213 
5214   // can only set dynamic nest-host after static nest information is set
5215   if (cl_inst_info.dynamic_nest_host() != nullptr) {
5216     ik->set_nest_host(cl_inst_info.dynamic_nest_host());
5217   }
5218 
5219   // note that is not safe to use the fields in the parser from this point on
5220   assert(nullptr == _cp, "invariant");
5221   assert(nullptr == _fieldinfo_stream, "invariant");
5222   assert(nullptr == _fields_status, "invariant");
5223   assert(nullptr == _methods, "invariant");
5224   assert(nullptr == _inner_classes, "invariant");
5225   assert(nullptr == _nest_members, "invariant");

5226   assert(nullptr == _combined_annotations, "invariant");
5227   assert(nullptr == _record_components, "invariant");
5228   assert(nullptr == _permitted_subclasses, "invariant");
5229 
5230   if (_has_localvariable_table) {
5231     ik->set_has_localvariable_table(true);
5232   }
5233 
5234   if (_has_final_method) {
5235     ik->set_has_final_method();
5236   }
5237 
5238   ik->copy_method_ordering(_method_ordering, CHECK);
5239   // The InstanceKlass::_methods_jmethod_ids cache
5240   // is managed on the assumption that the initial cache
5241   // size is equal to the number of methods in the class. If
5242   // that changes, then InstanceKlass::idnum_can_increment()
5243   // has to be changed accordingly.
5244   ik->set_initial_method_idnum(ik->methods()->length());
5245 
5246   ik->set_this_class_index(_this_class_index);
5247 
5248   if (_is_hidden) {
5249     // _this_class_index is a CONSTANT_Class entry that refers to this
5250     // hidden class itself. If this class needs to refer to its own methods
5251     // or fields, it would use a CONSTANT_MethodRef, etc, which would reference
5252     // _this_class_index. However, because this class is hidden (it's
5253     // not stored in SystemDictionary), _this_class_index cannot be resolved
5254     // with ConstantPool::klass_at_impl, which does a SystemDictionary lookup.
5255     // Therefore, we must eagerly resolve _this_class_index now.
5256     ik->constants()->klass_at_put(_this_class_index, ik);
5257   }
5258 
5259   ik->set_minor_version(_minor_version);
5260   ik->set_major_version(_major_version);
5261   ik->set_has_nonstatic_concrete_methods(_has_nonstatic_concrete_methods);
5262   ik->set_declares_nonstatic_concrete_methods(_declares_nonstatic_concrete_methods);



5263 
5264   if (_is_hidden) {
5265     ik->set_is_hidden();
5266   }
5267 
5268   // Set PackageEntry for this_klass
5269   oop cl = ik->class_loader();
5270   Handle clh = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(cl));
5271   ClassLoaderData* cld = ClassLoaderData::class_loader_data_or_null(clh());
5272   ik->set_package(cld, nullptr, CHECK);
5273 
5274   const Array<Method*>* const methods = ik->methods();
5275   assert(methods != nullptr, "invariant");
5276   const int methods_len = methods->length();
5277 
5278   check_methods_for_intrinsics(ik, methods);
5279 
5280   // Fill in field values obtained by parse_classfile_attributes
5281   if (_parsed_annotations->has_any_annotations()) {
5282     _parsed_annotations->apply_to(ik);

5350 
5351   assert(_all_mirandas != nullptr, "invariant");
5352 
5353   // Generate any default methods - default methods are public interface methods
5354   // that have a default implementation.  This is new with Java 8.
5355   if (_has_nonstatic_concrete_methods) {
5356     DefaultMethods::generate_default_methods(ik,
5357                                              _all_mirandas,
5358                                              CHECK);
5359   }
5360 
5361   // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5362   if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5363       !module_entry->has_default_read_edges()) {
5364     if (!module_entry->set_has_default_read_edges()) {
5365       // We won a potential race
5366       JvmtiExport::add_default_read_edges(module_handle, THREAD);
5367     }
5368   }
5369 



























5370   ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5371 
5372   if (!is_internal()) {
5373     ik->print_class_load_logging(_loader_data, module_entry, _stream);
5374 
5375     if (ik->minor_version() == JAVA_PREVIEW_MINOR_VERSION &&
5376         ik->major_version() == JVM_CLASSFILE_MAJOR_VERSION &&
5377         log_is_enabled(Info, class, preview)) {
5378       ResourceMark rm;
5379       log_info(class, preview)("Loading class %s that depends on preview features (class file version %d.65535)",
5380                                ik->external_name(), JVM_CLASSFILE_MAJOR_VERSION);
5381     }
5382 
5383     if (log_is_enabled(Debug, class, resolve))  {
5384       ResourceMark rm;
5385       // print out the superclass.
5386       const char * from = ik->external_name();
5387       if (ik->java_super() != nullptr) {
5388         log_debug(class, resolve)("%s %s (super)",
5389                    from,

5441                                  Symbol* name,
5442                                  ClassLoaderData* loader_data,
5443                                  const ClassLoadInfo* cl_info,
5444                                  Publicity pub_level,
5445                                  TRAPS) :
5446   _stream(stream),
5447   _class_name(nullptr),
5448   _loader_data(loader_data),
5449   _is_hidden(cl_info->is_hidden()),
5450   _can_access_vm_annotations(cl_info->can_access_vm_annotations()),
5451   _orig_cp_size(0),
5452   _super_klass(),
5453   _cp(nullptr),
5454   _fieldinfo_stream(nullptr),
5455   _fields_status(nullptr),
5456   _methods(nullptr),
5457   _inner_classes(nullptr),
5458   _nest_members(nullptr),
5459   _nest_host(0),
5460   _permitted_subclasses(nullptr),

5461   _record_components(nullptr),
5462   _local_interfaces(nullptr),

5463   _transitive_interfaces(nullptr),
5464   _combined_annotations(nullptr),
5465   _class_annotations(nullptr),
5466   _class_type_annotations(nullptr),
5467   _fields_annotations(nullptr),
5468   _fields_type_annotations(nullptr),
5469   _klass(nullptr),
5470   _klass_to_deallocate(nullptr),
5471   _parsed_annotations(nullptr),
5472   _fac(nullptr),
5473   _field_info(nullptr),

5474   _temp_field_info(nullptr),
5475   _method_ordering(nullptr),
5476   _all_mirandas(nullptr),
5477   _vtable_size(0),
5478   _itable_size(0),
5479   _num_miranda_methods(0),
5480   _protection_domain(cl_info->protection_domain()),
5481   _access_flags(),
5482   _pub_level(pub_level),
5483   _bad_constant_seen(0),
5484   _synthetic_flag(false),
5485   _sde_length(false),
5486   _sde_buffer(nullptr),
5487   _sourcefile_index(0),
5488   _generic_signature_index(0),
5489   _major_version(0),
5490   _minor_version(0),
5491   _this_class_index(0),
5492   _super_class_index(0),
5493   _itfs_len(0),
5494   _java_fields_count(0),
5495   _need_verify(false),
5496   _relax_verify(false),
5497   _has_nonstatic_concrete_methods(false),
5498   _declares_nonstatic_concrete_methods(false),
5499   _has_localvariable_table(false),
5500   _has_final_method(false),
5501   _has_contended_fields(false),







5502   _has_finalizer(false),
5503   _has_empty_finalizer(false),
5504   _has_vanilla_constructor(false),
5505   _max_bootstrap_specifier_index(-1) {
5506 
5507   _class_name = name != nullptr ? name : vmSymbols::unknown_class_name();
5508   _class_name->increment_refcount();
5509 
5510   assert(_loader_data != nullptr, "invariant");
5511   assert(stream != nullptr, "invariant");
5512   assert(_stream != nullptr, "invariant");
5513   assert(_stream->buffer() == _stream->current(), "invariant");
5514   assert(_class_name != nullptr, "invariant");
5515   assert(0 == _access_flags.as_int(), "invariant");
5516 
5517   // Figure out whether we can skip format checking (matching classic VM behavior)
5518   if (DumpSharedSpaces) {
5519     // verify == true means it's a 'remote' class (i.e., non-boot class)
5520     // Verification decision is based on BytecodeVerificationRemote flag
5521     // for those classes.

5532 
5533   // Check if verification needs to be relaxed for this class file
5534   // Do not restrict it to jdk1.0 or jdk1.1 to maintain backward compatibility (4982376)
5535   _relax_verify = relax_format_check_for(_loader_data);
5536 
5537   parse_stream(stream, CHECK);
5538 
5539   post_process_parsed_stream(stream, _cp, CHECK);
5540 }
5541 
5542 void ClassFileParser::clear_class_metadata() {
5543   // metadata created before the instance klass is created.  Must be
5544   // deallocated if classfile parsing returns an error.
5545   _cp = nullptr;
5546   _fieldinfo_stream = nullptr;
5547   _fields_status = nullptr;
5548   _methods = nullptr;
5549   _inner_classes = nullptr;
5550   _nest_members = nullptr;
5551   _permitted_subclasses = nullptr;

5552   _combined_annotations = nullptr;
5553   _class_annotations = _class_type_annotations = nullptr;
5554   _fields_annotations = _fields_type_annotations = nullptr;
5555   _record_components = nullptr;
5556 }
5557 
5558 // Destructor to clean up
5559 ClassFileParser::~ClassFileParser() {
5560   _class_name->decrement_refcount();
5561 
5562   if (_cp != nullptr) {
5563     MetadataFactory::free_metadata(_loader_data, _cp);
5564   }
5565 
5566   if (_fieldinfo_stream != nullptr) {
5567     MetadataFactory::free_array<u1>(_loader_data, _fieldinfo_stream);
5568   }
5569 
5570   if (_fields_status != nullptr) {
5571     MetadataFactory::free_array<FieldStatus>(_loader_data, _fields_status);
5572   }
5573 




5574   if (_methods != nullptr) {
5575     // Free methods
5576     InstanceKlass::deallocate_methods(_loader_data, _methods);
5577   }
5578 
5579   // beware of the Universe::empty_blah_array!!
5580   if (_inner_classes != nullptr && _inner_classes != Universe::the_empty_short_array()) {
5581     MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
5582   }
5583 
5584   if (_nest_members != nullptr && _nest_members != Universe::the_empty_short_array()) {
5585     MetadataFactory::free_array<u2>(_loader_data, _nest_members);
5586   }
5587 
5588   if (_record_components != nullptr) {
5589     InstanceKlass::deallocate_record_components(_loader_data, _record_components);
5590   }
5591 
5592   if (_permitted_subclasses != nullptr && _permitted_subclasses != Universe::the_empty_short_array()) {
5593     MetadataFactory::free_array<u2>(_loader_data, _permitted_subclasses);
5594   }
5595 




5596   // Free interfaces
5597   InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
5598                                        _local_interfaces, _transitive_interfaces);
5599 
5600   if (_combined_annotations != nullptr) {
5601     // After all annotations arrays have been created, they are installed into the
5602     // Annotations object that will be assigned to the InstanceKlass being created.
5603 
5604     // Deallocate the Annotations object and the installed annotations arrays.
5605     _combined_annotations->deallocate_contents(_loader_data);
5606 
5607     // If the _combined_annotations pointer is non-null,
5608     // then the other annotations fields should have been cleared.
5609     assert(_class_annotations       == nullptr, "Should have been cleared");
5610     assert(_class_type_annotations  == nullptr, "Should have been cleared");
5611     assert(_fields_annotations      == nullptr, "Should have been cleared");
5612     assert(_fields_type_annotations == nullptr, "Should have been cleared");
5613   } else {
5614     // If the annotations arrays were not installed into the Annotations object,
5615     // then they have to be deallocated explicitly.

5660     cp_size, CHECK);
5661 
5662   _orig_cp_size = cp_size;
5663   if (is_hidden()) { // Add a slot for hidden class name.
5664     cp_size++;
5665   }
5666 
5667   _cp = ConstantPool::allocate(_loader_data,
5668                                cp_size,
5669                                CHECK);
5670 
5671   ConstantPool* const cp = _cp;
5672 
5673   parse_constant_pool(stream, cp, _orig_cp_size, CHECK);
5674 
5675   assert(cp_size == (u2)cp->length(), "invariant");
5676 
5677   // ACCESS FLAGS
5678   stream->guarantee_more(8, CHECK);  // flags, this_class, super_class, infs_len
5679 
5680   // Access flags
5681   jint flags;
5682   // JVM_ACC_MODULE is defined in JDK-9 and later.
5683   if (_major_version >= JAVA_9_VERSION) {
5684     flags = stream->get_u2_fast() & (JVM_RECOGNIZED_CLASS_MODIFIERS | JVM_ACC_MODULE);
5685   } else {
5686     flags = stream->get_u2_fast() & JVM_RECOGNIZED_CLASS_MODIFIERS;


5687   }
5688 



5689   if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
5690     // Set abstract bit for old class files for backward compatibility
5691     flags |= JVM_ACC_ABSTRACT;
5692   }
5693 
5694   verify_legal_class_modifiers(flags, CHECK);
5695 
5696   short bad_constant = class_bad_constant_seen();
5697   if (bad_constant != 0) {
5698     // Do not throw CFE until after the access_flags are checked because if
5699     // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
5700     classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, THREAD);
5701     return;
5702   }
5703 
5704   _access_flags.set_flags(flags);
5705 
5706   // This class and superclass
5707   _this_class_index = stream->get_u2_fast();
5708   check_property(
5709     valid_cp_range(_this_class_index, cp_size) &&
5710       cp->tag_at(_this_class_index).is_unresolved_klass(),
5711     "Invalid this class index %u in constant pool in class file %s",
5712     _this_class_index, CHECK);
5713 
5714   Symbol* const class_name_in_cp = cp->klass_name_at(_this_class_index);
5715   assert(class_name_in_cp != nullptr, "class_name can't be null");
5716 
































5717   // Don't need to check whether this class name is legal or not.
5718   // It has been checked when constant pool is parsed.
5719   // However, make sure it is not an array type.
5720   if (_need_verify) {
5721     guarantee_property(class_name_in_cp->char_at(0) != JVM_SIGNATURE_ARRAY,
5722                        "Bad class name in class file %s",
5723                        CHECK);
5724   }
5725 
5726 #ifdef ASSERT
5727   // Basic sanity checks
5728   if (_is_hidden) {
5729     assert(_class_name != vmSymbols::unknown_class_name(), "hidden classes should have a special name");
5730   }
5731 #endif
5732 
5733   // Update the _class_name as needed depending on whether this is a named, un-named, or hidden class.
5734 
5735   if (_is_hidden) {
5736     assert(_class_name != nullptr, "Unexpected null _class_name");

5774       if (stream->source() != nullptr) {
5775         ls.print(" source: %s", stream->source());
5776       }
5777       ls.cr();
5778     }
5779   }
5780 
5781   // SUPERKLASS
5782   _super_class_index = stream->get_u2_fast();
5783   _super_klass = parse_super_class(cp,
5784                                    _super_class_index,
5785                                    _need_verify,
5786                                    CHECK);
5787 
5788   // Interfaces
5789   _itfs_len = stream->get_u2_fast();
5790   parse_interfaces(stream,
5791                    _itfs_len,
5792                    cp,
5793                    &_has_nonstatic_concrete_methods,

5794                    CHECK);
5795 
5796   assert(_local_interfaces != nullptr, "invariant");
5797 
5798   // Fields (offsets are filled in later)
5799   _fac = new FieldAllocationCount();
5800   parse_fields(stream,
5801                _access_flags.is_interface(),
5802                _fac,
5803                cp,
5804                cp_size,
5805                &_java_fields_count,
5806                CHECK);
5807 
5808   assert(_temp_field_info != nullptr, "invariant");
5809 
5810   // Methods
5811   parse_methods(stream,
5812                 _access_flags.is_interface(),


5813                 &_has_localvariable_table,
5814                 &_has_final_method,
5815                 &_declares_nonstatic_concrete_methods,
5816                 CHECK);
5817 
5818   assert(_methods != nullptr, "invariant");
5819 
5820   if (_declares_nonstatic_concrete_methods) {
5821     _has_nonstatic_concrete_methods = true;
5822   }
5823 
5824   // Additional attributes/annotations
5825   _parsed_annotations = new ClassAnnotationCollector();
5826   parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK);
5827 
5828   assert(_inner_classes != nullptr, "invariant");
5829 
5830   // Finalize the Annotations metadata object,
5831   // now that all annotation arrays have been created.
5832   create_combined_annotations(CHECK);

5872   // Update this_class_index's slot in the constant pool with the new Utf8 entry.
5873   // We have to update the resolved_klass_index and the name_index together
5874   // so extract the existing resolved_klass_index first.
5875   CPKlassSlot cp_klass_slot = _cp->klass_slot_at(_this_class_index);
5876   int resolved_klass_index = cp_klass_slot.resolved_klass_index();
5877   _cp->unresolved_klass_at_put(_this_class_index, hidden_index, resolved_klass_index);
5878   assert(_cp->klass_slot_at(_this_class_index).name_index() == _orig_cp_size,
5879          "Bad name_index");
5880 }
5881 
5882 void ClassFileParser::post_process_parsed_stream(const ClassFileStream* const stream,
5883                                                  ConstantPool* cp,
5884                                                  TRAPS) {
5885   assert(stream != nullptr, "invariant");
5886   assert(stream->at_eos(), "invariant");
5887   assert(cp != nullptr, "invariant");
5888   assert(_loader_data != nullptr, "invariant");
5889 
5890   if (_class_name == vmSymbols::java_lang_Object()) {
5891     check_property(_local_interfaces == Universe::the_empty_instance_klass_array(),
5892                    "java.lang.Object cannot implement an interface in class file %s",
5893                    CHECK);
5894   }
5895   // We check super class after class file is parsed and format is checked
5896   if (_super_class_index > 0 && nullptr == _super_klass) {
5897     Symbol* const super_class_name = cp->klass_name_at(_super_class_index);
5898     if (_access_flags.is_interface()) {
5899       // Before attempting to resolve the superclass, check for class format
5900       // errors not checked yet.
5901       guarantee_property(super_class_name == vmSymbols::java_lang_Object(),
5902         "Interfaces must have java.lang.Object as superclass in class file %s",
5903         CHECK);
5904     }
5905     Handle loader(THREAD, _loader_data->class_loader());
5906     if (loader.is_null() && super_class_name == vmSymbols::java_lang_Object()) {
5907       _super_klass = vmClasses::Object_klass();
5908     } else {
5909       _super_klass = (const InstanceKlass*)
5910                        SystemDictionary::resolve_super_or_fail(_class_name,
5911                                                                super_class_name,
5912                                                                loader,
5913                                                                _protection_domain,
5914                                                                true,
5915                                                                CHECK);
5916     }
5917   }
5918 
5919   if (_super_klass != nullptr) {









5920     if (_super_klass->has_nonstatic_concrete_methods()) {
5921       _has_nonstatic_concrete_methods = true;
5922     }




5923 
5924     if (_super_klass->is_interface()) {
5925       classfile_icce_error("class %s has interface %s as super class", _super_klass, THREAD);
5926       return;



















































5927     }
5928   }

5929 
5930   // Compute the transitive list of all unique interfaces implemented by this class
5931   _transitive_interfaces =
5932     compute_transitive_interfaces(_super_klass,
5933                                   _local_interfaces,
5934                                   _loader_data,
5935                                   CHECK);
5936 
5937   assert(_transitive_interfaces != nullptr, "invariant");
5938 
5939   // sort methods
5940   _method_ordering = sort_methods(_methods);
5941 
5942   _all_mirandas = new GrowableArray<Method*>(20);
5943 
5944   Handle loader(THREAD, _loader_data->class_loader());
5945   klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
5946                                                     &_num_miranda_methods,
5947                                                     _all_mirandas,
5948                                                     _super_klass,
5949                                                     _methods,
5950                                                     _access_flags,
5951                                                     _major_version,
5952                                                     loader,
5953                                                     _class_name,
5954                                                     _local_interfaces);
5955 
5956   // Size of Java itable (in words)
5957   _itable_size = _access_flags.is_interface() ? 0 :
5958     klassItable::compute_itable_size(_transitive_interfaces);
5959 
5960   assert(_fac != nullptr, "invariant");
5961   assert(_parsed_annotations != nullptr, "invariant");
5962 





























5963   _field_info = new FieldLayoutInfo();
5964   FieldLayoutBuilder lb(class_name(), super_klass(), _cp, /*_fields*/ _temp_field_info,
5965                         _parsed_annotations->is_contended(), _field_info);
5966   lb.build_layout();







5967 
5968   int injected_fields_count = _temp_field_info->length() - _java_fields_count;
5969   _fieldinfo_stream =
5970     FieldInfoStream::create_FieldInfoStream(_temp_field_info, _java_fields_count,
5971                                             injected_fields_count, loader_data(), CHECK);
5972   _fields_status =
5973     MetadataFactory::new_array<FieldStatus>(_loader_data, _temp_field_info->length(),
5974                                             FieldStatus(0), CHECK);
5975 }
5976 
5977 void ClassFileParser::set_klass(InstanceKlass* klass) {
5978 
5979 #ifdef ASSERT
5980   if (klass != nullptr) {
5981     assert(nullptr == _klass, "leaking?");
5982   }
5983 #endif
5984 
5985   _klass = klass;
5986 }

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

 134 #define JAVA_13_VERSION                   57
 135 
 136 #define JAVA_14_VERSION                   58
 137 
 138 #define JAVA_15_VERSION                   59
 139 
 140 #define JAVA_16_VERSION                   60
 141 
 142 #define JAVA_17_VERSION                   61
 143 
 144 #define JAVA_18_VERSION                   62
 145 
 146 #define JAVA_19_VERSION                   63
 147 
 148 #define JAVA_20_VERSION                   64
 149 
 150 #define JAVA_21_VERSION                   65
 151 
 152 #define JAVA_22_VERSION                   66
 153 
 154 #define CONSTANT_CLASS_DESCRIPTORS        66
 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 
 516         Symbol* const name = cp->symbol_at(class_index);
 517         const unsigned int name_len = name->utf8_length();
 518         if (name->is_Q_signature()) {
 519           cp->unresolved_qdescriptor_at_put(index, class_index, num_klasses++);
 520         } else {
 521           cp->unresolved_klass_at_put(index, class_index, num_klasses++);
 522         }
 523         break;
 524       }
 525       case JVM_CONSTANT_StringIndex: {
 526         const int string_index = cp->string_index_at(index);
 527         check_property(valid_symbol_at(string_index),
 528           "Invalid constant pool index %u in class file %s",
 529           string_index, CHECK);
 530         Symbol* const sym = cp->symbol_at(string_index);
 531         cp->unresolved_string_at_put(index, sym);
 532         break;
 533       }
 534       case JVM_CONSTANT_MethodHandle: {
 535         const int ref_index = cp->method_handle_index_at(index);
 536         check_property(valid_cp_range(ref_index, length),
 537           "Invalid constant pool index %u in class file %s",
 538           ref_index, CHECK);
 539         const constantTag tag = cp->tag_at(ref_index);
 540         const int ref_kind = cp->method_handle_ref_kind_at(index);
 541 
 542         switch (ref_kind) {

 702           cp->signature_ref_index_at(name_and_type_ref_index);
 703         const Symbol* const name = cp->symbol_at(name_ref_index);
 704         const Symbol* const signature = cp->symbol_at(signature_ref_index);
 705         if (tag == JVM_CONSTANT_Fieldref) {
 706           if (_need_verify) {
 707             // Field name and signature are verified above, when iterating NameAndType_info.
 708             // Need only to be sure signature is non-zero length and the right type.
 709             if (Signature::is_method(signature)) {
 710               throwIllegalSignature("Field", name, signature, CHECK);
 711             }
 712           }
 713         } else {
 714           if (_need_verify) {
 715             // Method name and signature are individually verified above, when iterating
 716             // NameAndType_info.  Need to check here that signature is non-zero length and
 717             // the right type.
 718             if (!Signature::is_method(signature)) {
 719               throwIllegalSignature("Method", name, signature, CHECK);
 720             }
 721           }
 722           // If a class method name begins with '<', it must be "<init>" and have void signature,
 723           // or if it is an inline type, <vnew> with return.
 724           const unsigned int name_len = name->utf8_length();
 725           if (tag == JVM_CONSTANT_Methodref && name_len != 0 &&
 726               name->char_at(0) == JVM_SIGNATURE_SPECIAL) {
 727             if (name != vmSymbols::object_initializer_name() &&
 728                 name != vmSymbols::inline_factory_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)) {
 734               // if return type is non-void then it must be an inline type
 735               if (name == vmSymbols::object_initializer_name() ||
 736                   !EnableValhalla || !supports_inline_types() ||
 737                   !signature->ends_with(JVM_SIGNATURE_ENDCLASS)) {
 738                 throwIllegalSignature("Method", name, signature, CHECK);
 739               }
 740             }
 741           }
 742         }
 743         break;
 744       }
 745       case JVM_CONSTANT_MethodHandle: {
 746         const int ref_index = cp->method_handle_index_at(index);
 747         const int ref_kind = cp->method_handle_ref_kind_at(index);
 748         switch (ref_kind) {
 749           case JVM_REF_invokeVirtual:
 750           case JVM_REF_invokeStatic:
 751           case JVM_REF_invokeSpecial:
 752           case JVM_REF_newInvokeSpecial: {
 753             const int name_and_type_ref_index =
 754               cp->uncached_name_and_type_ref_index_at(ref_index);
 755             const int name_ref_index =
 756               cp->name_ref_index_at(name_and_type_ref_index);
 757             const Symbol* const name = cp->symbol_at(name_ref_index);
 758 
 759             if (EnableValhalla && supports_inline_types() && name == vmSymbols::inline_factory_name()) { // <vnew>
 760               // <vnew> factory methods must be non-void return and invokeStatic.
 761               const int signature_ref_index =
 762                 cp->signature_ref_index_at(name_and_type_ref_index);
 763               const Symbol* const signature = cp->symbol_at(signature_ref_index);
 764               if (signature->is_void_method_signature() || ref_kind != JVM_REF_invokeStatic) {
 765                 classfile_parse_error(
 766                   "Bad factory method name at constant pool index %u in class file %s",
 767                   name_ref_index, CHECK);
 768               }
 769             } else if (name != vmSymbols::object_initializer_name()) { // !<init>
 770               if (ref_kind == JVM_REF_newInvokeSpecial) {
 771                 classfile_parse_error(
 772                   "Bad constructor name at constant pool index %u in class file %s",
 773                     name_ref_index, THREAD);
 774                 return;
 775               }
 776             } else { // <init>
 777               // The allowed invocation mode of <init> depends on its signature.
 778               // This test corresponds to verify_invoke_instructions in the verifier.
 779               const int signature_ref_index =
 780                 cp->signature_ref_index_at(name_and_type_ref_index);
 781               const Symbol* const signature = cp->symbol_at(signature_ref_index);
 782               if (signature->is_void_method_signature()
 783                   && ref_kind == JVM_REF_newInvokeSpecial) {
 784                 // OK, could be a constructor call
 785               } else {
 786                 classfile_parse_error(
 787                   "Bad method name at constant pool index %u in class file %s",
 788                   name_ref_index, THREAD);
 789                 return;
 790               }
 791             }
 792             break;
 793           }
 794           // Other ref_kinds are already fully checked in previous pass.
 795         } // switch(ref_kind)
 796         break;
 797       }
 798       case JVM_CONSTANT_MethodType: {
 799         const Symbol* const no_name = vmSymbols::type_name(); // place holder
 800         const Symbol* const signature = cp->method_type_signature_at(index);
 801         verify_legal_method_signature(no_name, signature, CHECK);
 802         break;
 803       }
 804       case JVM_CONSTANT_Utf8: {
 805         assert(cp->symbol_at(index)->refcount() != 0, "count corrupted");

 817 
 818   NameSigHash(Symbol* name, Symbol* sig) :
 819     _name(name),
 820     _sig(sig) {}
 821 
 822   static unsigned int hash(NameSigHash const& namesig) {
 823     return namesig._name->identity_hash() ^ namesig._sig->identity_hash();
 824   }
 825 
 826   static bool equals(NameSigHash const& e0, NameSigHash const& e1) {
 827     return (e0._name == e1._name) &&
 828           (e0._sig  == e1._sig);
 829   }
 830 };
 831 
 832 using NameSigHashtable = ResourceHashtable<NameSigHash, int,
 833                                            NameSigHash::HASH_ROW_SIZE,
 834                                            AnyObj::RESOURCE_AREA, mtInternal,
 835                                            &NameSigHash::hash, &NameSigHash::equals>;
 836 
 837 static void check_identity_and_value_modifiers(ClassFileParser* current, const InstanceKlass* super_type, TRAPS) {
 838   assert(super_type != nullptr,"Method doesn't support null super type");
 839   if (super_type->carries_identity_modifier()) {
 840     if (current->carries_value_modifier()) {
 841         ResourceMark rm(THREAD);
 842         Exceptions::fthrow(
 843           THREAD_AND_LOCATION,
 844           vmSymbols::java_lang_IncompatibleClassChangeError(),
 845           "Value type %s has an identity type as supertype",
 846           current->class_name()->as_klass_external_name());
 847         return;
 848       }
 849     current->set_carries_identity_modifier();
 850   }
 851   if (super_type->carries_value_modifier()) {
 852     if (current->carries_identity_modifier()) {
 853       ResourceMark rm(THREAD);
 854       Exceptions::fthrow(
 855         THREAD_AND_LOCATION,
 856         vmSymbols::java_lang_IncompatibleClassChangeError(),
 857         "Identity type %s has a value type as supertype",
 858         current->class_name()->as_klass_external_name());
 859       return;
 860     }
 861     current->set_carries_value_modifier();
 862   }
 863 }
 864 
 865 void ClassFileParser::parse_interfaces(const ClassFileStream* stream,
 866                                        int itfs_len,
 867                                        ConstantPool* cp,
 868                                        bool* const has_nonstatic_concrete_methods,
 869                                        // FIXME: lots of these functions
 870                                        // declare their parameters as const,
 871                                        // which adds only noise to the code.
 872                                        // Remove the spurious const modifiers.
 873                                        // Many are of the form "const int x"
 874                                        // or "T* const x".
 875                                        bool* const is_declared_atomic,
 876                                        TRAPS) {
 877   assert(stream != nullptr, "invariant");
 878   assert(cp != nullptr, "invariant");
 879   assert(has_nonstatic_concrete_methods != nullptr, "invariant");
 880 
 881   if (itfs_len == 0) {
 882     _local_interfaces = Universe::the_empty_instance_klass_array();
 883 
 884   } else {
 885     assert(itfs_len > 0, "only called for len>0");
 886     _local_interface_indexes = new GrowableArray<u2>(itfs_len);
 887     int index = 0;

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

 890       check_property(
 891         valid_klass_reference_at(interface_index),
 892         "Interface name has bad constant pool index %u in class file %s",
 893         interface_index, CHECK);
 894       _local_interface_indexes->at_put_grow(index, interface_index);































 895     }
 896 
 897     if (!_need_verify || itfs_len <= 1) {
 898       return;
 899     }
 900 
 901     // Check if there's any duplicates in interfaces
 902     ResourceMark rm(THREAD);
 903     // Set containing interface names
 904     ResourceHashtable<Symbol*, int>* interface_names = new ResourceHashtable<Symbol*, int>();
 905     for (index = 0; index < itfs_len; index++) {
 906       Symbol* interface_name = cp->klass_name_at(_local_interface_indexes->at(index));

 907       // If no duplicates, add (name, nullptr) in hashtable interface_names.
 908       if (!interface_names->put(interface_name, 0)) {
 909         classfile_parse_error("Duplicate interface name \"%s\" in class file %s",
 910                                interface_name->as_C_string(), THREAD);
 911         return;
 912       }
 913     }
 914   }
 915 }
 916 
 917 void ClassFileParser::verify_constantvalue(const ConstantPool* const cp,
 918                                            int constantvalue_index,
 919                                            int signature_index,
 920                                            TRAPS) const {
 921   // Make sure the constant pool entry is of a type appropriate to this field
 922   guarantee_property(
 923     (constantvalue_index > 0 &&
 924       constantvalue_index < cp->length()),
 925     "Bad initial value index %u in ConstantValue attribute in class file %s",
 926     constantvalue_index, CHECK);

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


1521     access_flags.set_flags(flags);
1522     FieldInfo::FieldFlags fieldFlags(0);
1523 
1524     const u2 name_index = cfs->get_u2_fast();
1525     check_property(valid_symbol_at(name_index),
1526       "Invalid constant pool index %u for field name in class file %s",
1527       name_index, CHECK);
1528     const Symbol* const name = cp->symbol_at(name_index);
1529     verify_legal_field_name(name, CHECK);
1530 
1531     const u2 signature_index = cfs->get_u2_fast();
1532     check_property(valid_symbol_at(signature_index),
1533       "Invalid constant pool index %u for field signature in class file %s",
1534       signature_index, CHECK);
1535     const Symbol* const sig = cp->symbol_at(signature_index);
1536     verify_legal_field_signature(name, sig, CHECK);
1537     if (!access_flags.is_static()) instance_fields_count++;
1538 
1539     u2 constantvalue_index = 0;
1540     bool is_synthetic = false;
1541     u2 generic_signature_index = 0;
1542     const bool is_static = access_flags.is_static();
1543     FieldAnnotationCollector parsed_annotations(_loader_data);
1544 
1545     const u2 attributes_count = cfs->get_u2_fast();
1546     if (attributes_count > 0) {
1547       parse_field_attributes(cfs,
1548                              attributes_count,
1549                              is_static,
1550                              signature_index,
1551                              &constantvalue_index,
1552                              &is_synthetic,
1553                              &generic_signature_index,
1554                              &parsed_annotations,
1555                              CHECK);
1556 
1557       if (parsed_annotations.field_annotations() != nullptr) {

1569             MetadataFactory::new_array<AnnotationArray*>(_loader_data,
1570                                                          length,
1571                                                          nullptr,
1572                                                          CHECK);
1573         }
1574         _fields_type_annotations->at_put(n, parsed_annotations.field_type_annotations());
1575         parsed_annotations.set_field_type_annotations(nullptr);
1576       }
1577 
1578       if (is_synthetic) {
1579         access_flags.set_is_synthetic();
1580       }
1581       if (generic_signature_index != 0) {
1582         fieldFlags.update_generic(true);
1583       }
1584     }
1585 
1586     const BasicType type = cp->basic_type_for_signature_at(signature_index);
1587 
1588     // Update FieldAllocationCount for this kind of field
1589     fac->update(is_static, type, type == T_PRIMITIVE_OBJECT);
1590 
1591     // Here, we still detect that the field's type is an inline type by checking if it has
1592     // a Q-descriptor. This test will be replaced later by something not relying on Q-desriptors.
1593     // From this point forward, checking if a field's type is an inline type should be performed
1594     // using the inline_type flag of FieldFlags, and not by looking for a Q-descriptor in its signature
1595     if (type == T_PRIMITIVE_OBJECT) fieldFlags.update_null_free_inline_type(true);
1596 
1597     FieldInfo fi(access_flags, name_index, signature_index, constantvalue_index, fieldFlags);
1598     fi.set_index(n);
1599     if (fieldFlags.is_generic()) {
1600       fi.set_generic_signature_index(generic_signature_index);
1601     }
1602     parsed_annotations.apply_to(&fi);
1603     if (fi.field_flags().is_contended()) {
1604       _has_contended_fields = true;
1605     }
1606     _temp_field_info->append(fi);
1607   }
1608   assert(_temp_field_info->length() == length, "Must be");
1609 
1610   int index = length;
1611   if (num_injected != 0) {
1612     for (int n = 0; n < num_injected; n++) {
1613       // Check for duplicates
1614       if (injected[n].may_be_java) {
1615         const Symbol* const name      = injected[n].name();

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

1953         "Exception name has bad type at constant pool %u in class file %s",
1954         checked_exception, CHECK_NULL);
1955     }
1956   }
1957   // check exceptions attribute length
1958   if (_need_verify) {
1959     guarantee_property(method_attribute_length == (sizeof(*checked_exceptions_length) +
1960                                                    sizeof(u2) * size),
1961                       "Exceptions attribute has wrong length in class file %s", CHECK_NULL);
1962   }
1963   return checked_exceptions_start;
1964 }
1965 
1966 void ClassFileParser::throwIllegalSignature(const char* type,
1967                                             const Symbol* name,
1968                                             const Symbol* sig,
1969                                             TRAPS) const {
1970   assert(name != nullptr, "invariant");
1971   assert(sig != nullptr, "invariant");
1972 
1973   const char* class_note = "";
1974   if (is_inline_type() && name == vmSymbols::object_initializer_name()) {
1975     class_note = " (an inline class)";
1976   }
1977 
1978   ResourceMark rm(THREAD);
1979   Exceptions::fthrow(THREAD_AND_LOCATION,
1980       vmSymbols::java_lang_ClassFormatError(),
1981       "%s \"%s\" in class %s%s has illegal signature \"%s\"", type,
1982       name->as_C_string(), _class_name->as_C_string(), class_note, sig->as_C_string());
1983 }
1984 
1985 AnnotationCollector::ID
1986 AnnotationCollector::annotation_index(const ClassLoaderData* loader_data,
1987                                       const Symbol* name,
1988                                       const bool can_access_vm_annotations) {
1989   const vmSymbolID sid = vmSymbols::find_sid(name);
1990   // Privileged code can use all annotations.  Other code silently drops some.
1991   const bool privileged = loader_data->is_boot_class_loader_data() ||
1992                           loader_data->is_platform_class_loader_data() ||
1993                           can_access_vm_annotations;
1994   switch (sid) {
1995     case VM_SYMBOL_ENUM_NAME(reflect_CallerSensitive_signature): {
1996       if (_location != _in_method)  break;  // only allow for methods
1997       if (!privileged)              break;  // only allow in privileged code
1998       return _method_CallerSensitive;
1999     }
2000     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ForceInline_signature): {
2001       if (_location != _in_method)  break;  // only allow for methods
2002       if (!privileged)              break;  // only allow in privileged code

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

2307 
2308   const u2 signature_index = cfs->get_u2_fast();
2309   guarantee_property(
2310     valid_symbol_at(signature_index),
2311     "Illegal constant pool index %u for method signature in class file %s",
2312     signature_index, CHECK_NULL);
2313   const Symbol* const signature = cp->symbol_at(signature_index);
2314 
2315   if (name == vmSymbols::class_initializer_name()) {
2316     // We ignore the other access flags for a valid class initializer.
2317     // (JVM Spec 2nd ed., chapter 4.6)
2318     if (_major_version < 51) { // backward compatibility
2319       flags = JVM_ACC_STATIC;
2320     } else if ((flags & JVM_ACC_STATIC) == JVM_ACC_STATIC) {
2321       flags &= JVM_ACC_STATIC | (_major_version <= JAVA_16_VERSION ? JVM_ACC_STRICT : 0);
2322     } else {
2323       classfile_parse_error("Method <clinit> is not static in class file %s", THREAD);
2324       return nullptr;
2325     }
2326   } else {
2327     verify_legal_method_modifiers(flags, access_flags() , name, CHECK_NULL);
2328   }
2329 
2330   if (EnableValhalla && supports_inline_types() && name == vmSymbols::inline_factory_name()) {
2331     if (is_interface) {
2332       classfile_parse_error("Interface cannot have a method named <vnew>, class file %s", CHECK_NULL);
2333     } else if (!is_value_class) {
2334        classfile_parse_error("Identity class cannot have a method <vnew>, class file %s", CHECK_NULL);
2335     } else if (signature->is_void_method_signature()) {
2336        classfile_parse_error("Factory method <vnew> must have a non-void return type, class file %s", CHECK_NULL);
2337     } else { // also OK, a static factory, as long as the return value is good
2338       bool ok = false;
2339       SignatureStream ss((Symbol*) signature, true);
2340       while (!ss.at_return_type())  ss.next();
2341       if (ss.is_reference()) {
2342         Symbol* ret = ss.as_symbol();
2343         const Symbol* required = class_name();
2344         if (is_hidden()) {
2345           // The original class name for hidden classes changed.
2346           /// So using the original name in the return type is no longer valid.
2347           required = vmSymbols::java_lang_Object();
2348         }
2349         ok = (ret == required);
2350       }
2351       if (!ok) {
2352         throwIllegalSignature("Method", name, signature, CHECK_0);
2353       }
2354       // factory method, with a non-void return.  No other
2355       // definition of <vnew> is possible.
2356       //
2357       // The verifier (in verify_invoke_instructions) will inspect the
2358       // signature of any attempt to invoke <vnew>, and ensure that it
2359       // returns non-void.
2360     }
2361   }
2362 
2363   if (name == vmSymbols::object_initializer_name()) {
2364     if (is_interface) {
2365       classfile_parse_error("Interface cannot have a method named <init>, class file %s", CHECK_NULL);
2366     } else if ((!is_value_class || is_abstract_class) && signature->is_void_method_signature()) {
2367       // OK, a constructor
2368     } else {
2369       // not OK, so throw the same error as in verify_legal_method_signature.
2370       throwIllegalSignature("Method", name, signature, CHECK_0);
2371     }
2372     // A declared <init> method must always be a non-static
2373     // object constructor, with a void return.
2374     //
2375     // The verifier (in verify_invoke_instructions) will inspect the
2376     // signature of any attempt to invoke <init>, and ensure that it
2377     // returns void.
2378   }
2379 
2380   if (EnableValhalla) {
2381     if (((flags & JVM_ACC_SYNCHRONIZED) == JVM_ACC_SYNCHRONIZED)
2382         && ((flags & JVM_ACC_STATIC) == 0 )
2383         && !carries_identity_modifier()) {
2384       classfile_parse_error("Invalid synchronized method in non-identity class %s", THREAD);
2385         return nullptr;
2386     }
2387   }
2388 
2389   int args_size = -1;  // only used when _need_verify is true
2390   if (_need_verify) {
2391     verify_legal_name_with_signature(name, signature, CHECK_NULL);
2392     args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) +
2393                  verify_legal_method_signature(name, signature, CHECK_NULL);
2394     if (args_size > MAX_ARGS_SIZE) {
2395       classfile_parse_error("Too many arguments in method signature in class file %s", THREAD);
2396       return nullptr;
2397     }
2398   }
2399 
2400   AccessFlags access_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS);
2401 
2402   // Default values for code and exceptions attribute elements
2403   u2 max_stack = 0;
2404   u2 max_locals = 0;
2405   u4 code_length = 0;
2406   const u1* code_start = 0;

2933     if (m->is_empty_method()) {
2934       _has_empty_finalizer = true;
2935     } else {
2936       _has_finalizer = true;
2937     }
2938   }
2939   if (name == vmSymbols::object_initializer_name() &&
2940       signature == vmSymbols::void_method_signature() &&
2941       m->is_vanilla_constructor()) {
2942     _has_vanilla_constructor = true;
2943   }
2944 
2945   NOT_PRODUCT(m->verify());
2946   return m;
2947 }
2948 
2949 
2950 // Side-effects: populates the _methods field in the parser
2951 void ClassFileParser::parse_methods(const ClassFileStream* const cfs,
2952                                     bool is_interface,
2953                                     bool is_value_class,
2954                                     bool is_abstract_type,
2955                                     bool* const has_localvariable_table,
2956                                     bool* has_final_method,
2957                                     bool* declares_nonstatic_concrete_methods,
2958                                     TRAPS) {
2959   assert(cfs != nullptr, "invariant");
2960   assert(has_localvariable_table != nullptr, "invariant");
2961   assert(has_final_method != nullptr, "invariant");
2962   assert(declares_nonstatic_concrete_methods != nullptr, "invariant");
2963 
2964   assert(nullptr == _methods, "invariant");
2965 
2966   cfs->guarantee_more(2, CHECK);  // length
2967   const u2 length = cfs->get_u2_fast();
2968   if (length == 0) {
2969     _methods = Universe::the_empty_method_array();
2970   } else {
2971     _methods = MetadataFactory::new_array<Method*>(_loader_data,
2972                                                    length,
2973                                                    nullptr,
2974                                                    CHECK);
2975 
2976     for (int index = 0; index < length; index++) {
2977       Method* method = parse_method(cfs,
2978                                     is_interface,
2979                                     is_value_class,
2980                                     is_abstract_type,
2981                                     _cp,
2982                                     has_localvariable_table,
2983                                     CHECK);
2984 
2985       if (method->is_final()) {
2986         *has_final_method = true;
2987       }
2988       // declares_nonstatic_concrete_methods: declares concrete instance methods, any access flags
2989       // used for interface initialization, and default method inheritance analysis
2990       if (is_interface && !(*declares_nonstatic_concrete_methods)
2991         && !method->is_abstract() && !method->is_static()) {
2992         *declares_nonstatic_concrete_methods = true;
2993       }
2994       _methods->at_put(index, method);
2995     }
2996 
2997     if (_need_verify && length > 1) {
2998       // Check duplicated methods
2999       ResourceMark rm(THREAD);
3000       // Set containing name-signature pairs

3226         valid_klass_reference_at(outer_class_info_index),
3227       "outer_class_info_index %u has bad constant type in class file %s",
3228       outer_class_info_index, CHECK_0);
3229 
3230     if (outer_class_info_index != 0) {
3231       const Symbol* const outer_class_name = cp->klass_name_at(outer_class_info_index);
3232       char* bytes = (char*)outer_class_name->bytes();
3233       guarantee_property(bytes[0] != JVM_SIGNATURE_ARRAY,
3234                          "Outer class is an array class in class file %s", CHECK_0);
3235     }
3236     // Inner class name
3237     const u2 inner_name_index = cfs->get_u2_fast();
3238     check_property(
3239       inner_name_index == 0 || valid_symbol_at(inner_name_index),
3240       "inner_name_index %u has bad constant type in class file %s",
3241       inner_name_index, CHECK_0);
3242     if (_need_verify) {
3243       guarantee_property(inner_class_info_index != outer_class_info_index,
3244                          "Class is both outer and inner class in class file %s", CHECK_0);
3245     }
3246 
3247     jint recognized_modifiers = RECOGNIZED_INNER_CLASS_MODIFIERS;
3248     // JVM_ACC_MODULE is defined in JDK-9 and later.
3249     if (_major_version >= JAVA_9_VERSION) {
3250       recognized_modifiers |= JVM_ACC_MODULE;


3251     }
3252     if (supports_inline_types()) {
3253       recognized_modifiers |= JVM_ACC_PRIMITIVE | JVM_ACC_VALUE | JVM_ACC_IDENTITY;
3254     }
3255 
3256     // Access flags
3257     jint flags = cfs->get_u2_fast() & recognized_modifiers;
3258 
3259     if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
3260       // Set abstract bit for old class files for backward compatibility
3261       flags |= JVM_ACC_ABSTRACT;
3262     }
3263 
3264     if (EnableValhalla) {
3265       if (!supports_inline_types()) {
3266         const bool is_module = (flags & JVM_ACC_MODULE) != 0;
3267         const bool is_interface = (flags & JVM_ACC_INTERFACE) != 0;
3268         if (!is_module && !is_interface) {
3269           flags |= JVM_ACC_IDENTITY;
3270         }
3271       }
3272     }
3273 
3274     const char* name = inner_name_index == 0 ? "unnamed" : cp->symbol_at(inner_name_index)->as_utf8();
3275     verify_legal_class_modifiers(flags, name, false, CHECK_0);
3276     AccessFlags inner_access_flags(flags);
3277 
3278     inner_classes->at_put(index++, inner_class_info_index);
3279     inner_classes->at_put(index++, outer_class_info_index);
3280     inner_classes->at_put(index++, inner_name_index);
3281     inner_classes->at_put(index++, inner_access_flags.as_short());
3282   }
3283 
3284   // Check for circular and duplicate entries.
3285   bool has_circularity = false;
3286   if (_need_verify) {
3287     has_circularity = check_inner_classes_circularity(cp, length * 4, CHECK_0);
3288     if (has_circularity) {
3289       // If circularity check failed then ignore InnerClasses attribute.
3290       MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
3291       index = 0;
3292       if (parsed_enclosingmethod_attribute) {
3293         inner_classes = MetadataFactory::new_array<u2>(_loader_data, 2, CHECK_0);
3294         _inner_classes = inner_classes;
3295       } else {

3359   if (length > 0) {
3360     int index = 0;
3361     cfs->guarantee_more(2 * length, CHECK_0);
3362     for (int n = 0; n < length; n++) {
3363       const u2 class_info_index = cfs->get_u2_fast();
3364       check_property(
3365         valid_klass_reference_at(class_info_index),
3366         "Permitted subclass class_info_index %u has bad constant type in class file %s",
3367         class_info_index, CHECK_0);
3368       permitted_subclasses->at_put(index++, class_info_index);
3369     }
3370     assert(index == size, "wrong size");
3371   }
3372 
3373   // Restore buffer's current position.
3374   cfs->set_current(current_mark);
3375 
3376   return length;
3377 }
3378 
3379 u2 ClassFileParser::parse_classfile_preload_attribute(const ClassFileStream* const cfs,
3380                                                                    const u1* const preload_attribute_start,
3381                                                                    TRAPS) {
3382   const u1* const current_mark = cfs->current();
3383   u2 length = 0;
3384   if (preload_attribute_start != nullptr) {
3385     cfs->set_current(preload_attribute_start);
3386     cfs->guarantee_more(2, CHECK_0);  // length
3387     length = cfs->get_u2_fast();
3388   }
3389   const int size = length;
3390   Array<u2>* const preload_classes = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
3391   _preload_classes = preload_classes;
3392   if (length > 0) {
3393     int index = 0;
3394     cfs->guarantee_more(2 * length, CHECK_0);
3395     for (int n = 0; n < length; n++) {
3396       const u2 class_info_index = cfs->get_u2_fast();
3397       check_property(
3398         valid_klass_reference_at(class_info_index),
3399         "Preload class_info_index %u has bad constant type in class file %s",
3400         class_info_index, CHECK_0);
3401       preload_classes->at_put(index++, class_info_index);
3402     }
3403     assert(index == size, "wrong size");
3404   }
3405 
3406   // Restore buffer's current position.
3407   cfs->set_current(current_mark);
3408 
3409   return length;
3410 }
3411 
3412 //  Record {
3413 //    u2 attribute_name_index;
3414 //    u4 attribute_length;
3415 //    u2 components_count;
3416 //    component_info components[components_count];
3417 //  }
3418 //  component_info {
3419 //    u2 name_index;
3420 //    u2 descriptor_index
3421 //    u2 attributes_count;
3422 //    attribute_info_attributes[attributes_count];
3423 //  }
3424 u2 ClassFileParser::parse_classfile_record_attribute(const ClassFileStream* const cfs,
3425                                                      const ConstantPool* cp,
3426                                                      const u1* const record_attribute_start,
3427                                                      TRAPS) {
3428   const u1* const current_mark = cfs->current();
3429   int components_count = 0;
3430   unsigned int calculate_attr_size = 0;
3431   if (record_attribute_start != nullptr) {

3676   }
3677   guarantee_property(current_start + attribute_byte_length == cfs->current(),
3678                      "Bad length on BootstrapMethods in class file %s",
3679                      CHECK);
3680 }
3681 
3682 void ClassFileParser::parse_classfile_attributes(const ClassFileStream* const cfs,
3683                                                  ConstantPool* cp,
3684                  ClassFileParser::ClassAnnotationCollector* parsed_annotations,
3685                                                  TRAPS) {
3686   assert(cfs != nullptr, "invariant");
3687   assert(cp != nullptr, "invariant");
3688   assert(parsed_annotations != nullptr, "invariant");
3689 
3690   // Set inner classes attribute to default sentinel
3691   _inner_classes = Universe::the_empty_short_array();
3692   // Set nest members attribute to default sentinel
3693   _nest_members = Universe::the_empty_short_array();
3694   // Set _permitted_subclasses attribute to default sentinel
3695   _permitted_subclasses = Universe::the_empty_short_array();
3696   // Set _preload_classes attribute to default sentinel
3697   _preload_classes = Universe::the_empty_short_array();
3698   cfs->guarantee_more(2, CHECK);  // attributes_count
3699   u2 attributes_count = cfs->get_u2_fast();
3700   bool parsed_sourcefile_attribute = false;
3701   bool parsed_innerclasses_attribute = false;
3702   bool parsed_nest_members_attribute = false;
3703   bool parsed_permitted_subclasses_attribute = false;
3704   bool parsed_preload_attribute = false;
3705   bool parsed_nest_host_attribute = false;
3706   bool parsed_record_attribute = false;
3707   bool parsed_enclosingmethod_attribute = false;
3708   bool parsed_bootstrap_methods_attribute = false;
3709   const u1* runtime_visible_annotations = nullptr;
3710   int runtime_visible_annotations_length = 0;
3711   const u1* runtime_invisible_annotations = nullptr;
3712   int runtime_invisible_annotations_length = 0;
3713   const u1* runtime_visible_type_annotations = nullptr;
3714   int runtime_visible_type_annotations_length = 0;
3715   const u1* runtime_invisible_type_annotations = nullptr;
3716   int runtime_invisible_type_annotations_length = 0;
3717   bool runtime_invisible_type_annotations_exists = false;
3718   bool runtime_invisible_annotations_exists = false;
3719   bool parsed_source_debug_ext_annotations_exist = false;
3720   const u1* inner_classes_attribute_start = nullptr;
3721   u4  inner_classes_attribute_length = 0;
3722   u2  enclosing_method_class_index = 0;
3723   u2  enclosing_method_method_index = 0;
3724   const u1* nest_members_attribute_start = nullptr;
3725   u4  nest_members_attribute_length = 0;
3726   const u1* record_attribute_start = nullptr;
3727   u4  record_attribute_length = 0;
3728   const u1* permitted_subclasses_attribute_start = nullptr;
3729   u4  permitted_subclasses_attribute_length = 0;
3730   const u1* preload_attribute_start = nullptr;
3731   u4  preload_attribute_length = 0;
3732 
3733   // Iterate over attributes
3734   while (attributes_count--) {
3735     cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
3736     const u2 attribute_name_index = cfs->get_u2_fast();
3737     const u4 attribute_length = cfs->get_u4_fast();
3738     check_property(
3739       valid_symbol_at(attribute_name_index),
3740       "Attribute name has bad constant pool index %u in class file %s",
3741       attribute_name_index, CHECK);
3742     const Symbol* const tag = cp->symbol_at(attribute_name_index);
3743     if (tag == vmSymbols::tag_source_file()) {
3744       // Check for SourceFile tag
3745       if (_need_verify) {
3746         guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
3747       }
3748       if (parsed_sourcefile_attribute) {
3749         classfile_parse_error("Multiple SourceFile attributes in class file %s", THREAD);
3750         return;
3751       } else {

3938               return;
3939             }
3940             parsed_record_attribute = true;
3941             record_attribute_start = cfs->current();
3942             record_attribute_length = attribute_length;
3943           } else if (_major_version >= JAVA_17_VERSION) {
3944             if (tag == vmSymbols::tag_permitted_subclasses()) {
3945               if (parsed_permitted_subclasses_attribute) {
3946                 classfile_parse_error("Multiple PermittedSubclasses attributes in class file %s", CHECK);
3947                 return;
3948               }
3949               // Classes marked ACC_FINAL cannot have a PermittedSubclasses attribute.
3950               if (_access_flags.is_final()) {
3951                 classfile_parse_error("PermittedSubclasses attribute in final class file %s", CHECK);
3952                 return;
3953               }
3954               parsed_permitted_subclasses_attribute = true;
3955               permitted_subclasses_attribute_start = cfs->current();
3956               permitted_subclasses_attribute_length = attribute_length;
3957             }
3958             if (EnableValhalla && tag == vmSymbols::tag_preload()) {
3959               if (parsed_preload_attribute) {
3960                 classfile_parse_error("Multiple Preload attributes in class file %s", CHECK);
3961                 return;
3962               }
3963               parsed_preload_attribute = true;
3964               preload_attribute_start = cfs->current();
3965               preload_attribute_length = attribute_length;
3966             }
3967           }
3968           // Skip attribute_length for any attribute where major_verson >= JAVA_17_VERSION
3969           cfs->skip_u1(attribute_length, CHECK);
3970         } else {
3971           // Unknown attribute
3972           cfs->skip_u1(attribute_length, CHECK);
3973         }
3974       } else {
3975         // Unknown attribute
3976         cfs->skip_u1(attribute_length, CHECK);
3977       }
3978     } else {
3979       // Unknown attribute
3980       cfs->skip_u1(attribute_length, CHECK);
3981     }
3982   }
3983   _class_annotations = assemble_annotations(runtime_visible_annotations,
3984                                             runtime_visible_annotations_length,
3985                                             runtime_invisible_annotations,
3986                                             runtime_invisible_annotations_length,

4027                             CHECK);
4028     if (_need_verify) {
4029       guarantee_property(record_attribute_length == calculated_attr_length,
4030                          "Record attribute has wrong length in class file %s",
4031                          CHECK);
4032     }
4033   }
4034 
4035   if (parsed_permitted_subclasses_attribute) {
4036     const u2 num_subclasses = parse_classfile_permitted_subclasses_attribute(
4037                             cfs,
4038                             permitted_subclasses_attribute_start,
4039                             CHECK);
4040     if (_need_verify) {
4041       guarantee_property(
4042         permitted_subclasses_attribute_length == sizeof(num_subclasses) + sizeof(u2) * num_subclasses,
4043         "Wrong PermittedSubclasses attribute length in class file %s", CHECK);
4044     }
4045   }
4046 
4047   if (parsed_preload_attribute) {
4048     const u2 num_classes = parse_classfile_preload_attribute(
4049                             cfs,
4050                             preload_attribute_start,
4051                             CHECK);
4052     if (_need_verify) {
4053       guarantee_property(
4054         preload_attribute_length == sizeof(num_classes) + sizeof(u2) * num_classes,
4055         "Wrong Preload attribute length in class file %s", CHECK);
4056     }
4057   }
4058 
4059   if (_max_bootstrap_specifier_index >= 0) {
4060     guarantee_property(parsed_bootstrap_methods_attribute,
4061                        "Missing BootstrapMethods attribute in class file %s", CHECK);
4062   }
4063 }
4064 
4065 void ClassFileParser::apply_parsed_class_attributes(InstanceKlass* k) {
4066   assert(k != nullptr, "invariant");
4067 
4068   if (_synthetic_flag)
4069     k->set_is_synthetic();
4070   if (_sourcefile_index != 0) {
4071     k->set_source_file_name_index(_sourcefile_index);
4072   }
4073   if (_generic_signature_index != 0) {
4074     k->set_generic_signature_index(_generic_signature_index);
4075   }
4076   if (_sde_buffer != nullptr) {
4077     k->set_source_debug_extension(_sde_buffer, _sde_length);
4078   }

4104     _class_annotations       = nullptr;
4105     _class_type_annotations  = nullptr;
4106     _fields_annotations      = nullptr;
4107     _fields_type_annotations = nullptr;
4108 }
4109 
4110 // Transfer ownership of metadata allocated to the InstanceKlass.
4111 void ClassFileParser::apply_parsed_class_metadata(
4112                                             InstanceKlass* this_klass,
4113                                             int java_fields_count) {
4114   assert(this_klass != nullptr, "invariant");
4115 
4116   _cp->set_pool_holder(this_klass);
4117   this_klass->set_constants(_cp);
4118   this_klass->set_fieldinfo_stream(_fieldinfo_stream);
4119   this_klass->set_fields_status(_fields_status);
4120   this_klass->set_methods(_methods);
4121   this_klass->set_inner_classes(_inner_classes);
4122   this_klass->set_nest_members(_nest_members);
4123   this_klass->set_nest_host_index(_nest_host);
4124   this_klass->set_preload_classes(_preload_classes);
4125   this_klass->set_annotations(_combined_annotations);
4126   this_klass->set_permitted_subclasses(_permitted_subclasses);
4127   this_klass->set_record_components(_record_components);
4128   // Delay the setting of _local_interfaces and _transitive_interfaces until after
4129   // initialize_supers() in fill_instance_klass(). It is because the _local_interfaces could
4130   // be shared with _transitive_interfaces and _transitive_interfaces may be shared with
4131   // its _super. If an OOM occurs while loading the current klass, its _super field
4132   // may not have been set. When GC tries to free the klass, the _transitive_interfaces
4133   // may be deallocated mistakenly in InstanceKlass::deallocate_interfaces(). Subsequent
4134   // dereferences to the deallocated _transitive_interfaces will result in a crash.
4135 
4136   // Clear out these fields so they don't get deallocated by the destructor
4137   clear_class_metadata();
4138 }
4139 
4140 AnnotationArray* ClassFileParser::assemble_annotations(const u1* const runtime_visible_annotations,
4141                                                        int runtime_visible_annotations_length,
4142                                                        const u1* const runtime_invisible_annotations,
4143                                                        int runtime_invisible_annotations_length,
4144                                                        TRAPS) {

4156     }
4157     if (runtime_invisible_annotations != nullptr) {
4158       for (int i = 0; i < runtime_invisible_annotations_length; i++) {
4159         int append = runtime_visible_annotations_length+i;
4160         annotations->at_put(append, runtime_invisible_annotations[i]);
4161       }
4162     }
4163   }
4164   return annotations;
4165 }
4166 
4167 const InstanceKlass* ClassFileParser::parse_super_class(ConstantPool* const cp,
4168                                                         const int super_class_index,
4169                                                         const bool need_verify,
4170                                                         TRAPS) {
4171   assert(cp != nullptr, "invariant");
4172   const InstanceKlass* super_klass = nullptr;
4173 
4174   if (super_class_index == 0) {
4175     check_property(_class_name == vmSymbols::java_lang_Object(),
4176                    "Invalid superclass index 0 in class file %s",

4177                    CHECK_NULL);
4178   } else {
4179     check_property(valid_klass_reference_at(super_class_index),
4180                    "Invalid superclass index %u in class file %s",
4181                    super_class_index,
4182                    CHECK_NULL);
4183     // The class name should be legal because it is checked when parsing constant pool.
4184     // However, make sure it is not an array type.

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




4187     }
4188     if (need_verify) {
4189       bool is_array = (cp->klass_name_at(super_class_index)->char_at(0) == JVM_SIGNATURE_ARRAY);
4190       guarantee_property(!is_array,
4191                         "Bad superclass name in class file %s", CHECK_NULL);
4192     }
4193   }
4194   return super_klass;
4195 }
4196 
4197 OopMapBlocksBuilder::OopMapBlocksBuilder(unsigned int max_blocks) {
4198   _max_nonstatic_oop_maps = max_blocks;
4199   _nonstatic_oop_map_count = 0;
4200   if (max_blocks == 0) {
4201     _nonstatic_oop_maps = nullptr;
4202   } else {
4203     _nonstatic_oop_maps =
4204         NEW_RESOURCE_ARRAY(OopMapBlock, _max_nonstatic_oop_maps);
4205     memset(_nonstatic_oop_maps, 0, sizeof(OopMapBlock) * max_blocks);
4206   }
4207 }
4208 
4209 OopMapBlock* OopMapBlocksBuilder::last_oop_map() const {

4293 }
4294 
4295 void OopMapBlocksBuilder::print_on(outputStream* st) const {
4296   st->print_cr("  OopMapBlocks: %3d  /%3d", _nonstatic_oop_map_count, _max_nonstatic_oop_maps);
4297   if (_nonstatic_oop_map_count > 0) {
4298     OopMapBlock* map = _nonstatic_oop_maps;
4299     OopMapBlock* last_map = last_oop_map();
4300     assert(map <= last_map, "Last less than first");
4301     while (map <= last_map) {
4302       st->print_cr("    Offset: %3d  -%3d Count: %3d", map->offset(),
4303                    map->offset() + map->offset_span() - heapOopSize, map->count());
4304       map++;
4305     }
4306   }
4307 }
4308 
4309 void OopMapBlocksBuilder::print_value_on(outputStream* st) const {
4310   print_on(st);
4311 }
4312 
4313 void ClassFileParser::throwInlineTypeLimitation(THREAD_AND_LOCATION_DECL,
4314                                                 const char* msg,
4315                                                 const Symbol* name,
4316                                                 const Symbol* sig) const {
4317 
4318   ResourceMark rm(THREAD);
4319   if (name == nullptr || sig == nullptr) {
4320     Exceptions::fthrow(THREAD_AND_LOCATION_ARGS,
4321         vmSymbols::java_lang_ClassFormatError(),
4322         "class: %s - %s", _class_name->as_C_string(), msg);
4323   }
4324   else {
4325     Exceptions::fthrow(THREAD_AND_LOCATION_ARGS,
4326         vmSymbols::java_lang_ClassFormatError(),
4327         "\"%s\" sig: \"%s\" class: %s - %s", name->as_C_string(), sig->as_C_string(),
4328         _class_name->as_C_string(), msg);
4329   }
4330 }
4331 
4332 void ClassFileParser::set_precomputed_flags(InstanceKlass* ik) {
4333   assert(ik != nullptr, "invariant");
4334 
4335   const InstanceKlass* const super = ik->java_super();
4336 
4337   // Check if this klass has an empty finalize method (i.e. one with return bytecode only),
4338   // in which case we don't have to register objects as finalizable
4339   if (!_has_empty_finalizer) {
4340     if (_has_finalizer ||
4341         (super != nullptr && super->has_finalizer())) {
4342       ik->set_has_finalizer();
4343     }
4344   }
4345 
4346 #ifdef ASSERT
4347   bool f = false;
4348   const Method* const m = ik->lookup_method(vmSymbols::finalize_method_name(),
4349                                            vmSymbols::void_method_signature());
4350   if (InstanceKlass::is_finalization_enabled() &&
4351       (m != nullptr) && !m->is_empty_method()) {
4352       f = true;
4353   }
4354 
4355   // Spec doesn't prevent agent from redefinition of empty finalizer.
4356   // Despite the fact that it's generally bad idea and redefined finalizer
4357   // will not work as expected we shouldn't abort vm in this case
4358   if (!ik->has_redefined_this_or_super()) {
4359     assert(ik->has_finalizer() == f, "inconsistent has_finalizer");
4360   }
4361 #endif
4362 
4363   // Check if this klass supports the java.lang.Cloneable interface
4364   if (vmClasses::Cloneable_klass_loaded()) {
4365     if (ik->is_subtype_of(vmClasses::Cloneable_klass())) {
4366       if (ik->is_inline_klass()) {
4367         JavaThread *THREAD = JavaThread::current();
4368         throwInlineTypeLimitation(THREAD_AND_LOCATION, "Inline Types do not support Cloneable");
4369         return;
4370       }
4371       ik->set_is_cloneable();
4372     }
4373   }
4374 
4375   // Check if this klass has a vanilla default constructor
4376   if (super == nullptr) {
4377     // java.lang.Object has empty default constructor
4378     ik->set_has_vanilla_constructor();
4379   } else {
4380     if (super->has_vanilla_constructor() &&
4381         _has_vanilla_constructor) {
4382       ik->set_has_vanilla_constructor();
4383     }
4384 #ifdef ASSERT
4385     bool v = false;
4386     if (super->has_vanilla_constructor()) {
4387       const Method* const constructor =
4388         ik->find_method(vmSymbols::object_initializer_name(),
4389                        vmSymbols::void_method_signature());
4390       if (constructor != nullptr && constructor->is_vanilla_constructor()) {
4391         v = true;
4392       }
4393     }
4394     assert(v == ik->has_vanilla_constructor(), "inconsistent has_vanilla_constructor");
4395 #endif
4396   }
4397 
4398   // If it cannot be fast-path allocated, set a bit in the layout helper.
4399   // See documentation of InstanceKlass::can_be_fastpath_allocated().
4400   assert(ik->size_helper() > 0, "layout_helper is initialized");
4401   if ((!RegisterFinalizersAtInit && ik->has_finalizer())
4402       || ik->is_abstract() || ik->is_interface()
4403       || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == nullptr)
4404       || ik->size_helper() >= FastAllocateSizeLimit) {
4405     // Forbid fast-path allocation.
4406     const jint lh = Klass::instance_layout_helper(ik->size_helper(), true);
4407     ik->set_layout_helper(lh);
4408   }
4409 }
4410 
4411 bool ClassFileParser::supports_inline_types() const {
4412   // Inline types are only supported by class file version 61.65535 and later
4413   return _major_version > JAVA_22_VERSION ||
4414          (_major_version == JAVA_22_VERSION /*&& _minor_version == JAVA_PREVIEW_MINOR_VERSION*/); // JAVA_PREVIEW_MINOR_VERSION not yet implemented by javac, check JVMS draft
4415 }
4416 
4417 // utility methods for appending an array with check for duplicates
4418 
4419 static void append_interfaces(GrowableArray<InstanceKlass*>* result,
4420                               const Array<InstanceKlass*>* const ifs) {
4421   // iterate over new interfaces
4422   for (int i = 0; i < ifs->length(); i++) {
4423     InstanceKlass* const e = ifs->at(i);
4424     assert(e->is_klass() && e->is_interface(), "just checking");
4425     // add new interface
4426     result->append_if_missing(e);
4427   }
4428 }
4429 
4430 static Array<InstanceKlass*>* compute_transitive_interfaces(const InstanceKlass* super,
4431                                                             Array<InstanceKlass*>* local_ifs,
4432                                                             ClassLoaderData* loader_data,
4433                                                             TRAPS) {
4434   assert(local_ifs != nullptr, "invariant");
4435   assert(loader_data != nullptr, "invariant");
4436 

4440   // Add superclass transitive interfaces size
4441   if (super != nullptr) {
4442     super_size = super->transitive_interfaces()->length();
4443     max_transitive_size += super_size;
4444   }
4445   // Add local interfaces' super interfaces
4446   const int local_size = local_ifs->length();
4447   for (int i = 0; i < local_size; i++) {
4448     InstanceKlass* const l = local_ifs->at(i);
4449     max_transitive_size += l->transitive_interfaces()->length();
4450   }
4451   // Finally add local interfaces
4452   max_transitive_size += local_size;
4453   // Construct array
4454   if (max_transitive_size == 0) {
4455     // no interfaces, use canonicalized array
4456     return Universe::the_empty_instance_klass_array();
4457   } else if (max_transitive_size == super_size) {
4458     // no new local interfaces added, share superklass' transitive interface array
4459     return super->transitive_interfaces();
4460     // The three lines below are commented to work around bug JDK-8245487
4461 //  } else if (max_transitive_size == local_size) {
4462 //    // only local interfaces added, share local interface array
4463 //    return local_ifs;
4464   } else {
4465     ResourceMark rm;
4466     GrowableArray<InstanceKlass*>* const result = new GrowableArray<InstanceKlass*>(max_transitive_size);
4467 
4468     // Copy down from superclass
4469     if (super != nullptr) {
4470       append_interfaces(result, super->transitive_interfaces());
4471     }
4472 
4473     // Copy down from local interfaces' superinterfaces
4474     for (int i = 0; i < local_size; i++) {
4475       InstanceKlass* const l = local_ifs->at(i);
4476       append_interfaces(result, l->transitive_interfaces());
4477     }
4478     // Finally add local interfaces
4479     append_interfaces(result, local_ifs);
4480 
4481     // length will be less than the max_transitive_size if duplicates were removed
4482     const int length = result->length();
4483     assert(length <= max_transitive_size, "just checking");
4484 
4485     Array<InstanceKlass*>* const new_result =
4486       MetadataFactory::new_array<InstanceKlass*>(loader_data, length, CHECK_NULL);
4487     for (int i = 0; i < length; i++) {
4488       InstanceKlass* const e = result->at(i);
4489       assert(e != nullptr, "just checking");
4490       new_result->at_put(i, e);
4491     }
4492     return new_result;
4493   }
4494 }
4495 
4496 void ClassFileParser::check_super_class_access(const InstanceKlass* this_klass, TRAPS) {
4497   assert(this_klass != nullptr, "invariant");
4498   const Klass* const super = this_klass->super();
4499 
4500   if (super != nullptr) {
4501     const InstanceKlass* super_ik = InstanceKlass::cast(super);
4502 
4503     if (super->is_final()) {
4504       classfile_icce_error("class %s cannot inherit from final class %s", super_ik, THREAD);
4505       return;
4506     }
4507 
4508     if (super_ik->is_sealed() && !super_ik->has_as_permitted_subclass(this_klass)) {
4509       classfile_icce_error("class %s cannot inherit from sealed class %s", super_ik, THREAD);
4510       return;
4511     }
4512 
4513     // The JVMS says that super classes for value types must not have the ACC_IDENTITY
4514     // flag set. But, java.lang.Object must still be allowed to be a direct super class
4515     // for a value classes.  So, it is treated as a special case for now.
4516     if (this_klass->access_flags().is_value_class() &&
4517         super_ik->name() != vmSymbols::java_lang_Object() &&
4518         super_ik->is_identity_class()) {
4519       classfile_icce_error("value class %s cannot inherit from class %s", super_ik, THREAD);
4520       return;
4521     }
4522 
4523     // If the loader is not the boot loader then throw an exception if its
4524     // superclass is in package jdk.internal.reflect and its loader is not a
4525     // special reflection class loader
4526     if (!this_klass->class_loader_data()->is_the_null_class_loader_data()) {
4527       PackageEntry* super_package = super->package();
4528       if (super_package != nullptr &&
4529           super_package->name()->fast_compare(vmSymbols::jdk_internal_reflect()) == 0 &&
4530           !java_lang_ClassLoader::is_reflection_class_loader(this_klass->class_loader())) {
4531         ResourceMark rm(THREAD);
4532         Exceptions::fthrow(
4533           THREAD_AND_LOCATION,
4534           vmSymbols::java_lang_IllegalAccessError(),
4535           "class %s loaded by %s cannot access jdk/internal/reflect superclass %s",
4536           this_klass->external_name(),
4537           this_klass->class_loader_data()->loader_name_and_id(),
4538           super->external_name());
4539         return;
4540       }
4541     }
4542 

4686 
4687   for (int index = 0; index < num_methods; index++) {
4688     const Method* const m = methods->at(index);
4689     // if m is static and not the init method, throw a verify error
4690     if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) {
4691       ResourceMark rm(THREAD);
4692       Exceptions::fthrow(
4693         THREAD_AND_LOCATION,
4694         vmSymbols::java_lang_VerifyError(),
4695         "Illegal static method %s in interface %s",
4696         m->name()->as_C_string(),
4697         this_klass->external_name()
4698       );
4699       return;
4700     }
4701   }
4702 }
4703 
4704 // utility methods for format checking
4705 
4706 void ClassFileParser::verify_legal_class_modifiers(jint flags, const char* name, bool is_Object, TRAPS) const {
4707   const bool is_module = (flags & JVM_ACC_MODULE) != 0;
4708   const bool is_value_class = (flags & JVM_ACC_VALUE) != 0;
4709   const bool is_primitive_class = (flags & JVM_ACC_PRIMITIVE) != 0;
4710   const bool is_identity_class = (flags & JVM_ACC_IDENTITY) != 0;
4711   const bool is_inner_class = name != nullptr;
4712   assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");
4713   if (is_module) {
4714     ResourceMark rm(THREAD);
4715     Exceptions::fthrow(
4716       THREAD_AND_LOCATION,
4717       vmSymbols::java_lang_NoClassDefFoundError(),
4718       "%s is not a class because access_flag ACC_MODULE is set",
4719       _class_name->as_C_string());
4720     return;
4721   }
4722 
4723   if (is_value_class && !EnableValhalla) {
4724       ResourceMark rm(THREAD);
4725       Exceptions::fthrow(
4726         THREAD_AND_LOCATION,
4727         vmSymbols::java_lang_ClassFormatError(),
4728         "Class modifier ACC_VALUE in class %s requires option -XX:+EnableValhalla",
4729         _class_name->as_C_string()
4730       );
4731     return;
4732   }
4733 
4734   if (is_primitive_class && !EnablePrimitiveClasses) {
4735       ResourceMark rm(THREAD);
4736       Exceptions::fthrow(
4737         THREAD_AND_LOCATION,
4738         vmSymbols::java_lang_ClassFormatError(),
4739         "Class modifier ACC_PRIMITIVE in class %s requires option -XX:+EnablePrimitiveClasses",
4740         _class_name->as_C_string()
4741       );
4742     return;
4743   }
4744 
4745   // if (!_need_verify) { return; }
4746 
4747   const bool is_interface  = (flags & JVM_ACC_INTERFACE)  != 0;
4748   const bool is_abstract   = (flags & JVM_ACC_ABSTRACT)   != 0;
4749   const bool is_final      = (flags & JVM_ACC_FINAL)      != 0;
4750   const bool is_super      = (flags & JVM_ACC_SUPER)      != 0;
4751   const bool is_enum       = (flags & JVM_ACC_ENUM)       != 0;
4752   const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4753   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4754 
4755   if ((is_abstract && is_final) ||
4756       (is_interface && !is_abstract) ||
4757       (is_interface && major_gte_1_5 && ((is_super && (!EnableValhalla || !supports_inline_types())) || is_enum)) ||   //  ACC_SUPER (now ACC_IDENTITY) was illegal for interfaces
4758       (!is_interface && major_gte_1_5 && is_annotation) ||
4759       (is_value_class && is_enum) ||
4760       (is_identity_class && is_value_class) ||
4761       (EnableValhalla && supports_inline_types() && !is_module && !is_abstract && !is_Object && !(is_identity_class || is_value_class) && !is_inner_class) ||
4762       (EnablePrimitiveClasses && supports_inline_types() && is_primitive_class && (!is_value_class || !is_final || is_interface || is_abstract))) {
4763     ResourceMark rm(THREAD);
4764     const char* class_note = "";
4765     if (is_value_class)  class_note = " (a value class)";
4766     if (is_primitive_class)  class_note = " (a primitive class)";
4767     if (is_value_class && is_identity_class) class_note = " (a value and identity class)";
4768     if (name == nullptr) { // Not an inner class
4769       Exceptions::fthrow(
4770         THREAD_AND_LOCATION,
4771         vmSymbols::java_lang_ClassFormatError(),
4772         "Illegal class modifiers in class %s%s: 0x%X",
4773         _class_name->as_C_string(), class_note, flags
4774       );
4775       return;
4776     } else {
4777       Exceptions::fthrow(
4778         THREAD_AND_LOCATION,
4779         vmSymbols::java_lang_ClassFormatError(),
4780         "Illegal class modifiers in declaration of inner class %s%s of class %s: 0x%X",
4781         name, class_note, _class_name->as_C_string(), flags
4782       );
4783       return;
4784     }
4785   }
4786 }
4787 
4788 static bool has_illegal_visibility(jint flags) {
4789   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4790   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4791   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4792 
4793   return ((is_public && is_protected) ||
4794           (is_public && is_private) ||
4795           (is_protected && is_private));
4796 }
4797 
4798 // A legal major_version.minor_version must be one of the following:
4799 //
4800 //  Major_version >= 45 and major_version < 56, any minor_version.
4801 //  Major_version >= 56 and major_version <= JVM_CLASSFILE_MAJOR_VERSION and minor_version = 0.
4802 //  Major_version = JVM_CLASSFILE_MAJOR_VERSION and minor_version = 65535 and --enable-preview is present.
4803 //
4804 void ClassFileParser::verify_class_version(u2 major, u2 minor, Symbol* class_name, TRAPS){

4830         THREAD_AND_LOCATION,
4831         vmSymbols::java_lang_UnsupportedClassVersionError(),
4832         "%s (class file version %u.%u) was compiled with preview features that are unsupported. "
4833         "This version of the Java Runtime only recognizes preview features for class file version %u.%u",
4834         class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION, JAVA_PREVIEW_MINOR_VERSION);
4835       return;
4836     }
4837 
4838     if (!Arguments::enable_preview()) {
4839       classfile_ucve_error("Preview features are not enabled for %s (class file version %u.%u). Try running with '--enable-preview'",
4840                            class_name, major, minor, THREAD);
4841       return;
4842     }
4843 
4844   } else { // minor != JAVA_PREVIEW_MINOR_VERSION
4845     classfile_ucve_error("%s (class file version %u.%u) was compiled with an invalid non-zero minor version",
4846                          class_name, major, minor, THREAD);
4847   }
4848 }
4849 
4850 void ClassFileParser:: verify_legal_field_modifiers(jint flags,
4851                                                    AccessFlags class_access_flags,
4852                                                    TRAPS) const {
4853   if (!_need_verify) { return; }
4854 
4855   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4856   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4857   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4858   const bool is_static    = (flags & JVM_ACC_STATIC)    != 0;
4859   const bool is_final     = (flags & JVM_ACC_FINAL)     != 0;
4860   const bool is_volatile  = (flags & JVM_ACC_VOLATILE)  != 0;
4861   const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
4862   const bool is_enum      = (flags & JVM_ACC_ENUM)      != 0;
4863   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4864 
4865   const bool is_interface = class_access_flags.is_interface();
4866   const bool is_abstract = class_access_flags.is_abstract();
4867   const bool is_value_class = class_access_flags.is_value_class();
4868   const bool is_identity_class = class_access_flags.is_identity_class();
4869 
4870   bool is_illegal = false;
4871 
4872   if (is_interface) {
4873     if (!is_public || !is_static || !is_final || is_private ||
4874         is_protected || is_volatile || is_transient ||
4875         (major_gte_1_5 && is_enum)) {
4876       is_illegal = true;
4877     }
4878   } else { // not interface
4879     if (has_illegal_visibility(flags) || (is_final && is_volatile)) {
4880       is_illegal = true;
4881     } else {
4882       if (is_value_class && !is_abstract && !is_static && !is_final) {
4883         is_illegal = true;
4884       } else if (is_abstract && !is_identity_class && !is_static) {
4885         is_illegal = true;
4886       }
4887     }
4888   }
4889 
4890   if (is_illegal) {
4891     ResourceMark rm(THREAD);
4892     Exceptions::fthrow(
4893       THREAD_AND_LOCATION,
4894       vmSymbols::java_lang_ClassFormatError(),
4895       "Illegal field modifiers in class %s: 0x%X",
4896       _class_name->as_C_string(), flags);
4897     return;
4898   }
4899 }
4900 
4901 void ClassFileParser::verify_legal_method_modifiers(jint flags,
4902                                                     AccessFlags class_access_flags,
4903                                                     const Symbol* name,
4904                                                     TRAPS) const {
4905   if (!_need_verify) { return; }
4906 
4907   const bool is_public       = (flags & JVM_ACC_PUBLIC)       != 0;
4908   const bool is_private      = (flags & JVM_ACC_PRIVATE)      != 0;
4909   const bool is_static       = (flags & JVM_ACC_STATIC)       != 0;
4910   const bool is_final        = (flags & JVM_ACC_FINAL)        != 0;
4911   const bool is_native       = (flags & JVM_ACC_NATIVE)       != 0;
4912   const bool is_abstract     = (flags & JVM_ACC_ABSTRACT)     != 0;
4913   const bool is_bridge       = (flags & JVM_ACC_BRIDGE)       != 0;
4914   const bool is_strict       = (flags & JVM_ACC_STRICT)       != 0;
4915   const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
4916   const bool is_protected    = (flags & JVM_ACC_PROTECTED)    != 0;
4917   const bool major_gte_1_5   = _major_version >= JAVA_1_5_VERSION;
4918   const bool major_gte_8     = _major_version >= JAVA_8_VERSION;
4919   const bool major_gte_17    = _major_version >= JAVA_17_VERSION;
4920   const bool is_initializer  = (name == vmSymbols::object_initializer_name());
4921   const bool is_factory      = (name == vmSymbols::inline_factory_name() && supports_inline_types());
4922   const bool is_interface    = class_access_flags.is_interface();
4923   const bool is_value_class  = class_access_flags.is_value_class();
4924   const bool is_identity_class = class_access_flags.is_identity_class();
4925   const bool is_abstract_class = class_access_flags.is_abstract();
4926 
4927   bool is_illegal = false;
4928 
4929   const char* class_note = "";
4930   if (is_interface) {
4931     if (major_gte_8) {
4932       // Class file version is JAVA_8_VERSION or later Methods of
4933       // interfaces may set any of the flags except ACC_PROTECTED,
4934       // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must
4935       // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.
4936       if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
4937           (is_native || is_protected || is_final || is_synchronized) ||
4938           // If a specific method of a class or interface has its
4939           // ACC_ABSTRACT flag set, it must not have any of its
4940           // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,
4941           // ACC_STRICT, or ACC_SYNCHRONIZED flags set.  No need to
4942           // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as
4943           // those flags are illegal irrespective of ACC_ABSTRACT being set or not.
4944           (is_abstract && (is_private || is_static || (!major_gte_17 && is_strict)))) {
4945         is_illegal = true;
4946       }
4947     } else if (major_gte_1_5) {
4948       // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)
4949       if (!is_public || is_private || is_protected || is_static || is_final ||
4950           is_synchronized || is_native || !is_abstract || is_strict) {
4951         is_illegal = true;
4952       }
4953     } else {
4954       // Class file version is pre-JAVA_1_5_VERSION
4955       if (!is_public || is_static || is_final || is_native || !is_abstract) {
4956         is_illegal = true;
4957       }
4958     }
4959   } else { // not interface
4960     if (has_illegal_visibility(flags)) {
4961       is_illegal = true;
4962     } else {
4963       if (is_factory) { // <vnew> factory method
4964         if (is_final || is_synchronized || is_native || !is_static ||
4965             is_abstract || is_bridge) {
4966           is_illegal = true;
4967           class_note = (is_value_class ? " (a value class)" : " (not a value class)");
4968         }
4969       } else if (is_initializer) {
4970         if (is_static || is_final || is_synchronized || is_native ||
4971             is_abstract || (major_gte_1_5 && is_bridge)) {
4972           is_illegal = true;
4973         }
4974       } else { // not initializer
4975         if (!is_identity_class && is_synchronized && !is_static) {
4976           is_illegal = true;
4977           class_note = " (not an identity class)";
4978         } else {
4979           if (is_abstract) {
4980             if ((is_final || is_native || is_private || is_static ||
4981                 (major_gte_1_5 && (is_synchronized || (!major_gte_17 && is_strict))))) {
4982               is_illegal = true;
4983             }
4984           }
4985         }
4986       }
4987     }
4988   }
4989 
4990   if (is_illegal) {
4991     ResourceMark rm(THREAD);
4992     if (is_value_class && is_initializer) {
4993       Exceptions::fthrow(
4994         THREAD_AND_LOCATION,
4995         vmSymbols::java_lang_ClassFormatError(),
4996         "Method <init> is not allowed in value class %s",
4997         _class_name->as_C_string());
4998     } else {
4999       Exceptions::fthrow(
5000         THREAD_AND_LOCATION,
5001         vmSymbols::java_lang_ClassFormatError(),
5002         "Method %s in class %s%s has illegal modifiers: 0x%X",
5003         name->as_C_string(), _class_name->as_C_string(),
5004         class_note, flags);
5005     }
5006     return;
5007   }
5008 }
5009 
5010 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer,
5011                                         int length,
5012                                         TRAPS) const {
5013   assert(_need_verify, "only called when _need_verify is true");
5014   if (!UTF8::is_legal_utf8(buffer, length, _major_version <= 47)) {
5015     classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", THREAD);
5016   }
5017 }
5018 
5019 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
5020 // In class names, '/' separates unqualified names.  This is verified in this function also.
5021 // Method names also may not contain the characters '<' or '>', unless <init>
5022 // or <clinit>.  Note that method names may not be <init> or <clinit> in this
5023 // method.  Because these names have been checked as special cases before
5024 // calling this method in verify_legal_method_name.
5025 //

5143 // be taken as a field signature. Allow "void" if void_ok.
5144 // Return a pointer to just past the signature.
5145 // Return null if no legal signature is found.
5146 const char* ClassFileParser::skip_over_field_signature(const char* signature,
5147                                                        bool void_ok,
5148                                                        unsigned int length,
5149                                                        TRAPS) const {
5150   unsigned int array_dim = 0;
5151   while (length > 0) {
5152     switch (signature[0]) {
5153     case JVM_SIGNATURE_VOID: if (!void_ok) { return nullptr; }
5154     case JVM_SIGNATURE_BOOLEAN:
5155     case JVM_SIGNATURE_BYTE:
5156     case JVM_SIGNATURE_CHAR:
5157     case JVM_SIGNATURE_SHORT:
5158     case JVM_SIGNATURE_INT:
5159     case JVM_SIGNATURE_FLOAT:
5160     case JVM_SIGNATURE_LONG:
5161     case JVM_SIGNATURE_DOUBLE:
5162       return signature + 1;
5163     case JVM_SIGNATURE_PRIMITIVE_OBJECT:
5164       // Can't enable this check fully until JDK upgrades the bytecode generators (TODO: JDK-8270852).
5165       // For now, compare to class file version 51 so old verifier doesn't see Q signatures.
5166       if ( (_major_version < 51 /* CONSTANT_CLASS_DESCRIPTORS */ ) || (!EnablePrimitiveClasses)) {
5167         classfile_parse_error("Class name contains illegal Q-signature "
5168                               "in descriptor in class file %s, requires option -XX:+EnablePrimitiveClasses",
5169                               CHECK_0);
5170         return nullptr;
5171       }
5172       // fall through
5173     case JVM_SIGNATURE_CLASS:
5174     {
5175       if (_major_version < JAVA_1_5_VERSION) {
5176         // Skip over the class name if one is there
5177         const char* const p = skip_over_field_name(signature + 1, true, --length);
5178 
5179         // The next character better be a semicolon
5180         if (p && (p - signature) > 1 && p[0] == JVM_SIGNATURE_ENDCLASS) {
5181           return p + 1;
5182         }
5183       }
5184       else {
5185         // Skip leading 'L' or 'Q' and ignore first appearance of ';'
5186         signature++;
5187         const char* c = (const char*) memchr(signature, JVM_SIGNATURE_ENDCLASS, length - 1);
5188         // Format check signature
5189         if (c != nullptr) {
5190           int newlen = c - (char*) signature;
5191           bool legal = verify_unqualified_name(signature, newlen, LegalClass);
5192           if (!legal) {
5193             classfile_parse_error("Class name is empty or contains illegal character "
5194                                   "in descriptor in class file %s",
5195                                   THREAD);
5196             return nullptr;
5197           }
5198           return signature + newlen + 1;
5199         }
5200       }
5201       return nullptr;
5202     }
5203     case JVM_SIGNATURE_ARRAY:
5204       array_dim++;
5205       if (array_dim > 255) {

5221 
5222 // Checks if name is a legal class name.
5223 void ClassFileParser::verify_legal_class_name(const Symbol* name, TRAPS) const {
5224   if (!_need_verify || _relax_verify) { return; }
5225 
5226   assert(name->refcount() > 0, "symbol must be kept alive");
5227   char* bytes = (char*)name->bytes();
5228   unsigned int length = name->utf8_length();
5229   bool legal = false;
5230 
5231   if (length > 0) {
5232     const char* p;
5233     if (bytes[0] == JVM_SIGNATURE_ARRAY) {
5234       p = skip_over_field_signature(bytes, false, length, CHECK);
5235       legal = (p != nullptr) && ((p - bytes) == (int)length);
5236     } else if (_major_version < JAVA_1_5_VERSION) {
5237       if (bytes[0] != JVM_SIGNATURE_SPECIAL) {
5238         p = skip_over_field_name(bytes, true, length);
5239         legal = (p != nullptr) && ((p - bytes) == (int)length);
5240       }
5241     } else if ((_major_version >= CONSTANT_CLASS_DESCRIPTORS || _class_name->starts_with("jdk/internal/reflect/"))
5242                    && bytes[length - 1] == ';' ) {
5243       // Support for L...; and Q...; descriptors
5244       legal = verify_unqualified_name(bytes + 1, length - 2, LegalClass);
5245     } else {
5246       // 4900761: relax the constraints based on JSR202 spec
5247       // Class names may be drawn from the entire Unicode character set.
5248       // Identifiers between '/' must be unqualified names.
5249       // The utf8 string has been verified when parsing cpool entries.
5250       legal = verify_unqualified_name(bytes, length, LegalClass);
5251     }
5252   }
5253   if (!legal) {
5254     ResourceMark rm(THREAD);
5255     assert(_class_name != nullptr, "invariant");
5256     Exceptions::fthrow(
5257       THREAD_AND_LOCATION,
5258       vmSymbols::java_lang_ClassFormatError(),
5259       "Illegal class name \"%.*s\" in class file %s", length, bytes,
5260       _class_name->as_C_string()
5261     );
5262     return;
5263   }
5264 }

5290       THREAD_AND_LOCATION,
5291       vmSymbols::java_lang_ClassFormatError(),
5292       "Illegal field name \"%.*s\" in class %s", length, bytes,
5293       _class_name->as_C_string()
5294     );
5295     return;
5296   }
5297 }
5298 
5299 // Checks if name is a legal method name.
5300 void ClassFileParser::verify_legal_method_name(const Symbol* name, TRAPS) const {
5301   if (!_need_verify || _relax_verify) { return; }
5302 
5303   assert(name != nullptr, "method name is null");
5304   char* bytes = (char*)name->bytes();
5305   unsigned int length = name->utf8_length();
5306   bool legal = false;
5307 
5308   if (length > 0) {
5309     if (bytes[0] == JVM_SIGNATURE_SPECIAL) {
5310       if (name == vmSymbols::object_initializer_name() ||
5311           name == vmSymbols::class_initializer_name()  ||
5312           (EnableValhalla && supports_inline_types() &&
5313           name == vmSymbols::inline_factory_name())) {
5314         legal = true;
5315       }
5316     } else if (_major_version < JAVA_1_5_VERSION) {
5317       const char* p;
5318       p = skip_over_field_name(bytes, false, length);
5319       legal = (p != nullptr) && ((p - bytes) == (int)length);
5320     } else {
5321       // 4881221: relax the constraints based on JSR202 spec
5322       legal = verify_unqualified_name(bytes, length, LegalMethod);
5323     }
5324   }
5325 
5326   if (!legal) {
5327     ResourceMark rm(THREAD);
5328     assert(_class_name != nullptr, "invariant");
5329     Exceptions::fthrow(
5330       THREAD_AND_LOCATION,
5331       vmSymbols::java_lang_ClassFormatError(),
5332       "Illegal method name \"%.*s\" in class %s", length, bytes,
5333       _class_name->as_C_string()
5334     );
5335     return;
5336   }
5337 }
5338 
5339 
5340 // Checks if signature is a legal field signature.
5341 void ClassFileParser::verify_legal_field_signature(const Symbol* name,
5342                                                    const Symbol* signature,
5343                                                    TRAPS) const {
5344   if (!_need_verify) { return; }
5345   if ((!supports_inline_types() || !EnablePrimitiveClasses) && (signature->is_Q_signature() || signature->is_Q_array_signature())) {
5346     throwIllegalSignature("Field", name, signature, CHECK);
5347   }
5348 
5349   const char* const bytes = (const char*)signature->bytes();
5350   const unsigned int length = signature->utf8_length();
5351   const char* const p = skip_over_field_signature(bytes, false, length, CHECK);
5352 
5353   if (p == nullptr || (p - bytes) != (int)length) {
5354     throwIllegalSignature("Field", name, signature, CHECK);
5355   }
5356 }
5357 
5358 // Check that the signature is compatible with the method name.  For example,
5359 // check that <init> has a void signature.
5360 void ClassFileParser::verify_legal_name_with_signature(const Symbol* name,
5361                                                        const Symbol* signature,
5362                                                        TRAPS) const {
5363   if (!_need_verify) {
5364     return;
5365   }
5366 
5367   // Class initializers cannot have args for class format version >= 51.
5368   if (name == vmSymbols::class_initializer_name() &&
5369       signature != vmSymbols::void_method_signature() &&
5370       _major_version >= JAVA_7_VERSION) {
5371     throwIllegalSignature("Method", name, signature, THREAD);
5372     return;
5373   }
5374 
5375   if (!is_value_class()) {
5376     int sig_length = signature->utf8_length();
5377     if (name->utf8_length() > 0 &&
5378       name->char_at(0) == JVM_SIGNATURE_SPECIAL &&
5379       sig_length > 0 &&
5380       signature->char_at(sig_length - 1) != JVM_SIGNATURE_VOID) {
5381       throwIllegalSignature("Method", name, signature, THREAD);
5382     }
5383   }
5384 }
5385 
5386 // Checks if signature is a legal method signature.
5387 // Returns number of parameters
5388 int ClassFileParser::verify_legal_method_signature(const Symbol* name,
5389                                                    const Symbol* signature,
5390                                                    TRAPS) const {
5391   if (!_need_verify) {
5392     // make sure caller's args_size will be less than 0 even for non-static
5393     // method so it will be recomputed in compute_size_of_parameters().
5394     return -2;
5395   }
5396 
5397   unsigned int args_size = 0;
5398   const char* p = (const char*)signature->bytes();
5399   unsigned int length = signature->utf8_length();
5400   const char* nextp;
5401 
5402   // The first character must be a '('

5538   }
5539 }
5540 
5541 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook,
5542                                                       const ClassInstanceInfo& cl_inst_info,
5543                                                       TRAPS) {
5544   if (_klass != nullptr) {
5545     return _klass;
5546   }
5547 
5548   InstanceKlass* const ik =
5549     InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
5550 
5551   if (is_hidden()) {
5552     mangle_hidden_class_name(ik);
5553   }
5554 
5555   fill_instance_klass(ik, changed_by_loadhook, cl_inst_info, CHECK_NULL);
5556 
5557   assert(_klass == ik, "invariant");

5558   return ik;
5559 }
5560 
5561 void ClassFileParser::fill_instance_klass(InstanceKlass* ik,
5562                                           bool changed_by_loadhook,
5563                                           const ClassInstanceInfo& cl_inst_info,
5564                                           TRAPS) {
5565   assert(ik != nullptr, "invariant");
5566 
5567   // Set name and CLD before adding to CLD
5568   ik->set_class_loader_data(_loader_data);
5569   ik->set_name(_class_name);
5570 
5571   // Add all classes to our internal class loader list here,
5572   // including classes in the bootstrap (null) class loader.
5573   const bool publicize = !is_internal();
5574 
5575   _loader_data->add_class(ik, publicize);
5576 
5577   set_klass_to_deallocate(ik);
5578 
5579   assert(_field_info != nullptr, "invariant");
5580   assert(ik->static_field_size() == _field_info->_static_field_size, "sanity");
5581   assert(ik->nonstatic_oop_map_count() == _field_info->oop_map_blocks->_nonstatic_oop_map_count,
5582          "sanity");
5583 
5584   assert(ik->is_instance_klass(), "sanity");
5585   assert(ik->size_helper() == _field_info->_instance_size, "sanity");
5586 
5587   // Fill in information already parsed
5588   ik->set_should_verify_class(_need_verify);
5589 
5590   // Not yet: supers are done below to support the new subtype-checking fields
5591   ik->set_nonstatic_field_size(_field_info->_nonstatic_field_size);
5592   ik->set_has_nonstatic_fields(_field_info->_has_nonstatic_fields);
5593   if (_field_info->_is_naturally_atomic && ik->is_inline_klass()) {
5594     ik->set_is_naturally_atomic();
5595   }
5596 
5597   if (carries_identity_modifier()) {
5598     ik->set_carries_identity_modifier();
5599   } else if (carries_value_modifier()) {
5600     ik->set_carries_value_modifier();
5601   }
5602 
5603   assert(_fac != nullptr, "invariant");
5604   ik->set_static_oop_field_count(_fac->count[STATIC_OOP] + _fac->count[STATIC_INLINE]);
5605 
5606   // this transfers ownership of a lot of arrays from
5607   // the parser onto the InstanceKlass*
5608   apply_parsed_class_metadata(ik, _java_fields_count);
5609   if (ik->is_inline_klass()) {
5610     InlineKlass::cast(ik)->init_fixed_block();
5611   }
5612 
5613   // can only set dynamic nest-host after static nest information is set
5614   if (cl_inst_info.dynamic_nest_host() != nullptr) {
5615     ik->set_nest_host(cl_inst_info.dynamic_nest_host());
5616   }
5617 
5618   // note that is not safe to use the fields in the parser from this point on
5619   assert(nullptr == _cp, "invariant");
5620   assert(nullptr == _fieldinfo_stream, "invariant");
5621   assert(nullptr == _fields_status, "invariant");
5622   assert(nullptr == _methods, "invariant");
5623   assert(nullptr == _inner_classes, "invariant");
5624   assert(nullptr == _nest_members, "invariant");
5625   assert(nullptr == _preload_classes, "invariant");
5626   assert(nullptr == _combined_annotations, "invariant");
5627   assert(nullptr == _record_components, "invariant");
5628   assert(nullptr == _permitted_subclasses, "invariant");
5629 
5630   if (_has_localvariable_table) {
5631     ik->set_has_localvariable_table(true);
5632   }
5633 
5634   if (_has_final_method) {
5635     ik->set_has_final_method();
5636   }
5637 
5638   ik->copy_method_ordering(_method_ordering, CHECK);
5639   // The InstanceKlass::_methods_jmethod_ids cache
5640   // is managed on the assumption that the initial cache
5641   // size is equal to the number of methods in the class. If
5642   // that changes, then InstanceKlass::idnum_can_increment()
5643   // has to be changed accordingly.
5644   ik->set_initial_method_idnum(ik->methods()->length());
5645 
5646   ik->set_this_class_index(_this_class_index);
5647 
5648   if (_is_hidden) {
5649     // _this_class_index is a CONSTANT_Class entry that refers to this
5650     // hidden class itself. If this class needs to refer to its own methods
5651     // or fields, it would use a CONSTANT_MethodRef, etc, which would reference
5652     // _this_class_index. However, because this class is hidden (it's
5653     // not stored in SystemDictionary), _this_class_index cannot be resolved
5654     // with ConstantPool::klass_at_impl, which does a SystemDictionary lookup.
5655     // Therefore, we must eagerly resolve _this_class_index now.
5656     ik->constants()->klass_at_put(_this_class_index, ik);
5657   }
5658 
5659   ik->set_minor_version(_minor_version);
5660   ik->set_major_version(_major_version);
5661   ik->set_has_nonstatic_concrete_methods(_has_nonstatic_concrete_methods);
5662   ik->set_declares_nonstatic_concrete_methods(_declares_nonstatic_concrete_methods);
5663   if (_is_declared_atomic) {
5664     ik->set_is_declared_atomic();
5665   }
5666 
5667   if (_is_hidden) {
5668     ik->set_is_hidden();
5669   }
5670 
5671   // Set PackageEntry for this_klass
5672   oop cl = ik->class_loader();
5673   Handle clh = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(cl));
5674   ClassLoaderData* cld = ClassLoaderData::class_loader_data_or_null(clh());
5675   ik->set_package(cld, nullptr, CHECK);
5676 
5677   const Array<Method*>* const methods = ik->methods();
5678   assert(methods != nullptr, "invariant");
5679   const int methods_len = methods->length();
5680 
5681   check_methods_for_intrinsics(ik, methods);
5682 
5683   // Fill in field values obtained by parse_classfile_attributes
5684   if (_parsed_annotations->has_any_annotations()) {
5685     _parsed_annotations->apply_to(ik);

5753 
5754   assert(_all_mirandas != nullptr, "invariant");
5755 
5756   // Generate any default methods - default methods are public interface methods
5757   // that have a default implementation.  This is new with Java 8.
5758   if (_has_nonstatic_concrete_methods) {
5759     DefaultMethods::generate_default_methods(ik,
5760                                              _all_mirandas,
5761                                              CHECK);
5762   }
5763 
5764   // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5765   if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5766       !module_entry->has_default_read_edges()) {
5767     if (!module_entry->set_has_default_read_edges()) {
5768       // We won a potential race
5769       JvmtiExport::add_default_read_edges(module_handle, THREAD);
5770     }
5771   }
5772 
5773   bool all_fields_empty = true;
5774   for (AllFieldStream fs(ik); !fs.done(); fs.next()) {
5775     if (!fs.access_flags().is_static()) {
5776       if (fs.field_descriptor().is_null_free_inline_type()) {
5777         Klass* k = _inline_type_field_klasses->at(fs.index());
5778         ik->set_inline_type_field_klass(fs.index(), k);
5779         if (!InlineKlass::cast(k)->is_empty_inline_type()) { all_fields_empty = false; }
5780       } else {
5781         all_fields_empty = false;
5782       }
5783     } else if (is_inline_type() && (fs.name() == vmSymbols::default_value_name())) {
5784       InlineKlass::cast(ik)->set_default_value_offset(ik->field_offset(fs.index()));
5785     }
5786   }
5787 
5788   if (_is_empty_inline_type || (is_inline_type() && all_fields_empty)) {
5789     ik->set_is_empty_inline_type();
5790   }
5791 
5792   if (is_inline_type()) {
5793     InlineKlass* vk = InlineKlass::cast(ik);
5794     vk->set_alignment(_alignment);
5795     vk->set_first_field_offset(_first_field_offset);
5796     vk->set_exact_size_in_bytes(_exact_size_in_bytes);
5797     InlineKlass::cast(ik)->initialize_calling_convention(CHECK);
5798   }
5799 
5800   ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5801 
5802   if (!is_internal()) {
5803     ik->print_class_load_logging(_loader_data, module_entry, _stream);
5804 
5805     if (ik->minor_version() == JAVA_PREVIEW_MINOR_VERSION &&
5806         ik->major_version() == JVM_CLASSFILE_MAJOR_VERSION &&
5807         log_is_enabled(Info, class, preview)) {
5808       ResourceMark rm;
5809       log_info(class, preview)("Loading class %s that depends on preview features (class file version %d.65535)",
5810                                ik->external_name(), JVM_CLASSFILE_MAJOR_VERSION);
5811     }
5812 
5813     if (log_is_enabled(Debug, class, resolve))  {
5814       ResourceMark rm;
5815       // print out the superclass.
5816       const char * from = ik->external_name();
5817       if (ik->java_super() != nullptr) {
5818         log_debug(class, resolve)("%s %s (super)",
5819                    from,

5871                                  Symbol* name,
5872                                  ClassLoaderData* loader_data,
5873                                  const ClassLoadInfo* cl_info,
5874                                  Publicity pub_level,
5875                                  TRAPS) :
5876   _stream(stream),
5877   _class_name(nullptr),
5878   _loader_data(loader_data),
5879   _is_hidden(cl_info->is_hidden()),
5880   _can_access_vm_annotations(cl_info->can_access_vm_annotations()),
5881   _orig_cp_size(0),
5882   _super_klass(),
5883   _cp(nullptr),
5884   _fieldinfo_stream(nullptr),
5885   _fields_status(nullptr),
5886   _methods(nullptr),
5887   _inner_classes(nullptr),
5888   _nest_members(nullptr),
5889   _nest_host(0),
5890   _permitted_subclasses(nullptr),
5891   _preload_classes(nullptr),
5892   _record_components(nullptr),
5893   _local_interfaces(nullptr),
5894   _local_interface_indexes(nullptr),
5895   _transitive_interfaces(nullptr),
5896   _combined_annotations(nullptr),
5897   _class_annotations(nullptr),
5898   _class_type_annotations(nullptr),
5899   _fields_annotations(nullptr),
5900   _fields_type_annotations(nullptr),
5901   _klass(nullptr),
5902   _klass_to_deallocate(nullptr),
5903   _parsed_annotations(nullptr),
5904   _fac(nullptr),
5905   _field_info(nullptr),
5906   _inline_type_field_klasses(nullptr),
5907   _temp_field_info(nullptr),
5908   _method_ordering(nullptr),
5909   _all_mirandas(nullptr),
5910   _vtable_size(0),
5911   _itable_size(0),
5912   _num_miranda_methods(0),
5913   _protection_domain(cl_info->protection_domain()),
5914   _access_flags(),
5915   _pub_level(pub_level),
5916   _bad_constant_seen(0),
5917   _synthetic_flag(false),
5918   _sde_length(false),
5919   _sde_buffer(nullptr),
5920   _sourcefile_index(0),
5921   _generic_signature_index(0),
5922   _major_version(0),
5923   _minor_version(0),
5924   _this_class_index(0),
5925   _super_class_index(0),
5926   _itfs_len(0),
5927   _java_fields_count(0),
5928   _need_verify(false),
5929   _relax_verify(false),
5930   _has_nonstatic_concrete_methods(false),
5931   _declares_nonstatic_concrete_methods(false),
5932   _has_localvariable_table(false),
5933   _has_final_method(false),
5934   _has_contended_fields(false),
5935   _has_inline_type_fields(false),
5936   _has_nonstatic_fields(false),
5937   _is_empty_inline_type(false),
5938   _is_naturally_atomic(false),
5939   _is_declared_atomic(false),
5940   _carries_value_modifier(false),
5941   _carries_identity_modifier(false),
5942   _has_finalizer(false),
5943   _has_empty_finalizer(false),
5944   _has_vanilla_constructor(false),
5945   _max_bootstrap_specifier_index(-1) {
5946 
5947   _class_name = name != nullptr ? name : vmSymbols::unknown_class_name();
5948   _class_name->increment_refcount();
5949 
5950   assert(_loader_data != nullptr, "invariant");
5951   assert(stream != nullptr, "invariant");
5952   assert(_stream != nullptr, "invariant");
5953   assert(_stream->buffer() == _stream->current(), "invariant");
5954   assert(_class_name != nullptr, "invariant");
5955   assert(0 == _access_flags.as_int(), "invariant");
5956 
5957   // Figure out whether we can skip format checking (matching classic VM behavior)
5958   if (DumpSharedSpaces) {
5959     // verify == true means it's a 'remote' class (i.e., non-boot class)
5960     // Verification decision is based on BytecodeVerificationRemote flag
5961     // for those classes.

5972 
5973   // Check if verification needs to be relaxed for this class file
5974   // Do not restrict it to jdk1.0 or jdk1.1 to maintain backward compatibility (4982376)
5975   _relax_verify = relax_format_check_for(_loader_data);
5976 
5977   parse_stream(stream, CHECK);
5978 
5979   post_process_parsed_stream(stream, _cp, CHECK);
5980 }
5981 
5982 void ClassFileParser::clear_class_metadata() {
5983   // metadata created before the instance klass is created.  Must be
5984   // deallocated if classfile parsing returns an error.
5985   _cp = nullptr;
5986   _fieldinfo_stream = nullptr;
5987   _fields_status = nullptr;
5988   _methods = nullptr;
5989   _inner_classes = nullptr;
5990   _nest_members = nullptr;
5991   _permitted_subclasses = nullptr;
5992   _preload_classes = nullptr;
5993   _combined_annotations = nullptr;
5994   _class_annotations = _class_type_annotations = nullptr;
5995   _fields_annotations = _fields_type_annotations = nullptr;
5996   _record_components = nullptr;
5997 }
5998 
5999 // Destructor to clean up
6000 ClassFileParser::~ClassFileParser() {
6001   _class_name->decrement_refcount();
6002 
6003   if (_cp != nullptr) {
6004     MetadataFactory::free_metadata(_loader_data, _cp);
6005   }
6006 
6007   if (_fieldinfo_stream != nullptr) {
6008     MetadataFactory::free_array<u1>(_loader_data, _fieldinfo_stream);
6009   }
6010 
6011   if (_fields_status != nullptr) {
6012     MetadataFactory::free_array<FieldStatus>(_loader_data, _fields_status);
6013   }
6014 
6015   if (_inline_type_field_klasses != nullptr) {
6016      MetadataFactory::free_array<InlineKlass*>(_loader_data, _inline_type_field_klasses);
6017   }
6018 
6019   if (_methods != nullptr) {
6020     // Free methods
6021     InstanceKlass::deallocate_methods(_loader_data, _methods);
6022   }
6023 
6024   // beware of the Universe::empty_blah_array!!
6025   if (_inner_classes != nullptr && _inner_classes != Universe::the_empty_short_array()) {
6026     MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
6027   }
6028 
6029   if (_nest_members != nullptr && _nest_members != Universe::the_empty_short_array()) {
6030     MetadataFactory::free_array<u2>(_loader_data, _nest_members);
6031   }
6032 
6033   if (_record_components != nullptr) {
6034     InstanceKlass::deallocate_record_components(_loader_data, _record_components);
6035   }
6036 
6037   if (_permitted_subclasses != nullptr && _permitted_subclasses != Universe::the_empty_short_array()) {
6038     MetadataFactory::free_array<u2>(_loader_data, _permitted_subclasses);
6039   }
6040 
6041   if (_preload_classes != nullptr && _preload_classes != Universe::the_empty_short_array()) {
6042     MetadataFactory::free_array<u2>(_loader_data, _preload_classes);
6043   }
6044 
6045   // Free interfaces
6046   InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
6047                                        _local_interfaces, _transitive_interfaces);
6048 
6049   if (_combined_annotations != nullptr) {
6050     // After all annotations arrays have been created, they are installed into the
6051     // Annotations object that will be assigned to the InstanceKlass being created.
6052 
6053     // Deallocate the Annotations object and the installed annotations arrays.
6054     _combined_annotations->deallocate_contents(_loader_data);
6055 
6056     // If the _combined_annotations pointer is non-null,
6057     // then the other annotations fields should have been cleared.
6058     assert(_class_annotations       == nullptr, "Should have been cleared");
6059     assert(_class_type_annotations  == nullptr, "Should have been cleared");
6060     assert(_fields_annotations      == nullptr, "Should have been cleared");
6061     assert(_fields_type_annotations == nullptr, "Should have been cleared");
6062   } else {
6063     // If the annotations arrays were not installed into the Annotations object,
6064     // then they have to be deallocated explicitly.

6109     cp_size, CHECK);
6110 
6111   _orig_cp_size = cp_size;
6112   if (is_hidden()) { // Add a slot for hidden class name.
6113     cp_size++;
6114   }
6115 
6116   _cp = ConstantPool::allocate(_loader_data,
6117                                cp_size,
6118                                CHECK);
6119 
6120   ConstantPool* const cp = _cp;
6121 
6122   parse_constant_pool(stream, cp, _orig_cp_size, CHECK);
6123 
6124   assert(cp_size == (u2)cp->length(), "invariant");
6125 
6126   // ACCESS FLAGS
6127   stream->guarantee_more(8, CHECK);  // flags, this_class, super_class, infs_len
6128 
6129   jint recognized_modifiers = JVM_RECOGNIZED_CLASS_MODIFIERS;

6130   // JVM_ACC_MODULE is defined in JDK-9 and later.
6131   if (_major_version >= JAVA_9_VERSION) {
6132     recognized_modifiers |= JVM_ACC_MODULE;
6133   }
6134   // JVM_ACC_VALUE and JVM_ACC_PRIMITIVE supported version
6135   if (supports_inline_types()) {
6136     recognized_modifiers |= JVM_ACC_PRIMITIVE | JVM_ACC_VALUE;
6137   }
6138 
6139   // Access flags
6140   jint flags = stream->get_u2_fast() & recognized_modifiers;
6141 
6142   if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
6143     // Set abstract bit for old class files for backward compatibility
6144     flags |= JVM_ACC_ABSTRACT;
6145   }
6146 












6147   // This class and superclass
6148   _this_class_index = stream->get_u2_fast();
6149   check_property(
6150     valid_cp_range(_this_class_index, cp_size) &&
6151       cp->tag_at(_this_class_index).is_unresolved_klass(),
6152     "Invalid this class index %u in constant pool in class file %s",
6153     _this_class_index, CHECK);
6154 
6155   Symbol* const class_name_in_cp = cp->klass_name_at(_this_class_index);
6156   assert(class_name_in_cp != nullptr, "class_name can't be null");
6157 
6158   bool is_java_lang_Object = class_name_in_cp == vmSymbols::java_lang_Object();
6159 
6160   verify_legal_class_modifiers(flags, nullptr, is_java_lang_Object, CHECK);
6161 
6162   if (EnableValhalla) {
6163     if(!supports_inline_types()) {
6164       const bool is_module = (flags & JVM_ACC_MODULE) != 0;
6165       const bool is_interface = (flags & JVM_ACC_INTERFACE) != 0;
6166       if (!is_module && !is_interface && !is_java_lang_Object) {
6167         flags |= JVM_ACC_IDENTITY;
6168       }
6169     }
6170   }
6171 
6172   _access_flags.set_flags(flags);
6173 
6174   if (EnableValhalla) {
6175     if (_access_flags.is_identity_class()) set_carries_identity_modifier();
6176     if (_access_flags.is_value_class()) set_carries_value_modifier();
6177     if (carries_identity_modifier() && carries_value_modifier()) {
6178       classfile_parse_error("Class %s has both ACC_IDENTITY and ACC_VALUE modifiers", THREAD);
6179     }
6180   }
6181 
6182   short bad_constant = class_bad_constant_seen();
6183   if (bad_constant != 0) {
6184     // Do not throw CFE until after the access_flags are checked because if
6185     // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
6186     classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, THREAD);
6187     return;
6188   }
6189 
6190   // Don't need to check whether this class name is legal or not.
6191   // It has been checked when constant pool is parsed.
6192   // However, make sure it is not an array type.
6193   if (_need_verify) {
6194     guarantee_property(class_name_in_cp->char_at(0) != JVM_SIGNATURE_ARRAY,
6195                        "Bad class name in class file %s",
6196                        CHECK);
6197   }
6198 
6199 #ifdef ASSERT
6200   // Basic sanity checks
6201   if (_is_hidden) {
6202     assert(_class_name != vmSymbols::unknown_class_name(), "hidden classes should have a special name");
6203   }
6204 #endif
6205 
6206   // Update the _class_name as needed depending on whether this is a named, un-named, or hidden class.
6207 
6208   if (_is_hidden) {
6209     assert(_class_name != nullptr, "Unexpected null _class_name");

6247       if (stream->source() != nullptr) {
6248         ls.print(" source: %s", stream->source());
6249       }
6250       ls.cr();
6251     }
6252   }
6253 
6254   // SUPERKLASS
6255   _super_class_index = stream->get_u2_fast();
6256   _super_klass = parse_super_class(cp,
6257                                    _super_class_index,
6258                                    _need_verify,
6259                                    CHECK);
6260 
6261   // Interfaces
6262   _itfs_len = stream->get_u2_fast();
6263   parse_interfaces(stream,
6264                    _itfs_len,
6265                    cp,
6266                    &_has_nonstatic_concrete_methods,
6267                    &_is_declared_atomic,
6268                    CHECK);
6269 


6270   // Fields (offsets are filled in later)
6271   _fac = new FieldAllocationCount();
6272   parse_fields(stream,
6273                _access_flags,
6274                _fac,
6275                cp,
6276                cp_size,
6277                &_java_fields_count,
6278                CHECK);
6279 
6280   assert(_temp_field_info != nullptr, "invariant");
6281 
6282   // Methods
6283   parse_methods(stream,
6284                 is_interface(),
6285                 is_value_class(),
6286                 is_abstract_class(),
6287                 &_has_localvariable_table,
6288                 &_has_final_method,
6289                 &_declares_nonstatic_concrete_methods,
6290                 CHECK);
6291 
6292   assert(_methods != nullptr, "invariant");
6293 
6294   if (_declares_nonstatic_concrete_methods) {
6295     _has_nonstatic_concrete_methods = true;
6296   }
6297 
6298   // Additional attributes/annotations
6299   _parsed_annotations = new ClassAnnotationCollector();
6300   parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK);
6301 
6302   assert(_inner_classes != nullptr, "invariant");
6303 
6304   // Finalize the Annotations metadata object,
6305   // now that all annotation arrays have been created.
6306   create_combined_annotations(CHECK);

6346   // Update this_class_index's slot in the constant pool with the new Utf8 entry.
6347   // We have to update the resolved_klass_index and the name_index together
6348   // so extract the existing resolved_klass_index first.
6349   CPKlassSlot cp_klass_slot = _cp->klass_slot_at(_this_class_index);
6350   int resolved_klass_index = cp_klass_slot.resolved_klass_index();
6351   _cp->unresolved_klass_at_put(_this_class_index, hidden_index, resolved_klass_index);
6352   assert(_cp->klass_slot_at(_this_class_index).name_index() == _orig_cp_size,
6353          "Bad name_index");
6354 }
6355 
6356 void ClassFileParser::post_process_parsed_stream(const ClassFileStream* const stream,
6357                                                  ConstantPool* cp,
6358                                                  TRAPS) {
6359   assert(stream != nullptr, "invariant");
6360   assert(stream->at_eos(), "invariant");
6361   assert(cp != nullptr, "invariant");
6362   assert(_loader_data != nullptr, "invariant");
6363 
6364   if (_class_name == vmSymbols::java_lang_Object()) {
6365     check_property(_local_interfaces == Universe::the_empty_instance_klass_array(),
6366         "java.lang.Object cannot implement an interface in class file %s",
6367         CHECK);
6368   }
6369   // We check super class after class file is parsed and format is checked
6370   if (_super_class_index > 0 && nullptr == _super_klass) {
6371     Symbol* const super_class_name = cp->klass_name_at(_super_class_index);
6372     if (is_interface()) {
6373       // Before attempting to resolve the superclass, check for class format
6374       // errors not checked yet.
6375       guarantee_property(super_class_name == vmSymbols::java_lang_Object(),
6376         "Interfaces must have java.lang.Object as superclass in class file %s",
6377         CHECK);
6378     }
6379     Handle loader(THREAD, _loader_data->class_loader());
6380     if (loader.is_null() && super_class_name == vmSymbols::java_lang_Object()) {
6381       _super_klass = vmClasses::Object_klass();
6382     } else {
6383       _super_klass = (const InstanceKlass*)
6384                        SystemDictionary::resolve_super_or_fail(_class_name,
6385                                                                super_class_name,
6386                                                                loader,
6387                                                                _protection_domain,
6388                                                                true,
6389                                                                CHECK);
6390     }
6391   }
6392 
6393   if (_super_klass != nullptr) {
6394     if (_super_klass->is_interface()) {
6395       classfile_icce_error("class %s has interface %s as super class", _super_klass, THREAD);
6396       return;
6397     }
6398 
6399     if (EnableValhalla) {
6400       check_identity_and_value_modifiers(this, _super_klass, CHECK);
6401     }
6402 
6403     if (_super_klass->has_nonstatic_concrete_methods()) {
6404       _has_nonstatic_concrete_methods = true;
6405     }
6406     if (_super_klass->is_declared_atomic()) {
6407       _is_declared_atomic = true;
6408     }
6409   }
6410 
6411   if (*ForceNonTearable != '\0') {
6412     // Allow a command line switch to force the same atomicity property:
6413     const char* class_name_str = _class_name->as_C_string();
6414     if (StringUtils::class_list_match(ForceNonTearable, class_name_str)) {
6415       _is_declared_atomic = true;
6416     }
6417   }
6418 
6419   int itfs_len = _local_interface_indexes == nullptr ? 0 : _local_interface_indexes->length();
6420   _local_interfaces = MetadataFactory::new_array<InstanceKlass*>(_loader_data, itfs_len, nullptr, CHECK);
6421   if (_local_interface_indexes != nullptr) {
6422     for (int i = 0; i < _local_interface_indexes->length(); i++) {
6423       u2 interface_index = _local_interface_indexes->at(i);
6424       Klass* interf;
6425       if (cp->tag_at(interface_index).is_klass()) {
6426         interf = cp->resolved_klass_at(interface_index);
6427       } else {
6428         Symbol* const unresolved_klass  = cp->klass_name_at(interface_index);
6429 
6430         // Don't need to check legal name because it's checked when parsing constant pool.
6431         // But need to make sure it's not an array type.
6432         guarantee_property(unresolved_klass->char_at(0) != JVM_SIGNATURE_ARRAY,
6433                             "Bad interface name in class file %s", CHECK);
6434 
6435         // Call resolve_super so class circularity is checked
6436         interf = SystemDictionary::resolve_super_or_fail(
6437                                                   _class_name,
6438                                                   unresolved_klass,
6439                                                   Handle(THREAD, _loader_data->class_loader()),
6440                                                   _protection_domain,
6441                                                   false,
6442                                                   CHECK);
6443       }
6444 
6445       if (!interf->is_interface()) {
6446         THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
6447                   err_msg("class %s can not implement %s, because it is not an interface (%s)",
6448                           _class_name->as_klass_external_name(),
6449                           interf->external_name(),
6450                           interf->class_in_module_of_loader()));
6451       }
6452 
6453       if (EnableValhalla) {
6454         // Check modifiers and set carries_identity_modifier/carries_value_modifier flags
6455         check_identity_and_value_modifiers(this, InstanceKlass::cast(interf), CHECK);
6456       }
6457 
6458       if (InstanceKlass::cast(interf)->has_nonstatic_concrete_methods()) {
6459         _has_nonstatic_concrete_methods = true;
6460       }
6461       if (InstanceKlass::cast(interf)->is_declared_atomic()) {
6462         _is_declared_atomic = true;
6463       }
6464       _local_interfaces->at_put(i, InstanceKlass::cast(interf));
6465     }
6466   }
6467   assert(_local_interfaces != nullptr, "invariant");
6468 
6469   // Compute the transitive list of all unique interfaces implemented by this class
6470   _transitive_interfaces =
6471     compute_transitive_interfaces(_super_klass,
6472                                   _local_interfaces,
6473                                   _loader_data,
6474                                   CHECK);
6475 
6476   assert(_transitive_interfaces != nullptr, "invariant");
6477 
6478   // sort methods
6479   _method_ordering = sort_methods(_methods);
6480 
6481   _all_mirandas = new GrowableArray<Method*>(20);
6482 
6483   Handle loader(THREAD, _loader_data->class_loader());
6484   klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
6485                                                     &_num_miranda_methods,
6486                                                     _all_mirandas,
6487                                                     _super_klass,
6488                                                     _methods,
6489                                                     _access_flags,
6490                                                     _major_version,
6491                                                     loader,
6492                                                     _class_name,
6493                                                     _local_interfaces);
6494 
6495   // Size of Java itable (in words)
6496   _itable_size = is_interface() ? 0 :
6497     klassItable::compute_itable_size(_transitive_interfaces);
6498 
6499   assert(_fac != nullptr, "invariant");
6500   assert(_parsed_annotations != nullptr, "invariant");
6501 
6502 
6503   if (EnablePrimitiveClasses) {
6504     _inline_type_field_klasses = MetadataFactory::new_array<InlineKlass*>(_loader_data,
6505                                                    java_fields_count(),
6506                                                    nullptr,
6507                                                    CHECK);
6508     for (GrowableArrayIterator<FieldInfo> it = _temp_field_info->begin(); it != _temp_field_info->end(); ++it) {
6509       FieldInfo fieldinfo = *it;
6510       Symbol* sig = fieldinfo.signature(cp);
6511 
6512       if (fieldinfo.field_flags().is_null_free_inline_type() && !fieldinfo.access_flags().is_static()) {
6513         // Pre-load inline class
6514         Klass* klass = SystemDictionary::resolve_inline_type_field_or_fail(sig,
6515             Handle(THREAD, _loader_data->class_loader()),
6516             _protection_domain, true, CHECK);
6517         assert(klass != nullptr, "Sanity check");
6518         if (!klass->access_flags().is_value_class()) {
6519           assert(klass->is_instance_klass(), "Sanity check");
6520           ResourceMark rm(THREAD);
6521             THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
6522                       err_msg("Class %s expects class %s to be an inline type, but it is not",
6523                       _class_name->as_C_string(),
6524                       InstanceKlass::cast(klass)->external_name()));
6525         }
6526         _inline_type_field_klasses->at_put(fieldinfo.index(), InlineKlass::cast(klass));
6527       }
6528     }
6529   }
6530 
6531   _field_info = new FieldLayoutInfo();
6532   FieldLayoutBuilder lb(class_name(), super_klass(), _cp, /*_fields*/ _temp_field_info,
6533       _parsed_annotations->is_contended(), is_inline_type(),
6534       _field_info, _inline_type_field_klasses);
6535   lb.build_layout(CHECK);
6536   if (is_inline_type()) {
6537     _alignment = lb.get_alignment();
6538     _first_field_offset = lb.get_first_field_offset();
6539     _exact_size_in_bytes = lb.get_exact_size_in_byte();
6540   }
6541   _has_inline_type_fields = _field_info->_has_inline_fields;
6542 
6543   int injected_fields_count = _temp_field_info->length() - _java_fields_count;
6544   _fieldinfo_stream =
6545     FieldInfoStream::create_FieldInfoStream(_temp_field_info, _java_fields_count,
6546                                             injected_fields_count, loader_data(), CHECK);
6547   _fields_status =
6548     MetadataFactory::new_array<FieldStatus>(_loader_data, _temp_field_info->length(),
6549                                             FieldStatus(0), CHECK);
6550 }
6551 
6552 void ClassFileParser::set_klass(InstanceKlass* klass) {
6553 
6554 #ifdef ASSERT
6555   if (klass != nullptr) {
6556     assert(nullptr == _klass, "leaking?");
6557   }
6558 #endif
6559 
6560   _klass = klass;
6561 }
< prev index next >