< prev index next >

src/hotspot/share/classfile/classFileParser.cpp

Print this page

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


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

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

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

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


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

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



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

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

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








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

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









 804                                        bool* const has_nonstatic_concrete_methods,






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

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

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



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

1359                                             CHECK);
1360   parsed_annotations->set_field_annotations(a);
1361   a = assemble_annotations(runtime_visible_type_annotations,
1362                            runtime_visible_type_annotations_length,
1363                            runtime_invisible_type_annotations,
1364                            runtime_invisible_type_annotations_length,
1365                            CHECK);
1366   parsed_annotations->set_field_type_annotations(a);
1367   return;
1368 }
1369 
1370 
1371 // Field allocation types. Used for computing field offsets.
1372 
1373 enum FieldAllocationType {
1374   STATIC_OOP,           // Oops
1375   STATIC_BYTE,          // Boolean, Byte, char
1376   STATIC_SHORT,         // shorts
1377   STATIC_WORD,          // ints
1378   STATIC_DOUBLE,        // aligned long or double

1379   NONSTATIC_OOP,
1380   NONSTATIC_BYTE,
1381   NONSTATIC_SHORT,
1382   NONSTATIC_WORD,
1383   NONSTATIC_DOUBLE,

1384   MAX_FIELD_ALLOCATION_TYPE,
1385   BAD_ALLOCATION_TYPE = -1
1386 };
1387 
1388 static FieldAllocationType _basic_type_to_atype[2 * (T_CONFLICT + 1)] = {
1389   BAD_ALLOCATION_TYPE, // 0
1390   BAD_ALLOCATION_TYPE, // 1
1391   BAD_ALLOCATION_TYPE, // 2
1392   BAD_ALLOCATION_TYPE, // 3
1393   NONSTATIC_BYTE ,     // T_BOOLEAN     =  4,
1394   NONSTATIC_SHORT,     // T_CHAR        =  5,
1395   NONSTATIC_WORD,      // T_FLOAT       =  6,
1396   NONSTATIC_DOUBLE,    // T_DOUBLE      =  7,
1397   NONSTATIC_BYTE,      // T_BYTE        =  8,
1398   NONSTATIC_SHORT,     // T_SHORT       =  9,
1399   NONSTATIC_WORD,      // T_INT         = 10,
1400   NONSTATIC_DOUBLE,    // T_LONG        = 11,
1401   NONSTATIC_OOP,       // T_OBJECT      = 12,
1402   NONSTATIC_OOP,       // T_ARRAY       = 13,
1403   BAD_ALLOCATION_TYPE, // T_VOID        = 14,
1404   BAD_ALLOCATION_TYPE, // T_ADDRESS     = 15,
1405   BAD_ALLOCATION_TYPE, // T_NARROWOOP   = 16,
1406   BAD_ALLOCATION_TYPE, // T_METADATA    = 17,
1407   BAD_ALLOCATION_TYPE, // T_NARROWKLASS = 18,
1408   BAD_ALLOCATION_TYPE, // T_CONFLICT    = 19,

1409   BAD_ALLOCATION_TYPE, // 0
1410   BAD_ALLOCATION_TYPE, // 1
1411   BAD_ALLOCATION_TYPE, // 2
1412   BAD_ALLOCATION_TYPE, // 3
1413   STATIC_BYTE ,        // T_BOOLEAN     =  4,
1414   STATIC_SHORT,        // T_CHAR        =  5,
1415   STATIC_WORD,         // T_FLOAT       =  6,
1416   STATIC_DOUBLE,       // T_DOUBLE      =  7,
1417   STATIC_BYTE,         // T_BYTE        =  8,
1418   STATIC_SHORT,        // T_SHORT       =  9,
1419   STATIC_WORD,         // T_INT         = 10,
1420   STATIC_DOUBLE,       // T_LONG        = 11,
1421   STATIC_OOP,          // T_OBJECT      = 12,
1422   STATIC_OOP,          // T_ARRAY       = 13,
1423   BAD_ALLOCATION_TYPE, // T_VOID        = 14,
1424   BAD_ALLOCATION_TYPE, // T_ADDRESS     = 15,
1425   BAD_ALLOCATION_TYPE, // T_NARROWOOP   = 16,
1426   BAD_ALLOCATION_TYPE, // T_METADATA    = 17,
1427   BAD_ALLOCATION_TYPE, // T_NARROWKLASS = 18,
1428   BAD_ALLOCATION_TYPE, // T_CONFLICT    = 19,

1429 };
1430 
1431 static FieldAllocationType basic_type_to_atype(bool is_static, BasicType type) {
1432   assert(type >= T_BOOLEAN && type < T_VOID, "only allowable values");
1433   FieldAllocationType result = _basic_type_to_atype[type + (is_static ? (T_CONFLICT + 1) : 0)];
1434   assert(result != BAD_ALLOCATION_TYPE, "bad type");



1435   return result;
1436 }
1437 
1438 class ClassFileParser::FieldAllocationCount : public ResourceObj {
1439  public:
1440   u2 count[MAX_FIELD_ALLOCATION_TYPE];
1441 
1442   FieldAllocationCount() {
1443     for (int i = 0; i < MAX_FIELD_ALLOCATION_TYPE; i++) {
1444       count[i] = 0;
1445     }
1446   }
1447 
1448   void update(bool is_static, BasicType type) {
1449     FieldAllocationType atype = basic_type_to_atype(is_static, type);
1450     if (atype != BAD_ALLOCATION_TYPE) {
1451       // Make sure there is no overflow with injected fields.
1452       assert(count[atype] < 0xFFFF, "More than 65535 fields");
1453       count[atype]++;
1454     }
1455   }
1456 };
1457 
1458 // Side-effects: populates the _fields, _fields_annotations,
1459 // _fields_type_annotations fields
1460 void ClassFileParser::parse_fields(const ClassFileStream* const cfs,
1461                                    bool is_interface,
1462                                    FieldAllocationCount* const fac,
1463                                    ConstantPool* cp,
1464                                    const int cp_size,
1465                                    u2* const java_fields_count_ptr,
1466                                    TRAPS) {
1467 
1468   assert(cfs != nullptr, "invariant");
1469   assert(fac != nullptr, "invariant");
1470   assert(cp != nullptr, "invariant");
1471   assert(java_fields_count_ptr != nullptr, "invariant");
1472 
1473   assert(nullptr == _fields_annotations, "invariant");
1474   assert(nullptr == _fields_type_annotations, "invariant");
1475 

1476   cfs->guarantee_more(2, CHECK);  // length
1477   const u2 length = cfs->get_u2_fast();
1478   *java_fields_count_ptr = length;
1479 
1480   int num_injected = 0;
1481   const InjectedField* const injected = JavaClasses::get_injected(_class_name,
1482                                                                   &num_injected);
1483   const int total_fields = length + num_injected;




1484 
1485   // Allocate a temporary resource array to collect field data.
1486   // After parsing all fields, data are stored in a UNSIGNED5 compressed stream.
1487   _temp_field_info = new GrowableArray<FieldInfo>(total_fields);
1488 

1489   ResourceMark rm(THREAD);
1490   for (int n = 0; n < length; n++) {
1491     // access_flags, name_index, descriptor_index, attributes_count
1492     cfs->guarantee_more(8, CHECK);
1493 







1494     AccessFlags access_flags;
1495     const jint flags = cfs->get_u2_fast() & JVM_RECOGNIZED_FIELD_MODIFIERS;
1496     verify_legal_field_modifiers(flags, is_interface, CHECK);
1497     access_flags.set_flags(flags);
1498     FieldInfo::FieldFlags fieldFlags(0);
1499 
1500     const u2 name_index = cfs->get_u2_fast();
1501     check_property(valid_symbol_at(name_index),
1502       "Invalid constant pool index %u for field name in class file %s",
1503       name_index, CHECK);
1504     const Symbol* const name = cp->symbol_at(name_index);
1505     verify_legal_field_name(name, CHECK);
1506 
1507     const u2 signature_index = cfs->get_u2_fast();
1508     check_property(valid_symbol_at(signature_index),
1509       "Invalid constant pool index %u for field signature in class file %s",
1510       signature_index, CHECK);
1511     const Symbol* const sig = cp->symbol_at(signature_index);
1512     verify_legal_field_signature(name, sig, CHECK);

1513 
1514     u2 constantvalue_index = 0;
1515     bool is_synthetic = false;
1516     u2 generic_signature_index = 0;
1517     const bool is_static = access_flags.is_static();
1518     FieldAnnotationCollector parsed_annotations(_loader_data);
1519 


1520     const u2 attributes_count = cfs->get_u2_fast();
1521     if (attributes_count > 0) {
1522       parse_field_attributes(cfs,
1523                              attributes_count,
1524                              is_static,
1525                              signature_index,
1526                              &constantvalue_index,
1527                              &is_synthetic,
1528                              &generic_signature_index,
1529                              &parsed_annotations,
1530                              CHECK);
1531 
1532       if (parsed_annotations.field_annotations() != nullptr) {
1533         if (_fields_annotations == nullptr) {
1534           _fields_annotations = MetadataFactory::new_array<AnnotationArray*>(
1535                                              _loader_data, length, nullptr,
1536                                              CHECK);
1537         }
1538         _fields_annotations->at_put(n, parsed_annotations.field_annotations());










1539         parsed_annotations.set_field_annotations(nullptr);
1540       }
1541       if (parsed_annotations.field_type_annotations() != nullptr) {
1542         if (_fields_type_annotations == nullptr) {
1543           _fields_type_annotations =
1544             MetadataFactory::new_array<AnnotationArray*>(_loader_data,
1545                                                          length,
1546                                                          nullptr,
1547                                                          CHECK);
1548         }
1549         _fields_type_annotations->at_put(n, parsed_annotations.field_type_annotations());
1550         parsed_annotations.set_field_type_annotations(nullptr);
1551       }
1552 
1553       if (is_synthetic) {
1554         access_flags.set_is_synthetic();
1555       }
1556       if (generic_signature_index != 0) {
1557         fieldFlags.update_generic(true);
1558       }
1559     }
1560 
1561     const BasicType type = cp->basic_type_for_signature_at(signature_index);
1562 
1563     // Update FieldAllocationCount for this kind of field
1564     fac->update(is_static, type);



1565 
1566     FieldInfo fi(access_flags, name_index, signature_index, constantvalue_index, fieldFlags);
1567     fi.set_index(n);
1568     if (fieldFlags.is_generic()) {
1569       fi.set_generic_signature_index(generic_signature_index);
1570     }
1571     parsed_annotations.apply_to(&fi);
1572     if (fi.field_flags().is_contended()) {
1573       _has_contended_fields = true;
1574     }
1575     _temp_field_info->append(fi);
1576   }
1577   assert(_temp_field_info->length() == length, "Must be");
1578 
1579   int index = length;
1580   if (num_injected != 0) {
1581     for (int n = 0; n < num_injected; n++) {
1582       // Check for duplicates
1583       if (injected[n].may_be_java) {
1584         const Symbol* const name      = injected[n].name();

1592             duplicate = true;
1593             break;
1594           }
1595         }
1596         if (duplicate) {
1597           // These will be removed from the field array at the end
1598           continue;
1599         }
1600       }
1601 
1602       // Injected field
1603       FieldInfo::FieldFlags fflags(0);
1604       fflags.update_injected(true);
1605       AccessFlags aflags;
1606       FieldInfo fi(aflags, (u2)(injected[n].name_index), (u2)(injected[n].signature_index), 0, fflags);
1607       fi.set_index(index);
1608       _temp_field_info->append(fi);
1609 
1610       // Update FieldAllocationCount for this kind of field
1611       const BasicType type = Signature::basic_type(injected[n].signature());
1612       fac->update(false, type);
1613       index++;
1614     }
1615   }
1616 










































1617   assert(_temp_field_info->length() == index, "Must be");
1618 
1619   if (_need_verify && length > 1) {
1620     // Check duplicated fields
1621     ResourceMark rm(THREAD);
1622     // Set containing name-signature pairs
1623     NameSigHashtable* names_and_sigs = new NameSigHashtable();
1624     for (int i = 0; i < _temp_field_info->length(); i++) {
1625       NameSigHash name_and_sig(_temp_field_info->adr_at(i)->name(_cp),
1626                                _temp_field_info->adr_at(i)->signature(_cp));
1627       // If no duplicates, add name/signature in hashtable names_and_sigs.
1628       if(!names_and_sigs->put(name_and_sig, 0)) {
1629         classfile_parse_error("Duplicate field name \"%s\" with signature \"%s\" in class file %s",
1630                                name_and_sig._name->as_C_string(), name_and_sig._sig->as_klass_external_name(), THREAD);
1631         return;
1632       }
1633     }
1634   }
1635 }
1636 

1971     }
1972     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Contended_signature): {
1973       if (_location != _in_field && _location != _in_class) {
1974         break;  // only allow for fields and classes
1975       }
1976       if (!EnableContended || (RestrictContended && !privileged)) {
1977         break;  // honor privileges
1978       }
1979       return _jdk_internal_vm_annotation_Contended;
1980     }
1981     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ReservedStackAccess_signature): {
1982       if (_location != _in_method)  break;  // only allow for methods
1983       if (RestrictReservedStack && !privileged) break; // honor privileges
1984       return _jdk_internal_vm_annotation_ReservedStackAccess;
1985     }
1986     case VM_SYMBOL_ENUM_NAME(jdk_internal_ValueBased_signature): {
1987       if (_location != _in_class)   break;  // only allow for classes
1988       if (!privileged)              break;  // only allow in privileged code
1989       return _jdk_internal_ValueBased;
1990     }












1991     case VM_SYMBOL_ENUM_NAME(java_lang_Deprecated): {
1992       return _java_lang_Deprecated;
1993     }
1994     default: {
1995       break;
1996     }
1997   }
1998   return AnnotationCollector::_unknown;
1999 }
2000 
2001 void ClassFileParser::FieldAnnotationCollector::apply_to(FieldInfo* f) {
2002   if (is_contended())
2003     // Setting the contended group also sets the contended bit in field flags
2004     f->set_contended_group(contended_group());
2005   if (is_stable())
2006     (f->field_flags_addr())->update_stable(true);
2007 }
2008 
2009 ClassFileParser::FieldAnnotationCollector::~FieldAnnotationCollector() {
2010   // If there's an error deallocate metadata for field annotations

2209       runtime_invisible_type_annotations_length > 0) {
2210     a = assemble_annotations(runtime_visible_type_annotations,
2211                              runtime_visible_type_annotations_length,
2212                              runtime_invisible_type_annotations,
2213                              runtime_invisible_type_annotations_length,
2214                              CHECK);
2215     cm->set_type_annotations(a);
2216   }
2217 }
2218 
2219 
2220 // Note: the parse_method below is big and clunky because all parsing of the code and exceptions
2221 // attribute is inlined. This is cumbersome to avoid since we inline most of the parts in the
2222 // Method* to save footprint, so we only know the size of the resulting Method* when the
2223 // entire method attribute is parsed.
2224 //
2225 // The has_localvariable_table parameter is used to pass up the value to InstanceKlass.
2226 
2227 Method* ClassFileParser::parse_method(const ClassFileStream* const cfs,
2228                                       bool is_interface,


2229                                       const ConstantPool* cp,
2230                                       bool* const has_localvariable_table,
2231                                       TRAPS) {
2232   assert(cfs != nullptr, "invariant");
2233   assert(cp != nullptr, "invariant");
2234   assert(has_localvariable_table != nullptr, "invariant");
2235 
2236   ResourceMark rm(THREAD);
2237   // Parse fixed parts:
2238   // access_flags, name_index, descriptor_index, attributes_count
2239   cfs->guarantee_more(8, CHECK_NULL);
2240 
2241   int flags = cfs->get_u2_fast();
2242   const u2 name_index = cfs->get_u2_fast();
2243   const int cp_size = cp->length();
2244   check_property(
2245     valid_symbol_at(name_index),
2246     "Illegal constant pool index %u for method name in class file %s",
2247     name_index, CHECK_NULL);
2248   const Symbol* const name = cp->symbol_at(name_index);

2250 
2251   const u2 signature_index = cfs->get_u2_fast();
2252   guarantee_property(
2253     valid_symbol_at(signature_index),
2254     "Illegal constant pool index %u for method signature in class file %s",
2255     signature_index, CHECK_NULL);
2256   const Symbol* const signature = cp->symbol_at(signature_index);
2257 
2258   if (name == vmSymbols::class_initializer_name()) {
2259     // We ignore the other access flags for a valid class initializer.
2260     // (JVM Spec 2nd ed., chapter 4.6)
2261     if (_major_version < 51) { // backward compatibility
2262       flags = JVM_ACC_STATIC;
2263     } else if ((flags & JVM_ACC_STATIC) == JVM_ACC_STATIC) {
2264       flags &= JVM_ACC_STATIC | (_major_version <= JAVA_16_VERSION ? JVM_ACC_STRICT : 0);
2265     } else {
2266       classfile_parse_error("Method <clinit> is not static in class file %s", THREAD);
2267       return nullptr;
2268     }
2269   } else {
2270     verify_legal_method_modifiers(flags, is_interface, name, CHECK_NULL);
2271   }
2272 
2273   if (name == vmSymbols::object_initializer_name() && is_interface) {
2274     classfile_parse_error("Interface cannot have a method named <init>, class file %s", THREAD);
2275     return nullptr;
2276   }
2277 









2278   int args_size = -1;  // only used when _need_verify is true
2279   if (_need_verify) {
2280     verify_legal_name_with_signature(name, signature, CHECK_NULL);
2281     args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) +
2282                  verify_legal_method_signature(name, signature, CHECK_NULL);
2283     if (args_size > MAX_ARGS_SIZE) {
2284       classfile_parse_error("Too many arguments in method signature in class file %s", THREAD);
2285       return nullptr;
2286     }
2287   }
2288 
2289   AccessFlags access_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS);
2290 
2291   // Default values for code and exceptions attribute elements
2292   u2 max_stack = 0;
2293   u2 max_locals = 0;
2294   u4 code_length = 0;
2295   const u1* code_start = 0;
2296   u2 exception_table_length = 0;
2297   const unsafe_u2* exception_table_start = nullptr; // (potentially unaligned) pointer to array of u2 elements

2822     if (m->is_empty_method()) {
2823       _has_empty_finalizer = true;
2824     } else {
2825       _has_finalizer = true;
2826     }
2827   }
2828   if (name == vmSymbols::object_initializer_name() &&
2829       signature == vmSymbols::void_method_signature() &&
2830       m->is_vanilla_constructor()) {
2831     _has_vanilla_constructor = true;
2832   }
2833 
2834   NOT_PRODUCT(m->verify());
2835   return m;
2836 }
2837 
2838 
2839 // Side-effects: populates the _methods field in the parser
2840 void ClassFileParser::parse_methods(const ClassFileStream* const cfs,
2841                                     bool is_interface,


2842                                     bool* const has_localvariable_table,
2843                                     bool* has_final_method,
2844                                     bool* declares_nonstatic_concrete_methods,
2845                                     TRAPS) {
2846   assert(cfs != nullptr, "invariant");
2847   assert(has_localvariable_table != nullptr, "invariant");
2848   assert(has_final_method != nullptr, "invariant");
2849   assert(declares_nonstatic_concrete_methods != nullptr, "invariant");
2850 
2851   assert(nullptr == _methods, "invariant");
2852 
2853   cfs->guarantee_more(2, CHECK);  // length
2854   const u2 length = cfs->get_u2_fast();
2855   if (length == 0) {
2856     _methods = Universe::the_empty_method_array();
2857   } else {
2858     _methods = MetadataFactory::new_array<Method*>(_loader_data,
2859                                                    length,
2860                                                    nullptr,
2861                                                    CHECK);
2862 
2863     for (int index = 0; index < length; index++) {
2864       Method* method = parse_method(cfs,
2865                                     is_interface,


2866                                     _cp,
2867                                     has_localvariable_table,
2868                                     CHECK);
2869 
2870       if (method->is_final()) {
2871         *has_final_method = true;
2872       }
2873       // declares_nonstatic_concrete_methods: declares concrete instance methods, any access flags
2874       // used for interface initialization, and default method inheritance analysis
2875       if (is_interface && !(*declares_nonstatic_concrete_methods)
2876         && !method->is_abstract() && !method->is_static()) {
2877         *declares_nonstatic_concrete_methods = true;
2878       }
2879       _methods->at_put(index, method);
2880     }
2881 
2882     if (_need_verify && length > 1) {
2883       // Check duplicated methods
2884       ResourceMark rm(THREAD);
2885       // Set containing name-signature pairs

3111         valid_klass_reference_at(outer_class_info_index),
3112       "outer_class_info_index %u has bad constant type in class file %s",
3113       outer_class_info_index, CHECK_0);
3114 
3115     if (outer_class_info_index != 0) {
3116       const Symbol* const outer_class_name = cp->klass_name_at(outer_class_info_index);
3117       char* bytes = (char*)outer_class_name->bytes();
3118       guarantee_property(bytes[0] != JVM_SIGNATURE_ARRAY,
3119                          "Outer class is an array class in class file %s", CHECK_0);
3120     }
3121     // Inner class name
3122     const u2 inner_name_index = cfs->get_u2_fast();
3123     check_property(
3124       inner_name_index == 0 || valid_symbol_at(inner_name_index),
3125       "inner_name_index %u has bad constant type in class file %s",
3126       inner_name_index, CHECK_0);
3127     if (_need_verify) {
3128       guarantee_property(inner_class_info_index != outer_class_info_index,
3129                          "Class is both outer and inner class in class file %s", CHECK_0);
3130     }
3131     // Access flags
3132     jint flags;
3133     // JVM_ACC_MODULE is defined in JDK-9 and later.
3134     if (_major_version >= JAVA_9_VERSION) {
3135       flags = cfs->get_u2_fast() & (RECOGNIZED_INNER_CLASS_MODIFIERS | JVM_ACC_MODULE);
3136     } else {
3137       flags = cfs->get_u2_fast() & RECOGNIZED_INNER_CLASS_MODIFIERS;
3138     }




3139     if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
3140       // Set abstract bit for old class files for backward compatibility
3141       flags |= JVM_ACC_ABSTRACT;
3142     }
3143     verify_legal_class_modifiers(flags, CHECK_0);










3144     AccessFlags inner_access_flags(flags);
3145 
3146     inner_classes->at_put(index++, inner_class_info_index);
3147     inner_classes->at_put(index++, outer_class_info_index);
3148     inner_classes->at_put(index++, inner_name_index);
3149     inner_classes->at_put(index++, inner_access_flags.as_short());
3150   }
3151 
3152   // Check for circular and duplicate entries.
3153   bool has_circularity = false;
3154   if (_need_verify) {
3155     has_circularity = check_inner_classes_circularity(cp, length * 4, CHECK_0);
3156     if (has_circularity) {
3157       // If circularity check failed then ignore InnerClasses attribute.
3158       MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
3159       index = 0;
3160       if (parsed_enclosingmethod_attribute) {
3161         inner_classes = MetadataFactory::new_array<u2>(_loader_data, 2, CHECK_0);
3162         _inner_classes = inner_classes;
3163       } else {

3227   if (length > 0) {
3228     int index = 0;
3229     cfs->guarantee_more(2 * length, CHECK_0);
3230     for (int n = 0; n < length; n++) {
3231       const u2 class_info_index = cfs->get_u2_fast();
3232       check_property(
3233         valid_klass_reference_at(class_info_index),
3234         "Permitted subclass class_info_index %u has bad constant type in class file %s",
3235         class_info_index, CHECK_0);
3236       permitted_subclasses->at_put(index++, class_info_index);
3237     }
3238     assert(index == size, "wrong size");
3239   }
3240 
3241   // Restore buffer's current position.
3242   cfs->set_current(current_mark);
3243 
3244   return length;
3245 }
3246 

































3247 //  Record {
3248 //    u2 attribute_name_index;
3249 //    u4 attribute_length;
3250 //    u2 components_count;
3251 //    component_info components[components_count];
3252 //  }
3253 //  component_info {
3254 //    u2 name_index;
3255 //    u2 descriptor_index
3256 //    u2 attributes_count;
3257 //    attribute_info_attributes[attributes_count];
3258 //  }
3259 u4 ClassFileParser::parse_classfile_record_attribute(const ClassFileStream* const cfs,
3260                                                      const ConstantPool* cp,
3261                                                      const u1* const record_attribute_start,
3262                                                      TRAPS) {
3263   const u1* const current_mark = cfs->current();
3264   int components_count = 0;
3265   unsigned int calculate_attr_size = 0;
3266   if (record_attribute_start != nullptr) {

3511   }
3512   guarantee_property(current_start + attribute_byte_length == cfs->current(),
3513                      "Bad length on BootstrapMethods in class file %s",
3514                      CHECK);
3515 }
3516 
3517 void ClassFileParser::parse_classfile_attributes(const ClassFileStream* const cfs,
3518                                                  ConstantPool* cp,
3519                  ClassFileParser::ClassAnnotationCollector* parsed_annotations,
3520                                                  TRAPS) {
3521   assert(cfs != nullptr, "invariant");
3522   assert(cp != nullptr, "invariant");
3523   assert(parsed_annotations != nullptr, "invariant");
3524 
3525   // Set inner classes attribute to default sentinel
3526   _inner_classes = Universe::the_empty_short_array();
3527   // Set nest members attribute to default sentinel
3528   _nest_members = Universe::the_empty_short_array();
3529   // Set _permitted_subclasses attribute to default sentinel
3530   _permitted_subclasses = Universe::the_empty_short_array();


3531   cfs->guarantee_more(2, CHECK);  // attributes_count
3532   u2 attributes_count = cfs->get_u2_fast();
3533   bool parsed_sourcefile_attribute = false;
3534   bool parsed_innerclasses_attribute = false;
3535   bool parsed_nest_members_attribute = false;
3536   bool parsed_permitted_subclasses_attribute = false;

3537   bool parsed_nest_host_attribute = false;
3538   bool parsed_record_attribute = false;
3539   bool parsed_enclosingmethod_attribute = false;
3540   bool parsed_bootstrap_methods_attribute = false;
3541   const u1* runtime_visible_annotations = nullptr;
3542   int runtime_visible_annotations_length = 0;
3543   const u1* runtime_invisible_annotations = nullptr;
3544   int runtime_invisible_annotations_length = 0;
3545   const u1* runtime_visible_type_annotations = nullptr;
3546   int runtime_visible_type_annotations_length = 0;
3547   const u1* runtime_invisible_type_annotations = nullptr;
3548   int runtime_invisible_type_annotations_length = 0;
3549   bool runtime_invisible_type_annotations_exists = false;
3550   bool runtime_invisible_annotations_exists = false;
3551   bool parsed_source_debug_ext_annotations_exist = false;
3552   const u1* inner_classes_attribute_start = nullptr;
3553   u4  inner_classes_attribute_length = 0;
3554   u2  enclosing_method_class_index = 0;
3555   u2  enclosing_method_method_index = 0;
3556   const u1* nest_members_attribute_start = nullptr;
3557   u4  nest_members_attribute_length = 0;
3558   const u1* record_attribute_start = nullptr;
3559   u4  record_attribute_length = 0;
3560   const u1* permitted_subclasses_attribute_start = nullptr;
3561   u4  permitted_subclasses_attribute_length = 0;


3562 
3563   // Iterate over attributes
3564   while (attributes_count--) {
3565     cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
3566     const u2 attribute_name_index = cfs->get_u2_fast();
3567     const u4 attribute_length = cfs->get_u4_fast();
3568     check_property(
3569       valid_symbol_at(attribute_name_index),
3570       "Attribute name has bad constant pool index %u in class file %s",
3571       attribute_name_index, CHECK);
3572     const Symbol* const tag = cp->symbol_at(attribute_name_index);
3573     if (tag == vmSymbols::tag_source_file()) {
3574       // Check for SourceFile tag
3575       if (_need_verify) {
3576         guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
3577       }
3578       if (parsed_sourcefile_attribute) {
3579         classfile_parse_error("Multiple SourceFile attributes in class file %s", THREAD);
3580         return;
3581       } else {

3768               return;
3769             }
3770             parsed_record_attribute = true;
3771             record_attribute_start = cfs->current();
3772             record_attribute_length = attribute_length;
3773           } else if (_major_version >= JAVA_17_VERSION) {
3774             if (tag == vmSymbols::tag_permitted_subclasses()) {
3775               if (parsed_permitted_subclasses_attribute) {
3776                 classfile_parse_error("Multiple PermittedSubclasses attributes in class file %s", CHECK);
3777                 return;
3778               }
3779               // Classes marked ACC_FINAL cannot have a PermittedSubclasses attribute.
3780               if (_access_flags.is_final()) {
3781                 classfile_parse_error("PermittedSubclasses attribute in final class file %s", CHECK);
3782                 return;
3783               }
3784               parsed_permitted_subclasses_attribute = true;
3785               permitted_subclasses_attribute_start = cfs->current();
3786               permitted_subclasses_attribute_length = attribute_length;
3787             }









3788           }
3789           // Skip attribute_length for any attribute where major_verson >= JAVA_17_VERSION
3790           cfs->skip_u1(attribute_length, CHECK);
3791         } else {
3792           // Unknown attribute
3793           cfs->skip_u1(attribute_length, CHECK);
3794         }
3795       } else {
3796         // Unknown attribute
3797         cfs->skip_u1(attribute_length, CHECK);
3798       }
3799     } else {
3800       // Unknown attribute
3801       cfs->skip_u1(attribute_length, CHECK);
3802     }
3803   }
3804   _class_annotations = assemble_annotations(runtime_visible_annotations,
3805                                             runtime_visible_annotations_length,
3806                                             runtime_invisible_annotations,
3807                                             runtime_invisible_annotations_length,

3848                             CHECK);
3849     if (_need_verify) {
3850       guarantee_property(record_attribute_length == calculated_attr_length,
3851                          "Record attribute has wrong length in class file %s",
3852                          CHECK);
3853     }
3854   }
3855 
3856   if (parsed_permitted_subclasses_attribute) {
3857     const u2 num_subclasses = parse_classfile_permitted_subclasses_attribute(
3858                             cfs,
3859                             permitted_subclasses_attribute_start,
3860                             CHECK);
3861     if (_need_verify) {
3862       guarantee_property(
3863         permitted_subclasses_attribute_length == sizeof(num_subclasses) + sizeof(u2) * num_subclasses,
3864         "Wrong PermittedSubclasses attribute length in class file %s", CHECK);
3865     }
3866   }
3867 












3868   if (_max_bootstrap_specifier_index >= 0) {
3869     guarantee_property(parsed_bootstrap_methods_attribute,
3870                        "Missing BootstrapMethods attribute in class file %s", CHECK);
3871   }
3872 }
3873 
3874 void ClassFileParser::apply_parsed_class_attributes(InstanceKlass* k) {
3875   assert(k != nullptr, "invariant");
3876 
3877   if (_synthetic_flag)
3878     k->set_is_synthetic();
3879   if (_sourcefile_index != 0) {
3880     k->set_source_file_name_index(_sourcefile_index);
3881   }
3882   if (_generic_signature_index != 0) {
3883     k->set_generic_signature_index(_generic_signature_index);
3884   }
3885   if (_sde_buffer != nullptr) {
3886     k->set_source_debug_extension(_sde_buffer, _sde_length);
3887   }

3913     _class_annotations       = nullptr;
3914     _class_type_annotations  = nullptr;
3915     _fields_annotations      = nullptr;
3916     _fields_type_annotations = nullptr;
3917 }
3918 
3919 // Transfer ownership of metadata allocated to the InstanceKlass.
3920 void ClassFileParser::apply_parsed_class_metadata(
3921                                             InstanceKlass* this_klass,
3922                                             int java_fields_count) {
3923   assert(this_klass != nullptr, "invariant");
3924 
3925   _cp->set_pool_holder(this_klass);
3926   this_klass->set_constants(_cp);
3927   this_klass->set_fieldinfo_stream(_fieldinfo_stream);
3928   this_klass->set_fields_status(_fields_status);
3929   this_klass->set_methods(_methods);
3930   this_klass->set_inner_classes(_inner_classes);
3931   this_klass->set_nest_members(_nest_members);
3932   this_klass->set_nest_host_index(_nest_host);

3933   this_klass->set_annotations(_combined_annotations);
3934   this_klass->set_permitted_subclasses(_permitted_subclasses);
3935   this_klass->set_record_components(_record_components);

3936   // Delay the setting of _local_interfaces and _transitive_interfaces until after
3937   // initialize_supers() in fill_instance_klass(). It is because the _local_interfaces could
3938   // be shared with _transitive_interfaces and _transitive_interfaces may be shared with
3939   // its _super. If an OOM occurs while loading the current klass, its _super field
3940   // may not have been set. When GC tries to free the klass, the _transitive_interfaces
3941   // may be deallocated mistakenly in InstanceKlass::deallocate_interfaces(). Subsequent
3942   // dereferences to the deallocated _transitive_interfaces will result in a crash.
3943 
3944   // Clear out these fields so they don't get deallocated by the destructor
3945   clear_class_metadata();
3946 }
3947 
3948 AnnotationArray* ClassFileParser::assemble_annotations(const u1* const runtime_visible_annotations,
3949                                                        int runtime_visible_annotations_length,
3950                                                        const u1* const runtime_invisible_annotations,
3951                                                        int runtime_invisible_annotations_length,
3952                                                        TRAPS) {
3953   AnnotationArray* annotations = nullptr;
3954   if (runtime_visible_annotations != nullptr ||
3955       runtime_invisible_annotations != nullptr) {

3964     }
3965     if (runtime_invisible_annotations != nullptr) {
3966       for (int i = 0; i < runtime_invisible_annotations_length; i++) {
3967         int append = runtime_visible_annotations_length+i;
3968         annotations->at_put(append, runtime_invisible_annotations[i]);
3969       }
3970     }
3971   }
3972   return annotations;
3973 }
3974 
3975 const InstanceKlass* ClassFileParser::parse_super_class(ConstantPool* const cp,
3976                                                         const int super_class_index,
3977                                                         const bool need_verify,
3978                                                         TRAPS) {
3979   assert(cp != nullptr, "invariant");
3980   const InstanceKlass* super_klass = nullptr;
3981 
3982   if (super_class_index == 0) {
3983     check_property(_class_name == vmSymbols::java_lang_Object(),
3984                    "Invalid superclass index %u in class file %s",
3985                    super_class_index,
3986                    CHECK_NULL);
3987   } else {
3988     check_property(valid_klass_reference_at(super_class_index),
3989                    "Invalid superclass index %u in class file %s",
3990                    super_class_index,
3991                    CHECK_NULL);
3992     // The class name should be legal because it is checked when parsing constant pool.
3993     // However, make sure it is not an array type.
3994     bool is_array = false;
3995     if (cp->tag_at(super_class_index).is_klass()) {
3996       super_klass = InstanceKlass::cast(cp->resolved_klass_at(super_class_index));
3997       if (need_verify)
3998         is_array = super_klass->is_array_klass();
3999     } else if (need_verify) {
4000       is_array = (cp->klass_name_at(super_class_index)->char_at(0) == JVM_SIGNATURE_ARRAY);
4001     }
4002     if (need_verify) {

4003       guarantee_property(!is_array,
4004                         "Bad superclass name in class file %s", CHECK_NULL);
4005     }
4006   }
4007   return super_klass;
4008 }
4009 
4010 OopMapBlocksBuilder::OopMapBlocksBuilder(unsigned int max_blocks) {
4011   _max_nonstatic_oop_maps = max_blocks;
4012   _nonstatic_oop_map_count = 0;
4013   if (max_blocks == 0) {
4014     _nonstatic_oop_maps = nullptr;
4015   } else {
4016     _nonstatic_oop_maps =
4017         NEW_RESOURCE_ARRAY(OopMapBlock, _max_nonstatic_oop_maps);
4018     memset(_nonstatic_oop_maps, 0, sizeof(OopMapBlock) * max_blocks);
4019   }
4020 }
4021 
4022 OopMapBlock* OopMapBlocksBuilder::last_oop_map() const {

4106 }
4107 
4108 void OopMapBlocksBuilder::print_on(outputStream* st) const {
4109   st->print_cr("  OopMapBlocks: %3d  /%3d", _nonstatic_oop_map_count, _max_nonstatic_oop_maps);
4110   if (_nonstatic_oop_map_count > 0) {
4111     OopMapBlock* map = _nonstatic_oop_maps;
4112     OopMapBlock* last_map = last_oop_map();
4113     assert(map <= last_map, "Last less than first");
4114     while (map <= last_map) {
4115       st->print_cr("    Offset: %3d  -%3d Count: %3d", map->offset(),
4116                    map->offset() + map->offset_span() - heapOopSize, map->count());
4117       map++;
4118     }
4119   }
4120 }
4121 
4122 void OopMapBlocksBuilder::print_value_on(outputStream* st) const {
4123   print_on(st);
4124 }
4125 



















4126 void ClassFileParser::set_precomputed_flags(InstanceKlass* ik) {
4127   assert(ik != nullptr, "invariant");
4128 
4129   const InstanceKlass* const super = ik->java_super();
4130 
4131   // Check if this klass has an empty finalize method (i.e. one with return bytecode only),
4132   // in which case we don't have to register objects as finalizable
4133   if (!_has_empty_finalizer) {
4134     if (_has_finalizer ||
4135         (super != nullptr && super->has_finalizer())) {
4136       ik->set_has_finalizer();
4137     }
4138   }
4139 
4140 #ifdef ASSERT
4141   bool f = false;
4142   const Method* const m = ik->lookup_method(vmSymbols::finalize_method_name(),
4143                                            vmSymbols::void_method_signature());
4144   if (InstanceKlass::is_finalization_enabled() &&
4145       (m != nullptr) && !m->is_empty_method()) {
4146       f = true;
4147   }
4148 
4149   // Spec doesn't prevent agent from redefinition of empty finalizer.
4150   // Despite the fact that it's generally bad idea and redefined finalizer
4151   // will not work as expected we shouldn't abort vm in this case
4152   if (!ik->has_redefined_this_or_super()) {
4153     assert(ik->has_finalizer() == f, "inconsistent has_finalizer");
4154   }
4155 #endif
4156 
4157   // Check if this klass supports the java.lang.Cloneable interface
4158   if (vmClasses::Cloneable_klass_loaded()) {
4159     if (ik->is_subtype_of(vmClasses::Cloneable_klass())) {





4160       ik->set_is_cloneable();
4161     }
4162   }
4163 
4164   // Check if this klass has a vanilla default constructor
4165   if (super == nullptr) {
4166     // java.lang.Object has empty default constructor
4167     ik->set_has_vanilla_constructor();
4168   } else {
4169     if (super->has_vanilla_constructor() &&
4170         _has_vanilla_constructor) {
4171       ik->set_has_vanilla_constructor();
4172     }
4173 #ifdef ASSERT
4174     bool v = false;
4175     if (super->has_vanilla_constructor()) {
4176       const Method* const constructor =
4177         ik->find_method(vmSymbols::object_initializer_name(),
4178                        vmSymbols::void_method_signature());
4179       if (constructor != nullptr && constructor->is_vanilla_constructor()) {
4180         v = true;
4181       }
4182     }
4183     assert(v == ik->has_vanilla_constructor(), "inconsistent has_vanilla_constructor");
4184 #endif
4185   }
4186 
4187   // If it cannot be fast-path allocated, set a bit in the layout helper.
4188   // See documentation of InstanceKlass::can_be_fastpath_allocated().
4189   assert(ik->size_helper() > 0, "layout_helper is initialized");
4190   if ((!RegisterFinalizersAtInit && ik->has_finalizer())
4191       || ik->is_abstract() || ik->is_interface()
4192       || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == nullptr)
4193       || ik->size_helper() >= FastAllocateSizeLimit) {
4194     // Forbid fast-path allocation.
4195     const jint lh = Klass::instance_layout_helper(ik->size_helper(), true);
4196     ik->set_layout_helper(lh);
4197   }
4198 }
4199 






4200 // utility methods for appending an array with check for duplicates
4201 
4202 static void append_interfaces(GrowableArray<InstanceKlass*>* result,
4203                               const Array<InstanceKlass*>* const ifs) {
4204   // iterate over new interfaces
4205   for (int i = 0; i < ifs->length(); i++) {
4206     InstanceKlass* const e = ifs->at(i);
4207     assert(e->is_klass() && e->is_interface(), "just checking");
4208     // add new interface
4209     result->append_if_missing(e);
4210   }
4211 }
4212 
4213 static Array<InstanceKlass*>* compute_transitive_interfaces(const InstanceKlass* super,
4214                                                             Array<InstanceKlass*>* local_ifs,
4215                                                             ClassLoaderData* loader_data,
4216                                                             TRAPS) {
4217   assert(local_ifs != nullptr, "invariant");
4218   assert(loader_data != nullptr, "invariant");
4219 

4223   // Add superclass transitive interfaces size
4224   if (super != nullptr) {
4225     super_size = super->transitive_interfaces()->length();
4226     max_transitive_size += super_size;
4227   }
4228   // Add local interfaces' super interfaces
4229   const int local_size = local_ifs->length();
4230   for (int i = 0; i < local_size; i++) {
4231     InstanceKlass* const l = local_ifs->at(i);
4232     max_transitive_size += l->transitive_interfaces()->length();
4233   }
4234   // Finally add local interfaces
4235   max_transitive_size += local_size;
4236   // Construct array
4237   if (max_transitive_size == 0) {
4238     // no interfaces, use canonicalized array
4239     return Universe::the_empty_instance_klass_array();
4240   } else if (max_transitive_size == super_size) {
4241     // no new local interfaces added, share superklass' transitive interface array
4242     return super->transitive_interfaces();
4243   } else if (max_transitive_size == local_size) {
4244     // only local interfaces added, share local interface array
4245     return local_ifs;

4246   } else {
4247     ResourceMark rm;
4248     GrowableArray<InstanceKlass*>* const result = new GrowableArray<InstanceKlass*>(max_transitive_size);
4249 
4250     // Copy down from superclass
4251     if (super != nullptr) {
4252       append_interfaces(result, super->transitive_interfaces());
4253     }
4254 
4255     // Copy down from local interfaces' superinterfaces
4256     for (int i = 0; i < local_size; i++) {
4257       InstanceKlass* const l = local_ifs->at(i);
4258       append_interfaces(result, l->transitive_interfaces());
4259     }
4260     // Finally add local interfaces
4261     append_interfaces(result, local_ifs);
4262 
4263     // length will be less than the max_transitive_size if duplicates were removed
4264     const int length = result->length();
4265     assert(length <= max_transitive_size, "just checking");

4266     Array<InstanceKlass*>* const new_result =
4267       MetadataFactory::new_array<InstanceKlass*>(loader_data, length, CHECK_NULL);
4268     for (int i = 0; i < length; i++) {
4269       InstanceKlass* const e = result->at(i);
4270       assert(e != nullptr, "just checking");
4271       new_result->at_put(i, e);
4272     }
4273     return new_result;
4274   }
4275 }
4276 
4277 void ClassFileParser::check_super_class_access(const InstanceKlass* this_klass, TRAPS) {
4278   assert(this_klass != nullptr, "invariant");
4279   const Klass* const super = this_klass->super();
4280 
4281   if (super != nullptr) {
4282     const InstanceKlass* super_ik = InstanceKlass::cast(super);
4283 
4284     if (super->is_final()) {
4285       classfile_icce_error("class %s cannot inherit from final class %s", super_ik, THREAD);
4286       return;
4287     }
4288 
4289     if (super_ik->is_sealed() && !super_ik->has_as_permitted_subclass(this_klass)) {
4290       classfile_icce_error("class %s cannot inherit from sealed class %s", super_ik, THREAD);
4291       return;
4292     }
4293 










4294     // If the loader is not the boot loader then throw an exception if its
4295     // superclass is in package jdk.internal.reflect and its loader is not a
4296     // special reflection class loader
4297     if (!this_klass->class_loader_data()->is_the_null_class_loader_data()) {
4298       PackageEntry* super_package = super->package();
4299       if (super_package != nullptr &&
4300           super_package->name()->fast_compare(vmSymbols::jdk_internal_reflect()) == 0 &&
4301           !java_lang_ClassLoader::is_reflection_class_loader(this_klass->class_loader())) {
4302         ResourceMark rm(THREAD);
4303         Exceptions::fthrow(
4304           THREAD_AND_LOCATION,
4305           vmSymbols::java_lang_IllegalAccessError(),
4306           "class %s loaded by %s cannot access jdk/internal/reflect superclass %s",
4307           this_klass->external_name(),
4308           this_klass->class_loader_data()->loader_name_and_id(),
4309           super->external_name());
4310         return;
4311       }
4312     }
4313 

4459 
4460   for (int index = 0; index < num_methods; index++) {
4461     const Method* const m = methods->at(index);
4462     // if m is static and not the init method, throw a verify error
4463     if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) {
4464       ResourceMark rm(THREAD);
4465       Exceptions::fthrow(
4466         THREAD_AND_LOCATION,
4467         vmSymbols::java_lang_VerifyError(),
4468         "Illegal static method %s in interface %s",
4469         m->name()->as_C_string(),
4470         this_klass->external_name()
4471       );
4472       return;
4473     }
4474   }
4475 }
4476 
4477 // utility methods for format checking
4478 
4479 void ClassFileParser::verify_legal_class_modifiers(jint flags, TRAPS) const {
4480   const bool is_module = (flags & JVM_ACC_MODULE) != 0;

4481   assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");
4482   if (is_module) {
4483     ResourceMark rm(THREAD);
4484     Exceptions::fthrow(
4485       THREAD_AND_LOCATION,
4486       vmSymbols::java_lang_NoClassDefFoundError(),
4487       "%s is not a class because access_flag ACC_MODULE is set",
4488       _class_name->as_C_string());
4489     return;
4490   }
4491 
4492   if (!_need_verify) { return; }
4493 
4494   const bool is_interface  = (flags & JVM_ACC_INTERFACE)  != 0;
4495   const bool is_abstract   = (flags & JVM_ACC_ABSTRACT)   != 0;
4496   const bool is_final      = (flags & JVM_ACC_FINAL)      != 0;
4497   const bool is_super      = (flags & JVM_ACC_SUPER)      != 0;
4498   const bool is_enum       = (flags & JVM_ACC_ENUM)       != 0;
4499   const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4500   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4501 
4502   if ((is_abstract && is_final) ||
4503       (is_interface && !is_abstract) ||
4504       (is_interface && major_gte_1_5 && (is_super || is_enum)) ||
4505       (!is_interface && major_gte_1_5 && is_annotation)) {
4506     ResourceMark rm(THREAD);
4507     Exceptions::fthrow(
4508       THREAD_AND_LOCATION,
4509       vmSymbols::java_lang_ClassFormatError(),
4510       "Illegal class modifiers in class %s: 0x%X",
4511       _class_name->as_C_string(), flags
4512     );
4513     return;












4514   }
4515 }
4516 
4517 static bool has_illegal_visibility(jint flags) {
4518   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4519   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4520   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4521 
4522   return ((is_public && is_protected) ||
4523           (is_public && is_private) ||
4524           (is_protected && is_private));
4525 }
4526 
4527 // A legal major_version.minor_version must be one of the following:
4528 //
4529 //  Major_version >= 45 and major_version < 56, any minor_version.
4530 //  Major_version >= 56 and major_version <= JVM_CLASSFILE_MAJOR_VERSION and minor_version = 0.
4531 //  Major_version = JVM_CLASSFILE_MAJOR_VERSION and minor_version = 65535 and --enable-preview is present.
4532 //
4533 void ClassFileParser::verify_class_version(u2 major, u2 minor, Symbol* class_name, TRAPS){

4559         THREAD_AND_LOCATION,
4560         vmSymbols::java_lang_UnsupportedClassVersionError(),
4561         "%s (class file version %u.%u) was compiled with preview features that are unsupported. "
4562         "This version of the Java Runtime only recognizes preview features for class file version %u.%u",
4563         class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION, JAVA_PREVIEW_MINOR_VERSION);
4564       return;
4565     }
4566 
4567     if (!Arguments::enable_preview()) {
4568       classfile_ucve_error("Preview features are not enabled for %s (class file version %u.%u). Try running with '--enable-preview'",
4569                            class_name, major, minor, THREAD);
4570       return;
4571     }
4572 
4573   } else { // minor != JAVA_PREVIEW_MINOR_VERSION
4574     classfile_ucve_error("%s (class file version %u.%u) was compiled with an invalid non-zero minor version",
4575                          class_name, major, minor, THREAD);
4576   }
4577 }
4578 
4579 void ClassFileParser::verify_legal_field_modifiers(jint flags,
4580                                                    bool is_interface,
4581                                                    TRAPS) const {
4582   if (!_need_verify) { return; }
4583 
4584   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4585   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4586   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4587   const bool is_static    = (flags & JVM_ACC_STATIC)    != 0;
4588   const bool is_final     = (flags & JVM_ACC_FINAL)     != 0;
4589   const bool is_volatile  = (flags & JVM_ACC_VOLATILE)  != 0;
4590   const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
4591   const bool is_enum      = (flags & JVM_ACC_ENUM)      != 0;

4592   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4593 




4594   bool is_illegal = false;
4595 









4596   if (is_interface) {
4597     if (!is_public || !is_static || !is_final || is_private ||
4598         is_protected || is_volatile || is_transient ||
4599         (major_gte_1_5 && is_enum)) {
4600       is_illegal = true;
4601     }
4602   } else { // not interface
4603     if (has_illegal_visibility(flags) || (is_final && is_volatile)) {
4604       is_illegal = true;











4605     }
4606   }
4607 
4608   if (is_illegal) {
4609     ResourceMark rm(THREAD);
4610     Exceptions::fthrow(
4611       THREAD_AND_LOCATION,
4612       vmSymbols::java_lang_ClassFormatError(),
4613       "Illegal field modifiers in class %s: 0x%X",
4614       _class_name->as_C_string(), flags);
4615     return;
4616   }
4617 }
4618 
4619 void ClassFileParser::verify_legal_method_modifiers(jint flags,
4620                                                     bool is_interface,
4621                                                     const Symbol* name,
4622                                                     TRAPS) const {
4623   if (!_need_verify) { return; }
4624 
4625   const bool is_public       = (flags & JVM_ACC_PUBLIC)       != 0;
4626   const bool is_private      = (flags & JVM_ACC_PRIVATE)      != 0;
4627   const bool is_static       = (flags & JVM_ACC_STATIC)       != 0;
4628   const bool is_final        = (flags & JVM_ACC_FINAL)        != 0;
4629   const bool is_native       = (flags & JVM_ACC_NATIVE)       != 0;
4630   const bool is_abstract     = (flags & JVM_ACC_ABSTRACT)     != 0;
4631   const bool is_bridge       = (flags & JVM_ACC_BRIDGE)       != 0;
4632   const bool is_strict       = (flags & JVM_ACC_STRICT)       != 0;
4633   const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
4634   const bool is_protected    = (flags & JVM_ACC_PROTECTED)    != 0;
4635   const bool major_gte_1_5   = _major_version >= JAVA_1_5_VERSION;
4636   const bool major_gte_8     = _major_version >= JAVA_8_VERSION;
4637   const bool major_gte_17    = _major_version >= JAVA_17_VERSION;
4638   const bool is_initializer  = (name == vmSymbols::object_initializer_name());





4639 
4640   bool is_illegal = false;
4641 

4642   if (is_interface) {
4643     if (major_gte_8) {
4644       // Class file version is JAVA_8_VERSION or later Methods of
4645       // interfaces may set any of the flags except ACC_PROTECTED,
4646       // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must
4647       // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.
4648       if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
4649           (is_native || is_protected || is_final || is_synchronized) ||
4650           // If a specific method of a class or interface has its
4651           // ACC_ABSTRACT flag set, it must not have any of its
4652           // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,
4653           // ACC_STRICT, or ACC_SYNCHRONIZED flags set.  No need to
4654           // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as
4655           // those flags are illegal irrespective of ACC_ABSTRACT being set or not.
4656           (is_abstract && (is_private || is_static || (!major_gte_17 && is_strict)))) {
4657         is_illegal = true;
4658       }
4659     } else if (major_gte_1_5) {
4660       // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)
4661       if (!is_public || is_private || is_protected || is_static || is_final ||
4662           is_synchronized || is_native || !is_abstract || is_strict) {
4663         is_illegal = true;
4664       }
4665     } else {
4666       // Class file version is pre-JAVA_1_5_VERSION
4667       if (!is_public || is_static || is_final || is_native || !is_abstract) {
4668         is_illegal = true;
4669       }
4670     }
4671   } else { // not interface
4672     if (has_illegal_visibility(flags)) {
4673       is_illegal = true;
4674     } else {
4675       if (is_initializer) {
4676         if (is_static || is_final || is_synchronized || is_native ||
4677             is_abstract || (major_gte_1_5 && is_bridge)) {
4678           is_illegal = true;
4679         }
4680       } else { // not initializer
4681         if (is_abstract) {
4682           if ((is_final || is_native || is_private || is_static ||
4683               (major_gte_1_5 && (is_synchronized || (!major_gte_17 && is_strict))))) {
4684             is_illegal = true;





4685           }
4686         }
4687       }
4688     }
4689   }
4690 
4691   if (is_illegal) {
4692     ResourceMark rm(THREAD);
4693     Exceptions::fthrow(
4694       THREAD_AND_LOCATION,
4695       vmSymbols::java_lang_ClassFormatError(),
4696       "Method %s in class %s has illegal modifiers: 0x%X",
4697       name->as_C_string(), _class_name->as_C_string(), flags);









4698     return;
4699   }
4700 }
4701 
4702 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer,
4703                                         int length,
4704                                         TRAPS) const {
4705   assert(_need_verify, "only called when _need_verify is true");
4706   if (!UTF8::is_legal_utf8(buffer, length, _major_version <= 47)) {
4707     classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", THREAD);
4708   }
4709 }
4710 
4711 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
4712 // In class names, '/' separates unqualified names.  This is verified in this function also.
4713 // Method names also may not contain the characters '<' or '>', unless <init>
4714 // or <clinit>.  Note that method names may not be <init> or <clinit> in this
4715 // method.  Because these names have been checked as special cases before
4716 // calling this method in verify_legal_method_name.
4717 //

4734         if (type == ClassFileParser::LegalClass) {
4735           if (p == name || p+1 >= name+length ||
4736               *(p+1) == JVM_SIGNATURE_SLASH) {
4737             return false;
4738           }
4739         } else {
4740           return false;   // do not permit '/' unless it's class name
4741         }
4742         break;
4743       case JVM_SIGNATURE_SPECIAL:
4744       case JVM_SIGNATURE_ENDSPECIAL:
4745         // do not permit '<' or '>' in method names
4746         if (type == ClassFileParser::LegalMethod) {
4747           return false;
4748         }
4749     }
4750   }
4751   return true;
4752 }
4753 









4754 // Take pointer to a UTF8 byte string (not NUL-terminated).
4755 // Skip over the longest part of the string that could
4756 // be taken as a fieldname. Allow non-trailing '/'s if slash_ok is true.
4757 // Return a pointer to just past the fieldname.
4758 // Return null if no fieldname at all was found, or in the case of slash_ok
4759 // being true, we saw consecutive slashes (meaning we were looking for a
4760 // qualified path but found something that was badly-formed).
4761 static const char* skip_over_field_name(const char* const name,
4762                                         bool slash_ok,
4763                                         unsigned int length) {
4764   const char* p;
4765   jboolean last_is_slash = false;
4766   jboolean not_first_ch = false;
4767 
4768   for (p = name; p != name + length; not_first_ch = true) {
4769     const char* old_p = p;
4770     jchar ch = *p;
4771     if (ch < 128) {
4772       p++;
4773       // quick check for ascii

4835 // be taken as a field signature. Allow "void" if void_ok.
4836 // Return a pointer to just past the signature.
4837 // Return null if no legal signature is found.
4838 const char* ClassFileParser::skip_over_field_signature(const char* signature,
4839                                                        bool void_ok,
4840                                                        unsigned int length,
4841                                                        TRAPS) const {
4842   unsigned int array_dim = 0;
4843   while (length > 0) {
4844     switch (signature[0]) {
4845     case JVM_SIGNATURE_VOID: if (!void_ok) { return nullptr; }
4846     case JVM_SIGNATURE_BOOLEAN:
4847     case JVM_SIGNATURE_BYTE:
4848     case JVM_SIGNATURE_CHAR:
4849     case JVM_SIGNATURE_SHORT:
4850     case JVM_SIGNATURE_INT:
4851     case JVM_SIGNATURE_FLOAT:
4852     case JVM_SIGNATURE_LONG:
4853     case JVM_SIGNATURE_DOUBLE:
4854       return signature + 1;
4855     case JVM_SIGNATURE_CLASS: {

4856       if (_major_version < JAVA_1_5_VERSION) {
4857         // Skip over the class name if one is there
4858         const char* const p = skip_over_field_name(signature + 1, true, --length);
4859 
4860         // The next character better be a semicolon
4861         if (p && (p - signature) > 1 && p[0] == JVM_SIGNATURE_ENDCLASS) {
4862           return p + 1;
4863         }
4864       }
4865       else {
4866         // Skip leading 'L' and ignore first appearance of ';'
4867         signature++;
4868         const char* c = (const char*) memchr(signature, JVM_SIGNATURE_ENDCLASS, length - 1);
4869         // Format check signature
4870         if (c != nullptr) {
4871           int newlen = pointer_delta_as_int(c, (char*) signature);
4872           bool legal = verify_unqualified_name(signature, newlen, LegalClass);
4873           if (!legal) {
4874             classfile_parse_error("Class name is empty or contains illegal character "
4875                                   "in descriptor in class file %s",
4876                                   THREAD);
4877             return nullptr;
4878           }
4879           return signature + newlen + 1;
4880         }
4881       }
4882       return nullptr;
4883     }
4884     case JVM_SIGNATURE_ARRAY:
4885       array_dim++;
4886       if (array_dim > 255) {

4902 
4903 // Checks if name is a legal class name.
4904 void ClassFileParser::verify_legal_class_name(const Symbol* name, TRAPS) const {
4905   if (!_need_verify || _relax_verify) { return; }
4906 
4907   assert(name->refcount() > 0, "symbol must be kept alive");
4908   char* bytes = (char*)name->bytes();
4909   unsigned int length = name->utf8_length();
4910   bool legal = false;
4911 
4912   if (length > 0) {
4913     const char* p;
4914     if (bytes[0] == JVM_SIGNATURE_ARRAY) {
4915       p = skip_over_field_signature(bytes, false, length, CHECK);
4916       legal = (p != nullptr) && ((p - bytes) == (int)length);
4917     } else if (_major_version < JAVA_1_5_VERSION) {
4918       if (bytes[0] != JVM_SIGNATURE_SPECIAL) {
4919         p = skip_over_field_name(bytes, true, length);
4920         legal = (p != nullptr) && ((p - bytes) == (int)length);
4921       }




4922     } else {
4923       // 4900761: relax the constraints based on JSR202 spec
4924       // Class names may be drawn from the entire Unicode character set.
4925       // Identifiers between '/' must be unqualified names.
4926       // The utf8 string has been verified when parsing cpool entries.
4927       legal = verify_unqualified_name(bytes, length, LegalClass);
4928     }
4929   }
4930   if (!legal) {
4931     ResourceMark rm(THREAD);
4932     assert(_class_name != nullptr, "invariant");
4933     Exceptions::fthrow(
4934       THREAD_AND_LOCATION,
4935       vmSymbols::java_lang_ClassFormatError(),
4936       "Illegal class name \"%.*s\" in class file %s", length, bytes,
4937       _class_name->as_C_string()
4938     );
4939     return;
4940   }
4941 }

4967       THREAD_AND_LOCATION,
4968       vmSymbols::java_lang_ClassFormatError(),
4969       "Illegal field name \"%.*s\" in class %s", length, bytes,
4970       _class_name->as_C_string()
4971     );
4972     return;
4973   }
4974 }
4975 
4976 // Checks if name is a legal method name.
4977 void ClassFileParser::verify_legal_method_name(const Symbol* name, TRAPS) const {
4978   if (!_need_verify || _relax_verify) { return; }
4979 
4980   assert(name != nullptr, "method name is null");
4981   char* bytes = (char*)name->bytes();
4982   unsigned int length = name->utf8_length();
4983   bool legal = false;
4984 
4985   if (length > 0) {
4986     if (bytes[0] == JVM_SIGNATURE_SPECIAL) {
4987       if (name == vmSymbols::object_initializer_name() || name == vmSymbols::class_initializer_name()) {

4988         legal = true;
4989       }
4990     } else if (_major_version < JAVA_1_5_VERSION) {
4991       const char* p;
4992       p = skip_over_field_name(bytes, false, length);
4993       legal = (p != nullptr) && ((p - bytes) == (int)length);
4994     } else {
4995       // 4881221: relax the constraints based on JSR202 spec
4996       legal = verify_unqualified_name(bytes, length, LegalMethod);
4997     }
4998   }
4999 
5000   if (!legal) {
5001     ResourceMark rm(THREAD);
5002     assert(_class_name != nullptr, "invariant");
5003     Exceptions::fthrow(
5004       THREAD_AND_LOCATION,
5005       vmSymbols::java_lang_ClassFormatError(),
5006       "Illegal method name \"%.*s\" in class %s", length, bytes,
5007       _class_name->as_C_string()

5028 
5029 // Check that the signature is compatible with the method name.  For example,
5030 // check that <init> has a void signature.
5031 void ClassFileParser::verify_legal_name_with_signature(const Symbol* name,
5032                                                        const Symbol* signature,
5033                                                        TRAPS) const {
5034   if (!_need_verify) {
5035     return;
5036   }
5037 
5038   // Class initializers cannot have args for class format version >= 51.
5039   if (name == vmSymbols::class_initializer_name() &&
5040       signature != vmSymbols::void_method_signature() &&
5041       _major_version >= JAVA_7_VERSION) {
5042     throwIllegalSignature("Method", name, signature, THREAD);
5043     return;
5044   }
5045 
5046   int sig_length = signature->utf8_length();
5047   if (name->utf8_length() > 0 &&
5048       name->char_at(0) == JVM_SIGNATURE_SPECIAL &&
5049       sig_length > 0 &&
5050       signature->char_at(sig_length - 1) != JVM_SIGNATURE_VOID) {
5051     throwIllegalSignature("Method", name, signature, THREAD);
5052   }
5053 }
5054 
5055 // Checks if signature is a legal method signature.
5056 // Returns number of parameters
5057 int ClassFileParser::verify_legal_method_signature(const Symbol* name,
5058                                                    const Symbol* signature,
5059                                                    TRAPS) const {
5060   if (!_need_verify) {
5061     // make sure caller's args_size will be less than 0 even for non-static
5062     // method so it will be recomputed in compute_size_of_parameters().
5063     return -2;
5064   }
5065 
5066   unsigned int args_size = 0;
5067   const char* p = (const char*)signature->bytes();
5068   unsigned int length = signature->utf8_length();
5069   const char* nextp;
5070 

5207   }
5208 }
5209 
5210 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook,
5211                                                       const ClassInstanceInfo& cl_inst_info,
5212                                                       TRAPS) {
5213   if (_klass != nullptr) {
5214     return _klass;
5215   }
5216 
5217   InstanceKlass* const ik =
5218     InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
5219 
5220   if (is_hidden()) {
5221     mangle_hidden_class_name(ik);
5222   }
5223 
5224   fill_instance_klass(ik, changed_by_loadhook, cl_inst_info, CHECK_NULL);
5225 
5226   assert(_klass == ik, "invariant");
5227 
5228   return ik;
5229 }
5230 
5231 void ClassFileParser::fill_instance_klass(InstanceKlass* ik,
5232                                           bool changed_by_loadhook,
5233                                           const ClassInstanceInfo& cl_inst_info,
5234                                           TRAPS) {
5235   assert(ik != nullptr, "invariant");
5236 
5237   // Set name and CLD before adding to CLD
5238   ik->set_class_loader_data(_loader_data);
5239   ik->set_name(_class_name);
5240 
5241   // Add all classes to our internal class loader list here,
5242   // including classes in the bootstrap (null) class loader.
5243   const bool publicize = !is_internal();
5244 
5245   _loader_data->add_class(ik, publicize);
5246 
5247   set_klass_to_deallocate(ik);
5248 
5249   assert(_field_info != nullptr, "invariant");
5250   assert(ik->static_field_size() == _field_info->_static_field_size, "sanity");
5251   assert(ik->nonstatic_oop_map_count() == _field_info->oop_map_blocks->_nonstatic_oop_map_count,
5252          "sanity");
5253 
5254   assert(ik->is_instance_klass(), "sanity");
5255   assert(ik->size_helper() == _field_info->_instance_size, "sanity");
5256 
5257   // Fill in information already parsed
5258   ik->set_should_verify_class(_need_verify);
5259 
5260   // Not yet: supers are done below to support the new subtype-checking fields
5261   ik->set_nonstatic_field_size(_field_info->_nonstatic_field_size);
5262   ik->set_has_nonstatic_fields(_field_info->_has_nonstatic_fields);




5263   assert(_fac != nullptr, "invariant");
5264   ik->set_static_oop_field_count(_fac->count[STATIC_OOP]);
5265 
5266   // this transfers ownership of a lot of arrays from
5267   // the parser onto the InstanceKlass*
5268   apply_parsed_class_metadata(ik, _java_fields_count);



5269 
5270   // can only set dynamic nest-host after static nest information is set
5271   if (cl_inst_info.dynamic_nest_host() != nullptr) {
5272     ik->set_nest_host(cl_inst_info.dynamic_nest_host());
5273   }
5274 
5275   // note that is not safe to use the fields in the parser from this point on
5276   assert(nullptr == _cp, "invariant");
5277   assert(nullptr == _fieldinfo_stream, "invariant");
5278   assert(nullptr == _fields_status, "invariant");
5279   assert(nullptr == _methods, "invariant");
5280   assert(nullptr == _inner_classes, "invariant");
5281   assert(nullptr == _nest_members, "invariant");

5282   assert(nullptr == _combined_annotations, "invariant");
5283   assert(nullptr == _record_components, "invariant");
5284   assert(nullptr == _permitted_subclasses, "invariant");

5285 
5286   if (_has_localvariable_table) {
5287     ik->set_has_localvariable_table(true);
5288   }
5289 
5290   if (_has_final_method) {
5291     ik->set_has_final_method();
5292   }
5293 
5294   ik->copy_method_ordering(_method_ordering, CHECK);
5295   // The InstanceKlass::_methods_jmethod_ids cache
5296   // is managed on the assumption that the initial cache
5297   // size is equal to the number of methods in the class. If
5298   // that changes, then InstanceKlass::idnum_can_increment()
5299   // has to be changed accordingly.
5300   ik->set_initial_method_idnum(checked_cast<u2>(ik->methods()->length()));
5301 
5302   ik->set_this_class_index(_this_class_index);
5303 
5304   if (_is_hidden) {
5305     // _this_class_index is a CONSTANT_Class entry that refers to this
5306     // hidden class itself. If this class needs to refer to its own methods
5307     // or fields, it would use a CONSTANT_MethodRef, etc, which would reference
5308     // _this_class_index. However, because this class is hidden (it's
5309     // not stored in SystemDictionary), _this_class_index cannot be resolved
5310     // with ConstantPool::klass_at_impl, which does a SystemDictionary lookup.
5311     // Therefore, we must eagerly resolve _this_class_index now.
5312     ik->constants()->klass_at_put(_this_class_index, ik);
5313   }
5314 
5315   ik->set_minor_version(_minor_version);
5316   ik->set_major_version(_major_version);
5317   ik->set_has_nonstatic_concrete_methods(_has_nonstatic_concrete_methods);
5318   ik->set_declares_nonstatic_concrete_methods(_declares_nonstatic_concrete_methods);
5319 






5320   if (_is_hidden) {
5321     ik->set_is_hidden();
5322   }
5323 
5324   // Set PackageEntry for this_klass
5325   oop cl = ik->class_loader();
5326   Handle clh = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(cl));
5327   ClassLoaderData* cld = ClassLoaderData::class_loader_data_or_null(clh());
5328   ik->set_package(cld, nullptr, CHECK);
5329 
5330   const Array<Method*>* const methods = ik->methods();
5331   assert(methods != nullptr, "invariant");
5332   const int methods_len = methods->length();
5333 
5334   check_methods_for_intrinsics(ik, methods);
5335 
5336   // Fill in field values obtained by parse_classfile_attributes
5337   if (_parsed_annotations->has_any_annotations()) {
5338     _parsed_annotations->apply_to(ik);
5339   }

5406 
5407   assert(_all_mirandas != nullptr, "invariant");
5408 
5409   // Generate any default methods - default methods are public interface methods
5410   // that have a default implementation.  This is new with Java 8.
5411   if (_has_nonstatic_concrete_methods) {
5412     DefaultMethods::generate_default_methods(ik,
5413                                              _all_mirandas,
5414                                              CHECK);
5415   }
5416 
5417   // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5418   if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5419       !module_entry->has_default_read_edges()) {
5420     if (!module_entry->set_has_default_read_edges()) {
5421       // We won a potential race
5422       JvmtiExport::add_default_read_edges(module_handle, THREAD);
5423     }
5424   }
5425 



























5426   ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5427 
5428   if (!is_internal()) {
5429     ik->print_class_load_logging(_loader_data, module_entry, _stream);
5430 
5431     if (ik->minor_version() == JAVA_PREVIEW_MINOR_VERSION &&
5432         ik->major_version() == JVM_CLASSFILE_MAJOR_VERSION &&
5433         log_is_enabled(Info, class, preview)) {
5434       ResourceMark rm;
5435       log_info(class, preview)("Loading class %s that depends on preview features (class file version %d.65535)",
5436                                ik->external_name(), JVM_CLASSFILE_MAJOR_VERSION);
5437     }
5438 
5439     if (log_is_enabled(Debug, class, resolve))  {
5440       ResourceMark rm;
5441       // print out the superclass.
5442       const char * from = ik->external_name();
5443       if (ik->java_super() != nullptr) {
5444         log_debug(class, resolve)("%s %s (super)",
5445                    from,

5497                                  Symbol* name,
5498                                  ClassLoaderData* loader_data,
5499                                  const ClassLoadInfo* cl_info,
5500                                  Publicity pub_level,
5501                                  TRAPS) :
5502   _stream(stream),
5503   _class_name(nullptr),
5504   _loader_data(loader_data),
5505   _is_hidden(cl_info->is_hidden()),
5506   _can_access_vm_annotations(cl_info->can_access_vm_annotations()),
5507   _orig_cp_size(0),
5508   _super_klass(),
5509   _cp(nullptr),
5510   _fieldinfo_stream(nullptr),
5511   _fields_status(nullptr),
5512   _methods(nullptr),
5513   _inner_classes(nullptr),
5514   _nest_members(nullptr),
5515   _nest_host(0),
5516   _permitted_subclasses(nullptr),

5517   _record_components(nullptr),
5518   _local_interfaces(nullptr),

5519   _transitive_interfaces(nullptr),
5520   _combined_annotations(nullptr),
5521   _class_annotations(nullptr),
5522   _class_type_annotations(nullptr),
5523   _fields_annotations(nullptr),
5524   _fields_type_annotations(nullptr),
5525   _klass(nullptr),
5526   _klass_to_deallocate(nullptr),
5527   _parsed_annotations(nullptr),
5528   _fac(nullptr),
5529   _field_info(nullptr),

5530   _temp_field_info(nullptr),
5531   _method_ordering(nullptr),
5532   _all_mirandas(nullptr),
5533   _vtable_size(0),
5534   _itable_size(0),
5535   _num_miranda_methods(0),
5536   _protection_domain(cl_info->protection_domain()),
5537   _access_flags(),
5538   _pub_level(pub_level),
5539   _bad_constant_seen(0),
5540   _synthetic_flag(false),
5541   _sde_length(false),
5542   _sde_buffer(nullptr),
5543   _sourcefile_index(0),
5544   _generic_signature_index(0),
5545   _major_version(0),
5546   _minor_version(0),
5547   _this_class_index(0),
5548   _super_class_index(0),
5549   _itfs_len(0),
5550   _java_fields_count(0),
5551   _need_verify(false),
5552   _relax_verify(false),
5553   _has_nonstatic_concrete_methods(false),
5554   _declares_nonstatic_concrete_methods(false),
5555   _has_localvariable_table(false),
5556   _has_final_method(false),
5557   _has_contended_fields(false),








5558   _has_finalizer(false),
5559   _has_empty_finalizer(false),
5560   _has_vanilla_constructor(false),
5561   _max_bootstrap_specifier_index(-1) {
5562 
5563   _class_name = name != nullptr ? name : vmSymbols::unknown_class_name();
5564   _class_name->increment_refcount();
5565 
5566   assert(_loader_data != nullptr, "invariant");
5567   assert(stream != nullptr, "invariant");
5568   assert(_stream != nullptr, "invariant");
5569   assert(_stream->buffer() == _stream->current(), "invariant");
5570   assert(_class_name != nullptr, "invariant");
5571   assert(0 == _access_flags.as_int(), "invariant");
5572 
5573   // Figure out whether we can skip format checking (matching classic VM behavior)
5574   if (CDSConfig::is_dumping_static_archive()) {
5575     // verify == true means it's a 'remote' class (i.e., non-boot class)
5576     // Verification decision is based on BytecodeVerificationRemote flag
5577     // for those classes.

5588 
5589   // Check if verification needs to be relaxed for this class file
5590   // Do not restrict it to jdk1.0 or jdk1.1 to maintain backward compatibility (4982376)
5591   _relax_verify = relax_format_check_for(_loader_data);
5592 
5593   parse_stream(stream, CHECK);
5594 
5595   post_process_parsed_stream(stream, _cp, CHECK);
5596 }
5597 
5598 void ClassFileParser::clear_class_metadata() {
5599   // metadata created before the instance klass is created.  Must be
5600   // deallocated if classfile parsing returns an error.
5601   _cp = nullptr;
5602   _fieldinfo_stream = nullptr;
5603   _fields_status = nullptr;
5604   _methods = nullptr;
5605   _inner_classes = nullptr;
5606   _nest_members = nullptr;
5607   _permitted_subclasses = nullptr;

5608   _combined_annotations = nullptr;
5609   _class_annotations = _class_type_annotations = nullptr;
5610   _fields_annotations = _fields_type_annotations = nullptr;
5611   _record_components = nullptr;

5612 }
5613 
5614 // Destructor to clean up
5615 ClassFileParser::~ClassFileParser() {
5616   _class_name->decrement_refcount();
5617 
5618   if (_cp != nullptr) {
5619     MetadataFactory::free_metadata(_loader_data, _cp);
5620   }
5621 
5622   if (_fieldinfo_stream != nullptr) {
5623     MetadataFactory::free_array<u1>(_loader_data, _fieldinfo_stream);
5624   }
5625 
5626   if (_fields_status != nullptr) {
5627     MetadataFactory::free_array<FieldStatus>(_loader_data, _fields_status);
5628   }
5629 




5630   if (_methods != nullptr) {
5631     // Free methods
5632     InstanceKlass::deallocate_methods(_loader_data, _methods);
5633   }
5634 
5635   // beware of the Universe::empty_blah_array!!
5636   if (_inner_classes != nullptr && _inner_classes != Universe::the_empty_short_array()) {
5637     MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
5638   }
5639 
5640   if (_nest_members != nullptr && _nest_members != Universe::the_empty_short_array()) {
5641     MetadataFactory::free_array<u2>(_loader_data, _nest_members);
5642   }
5643 
5644   if (_record_components != nullptr) {
5645     InstanceKlass::deallocate_record_components(_loader_data, _record_components);
5646   }
5647 
5648   if (_permitted_subclasses != nullptr && _permitted_subclasses != Universe::the_empty_short_array()) {
5649     MetadataFactory::free_array<u2>(_loader_data, _permitted_subclasses);
5650   }
5651 




5652   // Free interfaces
5653   InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
5654                                        _local_interfaces, _transitive_interfaces);
5655 
5656   if (_combined_annotations != nullptr) {
5657     // After all annotations arrays have been created, they are installed into the
5658     // Annotations object that will be assigned to the InstanceKlass being created.
5659 
5660     // Deallocate the Annotations object and the installed annotations arrays.
5661     _combined_annotations->deallocate_contents(_loader_data);
5662 
5663     // If the _combined_annotations pointer is non-null,
5664     // then the other annotations fields should have been cleared.
5665     assert(_class_annotations       == nullptr, "Should have been cleared");
5666     assert(_class_type_annotations  == nullptr, "Should have been cleared");
5667     assert(_fields_annotations      == nullptr, "Should have been cleared");
5668     assert(_fields_type_annotations == nullptr, "Should have been cleared");
5669   } else {
5670     // If the annotations arrays were not installed into the Annotations object,
5671     // then they have to be deallocated explicitly.

5716     cp_size, CHECK);
5717 
5718   _orig_cp_size = cp_size;
5719   if (is_hidden()) { // Add a slot for hidden class name.
5720     cp_size++;
5721   }
5722 
5723   _cp = ConstantPool::allocate(_loader_data,
5724                                cp_size,
5725                                CHECK);
5726 
5727   ConstantPool* const cp = _cp;
5728 
5729   parse_constant_pool(stream, cp, _orig_cp_size, CHECK);
5730 
5731   assert(cp_size == (u2)cp->length(), "invariant");
5732 
5733   // ACCESS FLAGS
5734   stream->guarantee_more(8, CHECK);  // flags, this_class, super_class, infs_len
5735 
5736   // Access flags
5737   jint flags;
5738   // JVM_ACC_MODULE is defined in JDK-9 and later.
5739   if (_major_version >= JAVA_9_VERSION) {
5740     flags = stream->get_u2_fast() & (JVM_RECOGNIZED_CLASS_MODIFIERS | JVM_ACC_MODULE);
5741   } else {
5742     flags = stream->get_u2_fast() & JVM_RECOGNIZED_CLASS_MODIFIERS;
5743   }
5744 



5745   if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
5746     // Set abstract bit for old class files for backward compatibility
5747     flags |= JVM_ACC_ABSTRACT;
5748   }
5749 
5750   verify_legal_class_modifiers(flags, CHECK);
5751 
5752   short bad_constant = class_bad_constant_seen();
5753   if (bad_constant != 0) {
5754     // Do not throw CFE until after the access_flags are checked because if
5755     // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
5756     classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, THREAD);
5757     return;
5758   }
5759 
5760   _access_flags.set_flags(flags);
5761 
5762   // This class and superclass
5763   _this_class_index = stream->get_u2_fast();
5764   check_property(
5765     valid_cp_range(_this_class_index, cp_size) &&
5766       cp->tag_at(_this_class_index).is_unresolved_klass(),
5767     "Invalid this class index %u in constant pool in class file %s",
5768     _this_class_index, CHECK);
5769 
5770   Symbol* const class_name_in_cp = cp->klass_name_at(_this_class_index);
5771   assert(class_name_in_cp != nullptr, "class_name can't be null");
5772 














5773   // Don't need to check whether this class name is legal or not.
5774   // It has been checked when constant pool is parsed.
5775   // However, make sure it is not an array type.
5776   if (_need_verify) {
5777     guarantee_property(class_name_in_cp->char_at(0) != JVM_SIGNATURE_ARRAY,
5778                        "Bad class name in class file %s",
5779                        CHECK);
5780   }
5781 
5782 #ifdef ASSERT
5783   // Basic sanity checks
5784   if (_is_hidden) {
5785     assert(_class_name != vmSymbols::unknown_class_name(), "hidden classes should have a special name");
5786   }
5787 #endif
5788 
5789   // Update the _class_name as needed depending on whether this is a named, un-named, or hidden class.
5790 
5791   if (_is_hidden) {
5792     assert(_class_name != nullptr, "Unexpected null _class_name");

5832       }
5833       ls.cr();
5834     }
5835   }
5836 
5837   // SUPERKLASS
5838   _super_class_index = stream->get_u2_fast();
5839   _super_klass = parse_super_class(cp,
5840                                    _super_class_index,
5841                                    _need_verify,
5842                                    CHECK);
5843 
5844   // Interfaces
5845   _itfs_len = stream->get_u2_fast();
5846   parse_interfaces(stream,
5847                    _itfs_len,
5848                    cp,
5849                    &_has_nonstatic_concrete_methods,
5850                    CHECK);
5851 
5852   assert(_local_interfaces != nullptr, "invariant");
5853 
5854   // Fields (offsets are filled in later)
5855   _fac = new FieldAllocationCount();
5856   parse_fields(stream,
5857                _access_flags.is_interface(),
5858                _fac,
5859                cp,
5860                cp_size,
5861                &_java_fields_count,
5862                CHECK);
5863 
5864   assert(_temp_field_info != nullptr, "invariant");
5865 
5866   // Methods
5867   parse_methods(stream,
5868                 _access_flags.is_interface(),


5869                 &_has_localvariable_table,
5870                 &_has_final_method,
5871                 &_declares_nonstatic_concrete_methods,
5872                 CHECK);
5873 
5874   assert(_methods != nullptr, "invariant");
5875 
5876   if (_declares_nonstatic_concrete_methods) {
5877     _has_nonstatic_concrete_methods = true;
5878   }
5879 
5880   // Additional attributes/annotations
5881   _parsed_annotations = new ClassAnnotationCollector();
5882   parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK);
5883 
5884   assert(_inner_classes != nullptr, "invariant");
5885 
5886   // Finalize the Annotations metadata object,
5887   // now that all annotation arrays have been created.
5888   create_combined_annotations(CHECK);

5928   // Update this_class_index's slot in the constant pool with the new Utf8 entry.
5929   // We have to update the resolved_klass_index and the name_index together
5930   // so extract the existing resolved_klass_index first.
5931   CPKlassSlot cp_klass_slot = _cp->klass_slot_at(_this_class_index);
5932   int resolved_klass_index = cp_klass_slot.resolved_klass_index();
5933   _cp->unresolved_klass_at_put(_this_class_index, hidden_index, resolved_klass_index);
5934   assert(_cp->klass_slot_at(_this_class_index).name_index() == _orig_cp_size,
5935          "Bad name_index");
5936 }
5937 
5938 void ClassFileParser::post_process_parsed_stream(const ClassFileStream* const stream,
5939                                                  ConstantPool* cp,
5940                                                  TRAPS) {
5941   assert(stream != nullptr, "invariant");
5942   assert(stream->at_eos(), "invariant");
5943   assert(cp != nullptr, "invariant");
5944   assert(_loader_data != nullptr, "invariant");
5945 
5946   if (_class_name == vmSymbols::java_lang_Object()) {
5947     check_property(_local_interfaces == Universe::the_empty_instance_klass_array(),
5948                    "java.lang.Object cannot implement an interface in class file %s",
5949                    CHECK);
5950   }
5951   // We check super class after class file is parsed and format is checked
5952   if (_super_class_index > 0 && nullptr == _super_klass) {
5953     Symbol* const super_class_name = cp->klass_name_at(_super_class_index);
5954     if (_access_flags.is_interface()) {
5955       // Before attempting to resolve the superclass, check for class format
5956       // errors not checked yet.
5957       guarantee_property(super_class_name == vmSymbols::java_lang_Object(),
5958         "Interfaces must have java.lang.Object as superclass in class file %s",
5959         CHECK);
5960     }
5961     Handle loader(THREAD, _loader_data->class_loader());
5962     if (loader.is_null() && super_class_name == vmSymbols::java_lang_Object()) {
5963       _super_klass = vmClasses::Object_klass();
5964     } else {
5965       _super_klass = (const InstanceKlass*)
5966                        SystemDictionary::resolve_super_or_fail(_class_name,
5967                                                                super_class_name,
5968                                                                loader,
5969                                                                _protection_domain,
5970                                                                true,
5971                                                                CHECK);
5972     }
5973   }
5974 
5975   if (_super_klass != nullptr) {









5976     if (_super_klass->has_nonstatic_concrete_methods()) {
5977       _has_nonstatic_concrete_methods = true;
5978     }
5979 
5980     if (_super_klass->is_interface()) {
5981       classfile_icce_error("class %s has interface %s as super class", _super_klass, THREAD);
5982       return;























































































5983     }
5984   }

5985 
5986   // Compute the transitive list of all unique interfaces implemented by this class
5987   _transitive_interfaces =
5988     compute_transitive_interfaces(_super_klass,
5989                                   _local_interfaces,
5990                                   _loader_data,
5991                                   CHECK);
5992 
5993   assert(_transitive_interfaces != nullptr, "invariant");
5994 
5995   // sort methods
5996   _method_ordering = sort_methods(_methods);
5997 
5998   _all_mirandas = new GrowableArray<Method*>(20);
5999 
6000   Handle loader(THREAD, _loader_data->class_loader());
6001   klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
6002                                                     &_num_miranda_methods,
6003                                                     _all_mirandas,
6004                                                     _super_klass,
6005                                                     _methods,
6006                                                     _access_flags,
6007                                                     _major_version,
6008                                                     loader,
6009                                                     _class_name,
6010                                                     _local_interfaces);
6011 
6012   // Size of Java itable (in words)
6013   _itable_size = _access_flags.is_interface() ? 0 :
6014     klassItable::compute_itable_size(_transitive_interfaces);
6015 
6016   assert(_fac != nullptr, "invariant");
6017   assert(_parsed_annotations != nullptr, "invariant");
6018 











































































6019   _field_info = new FieldLayoutInfo();
6020   FieldLayoutBuilder lb(class_name(), super_klass(), _cp, /*_fields*/ _temp_field_info,
6021                         _parsed_annotations->is_contended(), _field_info);
6022   lb.build_layout();







6023 
6024   int injected_fields_count = _temp_field_info->length() - _java_fields_count;
6025   _fieldinfo_stream =
6026     FieldInfoStream::create_FieldInfoStream(_temp_field_info, _java_fields_count,
6027                                             injected_fields_count, loader_data(), CHECK);
6028   _fields_status =
6029     MetadataFactory::new_array<FieldStatus>(_loader_data, _temp_field_info->length(),
6030                                             FieldStatus(0), CHECK);
6031 }
6032 
6033 void ClassFileParser::set_klass(InstanceKlass* klass) {
6034 
6035 #ifdef ASSERT
6036   if (klass != nullptr) {
6037     assert(nullptr == _klass, "leaking?");
6038   }
6039 #endif
6040 
6041   _klass = klass;
6042 }

   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "oops/inlineKlass.hpp"
  26 #include "precompiled.hpp"
  27 #include "cds/cdsConfig.hpp"
  28 #include "classfile/classFileParser.hpp"
  29 #include "classfile/classFileStream.hpp"
  30 #include "classfile/classLoader.hpp"
  31 #include "classfile/classLoaderData.inline.hpp"
  32 #include "classfile/classLoadInfo.hpp"
  33 #include "classfile/defaultMethods.hpp"
  34 #include "classfile/fieldLayoutBuilder.hpp"
  35 #include "classfile/javaClasses.inline.hpp"
  36 #include "classfile/moduleEntry.hpp"
  37 #include "classfile/packageEntry.hpp"
  38 #include "classfile/symbolTable.hpp"
  39 #include "classfile/systemDictionary.hpp"
  40 #include "classfile/verificationType.hpp"
  41 #include "classfile/verifier.hpp"
  42 #include "classfile/vmClasses.hpp"
  43 #include "classfile/vmSymbols.hpp"
  44 #include "jvm.h"
  45 #include "logging/log.hpp"
  46 #include "logging/logStream.hpp"
  47 #include "memory/allocation.hpp"
  48 #include "memory/metadataFactory.hpp"
  49 #include "memory/oopFactory.hpp"
  50 #include "memory/resourceArea.hpp"
  51 #include "memory/universe.hpp"
  52 #include "oops/annotations.hpp"
  53 #include "oops/constantPool.inline.hpp"
  54 #include "oops/fieldInfo.hpp"
  55 #include "oops/fieldStreams.inline.hpp"
  56 #include "oops/inlineKlass.inline.hpp"
  57 #include "oops/instanceKlass.inline.hpp"
  58 #include "oops/instanceMirrorKlass.hpp"
  59 #include "oops/klass.inline.hpp"
  60 #include "oops/klassVtable.hpp"
  61 #include "oops/metadata.hpp"
  62 #include "oops/method.inline.hpp"
  63 #include "oops/oop.inline.hpp"
  64 #include "oops/recordComponent.hpp"
  65 #include "oops/symbol.hpp"
  66 #include "prims/jvmtiExport.hpp"
  67 #include "prims/jvmtiThreadState.hpp"
  68 #include "runtime/arguments.hpp"
  69 #include "runtime/fieldDescriptor.inline.hpp"
  70 #include "runtime/handles.inline.hpp"
  71 #include "runtime/javaCalls.hpp"
  72 #include "runtime/os.hpp"
  73 #include "runtime/perfData.hpp"
  74 #include "runtime/reflection.hpp"
  75 #include "runtime/safepointVerifiers.hpp"
  76 #include "runtime/signature.hpp"
  77 #include "runtime/timer.hpp"
  78 #include "services/classLoadingService.hpp"
  79 #include "services/threadService.hpp"
  80 #include "utilities/align.hpp"
  81 #include "utilities/bitMap.inline.hpp"
  82 #include "utilities/checkedCast.hpp"
  83 #include "utilities/copy.hpp"
  84 #include "utilities/formatBuffer.hpp"
  85 #include "utilities/exceptions.hpp"
  86 #include "utilities/globalDefinitions.hpp"
  87 #include "utilities/growableArray.hpp"
  88 #include "utilities/macros.hpp"
  89 #include "utilities/ostream.hpp"
  90 #include "utilities/resourceHash.hpp"
  91 #include "utilities/stringUtils.hpp"
  92 #include "utilities/utf8.hpp"
  93 #if INCLUDE_CDS
  94 #include "classfile/systemDictionaryShared.hpp"
  95 #endif
  96 #if INCLUDE_JFR
  97 #include "jfr/support/jfrTraceIdExtension.hpp"
  98 #endif
  99 
 100 // We generally try to create the oops directly when parsing, rather than
 101 // allocating temporary data structures and copying the bytes twice. A
 102 // temporary area is only needed when parsing utf8 entries in the constant
 103 // pool and when parsing line number tables.
 104 
 105 // We add assert in debug mode when class format is not checked.
 106 
 107 #define JAVA_CLASSFILE_MAGIC              0xCAFEBABE
 108 #define JAVA_MIN_SUPPORTED_VERSION        45
 109 #define JAVA_PREVIEW_MINOR_VERSION        65535
 110 
 111 // Used for two backward compatibility reasons:

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

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

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

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

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

 852       check_property(
 853         valid_klass_reference_at(interface_index),
 854         "Interface name has bad constant pool index %u in class file %s",
 855         interface_index, CHECK);
 856       _local_interface_indexes->at_put_grow(index, interface_index);































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

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

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

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


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

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

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

2300       runtime_invisible_type_annotations_length > 0) {
2301     a = assemble_annotations(runtime_visible_type_annotations,
2302                              runtime_visible_type_annotations_length,
2303                              runtime_invisible_type_annotations,
2304                              runtime_invisible_type_annotations_length,
2305                              CHECK);
2306     cm->set_type_annotations(a);
2307   }
2308 }
2309 
2310 
2311 // Note: the parse_method below is big and clunky because all parsing of the code and exceptions
2312 // attribute is inlined. This is cumbersome to avoid since we inline most of the parts in the
2313 // Method* to save footprint, so we only know the size of the resulting Method* when the
2314 // entire method attribute is parsed.
2315 //
2316 // The has_localvariable_table parameter is used to pass up the value to InstanceKlass.
2317 
2318 Method* ClassFileParser::parse_method(const ClassFileStream* const cfs,
2319                                       bool is_interface,
2320                                       bool is_value_class,
2321                                       bool is_abstract_class,
2322                                       const ConstantPool* cp,
2323                                       bool* const has_localvariable_table,
2324                                       TRAPS) {
2325   assert(cfs != nullptr, "invariant");
2326   assert(cp != nullptr, "invariant");
2327   assert(has_localvariable_table != nullptr, "invariant");
2328 
2329   ResourceMark rm(THREAD);
2330   // Parse fixed parts:
2331   // access_flags, name_index, descriptor_index, attributes_count
2332   cfs->guarantee_more(8, CHECK_NULL);
2333 
2334   int flags = cfs->get_u2_fast();
2335   const u2 name_index = cfs->get_u2_fast();
2336   const int cp_size = cp->length();
2337   check_property(
2338     valid_symbol_at(name_index),
2339     "Illegal constant pool index %u for method name in class file %s",
2340     name_index, CHECK_NULL);
2341   const Symbol* const name = cp->symbol_at(name_index);

2343 
2344   const u2 signature_index = cfs->get_u2_fast();
2345   guarantee_property(
2346     valid_symbol_at(signature_index),
2347     "Illegal constant pool index %u for method signature in class file %s",
2348     signature_index, CHECK_NULL);
2349   const Symbol* const signature = cp->symbol_at(signature_index);
2350 
2351   if (name == vmSymbols::class_initializer_name()) {
2352     // We ignore the other access flags for a valid class initializer.
2353     // (JVM Spec 2nd ed., chapter 4.6)
2354     if (_major_version < 51) { // backward compatibility
2355       flags = JVM_ACC_STATIC;
2356     } else if ((flags & JVM_ACC_STATIC) == JVM_ACC_STATIC) {
2357       flags &= JVM_ACC_STATIC | (_major_version <= JAVA_16_VERSION ? JVM_ACC_STRICT : 0);
2358     } else {
2359       classfile_parse_error("Method <clinit> is not static in class file %s", THREAD);
2360       return nullptr;
2361     }
2362   } else {
2363     verify_legal_method_modifiers(flags, access_flags() , name, CHECK_NULL);
2364   }
2365 
2366   if (name == vmSymbols::object_initializer_name() && is_interface) {
2367     classfile_parse_error("Interface cannot have a method named <init>, class file %s", THREAD);
2368     return nullptr;
2369   }
2370 
2371   if (EnableValhalla) {
2372     if (((flags & JVM_ACC_SYNCHRONIZED) == JVM_ACC_SYNCHRONIZED)
2373         && ((flags & JVM_ACC_STATIC) == 0 )
2374         && !_access_flags.is_identity_class()) {
2375       classfile_parse_error("Invalid synchronized method in non-identity class %s", THREAD);
2376         return nullptr;
2377     }
2378   }
2379 
2380   int args_size = -1;  // only used when _need_verify is true
2381   if (_need_verify) {
2382     verify_legal_name_with_signature(name, signature, CHECK_NULL);
2383     args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) +
2384                  verify_legal_method_signature(name, signature, CHECK_NULL);
2385     if (args_size > MAX_ARGS_SIZE) {
2386       classfile_parse_error("Too many arguments in method signature in class file %s", THREAD);
2387       return nullptr;
2388     }
2389   }
2390 
2391   AccessFlags access_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS);
2392 
2393   // Default values for code and exceptions attribute elements
2394   u2 max_stack = 0;
2395   u2 max_locals = 0;
2396   u4 code_length = 0;
2397   const u1* code_start = 0;
2398   u2 exception_table_length = 0;
2399   const unsafe_u2* exception_table_start = nullptr; // (potentially unaligned) pointer to array of u2 elements

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

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


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

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

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

3924               return;
3925             }
3926             parsed_record_attribute = true;
3927             record_attribute_start = cfs->current();
3928             record_attribute_length = attribute_length;
3929           } else if (_major_version >= JAVA_17_VERSION) {
3930             if (tag == vmSymbols::tag_permitted_subclasses()) {
3931               if (parsed_permitted_subclasses_attribute) {
3932                 classfile_parse_error("Multiple PermittedSubclasses attributes in class file %s", CHECK);
3933                 return;
3934               }
3935               // Classes marked ACC_FINAL cannot have a PermittedSubclasses attribute.
3936               if (_access_flags.is_final()) {
3937                 classfile_parse_error("PermittedSubclasses attribute in final class file %s", CHECK);
3938                 return;
3939               }
3940               parsed_permitted_subclasses_attribute = true;
3941               permitted_subclasses_attribute_start = cfs->current();
3942               permitted_subclasses_attribute_length = attribute_length;
3943             }
3944             if (EnableValhalla && tag == vmSymbols::tag_preload()) {
3945               if (parsed_preload_attribute) {
3946                 classfile_parse_error("Multiple Preload attributes in class file %s", CHECK);
3947                 return;
3948               }
3949               parsed_preload_attribute = true;
3950               preload_attribute_start = cfs->current();
3951               preload_attribute_length = attribute_length;
3952             }
3953           }
3954           // Skip attribute_length for any attribute where major_verson >= JAVA_17_VERSION
3955           cfs->skip_u1(attribute_length, CHECK);
3956         } else {
3957           // Unknown attribute
3958           cfs->skip_u1(attribute_length, CHECK);
3959         }
3960       } else {
3961         // Unknown attribute
3962         cfs->skip_u1(attribute_length, CHECK);
3963       }
3964     } else {
3965       // Unknown attribute
3966       cfs->skip_u1(attribute_length, CHECK);
3967     }
3968   }
3969   _class_annotations = assemble_annotations(runtime_visible_annotations,
3970                                             runtime_visible_annotations_length,
3971                                             runtime_invisible_annotations,
3972                                             runtime_invisible_annotations_length,

4013                             CHECK);
4014     if (_need_verify) {
4015       guarantee_property(record_attribute_length == calculated_attr_length,
4016                          "Record attribute has wrong length in class file %s",
4017                          CHECK);
4018     }
4019   }
4020 
4021   if (parsed_permitted_subclasses_attribute) {
4022     const u2 num_subclasses = parse_classfile_permitted_subclasses_attribute(
4023                             cfs,
4024                             permitted_subclasses_attribute_start,
4025                             CHECK);
4026     if (_need_verify) {
4027       guarantee_property(
4028         permitted_subclasses_attribute_length == sizeof(num_subclasses) + sizeof(u2) * num_subclasses,
4029         "Wrong PermittedSubclasses attribute length in class file %s", CHECK);
4030     }
4031   }
4032 
4033   if (parsed_preload_attribute) {
4034     const u2 num_classes = parse_classfile_preload_attribute(
4035                             cfs,
4036                             preload_attribute_start,
4037                             CHECK);
4038     if (_need_verify) {
4039       guarantee_property(
4040         preload_attribute_length == sizeof(num_classes) + sizeof(u2) * num_classes,
4041         "Wrong Preload attribute length in class file %s", CHECK);
4042     }
4043   }
4044 
4045   if (_max_bootstrap_specifier_index >= 0) {
4046     guarantee_property(parsed_bootstrap_methods_attribute,
4047                        "Missing BootstrapMethods attribute in class file %s", CHECK);
4048   }
4049 }
4050 
4051 void ClassFileParser::apply_parsed_class_attributes(InstanceKlass* k) {
4052   assert(k != nullptr, "invariant");
4053 
4054   if (_synthetic_flag)
4055     k->set_is_synthetic();
4056   if (_sourcefile_index != 0) {
4057     k->set_source_file_name_index(_sourcefile_index);
4058   }
4059   if (_generic_signature_index != 0) {
4060     k->set_generic_signature_index(_generic_signature_index);
4061   }
4062   if (_sde_buffer != nullptr) {
4063     k->set_source_debug_extension(_sde_buffer, _sde_length);
4064   }

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

4143     }
4144     if (runtime_invisible_annotations != nullptr) {
4145       for (int i = 0; i < runtime_invisible_annotations_length; i++) {
4146         int append = runtime_visible_annotations_length+i;
4147         annotations->at_put(append, runtime_invisible_annotations[i]);
4148       }
4149     }
4150   }
4151   return annotations;
4152 }
4153 
4154 const InstanceKlass* ClassFileParser::parse_super_class(ConstantPool* const cp,
4155                                                         const int super_class_index,
4156                                                         const bool need_verify,
4157                                                         TRAPS) {
4158   assert(cp != nullptr, "invariant");
4159   const InstanceKlass* super_klass = nullptr;
4160 
4161   if (super_class_index == 0) {
4162     check_property(_class_name == vmSymbols::java_lang_Object(),
4163                    "Invalid superclass index 0 in class file %s",

4164                    CHECK_NULL);
4165   } else {
4166     check_property(valid_klass_reference_at(super_class_index),
4167                    "Invalid superclass index %u in class file %s",
4168                    super_class_index,
4169                    CHECK_NULL);
4170     // The class name should be legal because it is checked when parsing constant pool.
4171     // However, make sure it is not an array type.

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




4174     }
4175     if (need_verify) {
4176       bool is_array = (cp->klass_name_at(super_class_index)->char_at(0) == JVM_SIGNATURE_ARRAY);
4177       guarantee_property(!is_array,
4178                         "Bad superclass name in class file %s", CHECK_NULL);
4179     }
4180   }
4181   return super_klass;
4182 }
4183 
4184 OopMapBlocksBuilder::OopMapBlocksBuilder(unsigned int max_blocks) {
4185   _max_nonstatic_oop_maps = max_blocks;
4186   _nonstatic_oop_map_count = 0;
4187   if (max_blocks == 0) {
4188     _nonstatic_oop_maps = nullptr;
4189   } else {
4190     _nonstatic_oop_maps =
4191         NEW_RESOURCE_ARRAY(OopMapBlock, _max_nonstatic_oop_maps);
4192     memset(_nonstatic_oop_maps, 0, sizeof(OopMapBlock) * max_blocks);
4193   }
4194 }
4195 
4196 OopMapBlock* OopMapBlocksBuilder::last_oop_map() const {

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

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

4675 
4676   for (int index = 0; index < num_methods; index++) {
4677     const Method* const m = methods->at(index);
4678     // if m is static and not the init method, throw a verify error
4679     if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) {
4680       ResourceMark rm(THREAD);
4681       Exceptions::fthrow(
4682         THREAD_AND_LOCATION,
4683         vmSymbols::java_lang_VerifyError(),
4684         "Illegal static method %s in interface %s",
4685         m->name()->as_C_string(),
4686         this_klass->external_name()
4687       );
4688       return;
4689     }
4690   }
4691 }
4692 
4693 // utility methods for format checking
4694 
4695 void ClassFileParser::verify_legal_class_modifiers(jint flags, const char* name, bool is_Object, TRAPS) const {
4696   const bool is_module = (flags & JVM_ACC_MODULE) != 0;
4697   const bool is_inner_class = name != nullptr;
4698   assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");
4699   if (is_module) {
4700     ResourceMark rm(THREAD);
4701     Exceptions::fthrow(
4702       THREAD_AND_LOCATION,
4703       vmSymbols::java_lang_NoClassDefFoundError(),
4704       "%s is not a class because access_flag ACC_MODULE is set",
4705       _class_name->as_C_string());
4706     return;
4707   }
4708 
4709   if (!_need_verify) { return; }
4710 
4711   const bool is_interface  = (flags & JVM_ACC_INTERFACE)  != 0;
4712   const bool is_abstract   = (flags & JVM_ACC_ABSTRACT)   != 0;
4713   const bool is_final      = (flags & JVM_ACC_FINAL)      != 0;
4714   const bool is_identity   = (flags & JVM_ACC_IDENTITY)   != 0;
4715   const bool is_enum       = (flags & JVM_ACC_ENUM)       != 0;
4716   const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4717   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4718 
4719   if ((is_abstract && is_final) ||
4720       (is_interface && !is_abstract) ||
4721       (is_interface && major_gte_1_5 && (is_identity || is_enum)) ||   //  ACC_SUPER (now ACC_IDENTITY) was illegal for interfaces
4722       (!is_interface && major_gte_1_5 && is_annotation)) {
4723     ResourceMark rm(THREAD);
4724     const char* class_note = "";
4725     if (!is_identity)  class_note = " (a value class)";
4726     if (name == nullptr) { // Not an inner class
4727       Exceptions::fthrow(
4728         THREAD_AND_LOCATION,
4729         vmSymbols::java_lang_ClassFormatError(),
4730         "Illegal class modifiers in class %s%s: 0x%X",
4731         _class_name->as_C_string(), class_note, flags
4732       );
4733       return;
4734     } else {
4735       Exceptions::fthrow(
4736         THREAD_AND_LOCATION,
4737         vmSymbols::java_lang_ClassFormatError(),
4738         "Illegal class modifiers in declaration of inner class %s%s of class %s: 0x%X",
4739         name, class_note, _class_name->as_C_string(), flags
4740       );
4741       return;
4742     }
4743   }
4744 }
4745 
4746 static bool has_illegal_visibility(jint flags) {
4747   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4748   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4749   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4750 
4751   return ((is_public && is_protected) ||
4752           (is_public && is_private) ||
4753           (is_protected && is_private));
4754 }
4755 
4756 // A legal major_version.minor_version must be one of the following:
4757 //
4758 //  Major_version >= 45 and major_version < 56, any minor_version.
4759 //  Major_version >= 56 and major_version <= JVM_CLASSFILE_MAJOR_VERSION and minor_version = 0.
4760 //  Major_version = JVM_CLASSFILE_MAJOR_VERSION and minor_version = 65535 and --enable-preview is present.
4761 //
4762 void ClassFileParser::verify_class_version(u2 major, u2 minor, Symbol* class_name, TRAPS){

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

5008         if (type == ClassFileParser::LegalClass) {
5009           if (p == name || p+1 >= name+length ||
5010               *(p+1) == JVM_SIGNATURE_SLASH) {
5011             return false;
5012           }
5013         } else {
5014           return false;   // do not permit '/' unless it's class name
5015         }
5016         break;
5017       case JVM_SIGNATURE_SPECIAL:
5018       case JVM_SIGNATURE_ENDSPECIAL:
5019         // do not permit '<' or '>' in method names
5020         if (type == ClassFileParser::LegalMethod) {
5021           return false;
5022         }
5023     }
5024   }
5025   return true;
5026 }
5027 
5028 bool ClassFileParser::is_class_in_preload_attribute(Symbol *klass) {
5029   if (_preload_classes == nullptr) return false;
5030   for (int i = 0; i < _preload_classes->length(); i++) {
5031         Symbol* class_name = _cp->klass_at_noresolve(_preload_classes->at(i));
5032         if (class_name == klass) return true;
5033   }
5034   return false;
5035 }
5036 
5037 // Take pointer to a UTF8 byte string (not NUL-terminated).
5038 // Skip over the longest part of the string that could
5039 // be taken as a fieldname. Allow non-trailing '/'s if slash_ok is true.
5040 // Return a pointer to just past the fieldname.
5041 // Return null if no fieldname at all was found, or in the case of slash_ok
5042 // being true, we saw consecutive slashes (meaning we were looking for a
5043 // qualified path but found something that was badly-formed).
5044 static const char* skip_over_field_name(const char* const name,
5045                                         bool slash_ok,
5046                                         unsigned int length) {
5047   const char* p;
5048   jboolean last_is_slash = false;
5049   jboolean not_first_ch = false;
5050 
5051   for (p = name; p != name + length; not_first_ch = true) {
5052     const char* old_p = p;
5053     jchar ch = *p;
5054     if (ch < 128) {
5055       p++;
5056       // quick check for ascii

5118 // be taken as a field signature. Allow "void" if void_ok.
5119 // Return a pointer to just past the signature.
5120 // Return null if no legal signature is found.
5121 const char* ClassFileParser::skip_over_field_signature(const char* signature,
5122                                                        bool void_ok,
5123                                                        unsigned int length,
5124                                                        TRAPS) const {
5125   unsigned int array_dim = 0;
5126   while (length > 0) {
5127     switch (signature[0]) {
5128     case JVM_SIGNATURE_VOID: if (!void_ok) { return nullptr; }
5129     case JVM_SIGNATURE_BOOLEAN:
5130     case JVM_SIGNATURE_BYTE:
5131     case JVM_SIGNATURE_CHAR:
5132     case JVM_SIGNATURE_SHORT:
5133     case JVM_SIGNATURE_INT:
5134     case JVM_SIGNATURE_FLOAT:
5135     case JVM_SIGNATURE_LONG:
5136     case JVM_SIGNATURE_DOUBLE:
5137       return signature + 1;
5138     case JVM_SIGNATURE_CLASS:
5139     {
5140       if (_major_version < JAVA_1_5_VERSION) {
5141         // Skip over the class name if one is there
5142         const char* const p = skip_over_field_name(signature + 1, true, --length);
5143 
5144         // The next character better be a semicolon
5145         if (p && (p - signature) > 1 && p[0] == JVM_SIGNATURE_ENDCLASS) {
5146           return p + 1;
5147         }
5148       }
5149       else {
5150         // Skip leading 'L' or 'Q' and ignore first appearance of ';'
5151         signature++;
5152         const char* c = (const char*) memchr(signature, JVM_SIGNATURE_ENDCLASS, length - 1);
5153         // Format check signature
5154         if (c != nullptr) {
5155           int newlen = pointer_delta_as_int(c, (char*) signature);
5156           bool legal = verify_unqualified_name(signature, newlen, LegalClass);
5157           if (!legal) {
5158             classfile_parse_error("Class name is empty or contains illegal character "
5159                                   "in descriptor in class file %s",
5160                                   THREAD);
5161             return nullptr;
5162           }
5163           return signature + newlen + 1;
5164         }
5165       }
5166       return nullptr;
5167     }
5168     case JVM_SIGNATURE_ARRAY:
5169       array_dim++;
5170       if (array_dim > 255) {

5186 
5187 // Checks if name is a legal class name.
5188 void ClassFileParser::verify_legal_class_name(const Symbol* name, TRAPS) const {
5189   if (!_need_verify || _relax_verify) { return; }
5190 
5191   assert(name->refcount() > 0, "symbol must be kept alive");
5192   char* bytes = (char*)name->bytes();
5193   unsigned int length = name->utf8_length();
5194   bool legal = false;
5195 
5196   if (length > 0) {
5197     const char* p;
5198     if (bytes[0] == JVM_SIGNATURE_ARRAY) {
5199       p = skip_over_field_signature(bytes, false, length, CHECK);
5200       legal = (p != nullptr) && ((p - bytes) == (int)length);
5201     } else if (_major_version < JAVA_1_5_VERSION) {
5202       if (bytes[0] != JVM_SIGNATURE_SPECIAL) {
5203         p = skip_over_field_name(bytes, true, length);
5204         legal = (p != nullptr) && ((p - bytes) == (int)length);
5205       }
5206     } else if ((_major_version >= CONSTANT_CLASS_DESCRIPTORS || _class_name->starts_with("jdk/internal/reflect/"))
5207                    && bytes[length - 1] == ';' ) {
5208       // Support for L...; and Q...; descriptors
5209       legal = verify_unqualified_name(bytes + 1, length - 2, LegalClass);
5210     } else {
5211       // 4900761: relax the constraints based on JSR202 spec
5212       // Class names may be drawn from the entire Unicode character set.
5213       // Identifiers between '/' must be unqualified names.
5214       // The utf8 string has been verified when parsing cpool entries.
5215       legal = verify_unqualified_name(bytes, length, LegalClass);
5216     }
5217   }
5218   if (!legal) {
5219     ResourceMark rm(THREAD);
5220     assert(_class_name != nullptr, "invariant");
5221     Exceptions::fthrow(
5222       THREAD_AND_LOCATION,
5223       vmSymbols::java_lang_ClassFormatError(),
5224       "Illegal class name \"%.*s\" in class file %s", length, bytes,
5225       _class_name->as_C_string()
5226     );
5227     return;
5228   }
5229 }

5255       THREAD_AND_LOCATION,
5256       vmSymbols::java_lang_ClassFormatError(),
5257       "Illegal field name \"%.*s\" in class %s", length, bytes,
5258       _class_name->as_C_string()
5259     );
5260     return;
5261   }
5262 }
5263 
5264 // Checks if name is a legal method name.
5265 void ClassFileParser::verify_legal_method_name(const Symbol* name, TRAPS) const {
5266   if (!_need_verify || _relax_verify) { return; }
5267 
5268   assert(name != nullptr, "method name is null");
5269   char* bytes = (char*)name->bytes();
5270   unsigned int length = name->utf8_length();
5271   bool legal = false;
5272 
5273   if (length > 0) {
5274     if (bytes[0] == JVM_SIGNATURE_SPECIAL) {
5275       if (name == vmSymbols::object_initializer_name() ||
5276           name == vmSymbols::class_initializer_name()) {
5277         legal = true;
5278       }
5279     } else if (_major_version < JAVA_1_5_VERSION) {
5280       const char* p;
5281       p = skip_over_field_name(bytes, false, length);
5282       legal = (p != nullptr) && ((p - bytes) == (int)length);
5283     } else {
5284       // 4881221: relax the constraints based on JSR202 spec
5285       legal = verify_unqualified_name(bytes, length, LegalMethod);
5286     }
5287   }
5288 
5289   if (!legal) {
5290     ResourceMark rm(THREAD);
5291     assert(_class_name != nullptr, "invariant");
5292     Exceptions::fthrow(
5293       THREAD_AND_LOCATION,
5294       vmSymbols::java_lang_ClassFormatError(),
5295       "Illegal method name \"%.*s\" in class %s", length, bytes,
5296       _class_name->as_C_string()

5317 
5318 // Check that the signature is compatible with the method name.  For example,
5319 // check that <init> has a void signature.
5320 void ClassFileParser::verify_legal_name_with_signature(const Symbol* name,
5321                                                        const Symbol* signature,
5322                                                        TRAPS) const {
5323   if (!_need_verify) {
5324     return;
5325   }
5326 
5327   // Class initializers cannot have args for class format version >= 51.
5328   if (name == vmSymbols::class_initializer_name() &&
5329       signature != vmSymbols::void_method_signature() &&
5330       _major_version >= JAVA_7_VERSION) {
5331     throwIllegalSignature("Method", name, signature, THREAD);
5332     return;
5333   }
5334 
5335   int sig_length = signature->utf8_length();
5336   if (name->utf8_length() > 0 &&
5337     name->char_at(0) == JVM_SIGNATURE_SPECIAL &&
5338     sig_length > 0 &&
5339     signature->char_at(sig_length - 1) != JVM_SIGNATURE_VOID) {
5340     throwIllegalSignature("Method", name, signature, THREAD);
5341   }
5342 }
5343 
5344 // Checks if signature is a legal method signature.
5345 // Returns number of parameters
5346 int ClassFileParser::verify_legal_method_signature(const Symbol* name,
5347                                                    const Symbol* signature,
5348                                                    TRAPS) const {
5349   if (!_need_verify) {
5350     // make sure caller's args_size will be less than 0 even for non-static
5351     // method so it will be recomputed in compute_size_of_parameters().
5352     return -2;
5353   }
5354 
5355   unsigned int args_size = 0;
5356   const char* p = (const char*)signature->bytes();
5357   unsigned int length = signature->utf8_length();
5358   const char* nextp;
5359 

5496   }
5497 }
5498 
5499 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook,
5500                                                       const ClassInstanceInfo& cl_inst_info,
5501                                                       TRAPS) {
5502   if (_klass != nullptr) {
5503     return _klass;
5504   }
5505 
5506   InstanceKlass* const ik =
5507     InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
5508 
5509   if (is_hidden()) {
5510     mangle_hidden_class_name(ik);
5511   }
5512 
5513   fill_instance_klass(ik, changed_by_loadhook, cl_inst_info, CHECK_NULL);
5514 
5515   assert(_klass == ik, "invariant");

5516   return ik;
5517 }
5518 
5519 void ClassFileParser::fill_instance_klass(InstanceKlass* ik,
5520                                           bool changed_by_loadhook,
5521                                           const ClassInstanceInfo& cl_inst_info,
5522                                           TRAPS) {
5523   assert(ik != nullptr, "invariant");
5524 
5525   // Set name and CLD before adding to CLD
5526   ik->set_class_loader_data(_loader_data);
5527   ik->set_name(_class_name);
5528 
5529   // Add all classes to our internal class loader list here,
5530   // including classes in the bootstrap (null) class loader.
5531   const bool publicize = !is_internal();
5532 
5533   _loader_data->add_class(ik, publicize);
5534 
5535   set_klass_to_deallocate(ik);
5536 
5537   assert(_field_info != nullptr, "invariant");
5538   assert(ik->static_field_size() == _field_info->_static_field_size, "sanity");
5539   assert(ik->nonstatic_oop_map_count() == _field_info->oop_map_blocks->_nonstatic_oop_map_count,
5540          "sanity");
5541 
5542   assert(ik->is_instance_klass(), "sanity");
5543   assert(ik->size_helper() == _field_info->_instance_size, "sanity");
5544 
5545   // Fill in information already parsed
5546   ik->set_should_verify_class(_need_verify);
5547 
5548   // Not yet: supers are done below to support the new subtype-checking fields
5549   ik->set_nonstatic_field_size(_field_info->_nonstatic_field_size);
5550   ik->set_has_nonstatic_fields(_field_info->_has_nonstatic_fields);
5551   if (_field_info->_is_naturally_atomic && ik->is_inline_klass()) {
5552     ik->set_is_naturally_atomic();
5553   }
5554 
5555   assert(_fac != nullptr, "invariant");
5556   ik->set_static_oop_field_count(_fac->count[STATIC_OOP] + _fac->count[STATIC_INLINE]);
5557 
5558   // this transfers ownership of a lot of arrays from
5559   // the parser onto the InstanceKlass*
5560   apply_parsed_class_metadata(ik, _java_fields_count);
5561   if (ik->is_inline_klass()) {
5562     InlineKlass::cast(ik)->init_fixed_block();
5563   }
5564 
5565   // can only set dynamic nest-host after static nest information is set
5566   if (cl_inst_info.dynamic_nest_host() != nullptr) {
5567     ik->set_nest_host(cl_inst_info.dynamic_nest_host());
5568   }
5569 
5570   // note that is not safe to use the fields in the parser from this point on
5571   assert(nullptr == _cp, "invariant");
5572   assert(nullptr == _fieldinfo_stream, "invariant");
5573   assert(nullptr == _fields_status, "invariant");
5574   assert(nullptr == _methods, "invariant");
5575   assert(nullptr == _inner_classes, "invariant");
5576   assert(nullptr == _nest_members, "invariant");
5577   assert(nullptr == _preload_classes, "invariant");
5578   assert(nullptr == _combined_annotations, "invariant");
5579   assert(nullptr == _record_components, "invariant");
5580   assert(nullptr == _permitted_subclasses, "invariant");
5581   assert(nullptr == _inline_type_field_klasses, "invariant");
5582 
5583   if (_has_localvariable_table) {
5584     ik->set_has_localvariable_table(true);
5585   }
5586 
5587   if (_has_final_method) {
5588     ik->set_has_final_method();
5589   }
5590 
5591   ik->copy_method_ordering(_method_ordering, CHECK);
5592   // The InstanceKlass::_methods_jmethod_ids cache
5593   // is managed on the assumption that the initial cache
5594   // size is equal to the number of methods in the class. If
5595   // that changes, then InstanceKlass::idnum_can_increment()
5596   // has to be changed accordingly.
5597   ik->set_initial_method_idnum(checked_cast<u2>(ik->methods()->length()));
5598 
5599   ik->set_this_class_index(_this_class_index);
5600 
5601   if (_is_hidden) {
5602     // _this_class_index is a CONSTANT_Class entry that refers to this
5603     // hidden class itself. If this class needs to refer to its own methods
5604     // or fields, it would use a CONSTANT_MethodRef, etc, which would reference
5605     // _this_class_index. However, because this class is hidden (it's
5606     // not stored in SystemDictionary), _this_class_index cannot be resolved
5607     // with ConstantPool::klass_at_impl, which does a SystemDictionary lookup.
5608     // Therefore, we must eagerly resolve _this_class_index now.
5609     ik->constants()->klass_at_put(_this_class_index, ik);
5610   }
5611 
5612   ik->set_minor_version(_minor_version);
5613   ik->set_major_version(_major_version);
5614   ik->set_has_nonstatic_concrete_methods(_has_nonstatic_concrete_methods);
5615   ik->set_declares_nonstatic_concrete_methods(_declares_nonstatic_concrete_methods);
5616 
5617   if (_must_be_atomic) {
5618     ik->set_must_be_atomic();
5619   }
5620   if (_is_implicitly_constructible) {
5621     ik->set_is_implicitly_constructible();
5622   }
5623   if (_is_hidden) {
5624     ik->set_is_hidden();
5625   }
5626 
5627   // Set PackageEntry for this_klass
5628   oop cl = ik->class_loader();
5629   Handle clh = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(cl));
5630   ClassLoaderData* cld = ClassLoaderData::class_loader_data_or_null(clh());
5631   ik->set_package(cld, nullptr, CHECK);
5632 
5633   const Array<Method*>* const methods = ik->methods();
5634   assert(methods != nullptr, "invariant");
5635   const int methods_len = methods->length();
5636 
5637   check_methods_for_intrinsics(ik, methods);
5638 
5639   // Fill in field values obtained by parse_classfile_attributes
5640   if (_parsed_annotations->has_any_annotations()) {
5641     _parsed_annotations->apply_to(ik);
5642   }

5709 
5710   assert(_all_mirandas != nullptr, "invariant");
5711 
5712   // Generate any default methods - default methods are public interface methods
5713   // that have a default implementation.  This is new with Java 8.
5714   if (_has_nonstatic_concrete_methods) {
5715     DefaultMethods::generate_default_methods(ik,
5716                                              _all_mirandas,
5717                                              CHECK);
5718   }
5719 
5720   // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5721   if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5722       !module_entry->has_default_read_edges()) {
5723     if (!module_entry->set_has_default_read_edges()) {
5724       // We won a potential race
5725       JvmtiExport::add_default_read_edges(module_handle, THREAD);
5726     }
5727   }
5728 
5729   bool all_fields_empty = true;
5730   for (AllFieldStream fs(ik); !fs.done(); fs.next()) {
5731     if (!fs.access_flags().is_static()) {
5732       if (fs.field_descriptor().is_null_free_inline_type()) {
5733         Klass* k = ik->inline_type_field_klasses_array()->at(fs.index());
5734         assert(k->is_inline_klass(), "must be");
5735         if (!InlineKlass::cast(k)->is_empty_inline_type()) { all_fields_empty = false; }
5736       } else {
5737         all_fields_empty = false;
5738       }
5739     } else if (is_inline_type() && (fs.name() == vmSymbols::default_value_name())) {
5740       InlineKlass::cast(ik)->set_default_value_offset(ik->field_offset(fs.index()));
5741     }
5742   }
5743 
5744   if (_is_empty_inline_type || (is_inline_type() && all_fields_empty)) {
5745     ik->set_is_empty_inline_type();
5746   }
5747 
5748   if (is_inline_type()) {
5749     InlineKlass* vk = InlineKlass::cast(ik);
5750     vk->set_alignment(_alignment);
5751     vk->set_first_field_offset(_first_field_offset);
5752     vk->set_exact_size_in_bytes(_exact_size_in_bytes);
5753     InlineKlass::cast(ik)->initialize_calling_convention(CHECK);
5754   }
5755 
5756   ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5757 
5758   if (!is_internal()) {
5759     ik->print_class_load_logging(_loader_data, module_entry, _stream);
5760 
5761     if (ik->minor_version() == JAVA_PREVIEW_MINOR_VERSION &&
5762         ik->major_version() == JVM_CLASSFILE_MAJOR_VERSION &&
5763         log_is_enabled(Info, class, preview)) {
5764       ResourceMark rm;
5765       log_info(class, preview)("Loading class %s that depends on preview features (class file version %d.65535)",
5766                                ik->external_name(), JVM_CLASSFILE_MAJOR_VERSION);
5767     }
5768 
5769     if (log_is_enabled(Debug, class, resolve))  {
5770       ResourceMark rm;
5771       // print out the superclass.
5772       const char * from = ik->external_name();
5773       if (ik->java_super() != nullptr) {
5774         log_debug(class, resolve)("%s %s (super)",
5775                    from,

5827                                  Symbol* name,
5828                                  ClassLoaderData* loader_data,
5829                                  const ClassLoadInfo* cl_info,
5830                                  Publicity pub_level,
5831                                  TRAPS) :
5832   _stream(stream),
5833   _class_name(nullptr),
5834   _loader_data(loader_data),
5835   _is_hidden(cl_info->is_hidden()),
5836   _can_access_vm_annotations(cl_info->can_access_vm_annotations()),
5837   _orig_cp_size(0),
5838   _super_klass(),
5839   _cp(nullptr),
5840   _fieldinfo_stream(nullptr),
5841   _fields_status(nullptr),
5842   _methods(nullptr),
5843   _inner_classes(nullptr),
5844   _nest_members(nullptr),
5845   _nest_host(0),
5846   _permitted_subclasses(nullptr),
5847   _preload_classes(nullptr),
5848   _record_components(nullptr),
5849   _local_interfaces(nullptr),
5850   _local_interface_indexes(nullptr),
5851   _transitive_interfaces(nullptr),
5852   _combined_annotations(nullptr),
5853   _class_annotations(nullptr),
5854   _class_type_annotations(nullptr),
5855   _fields_annotations(nullptr),
5856   _fields_type_annotations(nullptr),
5857   _klass(nullptr),
5858   _klass_to_deallocate(nullptr),
5859   _parsed_annotations(nullptr),
5860   _fac(nullptr),
5861   _field_info(nullptr),
5862   _inline_type_field_klasses(nullptr),
5863   _temp_field_info(nullptr),
5864   _method_ordering(nullptr),
5865   _all_mirandas(nullptr),
5866   _vtable_size(0),
5867   _itable_size(0),
5868   _num_miranda_methods(0),
5869   _protection_domain(cl_info->protection_domain()),
5870   _access_flags(),
5871   _pub_level(pub_level),
5872   _bad_constant_seen(0),
5873   _synthetic_flag(false),
5874   _sde_length(false),
5875   _sde_buffer(nullptr),
5876   _sourcefile_index(0),
5877   _generic_signature_index(0),
5878   _major_version(0),
5879   _minor_version(0),
5880   _this_class_index(0),
5881   _super_class_index(0),
5882   _itfs_len(0),
5883   _java_fields_count(0),
5884   _need_verify(false),
5885   _relax_verify(false),
5886   _has_nonstatic_concrete_methods(false),
5887   _declares_nonstatic_concrete_methods(false),
5888   _has_localvariable_table(false),
5889   _has_final_method(false),
5890   _has_contended_fields(false),
5891   _has_inline_type_fields(false),
5892   _has_nonstatic_fields(false),
5893   _is_empty_inline_type(false),
5894   _is_naturally_atomic(false),
5895   _must_be_atomic(true),
5896   _is_implicitly_constructible(false),
5897   _has_loosely_consistent_annotation(false),
5898   _has_implicitly_constructible_annotation(false),
5899   _has_finalizer(false),
5900   _has_empty_finalizer(false),
5901   _has_vanilla_constructor(false),
5902   _max_bootstrap_specifier_index(-1) {
5903 
5904   _class_name = name != nullptr ? name : vmSymbols::unknown_class_name();
5905   _class_name->increment_refcount();
5906 
5907   assert(_loader_data != nullptr, "invariant");
5908   assert(stream != nullptr, "invariant");
5909   assert(_stream != nullptr, "invariant");
5910   assert(_stream->buffer() == _stream->current(), "invariant");
5911   assert(_class_name != nullptr, "invariant");
5912   assert(0 == _access_flags.as_int(), "invariant");
5913 
5914   // Figure out whether we can skip format checking (matching classic VM behavior)
5915   if (CDSConfig::is_dumping_static_archive()) {
5916     // verify == true means it's a 'remote' class (i.e., non-boot class)
5917     // Verification decision is based on BytecodeVerificationRemote flag
5918     // for those classes.

5929 
5930   // Check if verification needs to be relaxed for this class file
5931   // Do not restrict it to jdk1.0 or jdk1.1 to maintain backward compatibility (4982376)
5932   _relax_verify = relax_format_check_for(_loader_data);
5933 
5934   parse_stream(stream, CHECK);
5935 
5936   post_process_parsed_stream(stream, _cp, CHECK);
5937 }
5938 
5939 void ClassFileParser::clear_class_metadata() {
5940   // metadata created before the instance klass is created.  Must be
5941   // deallocated if classfile parsing returns an error.
5942   _cp = nullptr;
5943   _fieldinfo_stream = nullptr;
5944   _fields_status = nullptr;
5945   _methods = nullptr;
5946   _inner_classes = nullptr;
5947   _nest_members = nullptr;
5948   _permitted_subclasses = nullptr;
5949   _preload_classes = nullptr;
5950   _combined_annotations = nullptr;
5951   _class_annotations = _class_type_annotations = nullptr;
5952   _fields_annotations = _fields_type_annotations = nullptr;
5953   _record_components = nullptr;
5954   _inline_type_field_klasses = nullptr;
5955 }
5956 
5957 // Destructor to clean up
5958 ClassFileParser::~ClassFileParser() {
5959   _class_name->decrement_refcount();
5960 
5961   if (_cp != nullptr) {
5962     MetadataFactory::free_metadata(_loader_data, _cp);
5963   }
5964 
5965   if (_fieldinfo_stream != nullptr) {
5966     MetadataFactory::free_array<u1>(_loader_data, _fieldinfo_stream);
5967   }
5968 
5969   if (_fields_status != nullptr) {
5970     MetadataFactory::free_array<FieldStatus>(_loader_data, _fields_status);
5971   }
5972 
5973   if (_inline_type_field_klasses != nullptr) {
5974      MetadataFactory::free_array<InlineKlass*>(_loader_data, _inline_type_field_klasses);
5975   }
5976 
5977   if (_methods != nullptr) {
5978     // Free methods
5979     InstanceKlass::deallocate_methods(_loader_data, _methods);
5980   }
5981 
5982   // beware of the Universe::empty_blah_array!!
5983   if (_inner_classes != nullptr && _inner_classes != Universe::the_empty_short_array()) {
5984     MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
5985   }
5986 
5987   if (_nest_members != nullptr && _nest_members != Universe::the_empty_short_array()) {
5988     MetadataFactory::free_array<u2>(_loader_data, _nest_members);
5989   }
5990 
5991   if (_record_components != nullptr) {
5992     InstanceKlass::deallocate_record_components(_loader_data, _record_components);
5993   }
5994 
5995   if (_permitted_subclasses != nullptr && _permitted_subclasses != Universe::the_empty_short_array()) {
5996     MetadataFactory::free_array<u2>(_loader_data, _permitted_subclasses);
5997   }
5998 
5999   if (_preload_classes != nullptr && _preload_classes != Universe::the_empty_short_array()) {
6000     MetadataFactory::free_array<u2>(_loader_data, _preload_classes);
6001   }
6002 
6003   // Free interfaces
6004   InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
6005                                        _local_interfaces, _transitive_interfaces);
6006 
6007   if (_combined_annotations != nullptr) {
6008     // After all annotations arrays have been created, they are installed into the
6009     // Annotations object that will be assigned to the InstanceKlass being created.
6010 
6011     // Deallocate the Annotations object and the installed annotations arrays.
6012     _combined_annotations->deallocate_contents(_loader_data);
6013 
6014     // If the _combined_annotations pointer is non-null,
6015     // then the other annotations fields should have been cleared.
6016     assert(_class_annotations       == nullptr, "Should have been cleared");
6017     assert(_class_type_annotations  == nullptr, "Should have been cleared");
6018     assert(_fields_annotations      == nullptr, "Should have been cleared");
6019     assert(_fields_type_annotations == nullptr, "Should have been cleared");
6020   } else {
6021     // If the annotations arrays were not installed into the Annotations object,
6022     // then they have to be deallocated explicitly.

6067     cp_size, CHECK);
6068 
6069   _orig_cp_size = cp_size;
6070   if (is_hidden()) { // Add a slot for hidden class name.
6071     cp_size++;
6072   }
6073 
6074   _cp = ConstantPool::allocate(_loader_data,
6075                                cp_size,
6076                                CHECK);
6077 
6078   ConstantPool* const cp = _cp;
6079 
6080   parse_constant_pool(stream, cp, _orig_cp_size, CHECK);
6081 
6082   assert(cp_size == (u2)cp->length(), "invariant");
6083 
6084   // ACCESS FLAGS
6085   stream->guarantee_more(8, CHECK);  // flags, this_class, super_class, infs_len
6086 
6087   jint recognized_modifiers = JVM_RECOGNIZED_CLASS_MODIFIERS;

6088   // JVM_ACC_MODULE is defined in JDK-9 and later.
6089   if (_major_version >= JAVA_9_VERSION) {
6090     recognized_modifiers |= JVM_ACC_MODULE;


6091   }
6092 
6093   // Access flags
6094   jint flags = stream->get_u2_fast() & recognized_modifiers;
6095 
6096   if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
6097     // Set abstract bit for old class files for backward compatibility
6098     flags |= JVM_ACC_ABSTRACT;
6099   }
6100 
6101   // Fixing ACC_SUPER/ACC_IDENTITY for old class files
6102   if (!supports_inline_types()) {
6103     const bool is_module = (flags & JVM_ACC_MODULE) != 0;
6104     const bool is_interface = (flags & JVM_ACC_INTERFACE) != 0;
6105     if (!is_module && !is_interface) {
6106       flags |= JVM_ACC_IDENTITY;
6107     }

6108   }
6109 

6110 
6111   // This class and superclass
6112   _this_class_index = stream->get_u2_fast();
6113   check_property(
6114     valid_cp_range(_this_class_index, cp_size) &&
6115       cp->tag_at(_this_class_index).is_unresolved_klass(),
6116     "Invalid this class index %u in constant pool in class file %s",
6117     _this_class_index, CHECK);
6118 
6119   Symbol* const class_name_in_cp = cp->klass_name_at(_this_class_index);
6120   assert(class_name_in_cp != nullptr, "class_name can't be null");
6121 
6122   bool is_java_lang_Object = class_name_in_cp == vmSymbols::java_lang_Object();
6123 
6124   verify_legal_class_modifiers(flags, nullptr, is_java_lang_Object, CHECK);
6125 
6126   _access_flags.set_flags(flags);
6127 
6128   short bad_constant = class_bad_constant_seen();
6129   if (bad_constant != 0) {
6130     // Do not throw CFE until after the access_flags are checked because if
6131     // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
6132     classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, THREAD);
6133     return;
6134   }
6135 
6136   // Don't need to check whether this class name is legal or not.
6137   // It has been checked when constant pool is parsed.
6138   // However, make sure it is not an array type.
6139   if (_need_verify) {
6140     guarantee_property(class_name_in_cp->char_at(0) != JVM_SIGNATURE_ARRAY,
6141                        "Bad class name in class file %s",
6142                        CHECK);
6143   }
6144 
6145 #ifdef ASSERT
6146   // Basic sanity checks
6147   if (_is_hidden) {
6148     assert(_class_name != vmSymbols::unknown_class_name(), "hidden classes should have a special name");
6149   }
6150 #endif
6151 
6152   // Update the _class_name as needed depending on whether this is a named, un-named, or hidden class.
6153 
6154   if (_is_hidden) {
6155     assert(_class_name != nullptr, "Unexpected null _class_name");

6195       }
6196       ls.cr();
6197     }
6198   }
6199 
6200   // SUPERKLASS
6201   _super_class_index = stream->get_u2_fast();
6202   _super_klass = parse_super_class(cp,
6203                                    _super_class_index,
6204                                    _need_verify,
6205                                    CHECK);
6206 
6207   // Interfaces
6208   _itfs_len = stream->get_u2_fast();
6209   parse_interfaces(stream,
6210                    _itfs_len,
6211                    cp,
6212                    &_has_nonstatic_concrete_methods,
6213                    CHECK);
6214 


6215   // Fields (offsets are filled in later)
6216   _fac = new FieldAllocationCount();
6217   parse_fields(stream,
6218                _access_flags,
6219                _fac,
6220                cp,
6221                cp_size,
6222                &_java_fields_count,
6223                CHECK);
6224 
6225   assert(_temp_field_info != nullptr, "invariant");
6226 
6227   // Methods
6228   parse_methods(stream,
6229                 is_interface(),
6230                 !is_identity_class(),
6231                 is_abstract_class(),
6232                 &_has_localvariable_table,
6233                 &_has_final_method,
6234                 &_declares_nonstatic_concrete_methods,
6235                 CHECK);
6236 
6237   assert(_methods != nullptr, "invariant");
6238 
6239   if (_declares_nonstatic_concrete_methods) {
6240     _has_nonstatic_concrete_methods = true;
6241   }
6242 
6243   // Additional attributes/annotations
6244   _parsed_annotations = new ClassAnnotationCollector();
6245   parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK);
6246 
6247   assert(_inner_classes != nullptr, "invariant");
6248 
6249   // Finalize the Annotations metadata object,
6250   // now that all annotation arrays have been created.
6251   create_combined_annotations(CHECK);

6291   // Update this_class_index's slot in the constant pool with the new Utf8 entry.
6292   // We have to update the resolved_klass_index and the name_index together
6293   // so extract the existing resolved_klass_index first.
6294   CPKlassSlot cp_klass_slot = _cp->klass_slot_at(_this_class_index);
6295   int resolved_klass_index = cp_klass_slot.resolved_klass_index();
6296   _cp->unresolved_klass_at_put(_this_class_index, hidden_index, resolved_klass_index);
6297   assert(_cp->klass_slot_at(_this_class_index).name_index() == _orig_cp_size,
6298          "Bad name_index");
6299 }
6300 
6301 void ClassFileParser::post_process_parsed_stream(const ClassFileStream* const stream,
6302                                                  ConstantPool* cp,
6303                                                  TRAPS) {
6304   assert(stream != nullptr, "invariant");
6305   assert(stream->at_eos(), "invariant");
6306   assert(cp != nullptr, "invariant");
6307   assert(_loader_data != nullptr, "invariant");
6308 
6309   if (_class_name == vmSymbols::java_lang_Object()) {
6310     check_property(_local_interfaces == Universe::the_empty_instance_klass_array(),
6311         "java.lang.Object cannot implement an interface in class file %s",
6312         CHECK);
6313   }
6314   // We check super class after class file is parsed and format is checked
6315   if (_super_class_index > 0 && nullptr == _super_klass) {
6316     Symbol* const super_class_name = cp->klass_name_at(_super_class_index);
6317     if (is_interface()) {
6318       // Before attempting to resolve the superclass, check for class format
6319       // errors not checked yet.
6320       guarantee_property(super_class_name == vmSymbols::java_lang_Object(),
6321         "Interfaces must have java.lang.Object as superclass in class file %s",
6322         CHECK);
6323     }
6324     Handle loader(THREAD, _loader_data->class_loader());
6325     if (loader.is_null() && super_class_name == vmSymbols::java_lang_Object()) {
6326       _super_klass = vmClasses::Object_klass();
6327     } else {
6328       _super_klass = (const InstanceKlass*)
6329                        SystemDictionary::resolve_with_circularity_detection_or_fail(_class_name,
6330                                                                super_class_name,
6331                                                                loader,
6332                                                                _protection_domain,
6333                                                                true,
6334                                                                CHECK);
6335     }
6336   }
6337 
6338   if (_super_klass != nullptr) {
6339     if (_super_klass->is_interface()) {
6340       classfile_icce_error("class %s has interface %s as super class", _super_klass, THREAD);
6341       return;
6342     }
6343 
6344     if (EnableValhalla) {
6345       check_identity_and_value_modifiers(this, _super_klass, CHECK);
6346     }
6347 
6348     if (_super_klass->has_nonstatic_concrete_methods()) {
6349       _has_nonstatic_concrete_methods = true;
6350     }
6351 
6352     if (EnableValhalla && !_access_flags.is_identity_class()) {
6353       const InstanceKlass* k = _super_klass;
6354       int inherited_instance_fields = 0;
6355       while (k != nullptr) {
6356         for (AllFieldStream fs(k); !fs.done(); fs.next()) {
6357           if (!fs.access_flags().is_static()) inherited_instance_fields++;
6358         }
6359         k = k->super() == nullptr ? nullptr :  InstanceKlass::cast(k->super());
6360       }
6361       if (inherited_instance_fields > 0) {
6362         THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(), "Value classes don't support inherited non-static fields yet");
6363       }
6364     }
6365   }
6366 
6367   if (_parsed_annotations->has_annotation(AnnotationCollector::_jdk_internal_LooselyConsistentValue) && _access_flags.is_identity_class()) {
6368     THROW_MSG(vmSymbols::java_lang_ClassFormatError(),
6369           err_msg("class %s cannot have annotation jdk.internal.vm.annotation.LooselyConsistentValue, because it is not a value class",
6370                   _class_name->as_klass_external_name()));
6371   }
6372   if (_parsed_annotations->has_annotation(AnnotationCollector::_jdk_internal_ImplicitlyConstructible) && _access_flags.is_identity_class()) {
6373     THROW_MSG(vmSymbols::java_lang_ClassFormatError(),
6374           err_msg("class %s cannot have annotation jdk.internal.vm.annotation.ImplicitlyConstructible, because it is not a value class",
6375                   _class_name->as_klass_external_name()));
6376   }
6377 
6378   // Determining is the class allows tearing or not (default is not)
6379   // Test might need extensions when field inheritance is added for value classes
6380   if (EnableValhalla && !_access_flags.is_identity_class()) {
6381     if (_super_klass != nullptr  // not j.l.Object
6382               && _parsed_annotations->has_annotation(ClassAnnotationCollector::_jdk_internal_LooselyConsistentValue)
6383               && (_super_klass == vmClasses::Object_klass() || !_super_klass->must_be_atomic())) {
6384       _must_be_atomic = false;
6385     }
6386     if (_parsed_annotations->has_annotation(ClassAnnotationCollector::_jdk_internal_ImplicitlyConstructible)) {
6387       _is_implicitly_constructible = true;
6388     }
6389     // Apply VM options override
6390     if (*ForceNonTearable != '\0') {
6391       // Allow a command line switch to force the same atomicity property:
6392       const char* class_name_str = _class_name->as_C_string();
6393       if (StringUtils::class_list_match(ForceNonTearable, class_name_str)) {
6394         _must_be_atomic = true;
6395       }
6396     }
6397   }
6398 
6399   int itfs_len = _local_interface_indexes == nullptr ? 0 : _local_interface_indexes->length();
6400   _local_interfaces = MetadataFactory::new_array<InstanceKlass*>(_loader_data, itfs_len, nullptr, CHECK);
6401   if (_local_interface_indexes != nullptr) {
6402     for (int i = 0; i < _local_interface_indexes->length(); i++) {
6403       u2 interface_index = _local_interface_indexes->at(i);
6404       Klass* interf;
6405       if (cp->tag_at(interface_index).is_klass()) {
6406         interf = cp->resolved_klass_at(interface_index);
6407       } else {
6408         Symbol* const unresolved_klass  = cp->klass_name_at(interface_index);
6409 
6410         // Don't need to check legal name because it's checked when parsing constant pool.
6411         // But need to make sure it's not an array type.
6412         guarantee_property(unresolved_klass->char_at(0) != JVM_SIGNATURE_ARRAY,
6413                             "Bad interface name in class file %s", CHECK);
6414 
6415         // Call resolve_super so class circularity is checked
6416         interf = SystemDictionary::resolve_with_circularity_detection_or_fail(
6417                                                   _class_name,
6418                                                   unresolved_klass,
6419                                                   Handle(THREAD, _loader_data->class_loader()),
6420                                                   _protection_domain,
6421                                                   false,
6422                                                   CHECK);
6423       }
6424 
6425       if (!interf->is_interface()) {
6426         THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
6427                   err_msg("class %s can not implement %s, because it is not an interface (%s)",
6428                           _class_name->as_klass_external_name(),
6429                           interf->external_name(),
6430                           interf->class_in_module_of_loader()));
6431       }
6432 
6433       if (EnableValhalla) {
6434         // Check modifiers and set carries_identity_modifier/carries_value_modifier flags
6435         check_identity_and_value_modifiers(this, InstanceKlass::cast(interf), CHECK);
6436       }
6437 
6438       if (InstanceKlass::cast(interf)->has_nonstatic_concrete_methods()) {
6439         _has_nonstatic_concrete_methods = true;
6440       }
6441       _local_interfaces->at_put(i, InstanceKlass::cast(interf));
6442     }
6443   }
6444   assert(_local_interfaces != nullptr, "invariant");
6445 
6446   // Compute the transitive list of all unique interfaces implemented by this class
6447   _transitive_interfaces =
6448     compute_transitive_interfaces(_super_klass,
6449                                   _local_interfaces,
6450                                   _loader_data,
6451                                   CHECK);
6452 
6453   assert(_transitive_interfaces != nullptr, "invariant");
6454 
6455   // sort methods
6456   _method_ordering = sort_methods(_methods);
6457 
6458   _all_mirandas = new GrowableArray<Method*>(20);
6459 
6460   Handle loader(THREAD, _loader_data->class_loader());
6461   klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
6462                                                     &_num_miranda_methods,
6463                                                     _all_mirandas,
6464                                                     _super_klass,
6465                                                     _methods,
6466                                                     _access_flags,
6467                                                     _major_version,
6468                                                     loader,
6469                                                     _class_name,
6470                                                     _local_interfaces);
6471 
6472   // Size of Java itable (in words)
6473   _itable_size = is_interface() ? 0 :
6474     klassItable::compute_itable_size(_transitive_interfaces);
6475 
6476   assert(_fac != nullptr, "invariant");
6477   assert(_parsed_annotations != nullptr, "invariant");
6478 
6479   if (EnableValhalla) {
6480     _inline_type_field_klasses = MetadataFactory::new_array<InlineKlass*>(_loader_data,
6481                                                    java_fields_count(),
6482                                                    nullptr,
6483                                                    CHECK);
6484     for (GrowableArrayIterator<FieldInfo> it = _temp_field_info->begin(); it != _temp_field_info->end(); ++it) {
6485       FieldInfo fieldinfo = *it;
6486       if (fieldinfo.access_flags().is_static()) continue;  // Only non-static fields are processed at load time
6487       Symbol* sig = fieldinfo.signature(cp);
6488       if (fieldinfo.field_flags().is_null_free_inline_type()) {
6489         // Pre-load classes of null-free fields that are candidate for flattening
6490         TempNewSymbol s = Signature::strip_envelope(sig);
6491         if (s == _class_name) {
6492           THROW_MSG(vmSymbols::java_lang_ClassCircularityError(), err_msg("Class %s cannot have a null-free non-static field of its own type", _class_name->as_C_string()));
6493         }
6494         log_info(class, preload)("Preloading class %s during loading of class %s. Cause: a null-free non-static field is declared with this type", s->as_C_string(), _class_name->as_C_string());
6495         Klass* klass = SystemDictionary::resolve_with_circularity_detection_or_fail(_class_name, s, Handle(THREAD, _loader_data->class_loader()), _protection_domain, false, THREAD);
6496         if (HAS_PENDING_EXCEPTION) {
6497           log_warning(class, preload)("Preloading of class %s during loading of class %s (cause: null-free non-static field) failed: %s",
6498                                       s->as_C_string(), _class_name->as_C_string(), PENDING_EXCEPTION->klass()->name()->as_C_string());
6499           return; // Exception is still pending
6500         }
6501         assert(klass != nullptr, "Sanity check");
6502         if (klass->access_flags().is_identity_class()) {
6503           ResourceMark rm(THREAD);
6504           THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
6505                     err_msg("Class %s expects class %s to be a value class, but it is an identity class",
6506                     _class_name->as_C_string(),
6507                     InstanceKlass::cast(klass)->external_name()));
6508         }
6509         if (klass->is_abstract()) {
6510           assert(klass->is_instance_klass(), "Sanity check");
6511           ResourceMark rm(THREAD);
6512           THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
6513                     err_msg("Class %s expects class %s to be concrete value type, but it is an abstract class",
6514                     _class_name->as_C_string(),
6515                     InstanceKlass::cast(klass)->external_name()));
6516         }
6517         InlineKlass* vk = InlineKlass::cast(klass);
6518         if (!vk->is_implicitly_constructible()) {
6519           THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
6520                     err_msg("class %s is not implicitly constructible and it is used in a null restricted non-static field (not supported)",
6521                     klass->name()->as_C_string()));
6522         }
6523         _inline_type_field_klasses->at_put(fieldinfo.index(), vk);
6524         log_info(class, preload)("Preloading of class %s during loading of class %s (cause: null-free non-static field) succeeded", s->as_C_string(), _class_name->as_C_string());
6525       } else if (Signature::has_envelope(sig)) {
6526         // Preloading classes for nullable fields that are listed in the Preload attribute
6527         // Those classes would be required later for the flattening of nullable inline type fields
6528         TempNewSymbol name = Signature::strip_envelope(sig);
6529         if (name != _class_name && is_class_in_preload_attribute(name)) {
6530           log_info(class, preload)("Preloading class %s during loading of class %s. Cause: field type in Preload attribute", name->as_C_string(), _class_name->as_C_string());
6531           oop loader = loader_data()->class_loader();
6532           Klass* klass = SystemDictionary::resolve_with_circularity_detection_or_fail(_class_name, name, Handle(THREAD, loader), _protection_domain, false, THREAD);
6533           if (klass != nullptr) {
6534             if (klass->is_inline_klass()) {
6535               _inline_type_field_klasses->at_put(fieldinfo.index(), InlineKlass::cast(klass));
6536               log_info(class, preload)("Preloading of class %s during loading of class %s (cause: field type in Preload attribute) succeeded", name->as_C_string(), _class_name->as_C_string());
6537             } else {
6538               // Non value class are allowed by the current spec, but it could be an indication of an issue so let's log a warning
6539               log_warning(class, preload)("Preloading class %s during loading of class %s (cause: field type in Preload attribute) but loaded class is not a value class", name->as_C_string(), _class_name->as_C_string());
6540             }
6541             } else {
6542             log_warning(class, preload)("Preloading of class %s during loading of class %s (cause: field type in Preload attribute) failed : %s",
6543                                           name->as_C_string(), _class_name->as_C_string(), PENDING_EXCEPTION->klass()->name()->as_C_string());
6544           }
6545           // Loads triggered by the preload attribute are speculative, failures must not impact loading of current class
6546           if (HAS_PENDING_EXCEPTION) {
6547             CLEAR_PENDING_EXCEPTION;
6548           }
6549         }
6550       }
6551     }
6552   }
6553 
6554   _field_info = new FieldLayoutInfo();
6555   FieldLayoutBuilder lb(class_name(), super_klass(), _cp, /*_fields*/ _temp_field_info,
6556       _parsed_annotations->is_contended(), is_inline_type(),
6557       _field_info, _inline_type_field_klasses);
6558   lb.build_layout(CHECK);
6559   if (is_inline_type()) {
6560     _alignment = lb.get_alignment();
6561     _first_field_offset = lb.get_first_field_offset();
6562     _exact_size_in_bytes = lb.get_exact_size_in_byte();
6563   }
6564   _has_inline_type_fields = _field_info->_has_inline_fields;
6565 
6566   int injected_fields_count = _temp_field_info->length() - _java_fields_count;
6567   _fieldinfo_stream =
6568     FieldInfoStream::create_FieldInfoStream(_temp_field_info, _java_fields_count,
6569                                             injected_fields_count, loader_data(), CHECK);
6570   _fields_status =
6571     MetadataFactory::new_array<FieldStatus>(_loader_data, _temp_field_info->length(),
6572                                             FieldStatus(0), CHECK);
6573 }
6574 
6575 void ClassFileParser::set_klass(InstanceKlass* klass) {
6576 
6577 #ifdef ASSERT
6578   if (klass != nullptr) {
6579     assert(nullptr == _klass, "leaking?");
6580   }
6581 #endif
6582 
6583   _klass = klass;
6584 }
< prev index next >