< prev index next >

src/hotspot/share/classfile/classFileParser.cpp

Print this page

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

  24 #include "cds/cdsConfig.hpp"
  25 #include "classfile/classFileParser.hpp"
  26 #include "classfile/classFileStream.hpp"
  27 #include "classfile/classLoader.hpp"
  28 #include "classfile/classLoaderData.inline.hpp"
  29 #include "classfile/classLoadInfo.hpp"
  30 #include "classfile/defaultMethods.hpp"
  31 #include "classfile/fieldLayoutBuilder.hpp"
  32 #include "classfile/javaClasses.inline.hpp"
  33 #include "classfile/moduleEntry.hpp"
  34 #include "classfile/packageEntry.hpp"
  35 #include "classfile/symbolTable.hpp"
  36 #include "classfile/systemDictionary.hpp"
  37 #include "classfile/systemDictionaryShared.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/bsmAttribute.inline.hpp"
  52 #include "oops/constantPool.inline.hpp"
  53 #include "oops/fieldInfo.hpp"
  54 #include "oops/fieldStreams.inline.hpp"

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

  89 #include "utilities/utf8.hpp"
  90 
  91 // We generally try to create the oops directly when parsing, rather than
  92 // allocating temporary data structures and copying the bytes twice. A
  93 // temporary area is only needed when parsing utf8 entries in the constant
  94 // pool and when parsing line number tables.
  95 
  96 // We add assert in debug mode when class format is not checked.
  97 
  98 #define JAVA_CLASSFILE_MAGIC              0xCAFEBABE
  99 #define JAVA_MIN_SUPPORTED_VERSION        45
 100 #define JAVA_PREVIEW_MINOR_VERSION        65535
 101 
 102 // Used for two backward compatibility reasons:
 103 // - to check for new additions to the class file format in JDK1.5
 104 // - to check for bug fixes in the format checker in JDK1.5
 105 #define JAVA_1_5_VERSION                  49
 106 
 107 // Used for backward compatibility reasons:
 108 // - to check for javac bug fixes that happened after 1.5

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

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

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


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

1354   }
1355 
1356   *constantvalue_index_addr = constantvalue_index;
1357   *is_synthetic_addr = is_synthetic;
1358   *generic_signature_index_addr = generic_signature_index;
1359   AnnotationArray* a = allocate_annotations(runtime_visible_annotations,
1360                                             runtime_visible_annotations_length,
1361                                             CHECK);
1362   parsed_annotations->set_field_annotations(a);
1363   a = allocate_annotations(runtime_visible_type_annotations,
1364                            runtime_visible_type_annotations_length,
1365                            CHECK);
1366   parsed_annotations->set_field_type_annotations(a);
1367   return;
1368 }
1369 
1370 
1371 // Side-effects: populates the _fields, _fields_annotations,
1372 // _fields_type_annotations fields
1373 void ClassFileParser::parse_fields(const ClassFileStream* const cfs,
1374                                    bool is_interface,
1375                                    ConstantPool* cp,
1376                                    const int cp_size,
1377                                    u2* const java_fields_count_ptr,
1378                                    TRAPS) {
1379 
1380   assert(cfs != nullptr, "invariant");
1381   assert(cp != nullptr, "invariant");
1382   assert(java_fields_count_ptr != nullptr, "invariant");
1383 
1384   assert(nullptr == _fields_annotations, "invariant");
1385   assert(nullptr == _fields_type_annotations, "invariant");
1386 




1387   cfs->guarantee_more(2, CHECK);  // length
1388   const u2 length = cfs->get_u2_fast();
1389   *java_fields_count_ptr = length;
1390 
1391   int num_injected = 0;
1392   const InjectedField* const injected = JavaClasses::get_injected(_class_name,
1393                                                                   &num_injected);
1394   const int total_fields = length + num_injected;










1395 
1396   // Allocate a temporary resource array to collect field data.
1397   // After parsing all fields, data are stored in a UNSIGNED5 compressed stream.
1398   _temp_field_info = new GrowableArray<FieldInfo>(total_fields);
1399 
1400   ResourceMark rm(THREAD);
1401   for (int n = 0; n < length; n++) {
1402     // access_flags, name_index, descriptor_index, attributes_count
1403     cfs->guarantee_more(8, CHECK);
1404 







1405     AccessFlags access_flags;
1406     const jint flags = cfs->get_u2_fast() & JVM_RECOGNIZED_FIELD_MODIFIERS;
1407     verify_legal_field_modifiers(flags, is_interface, CHECK);
1408     access_flags.set_flags(flags);
1409     FieldInfo::FieldFlags fieldFlags(0);
1410 
1411     const u2 name_index = cfs->get_u2_fast();
1412     guarantee_property(valid_symbol_at(name_index),
1413       "Invalid constant pool index %u for field name in class file %s",
1414       name_index, CHECK);
1415     const Symbol* const name = cp->symbol_at(name_index);
1416     verify_legal_field_name(name, CHECK);
1417 
1418     const u2 signature_index = cfs->get_u2_fast();
1419     guarantee_property(valid_symbol_at(signature_index),
1420       "Invalid constant pool index %u for field signature in class file %s",
1421       signature_index, CHECK);
1422     const Symbol* const sig = cp->symbol_at(signature_index);
1423     verify_legal_field_signature(name, sig, CHECK);
1424 
1425     u2 constantvalue_index = 0;
1426     bool is_synthetic = false;
1427     u2 generic_signature_index = 0;
1428     const bool is_static = access_flags.is_static();
1429     FieldAnnotationCollector parsed_annotations(_loader_data);
1430 


1431     const u2 attributes_count = cfs->get_u2_fast();
1432     if (attributes_count > 0) {
1433       parse_field_attributes(cfs,
1434                              attributes_count,
1435                              is_static,
1436                              signature_index,
1437                              &constantvalue_index,
1438                              &is_synthetic,
1439                              &generic_signature_index,
1440                              &parsed_annotations,
1441                              CHECK);
1442 
1443       if (parsed_annotations.field_annotations() != nullptr) {
1444         if (_fields_annotations == nullptr) {
1445           _fields_annotations = MetadataFactory::new_array<AnnotationArray*>(
1446                                              _loader_data, length, nullptr,
1447                                              CHECK);
1448         }
1449         _fields_annotations->at_put(n, parsed_annotations.field_annotations());
1450         parsed_annotations.set_field_annotations(nullptr);


























1451       }
1452       if (parsed_annotations.field_type_annotations() != nullptr) {
1453         if (_fields_type_annotations == nullptr) {
1454           _fields_type_annotations =
1455             MetadataFactory::new_array<AnnotationArray*>(_loader_data,
1456                                                          length,
1457                                                          nullptr,
1458                                                          CHECK);
1459         }
1460         _fields_type_annotations->at_put(n, parsed_annotations.field_type_annotations());
1461         parsed_annotations.set_field_type_annotations(nullptr);
1462       }
1463 
1464       if (is_synthetic) {
1465         access_flags.set_is_synthetic();
1466       }
1467       if (generic_signature_index != 0) {
1468         fieldFlags.update_generic(true);
1469       }
1470     }
1471 




1472     const BasicType type = cp->basic_type_for_signature_at(signature_index);
1473 
1474     // Update number of static oop fields.
1475     if (is_static && is_reference_type(type)) {
1476       _static_oop_count++;
1477     }
1478 
1479     FieldInfo fi(access_flags, name_index, signature_index, constantvalue_index, fieldFlags);
1480     fi.set_index(n);
1481     if (fieldFlags.is_generic()) {
1482       fi.set_generic_signature_index(generic_signature_index);
1483     }
1484     parsed_annotations.apply_to(&fi);
1485     if (fi.field_flags().is_contended()) {
1486       _has_contended_fields = true;
1487     }



1488     _temp_field_info->append(fi);
1489   }
1490   assert(_temp_field_info->length() == length, "Must be");
1491 
1492   int index = length;
1493   if (num_injected != 0) {
1494     for (int n = 0; n < num_injected; n++) {
1495       // Check for duplicates
1496       if (injected[n].may_be_java) {
1497         const Symbol* const name      = injected[n].name();
1498         const Symbol* const signature = injected[n].signature();
1499         bool duplicate = false;
1500         for (int i = 0; i < length; i++) {
1501           const FieldInfo* const f = _temp_field_info->adr_at(i);
1502           if (name      == cp->symbol_at(f->name_index()) &&
1503               signature == cp->symbol_at(f->signature_index())) {
1504             // Symbol is desclared in Java so skip this one
1505             duplicate = true;
1506             break;
1507           }
1508         }
1509         if (duplicate) {
1510           // These will be removed from the field array at the end
1511           continue;
1512         }
1513       }
1514 
1515       // Injected field
1516       FieldInfo::FieldFlags fflags(0);
1517       fflags.update_injected(true);
1518       AccessFlags aflags;
1519       FieldInfo fi(aflags, (u2)(injected[n].name_index), (u2)(injected[n].signature_index), 0, fflags);
1520       fi.set_index(index);
1521       _temp_field_info->append(fi);
1522       index++;
1523     }
1524   }
1525 
1526   assert(_temp_field_info->length() == index, "Must be");
































1527 
1528   if (_need_verify && length > 1) {
1529     // Check duplicated fields
1530     ResourceMark rm(THREAD);
1531     // Set containing name-signature pairs
1532     NameSigHashtable* names_and_sigs = new NameSigHashtable();
1533     for (int i = 0; i < _temp_field_info->length(); i++) {
1534       NameSigHash name_and_sig(_temp_field_info->adr_at(i)->name(_cp),
1535                                _temp_field_info->adr_at(i)->signature(_cp));
1536       // If no duplicates, add name/signature in hashtable names_and_sigs.
1537       if(!names_and_sigs->put(name_and_sig, 0)) {
1538         classfile_parse_error("Duplicate field name \"%s\" with signature \"%s\" in class file %s",
1539                                name_and_sig._name->as_C_string(), name_and_sig._sig->as_klass_external_name(), THREAD);
1540         return;
1541       }
1542     }
1543   }
1544 }
1545 
1546 

1891     }
1892     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Contended_signature): {
1893       if (_location != _in_field && _location != _in_class) {
1894         break;  // only allow for fields and classes
1895       }
1896       if (!EnableContended || (RestrictContended && !privileged)) {
1897         break;  // honor privileges
1898       }
1899       return _jdk_internal_vm_annotation_Contended;
1900     }
1901     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ReservedStackAccess_signature): {
1902       if (_location != _in_method)  break;  // only allow for methods
1903       if (RestrictReservedStack && !privileged) break; // honor privileges
1904       return _jdk_internal_vm_annotation_ReservedStackAccess;
1905     }
1906     case VM_SYMBOL_ENUM_NAME(jdk_internal_ValueBased_signature): {
1907       if (_location != _in_class)   break;  // only allow for classes
1908       if (!privileged)              break;  // only allow in privileged code
1909       return _jdk_internal_ValueBased;
1910     }








1911     case VM_SYMBOL_ENUM_NAME(java_lang_Deprecated): {
1912       return _java_lang_Deprecated;
1913     }
1914     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_AOTSafeClassInitializer_signature): {
1915       if (_location != _in_class)   break;  // only allow for classes
1916       if (!privileged)              break;  // only allow in privileged code
1917       return _jdk_internal_vm_annotation_AOTSafeClassInitializer;
1918     }
1919     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_AOTRuntimeSetup_signature): {
1920       if (_location != _in_method)  break;  // only allow for methods
1921       if (!privileged)              break;  // only allow in privileged code
1922       return _method_AOTRuntimeSetup;
1923     }
1924     default: {
1925       break;
1926     }
1927   }
1928   return AnnotationCollector::_unknown;
1929 }
1930 

2171 
2172   const u2 signature_index = cfs->get_u2_fast();
2173   guarantee_property(
2174     valid_symbol_at(signature_index),
2175     "Illegal constant pool index %u for method signature in class file %s",
2176     signature_index, CHECK_NULL);
2177   const Symbol* const signature = cp->symbol_at(signature_index);
2178 
2179   if (name == vmSymbols::class_initializer_name()) {
2180     // We ignore the other access flags for a valid class initializer.
2181     // (JVM Spec 2nd ed., chapter 4.6)
2182     if (_major_version < 51) { // backward compatibility
2183       flags = JVM_ACC_STATIC;
2184     } else if ((flags & JVM_ACC_STATIC) == JVM_ACC_STATIC) {
2185       flags &= JVM_ACC_STATIC | (_major_version <= JAVA_16_VERSION ? JVM_ACC_STRICT : 0);
2186     } else {
2187       classfile_parse_error("Method <clinit> is not static in class file %s", THREAD);
2188       return nullptr;
2189     }
2190   } else {
2191     verify_legal_method_modifiers(flags, is_interface, name, CHECK_NULL);
2192   }
2193 
2194   if (name == vmSymbols::object_initializer_name() && is_interface) {
2195     classfile_parse_error("Interface cannot have a method named <init>, class file %s", THREAD);
2196     return nullptr;
2197   }
2198 









2199   int args_size = -1;  // only used when _need_verify is true
2200   if (_need_verify) {
2201     verify_legal_name_with_signature(name, signature, CHECK_NULL);
2202     args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) +
2203                  verify_legal_method_signature(name, signature, CHECK_NULL);
2204     if (args_size > MAX_ARGS_SIZE) {
2205       classfile_parse_error("Too many arguments in method signature in class file %s", THREAD);
2206       return nullptr;
2207     }
2208   }
2209 
2210   AccessFlags access_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS);
2211 
2212   // Default values for code and exceptions attribute elements
2213   u2 max_stack = 0;
2214   u2 max_locals = 0;
2215   u4 code_length = 0;
2216   const u1* code_start = nullptr;
2217   u2 exception_table_length = 0;
2218   const unsafe_u2* exception_table_start = nullptr; // (potentially unaligned) pointer to array of u2 elements

3002         valid_klass_reference_at(outer_class_info_index),
3003       "outer_class_info_index %u has bad constant type in class file %s",
3004       outer_class_info_index, CHECK_0);
3005 
3006     if (outer_class_info_index != 0) {
3007       const Symbol* const outer_class_name = cp->klass_name_at(outer_class_info_index);
3008       char* bytes = (char*)outer_class_name->bytes();
3009       guarantee_property(bytes[0] != JVM_SIGNATURE_ARRAY,
3010                          "Outer class is an array class in class file %s", CHECK_0);
3011     }
3012     // Inner class name
3013     const u2 inner_name_index = cfs->get_u2_fast();
3014     guarantee_property(
3015       inner_name_index == 0 || valid_symbol_at(inner_name_index),
3016       "inner_name_index %u has bad constant type in class file %s",
3017       inner_name_index, CHECK_0);
3018     if (_need_verify) {
3019       guarantee_property(inner_class_info_index != outer_class_info_index,
3020                          "Class is both outer and inner class in class file %s", CHECK_0);
3021     }

3022     // Access flags
3023     u2 flags;
3024     // JVM_ACC_MODULE is defined in JDK-9 and later.
3025     if (_major_version >= JAVA_9_VERSION) {
3026       flags = cfs->get_u2_fast() & (RECOGNIZED_INNER_CLASS_MODIFIERS | JVM_ACC_MODULE);
3027     } else {
3028       flags = cfs->get_u2_fast() & RECOGNIZED_INNER_CLASS_MODIFIERS;
3029     }

3030     if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
3031       // Set abstract bit for old class files for backward compatibility
3032       flags |= JVM_ACC_ABSTRACT;
3033     }
3034 








3035     Symbol* inner_name_symbol = inner_name_index == 0 ? nullptr : cp->symbol_at(inner_name_index);
3036     verify_legal_class_modifiers(flags, inner_name_symbol, inner_name_index == 0, CHECK_0);
3037     AccessFlags inner_access_flags(flags);
3038 
3039     inner_classes->at_put(index++, inner_class_info_index);
3040     inner_classes->at_put(index++, outer_class_info_index);
3041     inner_classes->at_put(index++, inner_name_index);
3042     inner_classes->at_put(index++, inner_access_flags.as_unsigned_short());
3043   }
3044 
3045   // Check for circular and duplicate entries.
3046   bool has_circularity = false;
3047   if (_need_verify) {
3048     has_circularity = check_inner_classes_circularity(cp, length * 4, CHECK_0);
3049     if (has_circularity) {
3050       // If circularity check failed then ignore InnerClasses attribute.
3051       MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
3052       index = 0;
3053       if (parsed_enclosingmethod_attribute) {
3054         inner_classes = MetadataFactory::new_array<u2>(_loader_data, 2, CHECK_0);

3120   if (length > 0) {
3121     int index = 0;
3122     cfs->guarantee_more(2 * length, CHECK_0);
3123     for (int n = 0; n < length; n++) {
3124       const u2 class_info_index = cfs->get_u2_fast();
3125       guarantee_property(
3126         valid_klass_reference_at(class_info_index),
3127         "Permitted subclass class_info_index %u has bad constant type in class file %s",
3128         class_info_index, CHECK_0);
3129       permitted_subclasses->at_put(index++, class_info_index);
3130     }
3131     assert(index == size, "wrong size");
3132   }
3133 
3134   // Restore buffer's current position.
3135   cfs->set_current(current_mark);
3136 
3137   return length;
3138 }
3139 











































3140 //  Record {
3141 //    u2 attribute_name_index;
3142 //    u4 attribute_length;
3143 //    u2 components_count;
3144 //    component_info components[components_count];
3145 //  }
3146 //  component_info {
3147 //    u2 name_index;
3148 //    u2 descriptor_index
3149 //    u2 attributes_count;
3150 //    attribute_info_attributes[attributes_count];
3151 //  }
3152 u4 ClassFileParser::parse_classfile_record_attribute(const ClassFileStream* const cfs,
3153                                                      const ConstantPool* cp,
3154                                                      const u1* const record_attribute_start,
3155                                                      TRAPS) {
3156   const u1* const current_mark = cfs->current();
3157   int components_count = 0;
3158   unsigned int calculate_attr_size = 0;
3159   if (record_attribute_start != nullptr) {

3370   cp->bsm_entries().end_extension(iter, _loader_data, CHECK);
3371   guarantee_property(current_before_parsing + attribute_byte_length == cfs->current(),
3372                      "Bad length on BootstrapMethods in class file %s",
3373                      CHECK);
3374 }
3375 
3376 void ClassFileParser::parse_classfile_attributes(const ClassFileStream* const cfs,
3377                                                  ConstantPool* cp,
3378                  ClassFileParser::ClassAnnotationCollector* parsed_annotations,
3379                                                  TRAPS) {
3380   assert(cfs != nullptr, "invariant");
3381   assert(cp != nullptr, "invariant");
3382   assert(parsed_annotations != nullptr, "invariant");
3383 
3384   // Set inner classes attribute to default sentinel
3385   _inner_classes = Universe::the_empty_short_array();
3386   // Set nest members attribute to default sentinel
3387   _nest_members = Universe::the_empty_short_array();
3388   // Set _permitted_subclasses attribute to default sentinel
3389   _permitted_subclasses = Universe::the_empty_short_array();


3390   cfs->guarantee_more(2, CHECK);  // attributes_count
3391   u2 attributes_count = cfs->get_u2_fast();
3392   bool parsed_sourcefile_attribute = false;
3393   bool parsed_innerclasses_attribute = false;
3394   bool parsed_nest_members_attribute = false;
3395   bool parsed_permitted_subclasses_attribute = false;

3396   bool parsed_nest_host_attribute = false;
3397   bool parsed_record_attribute = false;
3398   bool parsed_enclosingmethod_attribute = false;
3399   bool parsed_bootstrap_methods_attribute = false;
3400   const u1* runtime_visible_annotations = nullptr;
3401   int runtime_visible_annotations_length = 0;
3402   const u1* runtime_visible_type_annotations = nullptr;
3403   int runtime_visible_type_annotations_length = 0;
3404   bool runtime_invisible_type_annotations_exists = false;
3405   bool runtime_invisible_annotations_exists = false;
3406   bool parsed_source_debug_ext_annotations_exist = false;
3407   const u1* inner_classes_attribute_start = nullptr;
3408   u4  inner_classes_attribute_length = 0;
3409   u2  enclosing_method_class_index = 0;
3410   u2  enclosing_method_method_index = 0;
3411   const u1* nest_members_attribute_start = nullptr;
3412   u4  nest_members_attribute_length = 0;
3413   const u1* record_attribute_start = nullptr;
3414   u4  record_attribute_length = 0;
3415   const u1* permitted_subclasses_attribute_start = nullptr;
3416   u4  permitted_subclasses_attribute_length = 0;


3417 
3418   // Iterate over attributes
3419   while (attributes_count--) {
3420     cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
3421     const u2 attribute_name_index = cfs->get_u2_fast();
3422     const u4 attribute_length = cfs->get_u4_fast();
3423     guarantee_property(
3424       valid_symbol_at(attribute_name_index),
3425       "Attribute name has bad constant pool index %u in class file %s",
3426       attribute_name_index, CHECK);
3427     const Symbol* const tag = cp->symbol_at(attribute_name_index);
3428     if (tag == vmSymbols::tag_source_file()) {
3429       // Check for SourceFile tag
3430       if (_need_verify) {
3431         guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
3432       }
3433       if (parsed_sourcefile_attribute) {
3434         classfile_parse_error("Multiple SourceFile attributes in class file %s", THREAD);
3435         return;
3436       } else {

3612               return;
3613             }
3614             parsed_record_attribute = true;
3615             record_attribute_start = cfs->current();
3616             record_attribute_length = attribute_length;
3617           } else if (_major_version >= JAVA_17_VERSION) {
3618             if (tag == vmSymbols::tag_permitted_subclasses()) {
3619               if (parsed_permitted_subclasses_attribute) {
3620                 classfile_parse_error("Multiple PermittedSubclasses attributes in class file %s", CHECK);
3621                 return;
3622               }
3623               // Classes marked ACC_FINAL cannot have a PermittedSubclasses attribute.
3624               if (_access_flags.is_final()) {
3625                 classfile_parse_error("PermittedSubclasses attribute in final class file %s", CHECK);
3626                 return;
3627               }
3628               parsed_permitted_subclasses_attribute = true;
3629               permitted_subclasses_attribute_start = cfs->current();
3630               permitted_subclasses_attribute_length = attribute_length;
3631             }









3632           }
3633           // Skip attribute_length for any attribute where major_verson >= JAVA_17_VERSION
3634           cfs->skip_u1(attribute_length, CHECK);
3635         } else {
3636           // Unknown attribute
3637           cfs->skip_u1(attribute_length, CHECK);
3638         }
3639       } else {
3640         // Unknown attribute
3641         cfs->skip_u1(attribute_length, CHECK);
3642       }
3643     } else {
3644       // Unknown attribute
3645       cfs->skip_u1(attribute_length, CHECK);
3646     }
3647   }
3648   _class_annotations = allocate_annotations(runtime_visible_annotations,
3649                                             runtime_visible_annotations_length,
3650                                             CHECK);
3651   _class_type_annotations = allocate_annotations(runtime_visible_type_annotations,

3688                             CHECK);
3689     if (_need_verify) {
3690       guarantee_property(record_attribute_length == calculated_attr_length,
3691                          "Record attribute has wrong length in class file %s",
3692                          CHECK);
3693     }
3694   }
3695 
3696   if (parsed_permitted_subclasses_attribute) {
3697     const u2 num_subclasses = parse_classfile_permitted_subclasses_attribute(
3698                             cfs,
3699                             permitted_subclasses_attribute_start,
3700                             CHECK);
3701     if (_need_verify) {
3702       guarantee_property(
3703         permitted_subclasses_attribute_length == sizeof(num_subclasses) + sizeof(u2) * num_subclasses,
3704         "Wrong PermittedSubclasses attribute length in class file %s", CHECK);
3705     }
3706   }
3707 












3708   if (_max_bootstrap_specifier_index >= 0) {
3709     guarantee_property(parsed_bootstrap_methods_attribute,
3710                        "Missing BootstrapMethods attribute in class file %s", CHECK);
3711   }
3712 }
3713 
3714 void ClassFileParser::apply_parsed_class_attributes(InstanceKlass* k) {
3715   assert(k != nullptr, "invariant");
3716 
3717   if (_synthetic_flag)
3718     k->set_is_synthetic();
3719   if (_sourcefile_index != 0) {
3720     k->set_source_file_name_index(_sourcefile_index);
3721   }
3722   if (_generic_signature_index != 0) {
3723     k->set_generic_signature_index(_generic_signature_index);
3724   }
3725   if (_sde_buffer != nullptr) {
3726     k->set_source_debug_extension(_sde_buffer, _sde_length);
3727   }

3754     _class_type_annotations  = nullptr;
3755     _fields_annotations      = nullptr;
3756     _fields_type_annotations = nullptr;
3757 }
3758 
3759 // Transfer ownership of metadata allocated to the InstanceKlass.
3760 void ClassFileParser::apply_parsed_class_metadata(
3761                                             InstanceKlass* this_klass,
3762                                             int java_fields_count) {
3763   assert(this_klass != nullptr, "invariant");
3764 
3765   _cp->set_pool_holder(this_klass);
3766   this_klass->set_constants(_cp);
3767   this_klass->set_fieldinfo_stream(_fieldinfo_stream);
3768   this_klass->set_fieldinfo_search_table(_fieldinfo_search_table);
3769   this_klass->set_fields_status(_fields_status);
3770   this_klass->set_methods(_methods);
3771   this_klass->set_inner_classes(_inner_classes);
3772   this_klass->set_nest_members(_nest_members);
3773   this_klass->set_nest_host_index(_nest_host);

3774   this_klass->set_annotations(_combined_annotations);
3775   this_klass->set_permitted_subclasses(_permitted_subclasses);
3776   this_klass->set_record_components(_record_components);

3777 
3778   DEBUG_ONLY(FieldInfoStream::validate_search_table(_cp, _fieldinfo_stream, _fieldinfo_search_table));
3779 
3780   // Delay the setting of _local_interfaces and _transitive_interfaces until after
3781   // initialize_supers() in fill_instance_klass(). It is because the _local_interfaces could
3782   // be shared with _transitive_interfaces and _transitive_interfaces may be shared with
3783   // its _super. If an OOM occurs while loading the current klass, its _super field
3784   // may not have been set. When GC tries to free the klass, the _transitive_interfaces
3785   // may be deallocated mistakenly in InstanceKlass::deallocate_interfaces(). Subsequent
3786   // dereferences to the deallocated _transitive_interfaces will result in a crash.
3787 
3788   // Clear out these fields so they don't get deallocated by the destructor
3789   clear_class_metadata();
3790 }
3791 
3792 AnnotationArray* ClassFileParser::allocate_annotations(const u1* const anno,
3793                                                        int anno_length,
3794                                                        TRAPS) {
3795   AnnotationArray* annotations = nullptr;
3796   if (anno != nullptr) {
3797     annotations = MetadataFactory::new_array<u1>(_loader_data,
3798                                                  anno_length,
3799                                                  CHECK_(annotations));
3800     for (int i = 0; i < anno_length; i++) {
3801       annotations->at_put(i, anno[i]);
3802     }
3803   }
3804   return annotations;
3805 }
3806 
3807 void ClassFileParser::check_super_class(ConstantPool* const cp,
3808                                         const int super_class_index,
3809                                         const bool need_verify,
3810                                         TRAPS) {
3811   assert(cp != nullptr, "invariant");
3812 
3813   if (super_class_index == 0) {
3814     guarantee_property(_class_name == vmSymbols::java_lang_Object(),
3815                        "Invalid superclass index %u in class file %s",
3816                        super_class_index,
3817                        CHECK);
3818   } else {
3819     guarantee_property(valid_klass_reference_at(super_class_index),
3820                        "Invalid superclass index %u in class file %s",
3821                        super_class_index,
3822                        CHECK);
3823 
3824     // The class name should be legal because it is checked when parsing constant pool.
3825     // However, make sure it is not an array type.
3826     if (need_verify) {
3827       guarantee_property(cp->klass_name_at(super_class_index)->char_at(0) != JVM_SIGNATURE_ARRAY,
3828                         "Bad superclass name in class file %s", CHECK);
3829     }
3830   }
3831 }
3832 
3833 OopMapBlocksBuilder::OopMapBlocksBuilder(unsigned int max_blocks) {
3834   _max_nonstatic_oop_maps = max_blocks;
3835   _nonstatic_oop_map_count = 0;
3836   if (max_blocks == 0) {

3988   // See documentation of InstanceKlass::can_be_fastpath_allocated().
3989   assert(ik->size_helper() > 0, "layout_helper is initialized");
3990   if (ik->is_abstract() || ik->is_interface()
3991       || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == nullptr)
3992       || ik->size_helper() >= FastAllocateSizeLimit) {
3993     // Forbid fast-path allocation.
3994     const jint lh = Klass::instance_layout_helper(ik->size_helper(), true);
3995     ik->set_layout_helper(lh);
3996   }
3997 
3998   // Propagate the AOT runtimeSetup method discovery
3999   if (_has_aot_runtime_setup_method) {
4000     ik->set_is_runtime_setup_required();
4001     if (log_is_enabled(Info, aot, init)) {
4002       ResourceMark rm;
4003       log_info(aot, init)("Found @AOTRuntimeSetup class %s", ik->external_name());
4004     }
4005   }
4006 }
4007 






4008 // utility methods for appending an array with check for duplicates
4009 
4010 static void append_interfaces(GrowableArray<InstanceKlass*>* result,
4011                               const Array<InstanceKlass*>* const ifs) {
4012   // iterate over new interfaces
4013   for (int i = 0; i < ifs->length(); i++) {
4014     InstanceKlass* const e = ifs->at(i);
4015     assert(e->is_klass() && e->is_interface(), "just checking");
4016     // add new interface
4017     result->append_if_missing(e);
4018   }
4019 }
4020 
4021 static Array<InstanceKlass*>* compute_transitive_interfaces(const InstanceKlass* super,
4022                                                             Array<InstanceKlass*>* local_ifs,
4023                                                             ClassLoaderData* loader_data,
4024                                                             TRAPS) {
4025   assert(local_ifs != nullptr, "invariant");
4026   assert(loader_data != nullptr, "invariant");
4027 

4054   } else {
4055     ResourceMark rm;
4056     GrowableArray<InstanceKlass*>* const result = new GrowableArray<InstanceKlass*>(max_transitive_size);
4057 
4058     // Copy down from superclass
4059     if (super != nullptr) {
4060       append_interfaces(result, super->transitive_interfaces());
4061     }
4062 
4063     // Copy down from local interfaces' superinterfaces
4064     for (int i = 0; i < local_size; i++) {
4065       InstanceKlass* const l = local_ifs->at(i);
4066       append_interfaces(result, l->transitive_interfaces());
4067     }
4068     // Finally add local interfaces
4069     append_interfaces(result, local_ifs);
4070 
4071     // length will be less than the max_transitive_size if duplicates were removed
4072     const int length = result->length();
4073     assert(length <= max_transitive_size, "just checking");

4074     Array<InstanceKlass*>* const new_result =
4075       MetadataFactory::new_array<InstanceKlass*>(loader_data, length, CHECK_NULL);
4076     for (int i = 0; i < length; i++) {
4077       InstanceKlass* const e = result->at(i);
4078       assert(e != nullptr, "just checking");
4079       new_result->at_put(i, e);
4080     }
4081     return new_result;
4082   }
4083 }
4084 
4085 void ClassFileParser::check_super_class_access(const InstanceKlass* this_klass, TRAPS) {
4086   assert(this_klass != nullptr, "invariant");
4087   const InstanceKlass* const super = this_klass->super();
4088 
4089   if (super != nullptr) {
4090     if (super->is_final()) {
4091       classfile_icce_error("class %s cannot inherit from final class %s", super, THREAD);
4092       return;
4093     }
4094 
4095     if (super->is_sealed()) {
4096       stringStream ss;
4097       ResourceMark rm(THREAD);
4098       if (!super->has_as_permitted_subclass(this_klass, ss)) {
4099         classfile_icce_error(ss.as_string(), THREAD);
4100         return;
4101       }
4102     }
4103 










4104     Reflection::VerifyClassAccessResults vca_result =
4105       Reflection::verify_class_access(this_klass, super, false);
4106     if (vca_result != Reflection::ACCESS_OK) {
4107       ResourceMark rm(THREAD);
4108       char* msg = Reflection::verify_class_access_msg(this_klass,
4109                                                       super,
4110                                                       vca_result);
4111 
4112       // Names are all known to be < 64k so we know this formatted message is not excessively large.
4113       if (msg == nullptr) {
4114         bool same_module = (this_klass->module() == super->module());
4115         Exceptions::fthrow(
4116           THREAD_AND_LOCATION,
4117           vmSymbols::java_lang_IllegalAccessError(),
4118           "class %s cannot access its %ssuperclass %s (%s%s%s)",
4119           this_klass->external_name(),
4120           super->is_abstract() ? "abstract " : "",
4121           super->external_name(),
4122           (same_module) ? this_klass->joint_in_module_of_loader(super) : this_klass->class_in_module_of_loader(),
4123           (same_module) ? "" : "; ",

4276 // Verify the class modifiers for the current class, or an inner class if inner_name is non-null.
4277 void ClassFileParser::verify_legal_class_modifiers(jint flags, Symbol* inner_name, bool is_anonymous_inner_class, TRAPS) const {
4278   const bool is_module = (flags & JVM_ACC_MODULE) != 0;
4279   assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");
4280   if (is_module) {
4281     ResourceMark rm(THREAD);
4282     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4283     Exceptions::fthrow(
4284       THREAD_AND_LOCATION,
4285       vmSymbols::java_lang_NoClassDefFoundError(),
4286       "%s is not a class because access_flag ACC_MODULE is set",
4287       _class_name->as_C_string());
4288     return;
4289   }
4290 
4291   if (!_need_verify) { return; }
4292 
4293   const bool is_interface  = (flags & JVM_ACC_INTERFACE)  != 0;
4294   const bool is_abstract   = (flags & JVM_ACC_ABSTRACT)   != 0;
4295   const bool is_final      = (flags & JVM_ACC_FINAL)      != 0;
4296   const bool is_super      = (flags & JVM_ACC_SUPER)      != 0;
4297   const bool is_enum       = (flags & JVM_ACC_ENUM)       != 0;
4298   const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4299   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;

4300 
4301   if ((is_abstract && is_final) ||
4302       (is_interface && !is_abstract) ||
4303       (is_interface && major_gte_1_5 && (is_super || is_enum)) ||
4304       (!is_interface && major_gte_1_5 && is_annotation)) {

4305     ResourceMark rm(THREAD);
4306     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4307     if (inner_name == nullptr && !is_anonymous_inner_class) {
4308       Exceptions::fthrow(
4309         THREAD_AND_LOCATION,
4310         vmSymbols::java_lang_ClassFormatError(),
4311         "Illegal class modifiers in class %s: 0x%X",
4312         _class_name->as_C_string(), flags
4313       );
4314     } else {
4315       if (is_anonymous_inner_class) {
4316         Exceptions::fthrow(
4317           THREAD_AND_LOCATION,
4318           vmSymbols::java_lang_ClassFormatError(),
4319           "Illegal class modifiers in anonymous inner class of class %s: 0x%X",
4320           _class_name->as_C_string(), flags
4321         );
4322       } else {
4323         Exceptions::fthrow(
4324           THREAD_AND_LOCATION,

4379         THREAD_AND_LOCATION,
4380         vmSymbols::java_lang_UnsupportedClassVersionError(),
4381         "%s (class file version %u.%u) was compiled with preview features that are unsupported. "
4382         "This version of the Java Runtime only recognizes preview features for class file version %u.%u",
4383         class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION, JAVA_PREVIEW_MINOR_VERSION);
4384       return;
4385     }
4386 
4387     if (!Arguments::enable_preview()) {
4388       classfile_ucve_error("Preview features are not enabled for %s (class file version %u.%u). Try running with '--enable-preview'",
4389                            class_name, major, minor, THREAD);
4390       return;
4391     }
4392 
4393   } else { // minor != JAVA_PREVIEW_MINOR_VERSION
4394     classfile_ucve_error("%s (class file version %u.%u) was compiled with an invalid non-zero minor version",
4395                          class_name, major, minor, THREAD);
4396   }
4397 }
4398 
4399 void ClassFileParser::verify_legal_field_modifiers(jint flags,
4400                                                    bool is_interface,
4401                                                    TRAPS) const {
4402   if (!_need_verify) { return; }
4403 
4404   const bool is_public    = (flags & JVM_ACC_PUBLIC)      != 0;
4405   const bool is_protected = (flags & JVM_ACC_PROTECTED)   != 0;
4406   const bool is_private   = (flags & JVM_ACC_PRIVATE)     != 0;
4407   const bool is_static    = (flags & JVM_ACC_STATIC)      != 0;
4408   const bool is_final     = (flags & JVM_ACC_FINAL)       != 0;
4409   const bool is_volatile  = (flags & JVM_ACC_VOLATILE)    != 0;
4410   const bool is_transient = (flags & JVM_ACC_TRANSIENT)   != 0;
4411   const bool is_enum      = (flags & JVM_ACC_ENUM)        != 0;

4412   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4413 
4414   bool is_illegal = false;

4415 
4416   if (is_interface) {
4417     if (!is_public || !is_static || !is_final || is_private ||
4418         is_protected || is_volatile || is_transient ||
4419         (major_gte_1_5 && is_enum)) {
4420       is_illegal = true;
4421     }
4422   } else { // not interface
4423     if (has_illegal_visibility(flags) || (is_final && is_volatile)) {
4424       is_illegal = true;





















4425     }
4426   }
4427 
4428   if (is_illegal) {
4429     ResourceMark rm(THREAD);
4430     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4431     Exceptions::fthrow(
4432       THREAD_AND_LOCATION,
4433       vmSymbols::java_lang_ClassFormatError(),
4434       "Illegal field modifiers in class %s: 0x%X",
4435       _class_name->as_C_string(), flags);
4436     return;
4437   }
4438 }
4439 
4440 void ClassFileParser::verify_legal_method_modifiers(jint flags,
4441                                                     bool is_interface,
4442                                                     const Symbol* name,
4443                                                     TRAPS) const {
4444   if (!_need_verify) { return; }
4445 
4446   const bool is_public       = (flags & JVM_ACC_PUBLIC)       != 0;
4447   const bool is_private      = (flags & JVM_ACC_PRIVATE)      != 0;
4448   const bool is_static       = (flags & JVM_ACC_STATIC)       != 0;
4449   const bool is_final        = (flags & JVM_ACC_FINAL)        != 0;
4450   const bool is_native       = (flags & JVM_ACC_NATIVE)       != 0;
4451   const bool is_abstract     = (flags & JVM_ACC_ABSTRACT)     != 0;
4452   const bool is_bridge       = (flags & JVM_ACC_BRIDGE)       != 0;
4453   const bool is_strict       = (flags & JVM_ACC_STRICT)       != 0;
4454   const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
4455   const bool is_protected    = (flags & JVM_ACC_PROTECTED)    != 0;
4456   const bool major_gte_1_5   = _major_version >= JAVA_1_5_VERSION;
4457   const bool major_gte_8     = _major_version >= JAVA_8_VERSION;
4458   const bool major_gte_17    = _major_version >= JAVA_17_VERSION;
4459   const bool is_initializer  = (name == vmSymbols::object_initializer_name());


4460 
4461   bool is_illegal = false;

4462 
4463   if (is_interface) {
4464     if (major_gte_8) {
4465       // Class file version is JAVA_8_VERSION or later Methods of
4466       // interfaces may set any of the flags except ACC_PROTECTED,
4467       // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must
4468       // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.
4469       if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
4470           (is_native || is_protected || is_final || is_synchronized) ||
4471           // If a specific method of a class or interface has its
4472           // ACC_ABSTRACT flag set, it must not have any of its
4473           // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,
4474           // ACC_STRICT, or ACC_SYNCHRONIZED flags set.  No need to
4475           // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as
4476           // those flags are illegal irrespective of ACC_ABSTRACT being set or not.
4477           (is_abstract && (is_private || is_static || (!major_gte_17 && is_strict)))) {
4478         is_illegal = true;
4479       }
4480     } else if (major_gte_1_5) {
4481       // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)
4482       if (!is_public || is_private || is_protected || is_static || is_final ||
4483           is_synchronized || is_native || !is_abstract || is_strict) {
4484         is_illegal = true;
4485       }
4486     } else {
4487       // Class file version is pre-JAVA_1_5_VERSION
4488       if (!is_public || is_static || is_final || is_native || !is_abstract) {
4489         is_illegal = true;
4490       }
4491     }
4492   } else { // not interface
4493     if (has_illegal_visibility(flags)) {
4494       is_illegal = true;
4495     } else {
4496       if (is_initializer) {
4497         if (is_static || is_final || is_synchronized || is_native ||
4498             is_abstract || (major_gte_1_5 && is_bridge)) {
4499           is_illegal = true;
4500         }
4501       } else { // not initializer
4502         if (is_abstract) {
4503           if ((is_final || is_native || is_private || is_static ||
4504               (major_gte_1_5 && (is_synchronized || (!major_gte_17 && is_strict))))) {
4505             is_illegal = true;





4506           }
4507         }
4508       }
4509     }
4510   }
4511 
4512   if (is_illegal) {
4513     ResourceMark rm(THREAD);
4514     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4515     Exceptions::fthrow(
4516       THREAD_AND_LOCATION,
4517       vmSymbols::java_lang_ClassFormatError(),
4518       "Method %s in class %s has illegal modifiers: 0x%X",
4519       name->as_C_string(), _class_name->as_C_string(), flags);
4520     return;
4521   }
4522 }
4523 
4524 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer,
4525                                         int length,
4526                                         TRAPS) const {
4527   assert(_need_verify, "only called when _need_verify is true");
4528   // Note: 0 <= length < 64K, as it comes from a u2 entry in the CP.
4529   if (!UTF8::is_legal_utf8(buffer, static_cast<size_t>(length), _major_version <= 47)) {
4530     classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", THREAD);
4531   }
4532 }
4533 
4534 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
4535 // In class names, '/' separates unqualified names.  This is verified in this function also.
4536 // Method names also may not contain the characters '<' or '>', unless <init>
4537 // or <clinit>.  Note that method names may not be <init> or <clinit> in this
4538 // method.  Because these names have been checked as special cases before
4539 // calling this method in verify_legal_method_name.

4557         if (type == ClassFileParser::LegalClass) {
4558           if (p == name || p+1 >= name+length ||
4559               *(p+1) == JVM_SIGNATURE_SLASH) {
4560             return false;
4561           }
4562         } else {
4563           return false;   // do not permit '/' unless it's class name
4564         }
4565         break;
4566       case JVM_SIGNATURE_SPECIAL:
4567       case JVM_SIGNATURE_ENDSPECIAL:
4568         // do not permit '<' or '>' in method names
4569         if (type == ClassFileParser::LegalMethod) {
4570           return false;
4571         }
4572     }
4573   }
4574   return true;
4575 }
4576 









4577 // Take pointer to a UTF8 byte string (not NUL-terminated).
4578 // Skip over the longest part of the string that could
4579 // be taken as a fieldname. Allow non-trailing '/'s if slash_ok is true.
4580 // Return a pointer to just past the fieldname.
4581 // Return null if no fieldname at all was found, or in the case of slash_ok
4582 // being true, we saw consecutive slashes (meaning we were looking for a
4583 // qualified path but found something that was badly-formed).
4584 static const char* skip_over_field_name(const char* const name,
4585                                         bool slash_ok,
4586                                         unsigned int length) {
4587   const char* p;
4588   jboolean last_is_slash = false;
4589   jboolean not_first_ch = false;
4590 
4591   for (p = name; p != name + length; not_first_ch = true) {
4592     const char* old_p = p;
4593     jchar ch = *p;
4594     if (ch < 128) {
4595       p++;
4596       // quick check for ascii

4658 // be taken as a field signature. Allow "void" if void_ok.
4659 // Return a pointer to just past the signature.
4660 // Return null if no legal signature is found.
4661 const char* ClassFileParser::skip_over_field_signature(const char* signature,
4662                                                        bool void_ok,
4663                                                        unsigned int length,
4664                                                        TRAPS) const {
4665   unsigned int array_dim = 0;
4666   while (length > 0) {
4667     switch (signature[0]) {
4668     case JVM_SIGNATURE_VOID: if (!void_ok) { return nullptr; }
4669     case JVM_SIGNATURE_BOOLEAN:
4670     case JVM_SIGNATURE_BYTE:
4671     case JVM_SIGNATURE_CHAR:
4672     case JVM_SIGNATURE_SHORT:
4673     case JVM_SIGNATURE_INT:
4674     case JVM_SIGNATURE_FLOAT:
4675     case JVM_SIGNATURE_LONG:
4676     case JVM_SIGNATURE_DOUBLE:
4677       return signature + 1;
4678     case JVM_SIGNATURE_CLASS: {

4679       if (_major_version < JAVA_1_5_VERSION) {
4680         signature++;
4681         length--;
4682         // Skip over the class name if one is there
4683         const char* const p = skip_over_field_name(signature, true, length);
4684         assert(p == nullptr || p > signature, "must parse one character at least");
4685         // The next character better be a semicolon
4686         if (p != nullptr                             && // Parse of field name succeeded.
4687             p - signature < static_cast<int>(length) && // There is at least one character left to parse.
4688             p[0] == JVM_SIGNATURE_ENDCLASS) {
4689           return p + 1;
4690         }
4691       }
4692       else {
4693         // Skip leading 'L' and ignore first appearance of ';'
4694         signature++;
4695         const char* c = (const char*) memchr(signature, JVM_SIGNATURE_ENDCLASS, length - 1);
4696         // Format check signature
4697         if (c != nullptr) {
4698           int newlen = pointer_delta_as_int(c, (char*) signature);

4823     } else {
4824       // 4881221: relax the constraints based on JSR202 spec
4825       legal = verify_unqualified_name(bytes, length, LegalMethod);
4826     }
4827   }
4828 
4829   if (!legal) {
4830     ResourceMark rm(THREAD);
4831     assert(_class_name != nullptr, "invariant");
4832     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4833     Exceptions::fthrow(
4834       THREAD_AND_LOCATION,
4835       vmSymbols::java_lang_ClassFormatError(),
4836       "Illegal method name \"%.*s\" in class %s", length, bytes,
4837       _class_name->as_C_string()
4838     );
4839     return;
4840   }
4841 }
4842 










4843 
4844 // Checks if signature is a legal field signature.
4845 void ClassFileParser::verify_legal_field_signature(const Symbol* name,
4846                                                    const Symbol* signature,
4847                                                    TRAPS) const {
4848   if (!_need_verify) { return; }
4849 
4850   const char* const bytes = (const char*)signature->bytes();
4851   const unsigned int length = signature->utf8_length();
4852   const char* const p = skip_over_field_signature(bytes, false, length, CHECK);
4853 
4854   if (p == nullptr || (p - bytes) != (int)length) {
4855     throwIllegalSignature("Field", name, signature, CHECK);
4856   }
4857 }
4858 
4859 // Check that the signature is compatible with the method name.  For example,
4860 // check that <init> has a void signature.
4861 void ClassFileParser::verify_legal_name_with_signature(const Symbol* name,
4862                                                        const Symbol* signature,
4863                                                        TRAPS) const {
4864   if (!_need_verify) {
4865     return;
4866   }
4867 
4868   // Class initializers cannot have args for class format version >= 51.
4869   if (name == vmSymbols::class_initializer_name() &&
4870       signature != vmSymbols::void_method_signature() &&
4871       _major_version >= JAVA_7_VERSION) {
4872     throwIllegalSignature("Method", name, signature, THREAD);
4873     return;
4874   }

4911       length -= pointer_delta_as_int(nextp, p);
4912       p = nextp;
4913       nextp = skip_over_field_signature(p, false, length, CHECK_0);
4914     }
4915     // The first non-signature thing better be a ')'
4916     if ((length > 0) && (*p++ == JVM_SIGNATURE_ENDFUNC)) {
4917       length--;
4918       // Now we better just have a return value
4919       nextp = skip_over_field_signature(p, true, length, CHECK_0);
4920       if (nextp && ((int)length == (nextp - p))) {
4921         return args_size;
4922       }
4923     }
4924   }
4925   // Report error
4926   throwIllegalSignature("Method", name, signature, THREAD);
4927   return 0;
4928 }
4929 
4930 int ClassFileParser::static_field_size() const {
4931   assert(_field_info != nullptr, "invariant");
4932   return _field_info->_static_field_size;
4933 }
4934 
4935 int ClassFileParser::total_oop_map_count() const {
4936   assert(_field_info != nullptr, "invariant");
4937   return _field_info->oop_map_blocks->_nonstatic_oop_map_count;
4938 }
4939 
4940 jint ClassFileParser::layout_size() const {
4941   assert(_field_info != nullptr, "invariant");
4942   return _field_info->_instance_size;
4943 }
4944 
4945 static void check_methods_for_intrinsics(const InstanceKlass* ik,
4946                                          const Array<Method*>* methods) {
4947   assert(ik != nullptr, "invariant");
4948   assert(methods != nullptr, "invariant");
4949 
4950   // Set up Method*::intrinsic_id as soon as we know the names of methods.
4951   // (We used to do this lazily, but now we query it in Rewriter,
4952   // which is eagerly done for every method, so we might as well do it now,
4953   // when everything is fresh in memory.)
4954   const vmSymbolID klass_id = Method::klass_id_for_intrinsics(ik);
4955 
4956   if (klass_id != vmSymbolID::NO_SID) {
4957     for (int j = 0; j < methods->length(); ++j) {
4958       Method* method = methods->at(j);
4959       method->init_intrinsic_id(klass_id);
4960 
4961       if (CheckIntrinsics) {
4962         // Check if an intrinsic is defined for method 'method',

5037   }
5038 }
5039 
5040 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook,
5041                                                       const ClassInstanceInfo& cl_inst_info,
5042                                                       TRAPS) {
5043   if (_klass != nullptr) {
5044     return _klass;
5045   }
5046 
5047   InstanceKlass* const ik =
5048     InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
5049 
5050   if (is_hidden()) {
5051     mangle_hidden_class_name(ik);
5052   }
5053 
5054   fill_instance_klass(ik, changed_by_loadhook, cl_inst_info, CHECK_NULL);
5055 
5056   assert(_klass == ik, "invariant");
5057 
5058   return ik;
5059 }
5060 






















































































































5061 void ClassFileParser::fill_instance_klass(InstanceKlass* ik,
5062                                           bool changed_by_loadhook,
5063                                           const ClassInstanceInfo& cl_inst_info,
5064                                           TRAPS) {
5065   assert(ik != nullptr, "invariant");
5066 
5067   // Set name and CLD before adding to CLD
5068   ik->set_class_loader_data(_loader_data);
5069   ik->set_class_loader_type();
5070   ik->set_name(_class_name);
5071 
5072   // Add all classes to our internal class loader list here,
5073   // including classes in the bootstrap (null) class loader.
5074   const bool publicize = !is_internal();
5075 
5076   _loader_data->add_class(ik, publicize);
5077 
5078   set_klass_to_deallocate(ik);
5079 
5080   assert(_field_info != nullptr, "invariant");
5081   assert(ik->static_field_size() == _field_info->_static_field_size, "sanity");
5082   assert(ik->nonstatic_oop_map_count() == _field_info->oop_map_blocks->_nonstatic_oop_map_count,
5083          "sanity");
5084 
5085   assert(ik->is_instance_klass(), "sanity");
5086   assert(ik->size_helper() == _field_info->_instance_size, "sanity");
5087 
5088   // Fill in information already parsed
5089   ik->set_should_verify_class(_need_verify);
5090 
5091   // Not yet: supers are done below to support the new subtype-checking fields
5092   ik->set_nonstatic_field_size(_field_info->_nonstatic_field_size);
5093   ik->set_has_nonstatic_fields(_field_info->_has_nonstatic_fields);










5094   ik->set_static_oop_field_count(_static_oop_count);
5095 
5096   // this transfers ownership of a lot of arrays from
5097   // the parser onto the InstanceKlass*
5098   apply_parsed_class_metadata(ik, _java_fields_count);
5099 
5100   // can only set dynamic nest-host after static nest information is set
5101   if (cl_inst_info.dynamic_nest_host() != nullptr) {
5102     ik->set_nest_host(cl_inst_info.dynamic_nest_host());
5103   }
5104 
5105   // note that is not safe to use the fields in the parser from this point on
5106   assert(nullptr == _cp, "invariant");
5107   assert(nullptr == _fieldinfo_stream, "invariant");
5108   assert(nullptr == _fieldinfo_search_table, "invariant");
5109   assert(nullptr == _fields_status, "invariant");
5110   assert(nullptr == _methods, "invariant");
5111   assert(nullptr == _inner_classes, "invariant");
5112   assert(nullptr == _nest_members, "invariant");

5113   assert(nullptr == _combined_annotations, "invariant");
5114   assert(nullptr == _record_components, "invariant");
5115   assert(nullptr == _permitted_subclasses, "invariant");

5116 
5117   if (_has_localvariable_table) {
5118     ik->set_has_localvariable_table(true);
5119   }
5120 
5121   if (_has_final_method) {
5122     ik->set_has_final_method();
5123   }
5124 
5125   ik->copy_method_ordering(_method_ordering, CHECK);
5126   // The InstanceKlass::_methods_jmethod_ids cache
5127   // is managed on the assumption that the initial cache
5128   // size is equal to the number of methods in the class. If
5129   // that changes, then InstanceKlass::idnum_can_increment()
5130   // has to be changed accordingly.
5131   ik->set_initial_method_idnum(checked_cast<u2>(ik->methods()->length()));
5132 
5133   ik->set_this_class_index(_this_class_index);
5134 
5135   if (_is_hidden) {

5172   if ((_num_miranda_methods > 0) ||
5173       // if this class introduced new miranda methods or
5174       (_super_klass != nullptr && _super_klass->has_miranda_methods())
5175         // super class exists and this class inherited miranda methods
5176      ) {
5177        ik->set_has_miranda_methods(); // then set a flag
5178   }
5179 
5180   // Fill in information needed to compute superclasses.
5181   ik->initialize_supers(const_cast<InstanceKlass*>(_super_klass), _transitive_interfaces, CHECK);
5182   ik->set_transitive_interfaces(_transitive_interfaces);
5183   ik->set_local_interfaces(_local_interfaces);
5184   _transitive_interfaces = nullptr;
5185   _local_interfaces = nullptr;
5186 
5187   // Initialize itable offset tables
5188   klassItable::setup_itable_offset_table(ik);
5189 
5190   // Compute transitive closure of interfaces this class implements
5191   // Do final class setup
5192   OopMapBlocksBuilder* oop_map_blocks = _field_info->oop_map_blocks;
5193   if (oop_map_blocks->_nonstatic_oop_map_count > 0) {
5194     oop_map_blocks->copy(ik->start_of_nonstatic_oop_maps());
5195   }
5196 
5197   if (_has_contended_fields || _parsed_annotations->is_contended() ||
5198       ( _super_klass != nullptr && _super_klass->has_contended_annotations())) {
5199     ik->set_has_contended_annotations(true);
5200   }
5201 
5202   // Fill in has_finalizer and layout_helper
5203   set_precomputed_flags(ik);
5204 
5205   // check if this class can access its super class
5206   check_super_class_access(ik, CHECK);
5207 
5208   // check if this class can access its superinterfaces
5209   check_super_interface_access(ik, CHECK);
5210 
5211   // check if this class overrides any final method
5212   check_final_method_override(ik, CHECK);

5233 
5234   assert(_all_mirandas != nullptr, "invariant");
5235 
5236   // Generate any default methods - default methods are public interface methods
5237   // that have a default implementation.  This is new with Java 8.
5238   if (_has_nonstatic_concrete_methods) {
5239     DefaultMethods::generate_default_methods(ik,
5240                                              _all_mirandas,
5241                                              CHECK);
5242   }
5243 
5244   // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5245   if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5246       !module_entry->has_default_read_edges()) {
5247     if (!module_entry->set_has_default_read_edges()) {
5248       // We won a potential race
5249       JvmtiExport::add_default_read_edges(module_handle, THREAD);
5250     }
5251   }
5252 



























5253   ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5254 
5255   if (!is_internal()) {
5256     ik->print_class_load_logging(_loader_data, module_entry, _stream);
5257     if (CDSConfig::is_dumping_archive()) {
5258       SystemDictionaryShared::check_code_source(ik, _stream);
5259     }
5260 
5261     if (ik->minor_version() == JAVA_PREVIEW_MINOR_VERSION &&
5262         ik->major_version() == JVM_CLASSFILE_MAJOR_VERSION &&
5263         log_is_enabled(Info, class, preview)) {
5264       ResourceMark rm;
5265       log_info(class, preview)("Loading class %s that depends on preview features (class file version %d.65535)",
5266                                ik->external_name(), JVM_CLASSFILE_MAJOR_VERSION);
5267     }
5268 
5269     if (log_is_enabled(Debug, class, resolve))  {
5270       ResourceMark rm;
5271       // print out the superclass.
5272       const char * from = ik->external_name();

5316                                  const ClassLoadInfo* cl_info,
5317                                  Publicity pub_level,
5318                                  TRAPS) :
5319   _stream(stream),
5320   _class_name(nullptr),
5321   _loader_data(loader_data),
5322   _is_hidden(cl_info->is_hidden()),
5323   _can_access_vm_annotations(cl_info->can_access_vm_annotations()),
5324   _orig_cp_size(0),
5325   _static_oop_count(0),
5326   _super_klass(),
5327   _cp(nullptr),
5328   _fieldinfo_stream(nullptr),
5329   _fieldinfo_search_table(nullptr),
5330   _fields_status(nullptr),
5331   _methods(nullptr),
5332   _inner_classes(nullptr),
5333   _nest_members(nullptr),
5334   _nest_host(0),
5335   _permitted_subclasses(nullptr),

5336   _record_components(nullptr),
5337   _local_interfaces(nullptr),
5338   _transitive_interfaces(nullptr),
5339   _combined_annotations(nullptr),
5340   _class_annotations(nullptr),
5341   _class_type_annotations(nullptr),
5342   _fields_annotations(nullptr),
5343   _fields_type_annotations(nullptr),
5344   _klass(nullptr),
5345   _klass_to_deallocate(nullptr),
5346   _parsed_annotations(nullptr),
5347   _field_info(nullptr),

5348   _temp_field_info(nullptr),
5349   _method_ordering(nullptr),
5350   _all_mirandas(nullptr),
5351   _vtable_size(0),
5352   _itable_size(0),
5353   _num_miranda_methods(0),
5354   _protection_domain(cl_info->protection_domain()),
5355   _access_flags(),
5356   _pub_level(pub_level),
5357   _bad_constant_seen(0),
5358   _synthetic_flag(false),
5359   _sde_length(false),
5360   _sde_buffer(nullptr),
5361   _sourcefile_index(0),
5362   _generic_signature_index(0),
5363   _major_version(0),
5364   _minor_version(0),
5365   _this_class_index(0),
5366   _super_class_index(0),
5367   _itfs_len(0),
5368   _java_fields_count(0),
5369   _need_verify(false),
5370   _has_nonstatic_concrete_methods(false),
5371   _declares_nonstatic_concrete_methods(false),
5372   _has_localvariable_table(false),
5373   _has_final_method(false),
5374   _has_contended_fields(false),
5375   _has_aot_runtime_setup_method(false),




5376   _has_finalizer(false),
5377   _has_empty_finalizer(false),
5378   _max_bootstrap_specifier_index(-1) {
5379 
5380   _class_name = name != nullptr ? name : vmSymbols::unknown_class_name();
5381   _class_name->increment_refcount();
5382 
5383   assert(_loader_data != nullptr, "invariant");
5384   assert(stream != nullptr, "invariant");
5385   assert(_stream != nullptr, "invariant");
5386   assert(_stream->buffer() == _stream->current(), "invariant");
5387   assert(_class_name != nullptr, "invariant");
5388   assert(0 == _access_flags.as_unsigned_short(), "invariant");
5389 
5390   // Figure out whether we can skip format checking (matching classic VM behavior)
5391   // Always verify CFLH bytes from the user agents.
5392   _need_verify = stream->from_class_file_load_hook() ? true : Verifier::should_verify_for(_loader_data->class_loader());
5393 
5394   // synch back verification state to stream to check for truncation.
5395   stream->set_need_verify(_need_verify);
5396 
5397   parse_stream(stream, CHECK);
5398 
5399   post_process_parsed_stream(stream, _cp, CHECK);
5400 }
5401 
5402 void ClassFileParser::clear_class_metadata() {
5403   // metadata created before the instance klass is created.  Must be
5404   // deallocated if classfile parsing returns an error.
5405   _cp = nullptr;
5406   _fieldinfo_stream = nullptr;
5407   _fieldinfo_search_table = nullptr;
5408   _fields_status = nullptr;
5409   _methods = nullptr;
5410   _inner_classes = nullptr;
5411   _nest_members = nullptr;
5412   _permitted_subclasses = nullptr;

5413   _combined_annotations = nullptr;
5414   _class_annotations = _class_type_annotations = nullptr;
5415   _fields_annotations = _fields_type_annotations = nullptr;
5416   _record_components = nullptr;

5417 }
5418 
5419 // Destructor to clean up
5420 ClassFileParser::~ClassFileParser() {
5421   _class_name->decrement_refcount();
5422 
5423   if (_cp != nullptr) {
5424     MetadataFactory::free_metadata(_loader_data, _cp);
5425   }
5426 
5427   if (_fieldinfo_stream != nullptr) {
5428     MetadataFactory::free_array<u1>(_loader_data, _fieldinfo_stream);
5429   }
5430   MetadataFactory::free_array<u1>(_loader_data, _fieldinfo_search_table);
5431 
5432   if (_fields_status != nullptr) {
5433     MetadataFactory::free_array<FieldStatus>(_loader_data, _fields_status);
5434   }
5435 




5436   if (_methods != nullptr) {
5437     // Free methods
5438     InstanceKlass::deallocate_methods(_loader_data, _methods);
5439   }
5440 
5441   // beware of the Universe::empty_blah_array!!
5442   if (_inner_classes != nullptr && _inner_classes != Universe::the_empty_short_array()) {
5443     MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
5444   }
5445 
5446   if (_nest_members != nullptr && _nest_members != Universe::the_empty_short_array()) {
5447     MetadataFactory::free_array<u2>(_loader_data, _nest_members);
5448   }
5449 
5450   if (_record_components != nullptr) {
5451     InstanceKlass::deallocate_record_components(_loader_data, _record_components);
5452   }
5453 
5454   if (_permitted_subclasses != nullptr && _permitted_subclasses != Universe::the_empty_short_array()) {
5455     MetadataFactory::free_array<u2>(_loader_data, _permitted_subclasses);
5456   }
5457 




5458   // Free interfaces
5459   InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
5460                                        _local_interfaces, _transitive_interfaces);
5461 
5462   if (_combined_annotations != nullptr) {
5463     // After all annotations arrays have been created, they are installed into the
5464     // Annotations object that will be assigned to the InstanceKlass being created.
5465 
5466     // Deallocate the Annotations object and the installed annotations arrays.
5467     _combined_annotations->deallocate_contents(_loader_data);
5468 
5469     // If the _combined_annotations pointer is non-null,
5470     // then the other annotations fields should have been cleared.
5471     assert(_class_annotations       == nullptr, "Should have been cleared");
5472     assert(_class_type_annotations  == nullptr, "Should have been cleared");
5473     assert(_fields_annotations      == nullptr, "Should have been cleared");
5474     assert(_fields_type_annotations == nullptr, "Should have been cleared");
5475   } else {
5476     // If the annotations arrays were not installed into the Annotations object,
5477     // then they have to be deallocated explicitly.

5537 
5538   assert(cp_size == (u2)cp->length(), "invariant");
5539 
5540   // ACCESS FLAGS
5541   stream->guarantee_more(8, CHECK);  // flags, this_class, super_class, infs_len
5542 
5543   // Access flags
5544   u2 flags;
5545   // JVM_ACC_MODULE is defined in JDK-9 and later.
5546   if (_major_version >= JAVA_9_VERSION) {
5547     flags = stream->get_u2_fast() & (JVM_RECOGNIZED_CLASS_MODIFIERS | JVM_ACC_MODULE);
5548   } else {
5549     flags = stream->get_u2_fast() & JVM_RECOGNIZED_CLASS_MODIFIERS;
5550   }
5551 
5552   if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
5553     // Set abstract bit for old class files for backward compatibility
5554     flags |= JVM_ACC_ABSTRACT;
5555   }
5556 









5557   verify_legal_class_modifiers(flags, nullptr, false, CHECK);
5558 
5559   short bad_constant = class_bad_constant_seen();
5560   if (bad_constant != 0) {
5561     // Do not throw CFE until after the access_flags are checked because if
5562     // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
5563     classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, THREAD);
5564     return;
5565   }
5566 
5567   _access_flags.set_flags(flags);
5568 
5569   // This class and superclass
5570   _this_class_index = stream->get_u2_fast();
5571   guarantee_property(
5572     valid_cp_range(_this_class_index, cp_size) &&
5573       cp->tag_at(_this_class_index).is_unresolved_klass(),
5574     "Invalid this class index %u in constant pool in class file %s",
5575     _this_class_index, CHECK);
5576 

5644 
5645   // SUPERKLASS
5646   _super_class_index = stream->get_u2_fast();
5647   check_super_class(cp,
5648                     _super_class_index,
5649                     _need_verify,
5650                     CHECK);
5651 
5652   // Interfaces
5653   _itfs_len = stream->get_u2_fast();
5654   parse_interfaces(stream,
5655                    _itfs_len,
5656                    cp,
5657                    &_has_nonstatic_concrete_methods,
5658                    CHECK);
5659 
5660   assert(_local_interfaces != nullptr, "invariant");
5661 
5662   // Fields (offsets are filled in later)
5663   parse_fields(stream,
5664                _access_flags.is_interface(),
5665                cp,
5666                cp_size,
5667                &_java_fields_count,
5668                CHECK);
5669 
5670   assert(_temp_field_info != nullptr, "invariant");
5671 
5672   // Methods
5673   parse_methods(stream,
5674                 _access_flags.is_interface(),
5675                 &_has_localvariable_table,
5676                 &_has_final_method,
5677                 &_declares_nonstatic_concrete_methods,
5678                 CHECK);
5679 
5680   assert(_methods != nullptr, "invariant");
5681 
5682   if (_declares_nonstatic_concrete_methods) {
5683     _has_nonstatic_concrete_methods = true;
5684   }

5764       // errors not checked yet.
5765       guarantee_property(super_class_name == vmSymbols::java_lang_Object(),
5766         "Interfaces must have java.lang.Object as superclass in class file %s",
5767         CHECK);
5768     }
5769     Handle loader(THREAD, _loader_data->class_loader());
5770     if (loader.is_null() && super_class_name == vmSymbols::java_lang_Object()) {
5771       // fast path to avoid lookup
5772       _super_klass = vmClasses::Object_klass();
5773     } else {
5774       _super_klass = (const InstanceKlass*)
5775                        SystemDictionary::resolve_super_or_fail(_class_name,
5776                                                                super_class_name,
5777                                                                loader,
5778                                                                true,
5779                                                                CHECK);
5780     }
5781   }
5782 
5783   if (_super_klass != nullptr) {




















5784     if (_super_klass->has_nonstatic_concrete_methods()) {
5785       _has_nonstatic_concrete_methods = true;
5786     }

5787 
5788     if (_super_klass->is_interface()) {
5789       classfile_icce_error("class %s has interface %s as super class", _super_klass, THREAD);
5790       return;





















5791     }
5792   }
5793 
5794   // Compute the transitive list of all unique interfaces implemented by this class
5795   _transitive_interfaces =
5796     compute_transitive_interfaces(_super_klass,
5797                                   _local_interfaces,
5798                                   _loader_data,
5799                                   CHECK);
5800 
5801   assert(_transitive_interfaces != nullptr, "invariant");
5802 
5803   // sort methods
5804   _method_ordering = sort_methods(_methods);
5805 
5806   _all_mirandas = new GrowableArray<Method*>(20);
5807 
5808   Handle loader(THREAD, _loader_data->class_loader());
5809   klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
5810                                                     &_num_miranda_methods,
5811                                                     _all_mirandas,
5812                                                     _super_klass,
5813                                                     _methods,
5814                                                     _access_flags,
5815                                                     _major_version,
5816                                                     loader,
5817                                                     _class_name,
5818                                                     _local_interfaces);
5819 
5820   // Size of Java itable (in words)
5821   _itable_size = _access_flags.is_interface() ? 0 :
5822     klassItable::compute_itable_size(_transitive_interfaces);
5823 
5824   assert(_parsed_annotations != nullptr, "invariant");
5825 
5826   _field_info = new FieldLayoutInfo();
5827   FieldLayoutBuilder lb(class_name(), super_klass(), _cp, /*_fields*/ _temp_field_info,
5828                         _parsed_annotations->is_contended(), _field_info);






5829   lb.build_layout();
5830 








5831   int injected_fields_count = _temp_field_info->length() - _java_fields_count;
5832   _fieldinfo_stream =
5833     FieldInfoStream::create_FieldInfoStream(_temp_field_info, _java_fields_count,
5834                                             injected_fields_count, loader_data(), CHECK);
5835   _fieldinfo_search_table = FieldInfoStream::create_search_table(_cp, _fieldinfo_stream, _loader_data, CHECK);
5836   _fields_status =
5837     MetadataFactory::new_array<FieldStatus>(_loader_data, _temp_field_info->length(),
5838                                             FieldStatus(0), CHECK);





















































































































5839 }
5840 
5841 void ClassFileParser::set_klass(InstanceKlass* klass) {
5842 
5843 #ifdef ASSERT
5844   if (klass != nullptr) {
5845     assert(nullptr == _klass, "leaking?");
5846   }
5847 #endif
5848 
5849   _klass = klass;
5850 }
5851 















5852 void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) {
5853 
5854 #ifdef ASSERT
5855   if (klass != nullptr) {
5856     assert(nullptr == _klass_to_deallocate, "leaking?");
5857   }
5858 #endif
5859 
5860   _klass_to_deallocate = klass;
5861 }
5862 
5863 // Caller responsible for ResourceMark
5864 // clone stream with rewound position
5865 const ClassFileStream* ClassFileParser::clone_stream() const {
5866   assert(_stream != nullptr, "invariant");
5867 
5868   return _stream->clone();
5869 }
5870 
5871 ReferenceType ClassFileParser::super_reference_type() const {

   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 "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/systemDictionaryShared.hpp"
  39 #include "classfile/verificationType.hpp"
  40 #include "classfile/verifier.hpp"
  41 #include "classfile/vmClasses.hpp"
  42 #include "classfile/vmSymbols.hpp"
  43 #include "jvm.h"
  44 #include "logging/log.hpp"
  45 #include "logging/logStream.hpp"
  46 #include "memory/allocation.hpp"
  47 #include "memory/metadataFactory.hpp"
  48 #include "memory/oopFactory.hpp"
  49 #include "memory/resourceArea.hpp"
  50 #include "memory/universe.hpp"
  51 #include "oops/annotations.hpp"
  52 #include "oops/bsmAttribute.inline.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/exceptions.hpp"
  85 #include "utilities/formatBuffer.hpp"
  86 #include "utilities/globalDefinitions.hpp"
  87 #include "utilities/growableArray.hpp"
  88 #include "utilities/hashTable.hpp"
  89 #include "utilities/macros.hpp"
  90 #include "utilities/ostream.hpp"
  91 #include "utilities/stringUtils.hpp"
  92 #include "utilities/utf8.hpp"
  93 
  94 // We generally try to create the oops directly when parsing, rather than
  95 // allocating temporary data structures and copying the bytes twice. A
  96 // temporary area is only needed when parsing utf8 entries in the constant
  97 // pool and when parsing line number tables.
  98 
  99 // We add assert in debug mode when class format is not checked.
 100 
 101 #define JAVA_CLASSFILE_MAGIC              0xCAFEBABE
 102 #define JAVA_MIN_SUPPORTED_VERSION        45
 103 #define JAVA_PREVIEW_MINOR_VERSION        65535
 104 
 105 // Used for two backward compatibility reasons:
 106 // - to check for new additions to the class file format in JDK1.5
 107 // - to check for bug fixes in the format checker in JDK1.5
 108 #define JAVA_1_5_VERSION                  49
 109 
 110 // Used for backward compatibility reasons:
 111 // - to check for javac bug fixes that happened after 1.5

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

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

1360   }
1361 
1362   *constantvalue_index_addr = constantvalue_index;
1363   *is_synthetic_addr = is_synthetic;
1364   *generic_signature_index_addr = generic_signature_index;
1365   AnnotationArray* a = allocate_annotations(runtime_visible_annotations,
1366                                             runtime_visible_annotations_length,
1367                                             CHECK);
1368   parsed_annotations->set_field_annotations(a);
1369   a = allocate_annotations(runtime_visible_type_annotations,
1370                            runtime_visible_type_annotations_length,
1371                            CHECK);
1372   parsed_annotations->set_field_type_annotations(a);
1373   return;
1374 }
1375 
1376 
1377 // Side-effects: populates the _fields, _fields_annotations,
1378 // _fields_type_annotations fields
1379 void ClassFileParser::parse_fields(const ClassFileStream* const cfs,
1380                                    AccessFlags class_access_flags,
1381                                    ConstantPool* cp,
1382                                    const int cp_size,
1383                                    u2* const java_fields_count_ptr,
1384                                    TRAPS) {
1385 
1386   assert(cfs != nullptr, "invariant");
1387   assert(cp != nullptr, "invariant");
1388   assert(java_fields_count_ptr != nullptr, "invariant");
1389 
1390   assert(nullptr == _fields_annotations, "invariant");
1391   assert(nullptr == _fields_type_annotations, "invariant");
1392 
1393   // "inline type" means concrete value class
1394   bool is_inline_type = !class_access_flags.is_identity_class() && !class_access_flags.is_abstract();
1395   // "value class" can be either abstract or concrete value class
1396   bool is_value_class = !class_access_flags.is_identity_class() && !class_access_flags.is_interface();
1397   cfs->guarantee_more(2, CHECK);  // length
1398   const u2 length = cfs->get_u2_fast();
1399   *java_fields_count_ptr = length;
1400 
1401   int num_injected = 0;
1402   const InjectedField* const injected = JavaClasses::get_injected(_class_name,
1403                                                                   &num_injected);
1404 
1405   // Two more slots are required for inline classes:
1406   //   - The static field ".null_reset" which carries the nullable flat layout
1407   //     representation of null, added below
1408   //   - The nonstatic field ".empty" the JVM injects when detecting an empty
1409   //     inline class, added in FieldLayoutBuilder::compute_inline_class_layout
1410   // One more slot is required for both abstract value class and inline classes:
1411   //   - The static field ".acmp_maps" for acmp and identity hash, tracks
1412   //     nonstatic fields both inherited or declared, added below
1413   const int total_fields = length + num_injected + (is_inline_type ? 2 : 0)
1414                            + (is_value_class ? 1 : 0);
1415 
1416   // Allocate a temporary resource array to collect field data.
1417   // After parsing all fields, data are stored in a UNSIGNED5 compressed stream.
1418   _temp_field_info = new GrowableArray<FieldInfo>(total_fields);
1419 
1420   ResourceMark rm(THREAD);
1421   for (int n = 0; n < length; n++) {
1422     // access_flags, name_index, descriptor_index, attributes_count
1423     cfs->guarantee_more(8, CHECK);
1424 
1425     jint recognized_modifiers = JVM_RECOGNIZED_FIELD_MODIFIERS;
1426     if (!supports_inline_types()) {
1427       recognized_modifiers &= ~JVM_ACC_STRICT_INIT;
1428     }
1429 
1430     const jint flags = cfs->get_u2_fast() & recognized_modifiers;
1431     verify_legal_field_modifiers(flags, class_access_flags, CHECK);
1432     AccessFlags access_flags;


1433     access_flags.set_flags(flags);
1434     FieldInfo::FieldFlags fieldFlags(0);
1435 
1436     const u2 name_index = cfs->get_u2_fast();
1437     guarantee_property(valid_symbol_at(name_index),
1438       "Invalid constant pool index %u for field name in class file %s",
1439       name_index, CHECK);
1440     const Symbol* const name = cp->symbol_at(name_index);
1441     verify_legal_field_name(name, CHECK);
1442 
1443     const u2 signature_index = cfs->get_u2_fast();
1444     guarantee_property(valid_symbol_at(signature_index),
1445       "Invalid constant pool index %u for field signature in class file %s",
1446       signature_index, CHECK);
1447     const Symbol* const sig = cp->symbol_at(signature_index);
1448     verify_legal_field_signature(name, sig, CHECK);
1449 
1450     u2 constantvalue_index = 0;
1451     bool is_synthetic = false;
1452     u2 generic_signature_index = 0;
1453     const bool is_static = access_flags.is_static();
1454     FieldAnnotationCollector parsed_annotations(_loader_data);
1455 
1456     bool is_null_restricted = false;
1457 
1458     const u2 attributes_count = cfs->get_u2_fast();
1459     if (attributes_count > 0) {
1460       parse_field_attributes(cfs,
1461                              attributes_count,
1462                              is_static,
1463                              signature_index,
1464                              &constantvalue_index,
1465                              &is_synthetic,
1466                              &generic_signature_index,
1467                              &parsed_annotations,
1468                              CHECK);
1469 
1470       if (parsed_annotations.field_annotations() != nullptr) {
1471         if (_fields_annotations == nullptr) {
1472           _fields_annotations = MetadataFactory::new_array<AnnotationArray*>(
1473                                              _loader_data, length, nullptr,
1474                                              CHECK);
1475         }
1476         _fields_annotations->at_put(n, parsed_annotations.field_annotations());
1477         parsed_annotations.set_field_annotations(nullptr);
1478         if (parsed_annotations.has_annotation(AnnotationCollector::_jdk_internal_NullRestricted)) {
1479           if (!Signature::has_envelope(sig)) {
1480             Exceptions::fthrow(
1481               THREAD_AND_LOCATION,
1482               vmSymbols::java_lang_ClassFormatError(),
1483               "Illegal use of @jdk.internal.vm.annotation.NullRestricted annotation on field %s.%s with signature %s (primitive types can never be null)",
1484               class_name()->as_C_string(), name->as_C_string(), sig->as_C_string());
1485             return;
1486           }
1487           if (!supports_inline_types()) {
1488             Exceptions::fthrow(
1489               THREAD_AND_LOCATION,
1490               vmSymbols::java_lang_ClassFormatError(),
1491               "Illegal use of @jdk.internal.vm.annotation.NullRestricted annotation on field %s.%s in non-preview class file",
1492               class_name()->as_C_string(), name->as_C_string());
1493             return;
1494           }
1495 
1496           if ((flags & JVM_ACC_STRICT_INIT) == 0) {
1497             // Inject STRICT_INIT and validate in context
1498             const jint patched_flags = flags | JVM_ACC_STRICT_INIT;
1499             verify_legal_field_modifiers(patched_flags, class_access_flags, CHECK);
1500             access_flags.set_flags(patched_flags);
1501           }
1502           is_null_restricted = true;
1503         }
1504       }
1505       if (parsed_annotations.field_type_annotations() != nullptr) {
1506         if (_fields_type_annotations == nullptr) {
1507           _fields_type_annotations =
1508             MetadataFactory::new_array<AnnotationArray*>(_loader_data,
1509                                                          length,
1510                                                          nullptr,
1511                                                          CHECK);
1512         }
1513         _fields_type_annotations->at_put(n, parsed_annotations.field_type_annotations());
1514         parsed_annotations.set_field_type_annotations(nullptr);
1515       }
1516 
1517       if (is_synthetic) {
1518         access_flags.set_is_synthetic();
1519       }
1520       if (generic_signature_index != 0) {
1521         fieldFlags.update_generic(true);
1522       }
1523     }
1524 
1525     if (is_null_restricted) {
1526       fieldFlags.update_null_free_inline_type(true);
1527     }
1528 
1529     const BasicType type = cp->basic_type_for_signature_at(signature_index);
1530 
1531     // Update number of static oop fields.
1532     if (is_static && is_reference_type(type)) {
1533       _static_oop_count++;
1534     }
1535 
1536     FieldInfo fi(access_flags, name_index, signature_index, constantvalue_index, fieldFlags);
1537     fi.set_index(n);
1538     if (fieldFlags.is_generic()) {
1539       fi.set_generic_signature_index(generic_signature_index);
1540     }
1541     parsed_annotations.apply_to(&fi);
1542     if (fi.field_flags().is_contended()) {
1543       _has_contended_fields = true;
1544     }
1545     if (access_flags.is_strict() && access_flags.is_static()) {
1546       _has_strict_static_fields = true;
1547     }
1548     _temp_field_info->append(fi);
1549   }
1550   assert(_temp_field_info->length() == length, "Must be");
1551 

1552   if (num_injected != 0) {
1553     for (int n = 0; n < num_injected; n++) {
1554       // Check for duplicates
1555       if (injected[n].may_be_java) {
1556         const Symbol* const name      = injected[n].name();
1557         const Symbol* const signature = injected[n].signature();
1558         bool duplicate = false;
1559         for (int i = 0; i < length; i++) {
1560           const FieldInfo* const f = _temp_field_info->adr_at(i);
1561           if (name      == cp->symbol_at(f->name_index()) &&
1562               signature == cp->symbol_at(f->signature_index())) {
1563             // Symbol is desclared in Java so skip this one
1564             duplicate = true;
1565             break;
1566           }
1567         }
1568         if (duplicate) {
1569           // These will be removed from the field array at the end
1570           continue;
1571         }
1572       }
1573 
1574       // Injected field
1575       FieldInfo::FieldFlags fflags(0);
1576       fflags.update_injected(true);
1577       AccessFlags aflags;
1578       FieldInfo fi(aflags, (u2)(injected[n].name_index), (u2)(injected[n].signature_index), 0, fflags);
1579       int idx = _temp_field_info->append(fi);
1580       _temp_field_info->adr_at(idx)->set_index(idx);

1581     }
1582   }
1583 
1584   if (is_inline_type) {
1585     // Inject static ".null_reset" field. This is an all-zero value with its null-channel set to zero.
1586     // It should never be seen by user code, it is used when writing "null" to a nullable flat field
1587     // The all-zero value ensure that any embedded oop will be set to null, to avoid keeping dead objects
1588     // alive.
1589     FieldInfo::FieldFlags fflags2(0);
1590     fflags2.update_injected(true);
1591     AccessFlags aflags2(JVM_ACC_STATIC);
1592     FieldInfo fi2(aflags2,
1593                  (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(null_reset_value_name)),
1594                  (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(object_signature)),
1595                  0,
1596                  fflags2);
1597     int idx2 = _temp_field_info->append(fi2);
1598     _temp_field_info->adr_at(idx2)->set_index(idx2);
1599     _static_oop_count++;
1600   }
1601   if (!access_flags().is_identity_class() && !access_flags().is_interface()
1602       && _class_name != vmSymbols::java_lang_Object()) {
1603     // Acmp map ".acmp_maps" required for abstract and concrete value classes
1604     FieldInfo::FieldFlags fflags2(0);
1605     fflags2.update_injected(true);
1606     fflags2.update_stable(true);
1607     AccessFlags aflags2(JVM_ACC_STATIC | JVM_ACC_FINAL);
1608     FieldInfo fi3(aflags2,
1609                  (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(acmp_maps_name)),
1610                  (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(int_array_signature)),
1611                  0,
1612                  fflags2);
1613     int idx2 = _temp_field_info->append(fi3);
1614     _temp_field_info->adr_at(idx2)->set_index(idx2);
1615     _static_oop_count++;
1616   }
1617 
1618   if (_need_verify && length > 1) {
1619     // Check duplicated fields
1620     ResourceMark rm(THREAD);
1621     // Set containing name-signature pairs
1622     NameSigHashtable* names_and_sigs = new NameSigHashtable();
1623     for (int i = 0; i < _temp_field_info->length(); i++) {
1624       NameSigHash name_and_sig(_temp_field_info->adr_at(i)->name(_cp),
1625                                _temp_field_info->adr_at(i)->signature(_cp));
1626       // If no duplicates, add name/signature in hashtable names_and_sigs.
1627       if(!names_and_sigs->put(name_and_sig, 0)) {
1628         classfile_parse_error("Duplicate field name \"%s\" with signature \"%s\" in class file %s",
1629                                name_and_sig._name->as_C_string(), name_and_sig._sig->as_klass_external_name(), THREAD);
1630         return;
1631       }
1632     }
1633   }
1634 }
1635 
1636 

1981     }
1982     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Contended_signature): {
1983       if (_location != _in_field && _location != _in_class) {
1984         break;  // only allow for fields and classes
1985       }
1986       if (!EnableContended || (RestrictContended && !privileged)) {
1987         break;  // honor privileges
1988       }
1989       return _jdk_internal_vm_annotation_Contended;
1990     }
1991     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ReservedStackAccess_signature): {
1992       if (_location != _in_method)  break;  // only allow for methods
1993       if (RestrictReservedStack && !privileged) break; // honor privileges
1994       return _jdk_internal_vm_annotation_ReservedStackAccess;
1995     }
1996     case VM_SYMBOL_ENUM_NAME(jdk_internal_ValueBased_signature): {
1997       if (_location != _in_class)   break;  // only allow for classes
1998       if (!privileged)              break;  // only allow in privileged code
1999       return _jdk_internal_ValueBased;
2000     }
2001     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_LooselyConsistentValue_signature): {
2002       if (_location != _in_class)   break; // only allow for classes
2003       return _jdk_internal_LooselyConsistentValue;
2004     }
2005     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_NullRestricted_signature): {
2006       if (_location != _in_field)   break; // only allow for fields
2007       return _jdk_internal_NullRestricted;
2008     }
2009     case VM_SYMBOL_ENUM_NAME(java_lang_Deprecated): {
2010       return _java_lang_Deprecated;
2011     }
2012     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_AOTSafeClassInitializer_signature): {
2013       if (_location != _in_class)   break;  // only allow for classes
2014       if (!privileged)              break;  // only allow in privileged code
2015       return _jdk_internal_vm_annotation_AOTSafeClassInitializer;
2016     }
2017     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_AOTRuntimeSetup_signature): {
2018       if (_location != _in_method)  break;  // only allow for methods
2019       if (!privileged)              break;  // only allow in privileged code
2020       return _method_AOTRuntimeSetup;
2021     }
2022     default: {
2023       break;
2024     }
2025   }
2026   return AnnotationCollector::_unknown;
2027 }
2028 

2269 
2270   const u2 signature_index = cfs->get_u2_fast();
2271   guarantee_property(
2272     valid_symbol_at(signature_index),
2273     "Illegal constant pool index %u for method signature in class file %s",
2274     signature_index, CHECK_NULL);
2275   const Symbol* const signature = cp->symbol_at(signature_index);
2276 
2277   if (name == vmSymbols::class_initializer_name()) {
2278     // We ignore the other access flags for a valid class initializer.
2279     // (JVM Spec 2nd ed., chapter 4.6)
2280     if (_major_version < 51) { // backward compatibility
2281       flags = JVM_ACC_STATIC;
2282     } else if ((flags & JVM_ACC_STATIC) == JVM_ACC_STATIC) {
2283       flags &= JVM_ACC_STATIC | (_major_version <= JAVA_16_VERSION ? JVM_ACC_STRICT : 0);
2284     } else {
2285       classfile_parse_error("Method <clinit> is not static in class file %s", THREAD);
2286       return nullptr;
2287     }
2288   } else {
2289     verify_legal_method_modifiers(flags, access_flags(), name, CHECK_NULL);
2290   }
2291 
2292   if (name == vmSymbols::object_initializer_name() && is_interface) {
2293     classfile_parse_error("Interface cannot have a method named <init>, class file %s", THREAD);
2294     return nullptr;
2295   }
2296 
2297   if (Arguments::is_valhalla_enabled()) {
2298     if (((flags & JVM_ACC_SYNCHRONIZED) == JVM_ACC_SYNCHRONIZED)
2299         && ((flags & JVM_ACC_STATIC) == 0 )
2300         && !_access_flags.is_identity_class()) {
2301       classfile_parse_error("Invalid synchronized method in non-identity class %s", THREAD);
2302         return nullptr;
2303     }
2304   }
2305 
2306   int args_size = -1;  // only used when _need_verify is true
2307   if (_need_verify) {
2308     verify_legal_name_with_signature(name, signature, CHECK_NULL);
2309     args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) +
2310                  verify_legal_method_signature(name, signature, CHECK_NULL);
2311     if (args_size > MAX_ARGS_SIZE) {
2312       classfile_parse_error("Too many arguments in method signature in class file %s", THREAD);
2313       return nullptr;
2314     }
2315   }
2316 
2317   AccessFlags access_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS);
2318 
2319   // Default values for code and exceptions attribute elements
2320   u2 max_stack = 0;
2321   u2 max_locals = 0;
2322   u4 code_length = 0;
2323   const u1* code_start = nullptr;
2324   u2 exception_table_length = 0;
2325   const unsafe_u2* exception_table_start = nullptr; // (potentially unaligned) pointer to array of u2 elements

3109         valid_klass_reference_at(outer_class_info_index),
3110       "outer_class_info_index %u has bad constant type in class file %s",
3111       outer_class_info_index, CHECK_0);
3112 
3113     if (outer_class_info_index != 0) {
3114       const Symbol* const outer_class_name = cp->klass_name_at(outer_class_info_index);
3115       char* bytes = (char*)outer_class_name->bytes();
3116       guarantee_property(bytes[0] != JVM_SIGNATURE_ARRAY,
3117                          "Outer class is an array class in class file %s", CHECK_0);
3118     }
3119     // Inner class name
3120     const u2 inner_name_index = cfs->get_u2_fast();
3121     guarantee_property(
3122       inner_name_index == 0 || valid_symbol_at(inner_name_index),
3123       "inner_name_index %u has bad constant type in class file %s",
3124       inner_name_index, CHECK_0);
3125     if (_need_verify) {
3126       guarantee_property(inner_class_info_index != outer_class_info_index,
3127                          "Class is both outer and inner class in class file %s", CHECK_0);
3128     }
3129 
3130     // Access flags
3131     u2 flags;
3132     // JVM_ACC_MODULE is defined in JDK-9 and later.
3133     if (_major_version >= JAVA_9_VERSION) {
3134       flags = cfs->get_u2_fast() & (RECOGNIZED_INNER_CLASS_MODIFIERS | JVM_ACC_MODULE);
3135     } else {
3136       flags = cfs->get_u2_fast() & RECOGNIZED_INNER_CLASS_MODIFIERS;
3137     }
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 
3144     if (!supports_inline_types()) {
3145       const bool is_module = (flags & JVM_ACC_MODULE) != 0;
3146       const bool is_interface = (flags & JVM_ACC_INTERFACE) != 0;
3147       if (!is_module && !is_interface) {
3148         flags |= JVM_ACC_IDENTITY;
3149       }
3150     }
3151 
3152     Symbol* inner_name_symbol = inner_name_index == 0 ? nullptr : cp->symbol_at(inner_name_index);
3153     verify_legal_class_modifiers(flags, inner_name_symbol, inner_name_index == 0, CHECK_0);
3154     AccessFlags inner_access_flags(flags);
3155 
3156     inner_classes->at_put(index++, inner_class_info_index);
3157     inner_classes->at_put(index++, outer_class_info_index);
3158     inner_classes->at_put(index++, inner_name_index);
3159     inner_classes->at_put(index++, inner_access_flags.as_unsigned_short());
3160   }
3161 
3162   // Check for circular and duplicate entries.
3163   bool has_circularity = false;
3164   if (_need_verify) {
3165     has_circularity = check_inner_classes_circularity(cp, length * 4, CHECK_0);
3166     if (has_circularity) {
3167       // If circularity check failed then ignore InnerClasses attribute.
3168       MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
3169       index = 0;
3170       if (parsed_enclosingmethod_attribute) {
3171         inner_classes = MetadataFactory::new_array<u2>(_loader_data, 2, CHECK_0);

3237   if (length > 0) {
3238     int index = 0;
3239     cfs->guarantee_more(2 * length, CHECK_0);
3240     for (int n = 0; n < length; n++) {
3241       const u2 class_info_index = cfs->get_u2_fast();
3242       guarantee_property(
3243         valid_klass_reference_at(class_info_index),
3244         "Permitted subclass class_info_index %u has bad constant type in class file %s",
3245         class_info_index, CHECK_0);
3246       permitted_subclasses->at_put(index++, class_info_index);
3247     }
3248     assert(index == size, "wrong size");
3249   }
3250 
3251   // Restore buffer's current position.
3252   cfs->set_current(current_mark);
3253 
3254   return length;
3255 }
3256 
3257 u2 ClassFileParser::parse_classfile_loadable_descriptors_attribute(const ClassFileStream* const cfs,
3258                                                                    const u1* const loadable_descriptors_attribute_start,
3259                                                                    TRAPS) {
3260   const u1* const current_mark = cfs->current();
3261   u2 length = 0;
3262   if (loadable_descriptors_attribute_start != nullptr) {
3263     cfs->set_current(loadable_descriptors_attribute_start);
3264     cfs->guarantee_more(2, CHECK_0);  // length
3265     length = cfs->get_u2_fast();
3266   }
3267   const int size = length;
3268   Array<u2>* const loadable_descriptors = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
3269   _loadable_descriptors = loadable_descriptors;
3270   if (length > 0) {
3271     int index = 0;
3272     cfs->guarantee_more(2 * length, CHECK_0);
3273     for (int n = 0; n < length; n++) {
3274       const u2 descriptor_index = cfs->get_u2_fast();
3275       guarantee_property(
3276         valid_symbol_at(descriptor_index),
3277         "LoadableDescriptors descriptor_index %u has bad constant type in class file %s",
3278         descriptor_index, CHECK_0);
3279       Symbol* descriptor = _cp->symbol_at(descriptor_index);
3280       bool valid = legal_field_signature(descriptor, CHECK_0);
3281       if(!valid) {
3282         ResourceMark rm(THREAD);
3283         Exceptions::fthrow(THREAD_AND_LOCATION,
3284           vmSymbols::java_lang_ClassFormatError(),
3285           "Descriptor from LoadableDescriptors attribute at index \"%d\" in class %s has illegal signature \"%s\"",
3286           descriptor_index, _class_name->as_C_string(), descriptor->as_C_string());
3287         return 0;
3288       }
3289       loadable_descriptors->at_put(index++, descriptor_index);
3290     }
3291     assert(index == size, "wrong size");
3292   }
3293 
3294   // Restore buffer's current position.
3295   cfs->set_current(current_mark);
3296 
3297   return length;
3298 }
3299 
3300 //  Record {
3301 //    u2 attribute_name_index;
3302 //    u4 attribute_length;
3303 //    u2 components_count;
3304 //    component_info components[components_count];
3305 //  }
3306 //  component_info {
3307 //    u2 name_index;
3308 //    u2 descriptor_index
3309 //    u2 attributes_count;
3310 //    attribute_info_attributes[attributes_count];
3311 //  }
3312 u4 ClassFileParser::parse_classfile_record_attribute(const ClassFileStream* const cfs,
3313                                                      const ConstantPool* cp,
3314                                                      const u1* const record_attribute_start,
3315                                                      TRAPS) {
3316   const u1* const current_mark = cfs->current();
3317   int components_count = 0;
3318   unsigned int calculate_attr_size = 0;
3319   if (record_attribute_start != nullptr) {

3530   cp->bsm_entries().end_extension(iter, _loader_data, CHECK);
3531   guarantee_property(current_before_parsing + attribute_byte_length == cfs->current(),
3532                      "Bad length on BootstrapMethods in class file %s",
3533                      CHECK);
3534 }
3535 
3536 void ClassFileParser::parse_classfile_attributes(const ClassFileStream* const cfs,
3537                                                  ConstantPool* cp,
3538                  ClassFileParser::ClassAnnotationCollector* parsed_annotations,
3539                                                  TRAPS) {
3540   assert(cfs != nullptr, "invariant");
3541   assert(cp != nullptr, "invariant");
3542   assert(parsed_annotations != nullptr, "invariant");
3543 
3544   // Set inner classes attribute to default sentinel
3545   _inner_classes = Universe::the_empty_short_array();
3546   // Set nest members attribute to default sentinel
3547   _nest_members = Universe::the_empty_short_array();
3548   // Set _permitted_subclasses attribute to default sentinel
3549   _permitted_subclasses = Universe::the_empty_short_array();
3550   // Set _loadable_descriptors attribute to default sentinel
3551   _loadable_descriptors = Universe::the_empty_short_array();
3552   cfs->guarantee_more(2, CHECK);  // attributes_count
3553   u2 attributes_count = cfs->get_u2_fast();
3554   bool parsed_sourcefile_attribute = false;
3555   bool parsed_innerclasses_attribute = false;
3556   bool parsed_nest_members_attribute = false;
3557   bool parsed_permitted_subclasses_attribute = false;
3558   bool parsed_loadable_descriptors_attribute = false;
3559   bool parsed_nest_host_attribute = false;
3560   bool parsed_record_attribute = false;
3561   bool parsed_enclosingmethod_attribute = false;
3562   bool parsed_bootstrap_methods_attribute = false;
3563   const u1* runtime_visible_annotations = nullptr;
3564   int runtime_visible_annotations_length = 0;
3565   const u1* runtime_visible_type_annotations = nullptr;
3566   int runtime_visible_type_annotations_length = 0;
3567   bool runtime_invisible_type_annotations_exists = false;
3568   bool runtime_invisible_annotations_exists = false;
3569   bool parsed_source_debug_ext_annotations_exist = false;
3570   const u1* inner_classes_attribute_start = nullptr;
3571   u4  inner_classes_attribute_length = 0;
3572   u2  enclosing_method_class_index = 0;
3573   u2  enclosing_method_method_index = 0;
3574   const u1* nest_members_attribute_start = nullptr;
3575   u4  nest_members_attribute_length = 0;
3576   const u1* record_attribute_start = nullptr;
3577   u4  record_attribute_length = 0;
3578   const u1* permitted_subclasses_attribute_start = nullptr;
3579   u4  permitted_subclasses_attribute_length = 0;
3580   const u1* loadable_descriptors_attribute_start = nullptr;
3581   u4  loadable_descriptors_attribute_length = 0;
3582 
3583   // Iterate over attributes
3584   while (attributes_count--) {
3585     cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
3586     const u2 attribute_name_index = cfs->get_u2_fast();
3587     const u4 attribute_length = cfs->get_u4_fast();
3588     guarantee_property(
3589       valid_symbol_at(attribute_name_index),
3590       "Attribute name has bad constant pool index %u in class file %s",
3591       attribute_name_index, CHECK);
3592     const Symbol* const tag = cp->symbol_at(attribute_name_index);
3593     if (tag == vmSymbols::tag_source_file()) {
3594       // Check for SourceFile tag
3595       if (_need_verify) {
3596         guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
3597       }
3598       if (parsed_sourcefile_attribute) {
3599         classfile_parse_error("Multiple SourceFile attributes in class file %s", THREAD);
3600         return;
3601       } else {

3777               return;
3778             }
3779             parsed_record_attribute = true;
3780             record_attribute_start = cfs->current();
3781             record_attribute_length = attribute_length;
3782           } else if (_major_version >= JAVA_17_VERSION) {
3783             if (tag == vmSymbols::tag_permitted_subclasses()) {
3784               if (parsed_permitted_subclasses_attribute) {
3785                 classfile_parse_error("Multiple PermittedSubclasses attributes in class file %s", CHECK);
3786                 return;
3787               }
3788               // Classes marked ACC_FINAL cannot have a PermittedSubclasses attribute.
3789               if (_access_flags.is_final()) {
3790                 classfile_parse_error("PermittedSubclasses attribute in final class file %s", CHECK);
3791                 return;
3792               }
3793               parsed_permitted_subclasses_attribute = true;
3794               permitted_subclasses_attribute_start = cfs->current();
3795               permitted_subclasses_attribute_length = attribute_length;
3796             }
3797             if (Arguments::is_valhalla_enabled() && tag == vmSymbols::tag_loadable_descriptors()) {
3798               if (parsed_loadable_descriptors_attribute) {
3799                 classfile_parse_error("Multiple LoadableDescriptors attributes in class file %s", CHECK);
3800                 return;
3801               }
3802               parsed_loadable_descriptors_attribute = true;
3803               loadable_descriptors_attribute_start = cfs->current();
3804               loadable_descriptors_attribute_length = attribute_length;
3805             }
3806           }
3807           // Skip attribute_length for any attribute where major_verson >= JAVA_17_VERSION
3808           cfs->skip_u1(attribute_length, CHECK);
3809         } else {
3810           // Unknown attribute
3811           cfs->skip_u1(attribute_length, CHECK);
3812         }
3813       } else {
3814         // Unknown attribute
3815         cfs->skip_u1(attribute_length, CHECK);
3816       }
3817     } else {
3818       // Unknown attribute
3819       cfs->skip_u1(attribute_length, CHECK);
3820     }
3821   }
3822   _class_annotations = allocate_annotations(runtime_visible_annotations,
3823                                             runtime_visible_annotations_length,
3824                                             CHECK);
3825   _class_type_annotations = allocate_annotations(runtime_visible_type_annotations,

3862                             CHECK);
3863     if (_need_verify) {
3864       guarantee_property(record_attribute_length == calculated_attr_length,
3865                          "Record attribute has wrong length in class file %s",
3866                          CHECK);
3867     }
3868   }
3869 
3870   if (parsed_permitted_subclasses_attribute) {
3871     const u2 num_subclasses = parse_classfile_permitted_subclasses_attribute(
3872                             cfs,
3873                             permitted_subclasses_attribute_start,
3874                             CHECK);
3875     if (_need_verify) {
3876       guarantee_property(
3877         permitted_subclasses_attribute_length == sizeof(num_subclasses) + sizeof(u2) * num_subclasses,
3878         "Wrong PermittedSubclasses attribute length in class file %s", CHECK);
3879     }
3880   }
3881 
3882   if (parsed_loadable_descriptors_attribute) {
3883     const u2 num_classes = parse_classfile_loadable_descriptors_attribute(
3884                             cfs,
3885                             loadable_descriptors_attribute_start,
3886                             CHECK);
3887     if (_need_verify) {
3888       guarantee_property(
3889         loadable_descriptors_attribute_length == sizeof(num_classes) + sizeof(u2) * num_classes,
3890         "Wrong LoadableDescriptors attribute length in class file %s", CHECK);
3891     }
3892   }
3893 
3894   if (_max_bootstrap_specifier_index >= 0) {
3895     guarantee_property(parsed_bootstrap_methods_attribute,
3896                        "Missing BootstrapMethods attribute in class file %s", CHECK);
3897   }
3898 }
3899 
3900 void ClassFileParser::apply_parsed_class_attributes(InstanceKlass* k) {
3901   assert(k != nullptr, "invariant");
3902 
3903   if (_synthetic_flag)
3904     k->set_is_synthetic();
3905   if (_sourcefile_index != 0) {
3906     k->set_source_file_name_index(_sourcefile_index);
3907   }
3908   if (_generic_signature_index != 0) {
3909     k->set_generic_signature_index(_generic_signature_index);
3910   }
3911   if (_sde_buffer != nullptr) {
3912     k->set_source_debug_extension(_sde_buffer, _sde_length);
3913   }

3940     _class_type_annotations  = nullptr;
3941     _fields_annotations      = nullptr;
3942     _fields_type_annotations = nullptr;
3943 }
3944 
3945 // Transfer ownership of metadata allocated to the InstanceKlass.
3946 void ClassFileParser::apply_parsed_class_metadata(
3947                                             InstanceKlass* this_klass,
3948                                             int java_fields_count) {
3949   assert(this_klass != nullptr, "invariant");
3950 
3951   _cp->set_pool_holder(this_klass);
3952   this_klass->set_constants(_cp);
3953   this_klass->set_fieldinfo_stream(_fieldinfo_stream);
3954   this_klass->set_fieldinfo_search_table(_fieldinfo_search_table);
3955   this_klass->set_fields_status(_fields_status);
3956   this_klass->set_methods(_methods);
3957   this_klass->set_inner_classes(_inner_classes);
3958   this_klass->set_nest_members(_nest_members);
3959   this_klass->set_nest_host_index(_nest_host);
3960   this_klass->set_loadable_descriptors(_loadable_descriptors);
3961   this_klass->set_annotations(_combined_annotations);
3962   this_klass->set_permitted_subclasses(_permitted_subclasses);
3963   this_klass->set_record_components(_record_components);
3964   this_klass->set_inline_layout_info_array(_inline_layout_info_array);
3965 
3966   DEBUG_ONLY(FieldInfoStream::validate_search_table(_cp, _fieldinfo_stream, _fieldinfo_search_table));
3967 
3968   // Delay the setting of _local_interfaces and _transitive_interfaces until after
3969   // initialize_supers() in fill_instance_klass(). It is because the _local_interfaces could
3970   // be shared with _transitive_interfaces and _transitive_interfaces may be shared with
3971   // its _super. If an OOM occurs while loading the current klass, its _super field
3972   // may not have been set. When GC tries to free the klass, the _transitive_interfaces
3973   // may be deallocated mistakenly in InstanceKlass::deallocate_interfaces(). Subsequent
3974   // dereferences to the deallocated _transitive_interfaces will result in a crash.
3975 
3976   // Clear out these fields so they don't get deallocated by the destructor
3977   clear_class_metadata();
3978 }
3979 
3980 AnnotationArray* ClassFileParser::allocate_annotations(const u1* const anno,
3981                                                        int anno_length,
3982                                                        TRAPS) {
3983   AnnotationArray* annotations = nullptr;
3984   if (anno != nullptr) {
3985     annotations = MetadataFactory::new_array<u1>(_loader_data,
3986                                                  anno_length,
3987                                                  CHECK_(annotations));
3988     for (int i = 0; i < anno_length; i++) {
3989       annotations->at_put(i, anno[i]);
3990     }
3991   }
3992   return annotations;
3993 }
3994 
3995 void ClassFileParser::check_super_class(ConstantPool* const cp,
3996                                         const int super_class_index,
3997                                         const bool need_verify,
3998                                         TRAPS) {
3999   assert(cp != nullptr, "invariant");
4000 
4001   if (super_class_index == 0) {
4002     guarantee_property(_class_name == vmSymbols::java_lang_Object(),
4003                        "Invalid superclass index 0 in class file %s",

4004                        CHECK);
4005   } else {
4006     guarantee_property(valid_klass_reference_at(super_class_index),
4007                        "Invalid superclass index %u in class file %s",
4008                        super_class_index,
4009                        CHECK);
4010 
4011     // The class name should be legal because it is checked when parsing constant pool.
4012     // However, make sure it is not an array type.
4013     if (need_verify) {
4014       guarantee_property(cp->klass_name_at(super_class_index)->char_at(0) != JVM_SIGNATURE_ARRAY,
4015                         "Bad superclass name in class file %s", CHECK);
4016     }
4017   }
4018 }
4019 
4020 OopMapBlocksBuilder::OopMapBlocksBuilder(unsigned int max_blocks) {
4021   _max_nonstatic_oop_maps = max_blocks;
4022   _nonstatic_oop_map_count = 0;
4023   if (max_blocks == 0) {

4175   // See documentation of InstanceKlass::can_be_fastpath_allocated().
4176   assert(ik->size_helper() > 0, "layout_helper is initialized");
4177   if (ik->is_abstract() || ik->is_interface()
4178       || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == nullptr)
4179       || ik->size_helper() >= FastAllocateSizeLimit) {
4180     // Forbid fast-path allocation.
4181     const jint lh = Klass::instance_layout_helper(ik->size_helper(), true);
4182     ik->set_layout_helper(lh);
4183   }
4184 
4185   // Propagate the AOT runtimeSetup method discovery
4186   if (_has_aot_runtime_setup_method) {
4187     ik->set_is_runtime_setup_required();
4188     if (log_is_enabled(Info, aot, init)) {
4189       ResourceMark rm;
4190       log_info(aot, init)("Found @AOTRuntimeSetup class %s", ik->external_name());
4191     }
4192   }
4193 }
4194 
4195 bool ClassFileParser::supports_inline_types() const {
4196   // Inline types are only supported by class file version 71.65535 and later
4197   return _major_version > JAVA_27_VERSION ||
4198          (_major_version == JAVA_27_VERSION && _minor_version == JAVA_PREVIEW_MINOR_VERSION);
4199 }
4200 
4201 // utility methods for appending an array with check for duplicates
4202 
4203 static void append_interfaces(GrowableArray<InstanceKlass*>* result,
4204                               const Array<InstanceKlass*>* const ifs) {
4205   // iterate over new interfaces
4206   for (int i = 0; i < ifs->length(); i++) {
4207     InstanceKlass* const e = ifs->at(i);
4208     assert(e->is_klass() && e->is_interface(), "just checking");
4209     // add new interface
4210     result->append_if_missing(e);
4211   }
4212 }
4213 
4214 static Array<InstanceKlass*>* compute_transitive_interfaces(const InstanceKlass* super,
4215                                                             Array<InstanceKlass*>* local_ifs,
4216                                                             ClassLoaderData* loader_data,
4217                                                             TRAPS) {
4218   assert(local_ifs != nullptr, "invariant");
4219   assert(loader_data != nullptr, "invariant");
4220 

4247   } else {
4248     ResourceMark rm;
4249     GrowableArray<InstanceKlass*>* const result = new GrowableArray<InstanceKlass*>(max_transitive_size);
4250 
4251     // Copy down from superclass
4252     if (super != nullptr) {
4253       append_interfaces(result, super->transitive_interfaces());
4254     }
4255 
4256     // Copy down from local interfaces' superinterfaces
4257     for (int i = 0; i < local_size; i++) {
4258       InstanceKlass* const l = local_ifs->at(i);
4259       append_interfaces(result, l->transitive_interfaces());
4260     }
4261     // Finally add local interfaces
4262     append_interfaces(result, local_ifs);
4263 
4264     // length will be less than the max_transitive_size if duplicates were removed
4265     const int length = result->length();
4266     assert(length <= max_transitive_size, "just checking");
4267 
4268     Array<InstanceKlass*>* const new_result =
4269       MetadataFactory::new_array<InstanceKlass*>(loader_data, length, CHECK_NULL);
4270     for (int i = 0; i < length; i++) {
4271       InstanceKlass* const e = result->at(i);
4272       assert(e != nullptr, "just checking");
4273       new_result->at_put(i, e);
4274     }
4275     return new_result;
4276   }
4277 }
4278 
4279 void ClassFileParser::check_super_class_access(const InstanceKlass* this_klass, TRAPS) {
4280   assert(this_klass != nullptr, "invariant");
4281   const InstanceKlass* const super = this_klass->super();
4282 
4283   if (super != nullptr) {
4284     if (super->is_final()) {
4285       classfile_icce_error("class %s cannot inherit from final class %s", super, THREAD);
4286       return;
4287     }
4288 
4289     if (super->is_sealed()) {
4290       stringStream ss;
4291       ResourceMark rm(THREAD);
4292       if (!super->has_as_permitted_subclass(this_klass, ss)) {
4293         classfile_icce_error(ss.as_string(), THREAD);
4294         return;
4295       }
4296     }
4297 
4298     // The JVMS says that super classes for value types must not have the ACC_IDENTITY
4299     // flag set. But, java.lang.Object must still be allowed to be a direct super class
4300     // for a value classes.  So, it is treated as a special case for now.
4301     if (!this_klass->access_flags().is_identity_class() &&
4302         super->name() != vmSymbols::java_lang_Object() &&
4303         super->is_identity_class()) {
4304       classfile_icce_error("value class %s cannot inherit from class %s", super, THREAD);
4305       return;
4306     }
4307 
4308     Reflection::VerifyClassAccessResults vca_result =
4309       Reflection::verify_class_access(this_klass, super, false);
4310     if (vca_result != Reflection::ACCESS_OK) {
4311       ResourceMark rm(THREAD);
4312       char* msg = Reflection::verify_class_access_msg(this_klass,
4313                                                       super,
4314                                                       vca_result);
4315 
4316       // Names are all known to be < 64k so we know this formatted message is not excessively large.
4317       if (msg == nullptr) {
4318         bool same_module = (this_klass->module() == super->module());
4319         Exceptions::fthrow(
4320           THREAD_AND_LOCATION,
4321           vmSymbols::java_lang_IllegalAccessError(),
4322           "class %s cannot access its %ssuperclass %s (%s%s%s)",
4323           this_klass->external_name(),
4324           super->is_abstract() ? "abstract " : "",
4325           super->external_name(),
4326           (same_module) ? this_klass->joint_in_module_of_loader(super) : this_klass->class_in_module_of_loader(),
4327           (same_module) ? "" : "; ",

4480 // Verify the class modifiers for the current class, or an inner class if inner_name is non-null.
4481 void ClassFileParser::verify_legal_class_modifiers(jint flags, Symbol* inner_name, bool is_anonymous_inner_class, TRAPS) const {
4482   const bool is_module = (flags & JVM_ACC_MODULE) != 0;
4483   assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");
4484   if (is_module) {
4485     ResourceMark rm(THREAD);
4486     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4487     Exceptions::fthrow(
4488       THREAD_AND_LOCATION,
4489       vmSymbols::java_lang_NoClassDefFoundError(),
4490       "%s is not a class because access_flag ACC_MODULE is set",
4491       _class_name->as_C_string());
4492     return;
4493   }
4494 
4495   if (!_need_verify) { return; }
4496 
4497   const bool is_interface  = (flags & JVM_ACC_INTERFACE)  != 0;
4498   const bool is_abstract   = (flags & JVM_ACC_ABSTRACT)   != 0;
4499   const bool is_final      = (flags & JVM_ACC_FINAL)      != 0;
4500   const bool is_identity   = (flags & JVM_ACC_IDENTITY)   != 0;
4501   const bool is_enum       = (flags & JVM_ACC_ENUM)       != 0;
4502   const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4503   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4504   const bool valid_value_class = is_identity || is_interface || (supports_inline_types() && (is_abstract || is_final));
4505 
4506   if ((is_abstract && is_final) ||
4507       (is_interface && !is_abstract) ||
4508       (is_interface && major_gte_1_5 && (is_identity || is_enum)) ||   //  ACC_SUPER (now ACC_IDENTITY) was illegal for interfaces
4509       (!is_interface && major_gte_1_5 && is_annotation) ||
4510       (!valid_value_class)) {
4511     ResourceMark rm(THREAD);
4512     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4513     if (inner_name == nullptr && !is_anonymous_inner_class) {
4514       Exceptions::fthrow(
4515         THREAD_AND_LOCATION,
4516         vmSymbols::java_lang_ClassFormatError(),
4517         "Illegal class modifiers in class %s: 0x%X",
4518         _class_name->as_C_string(), flags
4519       );
4520     } else {
4521       if (is_anonymous_inner_class) {
4522         Exceptions::fthrow(
4523           THREAD_AND_LOCATION,
4524           vmSymbols::java_lang_ClassFormatError(),
4525           "Illegal class modifiers in anonymous inner class of class %s: 0x%X",
4526           _class_name->as_C_string(), flags
4527         );
4528       } else {
4529         Exceptions::fthrow(
4530           THREAD_AND_LOCATION,

4585         THREAD_AND_LOCATION,
4586         vmSymbols::java_lang_UnsupportedClassVersionError(),
4587         "%s (class file version %u.%u) was compiled with preview features that are unsupported. "
4588         "This version of the Java Runtime only recognizes preview features for class file version %u.%u",
4589         class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION, JAVA_PREVIEW_MINOR_VERSION);
4590       return;
4591     }
4592 
4593     if (!Arguments::enable_preview()) {
4594       classfile_ucve_error("Preview features are not enabled for %s (class file version %u.%u). Try running with '--enable-preview'",
4595                            class_name, major, minor, THREAD);
4596       return;
4597     }
4598 
4599   } else { // minor != JAVA_PREVIEW_MINOR_VERSION
4600     classfile_ucve_error("%s (class file version %u.%u) was compiled with an invalid non-zero minor version",
4601                          class_name, major, minor, THREAD);
4602   }
4603 }
4604 
4605 void ClassFileParser:: verify_legal_field_modifiers(jint flags,
4606                                                     AccessFlags class_access_flags,
4607                                                     TRAPS) const {
4608   if (!_need_verify) { return; }
4609 
4610   const bool is_public    = (flags & JVM_ACC_PUBLIC)      != 0;
4611   const bool is_protected = (flags & JVM_ACC_PROTECTED)   != 0;
4612   const bool is_private   = (flags & JVM_ACC_PRIVATE)     != 0;
4613   const bool is_static    = (flags & JVM_ACC_STATIC)      != 0;
4614   const bool is_final     = (flags & JVM_ACC_FINAL)       != 0;
4615   const bool is_volatile  = (flags & JVM_ACC_VOLATILE)    != 0;
4616   const bool is_transient = (flags & JVM_ACC_TRANSIENT)   != 0;
4617   const bool is_enum      = (flags & JVM_ACC_ENUM)        != 0;
4618   const bool is_strict    = (flags & JVM_ACC_STRICT_INIT) != 0;
4619   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4620 
4621   const bool is_interface = class_access_flags.is_interface();
4622   const bool is_identity_class = class_access_flags.is_identity_class();
4623 
4624   bool is_illegal = false;
4625   const char* error_msg = "";
4626 
4627   // There is some overlap in the checks that apply, for example interface fields
4628   // must be static, static fields can't be strict, and therefore interfaces can't
4629   // have strict fields. So we don't have to check every possible invalid combination
4630   // individually as long as all are covered. Once we have found an illegal combination
4631   // we can stop checking.
4632 
4633   if (!is_illegal) {
4634     if (is_interface) {
4635       if (!is_public || !is_static || !is_final || is_private ||
4636           is_protected || is_volatile || is_transient ||
4637           (major_gte_1_5 && is_enum)) {
4638         is_illegal = true;
4639         error_msg = "interface fields must be public, static and final, and may be synthetic";
4640       }
4641     } else { // not interface
4642       if (has_illegal_visibility(flags)) {
4643         is_illegal = true;
4644         error_msg = "invalid visibility flags for class field";
4645       } else if (is_final && is_volatile) {
4646         is_illegal = true;
4647         error_msg = "fields cannot be final and volatile";
4648       } else if (supports_inline_types()) {
4649         if (!is_identity_class && !is_static && (!is_strict || !is_final)) {
4650           is_illegal = true;
4651           error_msg = "value class fields must be either non-static final and strict, or static";
4652         }
4653       }
4654     }
4655   }
4656 
4657   if (is_illegal) {
4658     ResourceMark rm(THREAD);
4659     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4660     Exceptions::fthrow(
4661       THREAD_AND_LOCATION,
4662       vmSymbols::java_lang_ClassFormatError(),
4663       "Illegal field modifiers (%s) in class %s: 0x%X",
4664       error_msg, _class_name->as_C_string(), flags);
4665     return;
4666   }
4667 }
4668 
4669 void ClassFileParser::verify_legal_method_modifiers(jint flags,
4670                                                     AccessFlags class_access_flags,
4671                                                     const Symbol* name,
4672                                                     TRAPS) const {
4673   if (!_need_verify) { return; }
4674 
4675   const bool is_public       = (flags & JVM_ACC_PUBLIC)       != 0;
4676   const bool is_private      = (flags & JVM_ACC_PRIVATE)      != 0;
4677   const bool is_static       = (flags & JVM_ACC_STATIC)       != 0;
4678   const bool is_final        = (flags & JVM_ACC_FINAL)        != 0;
4679   const bool is_native       = (flags & JVM_ACC_NATIVE)       != 0;
4680   const bool is_abstract     = (flags & JVM_ACC_ABSTRACT)     != 0;
4681   const bool is_bridge       = (flags & JVM_ACC_BRIDGE)       != 0;
4682   const bool is_strict       = (flags & JVM_ACC_STRICT)       != 0;
4683   const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
4684   const bool is_protected    = (flags & JVM_ACC_PROTECTED)    != 0;
4685   const bool major_gte_1_5   = _major_version >= JAVA_1_5_VERSION;
4686   const bool major_gte_8     = _major_version >= JAVA_8_VERSION;
4687   const bool major_gte_17    = _major_version >= JAVA_17_VERSION;
4688   const bool is_initializer  = (name == vmSymbols::object_initializer_name());
4689   const bool is_interface    = class_access_flags.is_interface();
4690   const bool is_identity_class = class_access_flags.is_identity_class();
4691 
4692   bool is_illegal = false;
4693   const char* class_note = "";
4694 
4695   if (is_interface) {
4696     if (major_gte_8) {
4697       // Class file version is JAVA_8_VERSION or later Methods of
4698       // interfaces may set any of the flags except ACC_PROTECTED,
4699       // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must
4700       // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.
4701       if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
4702           (is_native || is_protected || is_final || is_synchronized) ||
4703           // If a specific method of a class or interface has its
4704           // ACC_ABSTRACT flag set, it must not have any of its
4705           // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,
4706           // ACC_STRICT, or ACC_SYNCHRONIZED flags set.  No need to
4707           // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as
4708           // those flags are illegal irrespective of ACC_ABSTRACT being set or not.
4709           (is_abstract && (is_private || is_static || (!major_gte_17 && is_strict)))) {
4710         is_illegal = true;
4711       }
4712     } else if (major_gte_1_5) {
4713       // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)
4714       if (!is_public || is_private || is_protected || is_static || is_final ||
4715           is_synchronized || is_native || !is_abstract || is_strict) {
4716         is_illegal = true;
4717       }
4718     } else {
4719       // Class file version is pre-JAVA_1_5_VERSION
4720       if (!is_public || is_static || is_final || is_native || !is_abstract) {
4721         is_illegal = true;
4722       }
4723     }
4724   } else { // not interface
4725     if (has_illegal_visibility(flags)) {
4726       is_illegal = true;
4727     } else {
4728       if (is_initializer) {
4729         if (is_static || is_final || is_synchronized || is_native ||
4730             is_abstract || (major_gte_1_5 && is_bridge)) {
4731           is_illegal = true;
4732         }
4733       } else { // not initializer
4734         if (!is_identity_class && is_synchronized && !is_static) {
4735           is_illegal = true;
4736           class_note = " (not an identity class)";
4737         } else {
4738           if (is_abstract) {
4739             if ((is_final || is_native || is_private || is_static ||
4740                 (major_gte_1_5 && (is_synchronized || (!major_gte_17 && is_strict))))) {
4741               is_illegal = true;
4742             }
4743           }
4744         }
4745       }
4746     }
4747   }
4748 
4749   if (is_illegal) {
4750     ResourceMark rm(THREAD);
4751     // Names are all known to be < 64k so we know this formatted message is not excessively large.
4752     Exceptions::fthrow(
4753       THREAD_AND_LOCATION,
4754       vmSymbols::java_lang_ClassFormatError(),
4755       "Method %s in class %s%s has illegal modifiers: 0x%X",
4756       name->as_C_string(), _class_name->as_C_string(), class_note, flags);
4757     return;
4758   }
4759 }
4760 
4761 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer,
4762                                         int length,
4763                                         TRAPS) const {
4764   assert(_need_verify, "only called when _need_verify is true");
4765   // Note: 0 <= length < 64K, as it comes from a u2 entry in the CP.
4766   if (!UTF8::is_legal_utf8(buffer, static_cast<size_t>(length), _major_version <= 47)) {
4767     classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", THREAD);
4768   }
4769 }
4770 
4771 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
4772 // In class names, '/' separates unqualified names.  This is verified in this function also.
4773 // Method names also may not contain the characters '<' or '>', unless <init>
4774 // or <clinit>.  Note that method names may not be <init> or <clinit> in this
4775 // method.  Because these names have been checked as special cases before
4776 // calling this method in verify_legal_method_name.

4794         if (type == ClassFileParser::LegalClass) {
4795           if (p == name || p+1 >= name+length ||
4796               *(p+1) == JVM_SIGNATURE_SLASH) {
4797             return false;
4798           }
4799         } else {
4800           return false;   // do not permit '/' unless it's class name
4801         }
4802         break;
4803       case JVM_SIGNATURE_SPECIAL:
4804       case JVM_SIGNATURE_ENDSPECIAL:
4805         // do not permit '<' or '>' in method names
4806         if (type == ClassFileParser::LegalMethod) {
4807           return false;
4808         }
4809     }
4810   }
4811   return true;
4812 }
4813 
4814 bool ClassFileParser::is_class_in_loadable_descriptors_attribute(Symbol *klass) {
4815   if (_loadable_descriptors == nullptr) return false;
4816   for (int i = 0; i < _loadable_descriptors->length(); i++) {
4817         Symbol* class_name = _cp->symbol_at(_loadable_descriptors->at(i));
4818         if (class_name == klass) return true;
4819   }
4820   return false;
4821 }
4822 
4823 // Take pointer to a UTF8 byte string (not NUL-terminated).
4824 // Skip over the longest part of the string that could
4825 // be taken as a fieldname. Allow non-trailing '/'s if slash_ok is true.
4826 // Return a pointer to just past the fieldname.
4827 // Return null if no fieldname at all was found, or in the case of slash_ok
4828 // being true, we saw consecutive slashes (meaning we were looking for a
4829 // qualified path but found something that was badly-formed).
4830 static const char* skip_over_field_name(const char* const name,
4831                                         bool slash_ok,
4832                                         unsigned int length) {
4833   const char* p;
4834   jboolean last_is_slash = false;
4835   jboolean not_first_ch = false;
4836 
4837   for (p = name; p != name + length; not_first_ch = true) {
4838     const char* old_p = p;
4839     jchar ch = *p;
4840     if (ch < 128) {
4841       p++;
4842       // quick check for ascii

4904 // be taken as a field signature. Allow "void" if void_ok.
4905 // Return a pointer to just past the signature.
4906 // Return null if no legal signature is found.
4907 const char* ClassFileParser::skip_over_field_signature(const char* signature,
4908                                                        bool void_ok,
4909                                                        unsigned int length,
4910                                                        TRAPS) const {
4911   unsigned int array_dim = 0;
4912   while (length > 0) {
4913     switch (signature[0]) {
4914     case JVM_SIGNATURE_VOID: if (!void_ok) { return nullptr; }
4915     case JVM_SIGNATURE_BOOLEAN:
4916     case JVM_SIGNATURE_BYTE:
4917     case JVM_SIGNATURE_CHAR:
4918     case JVM_SIGNATURE_SHORT:
4919     case JVM_SIGNATURE_INT:
4920     case JVM_SIGNATURE_FLOAT:
4921     case JVM_SIGNATURE_LONG:
4922     case JVM_SIGNATURE_DOUBLE:
4923       return signature + 1;
4924     case JVM_SIGNATURE_CLASS:
4925     {
4926       if (_major_version < JAVA_1_5_VERSION) {
4927         signature++;
4928         length--;
4929         // Skip over the class name if one is there
4930         const char* const p = skip_over_field_name(signature, true, length);
4931         assert(p == nullptr || p > signature, "must parse one character at least");
4932         // The next character better be a semicolon
4933         if (p != nullptr                             && // Parse of field name succeeded.
4934             p - signature < static_cast<int>(length) && // There is at least one character left to parse.
4935             p[0] == JVM_SIGNATURE_ENDCLASS) {
4936           return p + 1;
4937         }
4938       }
4939       else {
4940         // Skip leading 'L' and ignore first appearance of ';'
4941         signature++;
4942         const char* c = (const char*) memchr(signature, JVM_SIGNATURE_ENDCLASS, length - 1);
4943         // Format check signature
4944         if (c != nullptr) {
4945           int newlen = pointer_delta_as_int(c, (char*) signature);

5070     } else {
5071       // 4881221: relax the constraints based on JSR202 spec
5072       legal = verify_unqualified_name(bytes, length, LegalMethod);
5073     }
5074   }
5075 
5076   if (!legal) {
5077     ResourceMark rm(THREAD);
5078     assert(_class_name != nullptr, "invariant");
5079     // Names are all known to be < 64k so we know this formatted message is not excessively large.
5080     Exceptions::fthrow(
5081       THREAD_AND_LOCATION,
5082       vmSymbols::java_lang_ClassFormatError(),
5083       "Illegal method name \"%.*s\" in class %s", length, bytes,
5084       _class_name->as_C_string()
5085     );
5086     return;
5087   }
5088 }
5089 
5090 bool ClassFileParser::legal_field_signature(const Symbol* signature, TRAPS) const {
5091   const char* const bytes = (const char*)signature->bytes();
5092   const unsigned int length = signature->utf8_length();
5093   const char* const p = skip_over_field_signature(bytes, false, length, CHECK_false);
5094 
5095   if (p == nullptr || (p - bytes) != (int)length) {
5096     return false;
5097   }
5098   return true;
5099 }
5100 
5101 // Checks if signature is a legal field signature.
5102 void ClassFileParser::verify_legal_field_signature(const Symbol* name,
5103                                                    const Symbol* signature,
5104                                                    TRAPS) const {
5105   if (!_need_verify) { return; }
5106 
5107   if (!legal_field_signature(signature, THREAD)) {
5108     CLEAR_PENDING_EXCEPTION;  // throw this exception instead



5109     throwIllegalSignature("Field", name, signature, CHECK);
5110   }
5111 }
5112 
5113 // Check that the signature is compatible with the method name.  For example,
5114 // check that <init> has a void signature.
5115 void ClassFileParser::verify_legal_name_with_signature(const Symbol* name,
5116                                                        const Symbol* signature,
5117                                                        TRAPS) const {
5118   if (!_need_verify) {
5119     return;
5120   }
5121 
5122   // Class initializers cannot have args for class format version >= 51.
5123   if (name == vmSymbols::class_initializer_name() &&
5124       signature != vmSymbols::void_method_signature() &&
5125       _major_version >= JAVA_7_VERSION) {
5126     throwIllegalSignature("Method", name, signature, THREAD);
5127     return;
5128   }

5165       length -= pointer_delta_as_int(nextp, p);
5166       p = nextp;
5167       nextp = skip_over_field_signature(p, false, length, CHECK_0);
5168     }
5169     // The first non-signature thing better be a ')'
5170     if ((length > 0) && (*p++ == JVM_SIGNATURE_ENDFUNC)) {
5171       length--;
5172       // Now we better just have a return value
5173       nextp = skip_over_field_signature(p, true, length, CHECK_0);
5174       if (nextp && ((int)length == (nextp - p))) {
5175         return args_size;
5176       }
5177     }
5178   }
5179   // Report error
5180   throwIllegalSignature("Method", name, signature, THREAD);
5181   return 0;
5182 }
5183 
5184 int ClassFileParser::static_field_size() const {
5185   assert(_layout_info != nullptr, "invariant");
5186   return _layout_info->_static_field_size;
5187 }
5188 
5189 int ClassFileParser::total_oop_map_count() const {
5190   assert(_layout_info != nullptr, "invariant");
5191   return _layout_info->oop_map_blocks->_nonstatic_oop_map_count;
5192 }
5193 
5194 jint ClassFileParser::layout_size() const {
5195   assert(_layout_info != nullptr, "invariant");
5196   return _layout_info->_instance_size;
5197 }
5198 
5199 static void check_methods_for_intrinsics(const InstanceKlass* ik,
5200                                          const Array<Method*>* methods) {
5201   assert(ik != nullptr, "invariant");
5202   assert(methods != nullptr, "invariant");
5203 
5204   // Set up Method*::intrinsic_id as soon as we know the names of methods.
5205   // (We used to do this lazily, but now we query it in Rewriter,
5206   // which is eagerly done for every method, so we might as well do it now,
5207   // when everything is fresh in memory.)
5208   const vmSymbolID klass_id = Method::klass_id_for_intrinsics(ik);
5209 
5210   if (klass_id != vmSymbolID::NO_SID) {
5211     for (int j = 0; j < methods->length(); ++j) {
5212       Method* method = methods->at(j);
5213       method->init_intrinsic_id(klass_id);
5214 
5215       if (CheckIntrinsics) {
5216         // Check if an intrinsic is defined for method 'method',

5291   }
5292 }
5293 
5294 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook,
5295                                                       const ClassInstanceInfo& cl_inst_info,
5296                                                       TRAPS) {
5297   if (_klass != nullptr) {
5298     return _klass;
5299   }
5300 
5301   InstanceKlass* const ik =
5302     InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
5303 
5304   if (is_hidden()) {
5305     mangle_hidden_class_name(ik);
5306   }
5307 
5308   fill_instance_klass(ik, changed_by_loadhook, cl_inst_info, CHECK_NULL);
5309 
5310   assert(_klass == ik, "invariant");

5311   return ik;
5312 }
5313 
5314 void ClassFileParser::create_acmp_maps(InstanceKlass* ik, TRAPS) {
5315   ik->set_acmp_maps_offset(_layout_info->_acmp_maps_offset);
5316   // Current format of acmp maps:
5317   // All maps are stored contiguously in a single int array because it might
5318   // be too early to instantiate an Object array (to be investigated)
5319   // Format is:
5320   // [number_of_nonoop_entries][offset0][size0][offset1][size1]...[oop_offset0][oop_offset1]...
5321   //                           ^               ^
5322   //                           |               |
5323   //                           --------------------- Pair of integer describing a segment of
5324   //                                                 contiguous non-oop fields
5325   // First element is the number of segment of contiguous non-oop fields
5326   // Then, each segment of contiguous non-oop fields is described by two consecutive elements:
5327   // the offset then the size.
5328   // After the last segment of contiguous non-oop fields, oop fields are described, one element
5329   // per oop field, containing the offset of the field.
5330   int nonoop_acmp_map_size = _layout_info->_nonoop_acmp_map->length() * 2;
5331   int oop_acmp_map_size = _layout_info->_oop_acmp_map->length();
5332   int acmp_map_size = nonoop_acmp_map_size + oop_acmp_map_size + 1;
5333 
5334   typeArrayOop map = oopFactory::new_intArray(acmp_map_size, CHECK);
5335   typeArrayHandle map_h(THREAD, map);
5336   Array<int>* acmp_maps_array = MetadataFactory::new_array<int>(loader_data(), acmp_map_size, CHECK);
5337 
5338   map_h->int_at_put(0, _layout_info->_nonoop_acmp_map->length());
5339   acmp_maps_array->at_put(0, _layout_info->_nonoop_acmp_map->length());
5340   for (int i = 0; i < _layout_info->_nonoop_acmp_map->length(); i++) {
5341     map_h->int_at_put(i * 2 + 1, _layout_info->_nonoop_acmp_map->at(i)._offset);
5342     map_h->int_at_put(i * 2 + 2, _layout_info->_nonoop_acmp_map->at(i)._size);
5343 
5344     // Also store acmp maps as metadata for regeneration when using dynamic archive or AOT training data.
5345     acmp_maps_array->at_put(i * 2 + 1, _layout_info->_nonoop_acmp_map->at(i)._offset);
5346     acmp_maps_array->at_put(i * 2 + 2, _layout_info->_nonoop_acmp_map->at(i)._size);
5347   }
5348   int oop_map_start = nonoop_acmp_map_size + 1;
5349   for (int i = 0; i < _layout_info->_oop_acmp_map->length(); i++) {
5350     map_h->int_at_put(oop_map_start + i, _layout_info->_oop_acmp_map->at(i));
5351     acmp_maps_array->at_put(oop_map_start + i, _layout_info->_oop_acmp_map->at(i));
5352   }
5353   assert(acmp_maps_array->length() == map_h->length(), "sanity");
5354   ik->java_mirror()->obj_field_put(ik->acmp_maps_offset(), map_h());
5355   ik->set_acmp_maps_array(acmp_maps_array);
5356 }
5357 
5358 // See the declarations of _fast_acmp_offset and _fast_acmp_mask in InlineKlass::Members
5359 // for details about the fast path logic, and the meaning of these values.
5360 void ClassFileParser::set_fast_acmp_members(InlineKlass* vk) const {
5361   if (_layout_info->_oop_acmp_map->length() > 0) {  // Oops are not allowed in the fast path
5362     return;
5363   }
5364 
5365   int64_t mask = 0;
5366 #ifdef VM_LITTLE_ENDIAN
5367   // Compute the mask for a memory zone with offset "start" and of size "size", both in bytes,
5368   // assuming it won't overflow the long. In little endian, the byte with smallest address/smallest offset/closest from header
5369   // will be the least significant byte.
5370   //                         Value                    Memory layout
5371   // make_mask_piece(0, 1) = 0x0000 0000 0000 00ff => ff | 00 | 00 | 00 | 00 | 00 | 00 | 00
5372   // make_mask_piece(0, 1) = 0x0000 0000 0000 ffff => ff | ff | 00 | 00 | 00 | 00 | 00 | 00
5373   // make_mask_piece(1, 1) = 0x0000 0000 0000 ff00 => 00 | ff | 00 | 00 | 00 | 00 | 00 | 00
5374   // make_mask_piece(1, 3) = 0x0000 0000 ffff ff00 => 00 | ff | ff | ff | 00 | 00 | 00 | 00
5375   auto make_mask_piece = [](int start, int size) -> int64_t { return right_n_bits<int64_t>(size * BitsPerByte) << (start * BitsPerByte); };
5376 #else
5377   // Leaving the mask and offset to default values (that is just "return;") is a correct and easy way to implement this for other endianness, but it will
5378   // have a runtime cost in do_acmp, without the benefit. It is better, and probably easy with access to such an architecture, to adapt the logic above
5379   // for big-endian architectures, but filling the mask from the other end. I prefer not to do it blindly.
5380   Unimplemented()
5381 #endif
5382 
5383   // We build the mask for a 64-bit load from the start of the payload. For each contiguous piece of memory
5384   // we build the mask containing 1's where it would be in the loaded long: it must be as
5385   // long as the memory that is being accessed, but the placement depends on the endianness.
5386   for (int i = 0; i < _layout_info->_nonoop_acmp_map->length(); i++) {
5387     int piece_start = _layout_info->_nonoop_acmp_map->at(i)._offset - _layout_info->_payload_offset;
5388     int piece_size = _layout_info->_nonoop_acmp_map->at(i)._size;
5389     int piece_end = piece_start + piece_size - 1;
5390     if (piece_end >= BytesPerLong) {  // Too far! Can't fit in an 8-byte load, fast path will not be taken
5391       return;
5392     }
5393     int64_t mask_piece = make_mask_piece(piece_start, piece_size);
5394     mask |= mask_piece;
5395   }
5396 
5397   // If the payload is smaller than 64 bits, reading a long after the header can lead to an over-read. To avoid that, we can move the
5398   // load to a lower offset (toward the beginning of the object), and adjust the mask accordingly, even if it means reading (part of)
5399   // the header: the mask will filter that out.
5400   // Since an object cannot be less than 8 bytes, it's surely safe.
5401   if (mask == 0) {
5402     // Special case: empty object. There is nothing to compare, and no payload. We can just read from the start
5403     // of the header to ensure we load within the object. We can't use the general case: count_leading_zeros/count_trailing_zeros doesn't
5404     // accept null argument. This case is endianness-agnostic.
5405     vk->set_fast_acmp_offset(0);
5406     vk->set_fast_acmp_mask(mask);
5407   } else {
5408 #ifdef VM_LITTLE_ENDIAN
5409     // In little endian, if the payload is not a full 64 bits, the mask will have leading 0s (most significant bytes are bytes with
5410     // higher addresses/higher offset/further from the header). We can shift the mask so that there aren't leading 0s anymore, and
5411     // decrease the offset by the same amount.
5412     // For instance, let's say _payload_offset is 16, and the mask is 0x0000 ffff ffff 00ff, we have 16 leading 0s (the bubble at offset 1 is fine:
5413     // it might be due to padding). Reading from the start of the payload might read 2 bytes after the end of the payload. To avoid that, we
5414     // are going to shift the payload by 16 bits, and remove 2 bytes from the offset we should load from. At the end, fast_acmp_offset will be 14
5415     // and the mask 0xffff ffff 00ff 0000. The lowest 16 0s introduced by the shift will filter out the 2 bytes we read from the header.
5416     int leading_zeroes = static_cast<int>(count_leading_zeros(mask));
5417     assert(leading_zeroes % BitsPerByte == 0, "we should mask full bytes");
5418     mask <<= leading_zeroes;
5419     assert(count_leading_zeros(mask) == 0, "fast acmp mask can be moved further!");
5420     int offset = _layout_info->_payload_offset - leading_zeroes / BitsPerByte;
5421     assert(offset >= 0, "fast acmp path shouldn't load before the object");
5422     vk->set_fast_acmp_offset(offset);
5423     vk->set_fast_acmp_mask(mask);
5424 #else
5425     // Big endian architectures probably need to look at count_trailing_zeros, and shift right until the last bit is 1.
5426     // The offset still needs to be decreased.
5427     Unimplemented()
5428 #endif
5429   }
5430 }
5431 
5432 void ClassFileParser::fill_instance_klass(InstanceKlass* ik,
5433                                           bool changed_by_loadhook,
5434                                           const ClassInstanceInfo& cl_inst_info,
5435                                           TRAPS) {
5436   assert(ik != nullptr, "invariant");
5437 
5438   // Set name and CLD before adding to CLD
5439   ik->set_class_loader_data(_loader_data);
5440   ik->set_class_loader_type();
5441   ik->set_name(_class_name);
5442 
5443   // Add all classes to our internal class loader list here,
5444   // including classes in the bootstrap (null) class loader.
5445   const bool publicize = !is_internal();
5446 
5447   _loader_data->add_class(ik, publicize);
5448 
5449   set_klass_to_deallocate(ik);
5450 
5451   assert(_layout_info != nullptr, "invariant");
5452   assert(ik->static_field_size() == _layout_info->_static_field_size, "sanity");
5453   assert(ik->nonstatic_oop_map_count() == _layout_info->oop_map_blocks->_nonstatic_oop_map_count,
5454          "sanity");
5455 
5456   assert(ik->is_instance_klass(), "sanity");
5457   assert(ik->size_helper() == _layout_info->_instance_size, "sanity");
5458 
5459   // Fill in information already parsed
5460   ik->set_should_verify_class(_need_verify);
5461 
5462   // Not yet: supers are done below to support the new subtype-checking fields
5463   ik->set_nonstatic_field_size(_layout_info->_nonstatic_field_size);
5464   ik->set_has_nonstatic_fields(_layout_info->_has_nonstatic_fields);
5465   ik->set_has_strict_static_fields(_has_strict_static_fields);
5466 
5467   if (_layout_info->_is_naturally_atomic) {
5468     ik->set_is_naturally_atomic();
5469   }
5470 
5471   if (_layout_info->_must_be_atomic) {
5472     ik->set_must_be_atomic();
5473   }
5474 
5475   ik->set_static_oop_field_count(_static_oop_count);
5476 
5477   // this transfers ownership of a lot of arrays from
5478   // the parser onto the InstanceKlass*
5479   apply_parsed_class_metadata(ik, _java_fields_count);
5480 
5481   // can only set dynamic nest-host after static nest information is set
5482   if (cl_inst_info.dynamic_nest_host() != nullptr) {
5483     ik->set_nest_host(cl_inst_info.dynamic_nest_host());
5484   }
5485 
5486   // note that is not safe to use the fields in the parser from this point on
5487   assert(nullptr == _cp, "invariant");
5488   assert(nullptr == _fieldinfo_stream, "invariant");
5489   assert(nullptr == _fieldinfo_search_table, "invariant");
5490   assert(nullptr == _fields_status, "invariant");
5491   assert(nullptr == _methods, "invariant");
5492   assert(nullptr == _inner_classes, "invariant");
5493   assert(nullptr == _nest_members, "invariant");
5494   assert(nullptr == _loadable_descriptors, "invariant");
5495   assert(nullptr == _combined_annotations, "invariant");
5496   assert(nullptr == _record_components, "invariant");
5497   assert(nullptr == _permitted_subclasses, "invariant");
5498   assert(nullptr == _inline_layout_info_array, "invariant");
5499 
5500   if (_has_localvariable_table) {
5501     ik->set_has_localvariable_table(true);
5502   }
5503 
5504   if (_has_final_method) {
5505     ik->set_has_final_method();
5506   }
5507 
5508   ik->copy_method_ordering(_method_ordering, CHECK);
5509   // The InstanceKlass::_methods_jmethod_ids cache
5510   // is managed on the assumption that the initial cache
5511   // size is equal to the number of methods in the class. If
5512   // that changes, then InstanceKlass::idnum_can_increment()
5513   // has to be changed accordingly.
5514   ik->set_initial_method_idnum(checked_cast<u2>(ik->methods()->length()));
5515 
5516   ik->set_this_class_index(_this_class_index);
5517 
5518   if (_is_hidden) {

5555   if ((_num_miranda_methods > 0) ||
5556       // if this class introduced new miranda methods or
5557       (_super_klass != nullptr && _super_klass->has_miranda_methods())
5558         // super class exists and this class inherited miranda methods
5559      ) {
5560        ik->set_has_miranda_methods(); // then set a flag
5561   }
5562 
5563   // Fill in information needed to compute superclasses.
5564   ik->initialize_supers(const_cast<InstanceKlass*>(_super_klass), _transitive_interfaces, CHECK);
5565   ik->set_transitive_interfaces(_transitive_interfaces);
5566   ik->set_local_interfaces(_local_interfaces);
5567   _transitive_interfaces = nullptr;
5568   _local_interfaces = nullptr;
5569 
5570   // Initialize itable offset tables
5571   klassItable::setup_itable_offset_table(ik);
5572 
5573   // Compute transitive closure of interfaces this class implements
5574   // Do final class setup
5575   OopMapBlocksBuilder* oop_map_blocks = _layout_info->oop_map_blocks;
5576   if (oop_map_blocks->_nonstatic_oop_map_count > 0) {
5577     oop_map_blocks->copy(ik->start_of_nonstatic_oop_maps());
5578   }
5579 
5580   if (_has_contended_fields || _parsed_annotations->is_contended() ||
5581       ( _super_klass != nullptr && _super_klass->has_contended_annotations())) {
5582     ik->set_has_contended_annotations(true);
5583   }
5584 
5585   // Fill in has_finalizer and layout_helper
5586   set_precomputed_flags(ik);
5587 
5588   // check if this class can access its super class
5589   check_super_class_access(ik, CHECK);
5590 
5591   // check if this class can access its superinterfaces
5592   check_super_interface_access(ik, CHECK);
5593 
5594   // check if this class overrides any final method
5595   check_final_method_override(ik, CHECK);

5616 
5617   assert(_all_mirandas != nullptr, "invariant");
5618 
5619   // Generate any default methods - default methods are public interface methods
5620   // that have a default implementation.  This is new with Java 8.
5621   if (_has_nonstatic_concrete_methods) {
5622     DefaultMethods::generate_default_methods(ik,
5623                                              _all_mirandas,
5624                                              CHECK);
5625   }
5626 
5627   // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5628   if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5629       !module_entry->has_default_read_edges()) {
5630     if (!module_entry->set_has_default_read_edges()) {
5631       // We won a potential race
5632       JvmtiExport::add_default_read_edges(module_handle, THREAD);
5633     }
5634   }
5635 
5636   if (is_inline_type()) {
5637     InlineKlass* vk = InlineKlass::cast(ik);
5638     vk->set_payload_alignment(_layout_info->_payload_alignment);
5639     vk->set_payload_offset(_layout_info->_payload_offset);
5640     vk->set_payload_size_in_bytes(_layout_info->_payload_size_in_bytes);
5641     vk->set_null_free_non_atomic_size_in_bytes(_layout_info->_null_free_non_atomic_size_in_bytes);
5642     vk->set_null_free_non_atomic_alignment(_layout_info->_null_free_non_atomic_alignment);
5643     vk->set_null_free_atomic_size_in_bytes(_layout_info->_null_free_atomic_layout_size_in_bytes);
5644     vk->set_nullable_atomic_size_in_bytes(_layout_info->_nullable_atomic_layout_size_in_bytes);
5645     vk->set_nullable_non_atomic_size_in_bytes(_layout_info->_nullable_non_atomic_layout_size_in_bytes);
5646     vk->set_null_marker_offset(_layout_info->_null_marker_offset);
5647     vk->set_null_reset_value_offset(_layout_info->_null_reset_value_offset);
5648     if (_layout_info->_is_empty_inline_klass) vk->set_is_empty_inline_type();
5649 
5650     if (UseAcmpFastPath) {
5651       set_fast_acmp_members(vk);
5652     }
5653 
5654     vk->initialize_calling_convention(CHECK);
5655   }
5656 
5657   if (Arguments::is_valhalla_enabled() && !access_flags().is_identity_class() && !access_flags().is_interface()
5658       && _class_name != vmSymbols::java_lang_Object()) {
5659     // Both abstract and concrete value classes need a field map for acmp
5660     create_acmp_maps(ik, CHECK);
5661   }
5662 
5663   ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5664 
5665   if (!is_internal()) {
5666     ik->print_class_load_logging(_loader_data, module_entry, _stream);
5667     if (CDSConfig::is_dumping_archive()) {
5668       SystemDictionaryShared::check_code_source(ik, _stream);
5669     }
5670 
5671     if (ik->minor_version() == JAVA_PREVIEW_MINOR_VERSION &&
5672         ik->major_version() == JVM_CLASSFILE_MAJOR_VERSION &&
5673         log_is_enabled(Info, class, preview)) {
5674       ResourceMark rm;
5675       log_info(class, preview)("Loading class %s that depends on preview features (class file version %d.65535)",
5676                                ik->external_name(), JVM_CLASSFILE_MAJOR_VERSION);
5677     }
5678 
5679     if (log_is_enabled(Debug, class, resolve))  {
5680       ResourceMark rm;
5681       // print out the superclass.
5682       const char * from = ik->external_name();

5726                                  const ClassLoadInfo* cl_info,
5727                                  Publicity pub_level,
5728                                  TRAPS) :
5729   _stream(stream),
5730   _class_name(nullptr),
5731   _loader_data(loader_data),
5732   _is_hidden(cl_info->is_hidden()),
5733   _can_access_vm_annotations(cl_info->can_access_vm_annotations()),
5734   _orig_cp_size(0),
5735   _static_oop_count(0),
5736   _super_klass(),
5737   _cp(nullptr),
5738   _fieldinfo_stream(nullptr),
5739   _fieldinfo_search_table(nullptr),
5740   _fields_status(nullptr),
5741   _methods(nullptr),
5742   _inner_classes(nullptr),
5743   _nest_members(nullptr),
5744   _nest_host(0),
5745   _permitted_subclasses(nullptr),
5746   _loadable_descriptors(nullptr),
5747   _record_components(nullptr),
5748   _local_interfaces(nullptr),
5749   _transitive_interfaces(nullptr),
5750   _combined_annotations(nullptr),
5751   _class_annotations(nullptr),
5752   _class_type_annotations(nullptr),
5753   _fields_annotations(nullptr),
5754   _fields_type_annotations(nullptr),
5755   _klass(nullptr),
5756   _klass_to_deallocate(nullptr),
5757   _parsed_annotations(nullptr),
5758   _layout_info(nullptr),
5759   _inline_layout_info_array(nullptr),
5760   _temp_field_info(nullptr),
5761   _method_ordering(nullptr),
5762   _all_mirandas(nullptr),
5763   _vtable_size(0),
5764   _itable_size(0),
5765   _num_miranda_methods(0),
5766   _protection_domain(cl_info->protection_domain()),
5767   _access_flags(),
5768   _pub_level(pub_level),
5769   _bad_constant_seen(0),
5770   _synthetic_flag(false),
5771   _sde_length(false),
5772   _sde_buffer(nullptr),
5773   _sourcefile_index(0),
5774   _generic_signature_index(0),
5775   _major_version(0),
5776   _minor_version(0),
5777   _this_class_index(0),
5778   _super_class_index(0),
5779   _itfs_len(0),
5780   _java_fields_count(0),
5781   _need_verify(false),
5782   _has_nonstatic_concrete_methods(false),
5783   _declares_nonstatic_concrete_methods(false),
5784   _has_localvariable_table(false),
5785   _has_final_method(false),
5786   _has_contended_fields(false),
5787   _has_aot_runtime_setup_method(false),
5788   _has_strict_static_fields(false),
5789   _is_naturally_atomic(false),
5790   _must_be_atomic(true),
5791   _has_loosely_consistent_annotation(false),
5792   _has_finalizer(false),
5793   _has_empty_finalizer(false),
5794   _max_bootstrap_specifier_index(-1) {
5795 
5796   _class_name = name != nullptr ? name : vmSymbols::unknown_class_name();
5797   _class_name->increment_refcount();
5798 
5799   assert(_loader_data != nullptr, "invariant");
5800   assert(stream != nullptr, "invariant");
5801   assert(_stream != nullptr, "invariant");
5802   assert(_stream->buffer() == _stream->current(), "invariant");
5803   assert(_class_name != nullptr, "invariant");
5804   assert(0 == _access_flags.as_unsigned_short(), "invariant");
5805 
5806   // Figure out whether we can skip format checking (matching classic VM behavior)
5807   // Always verify CFLH bytes from the user agents.
5808   _need_verify = stream->from_class_file_load_hook() ? true : Verifier::should_verify_for(_loader_data->class_loader());
5809 
5810   // synch back verification state to stream to check for truncation.
5811   stream->set_need_verify(_need_verify);
5812 
5813   parse_stream(stream, CHECK);
5814 
5815   post_process_parsed_stream(stream, _cp, CHECK);
5816 }
5817 
5818 void ClassFileParser::clear_class_metadata() {
5819   // metadata created before the instance klass is created.  Must be
5820   // deallocated if classfile parsing returns an error.
5821   _cp = nullptr;
5822   _fieldinfo_stream = nullptr;
5823   _fieldinfo_search_table = nullptr;
5824   _fields_status = nullptr;
5825   _methods = nullptr;
5826   _inner_classes = nullptr;
5827   _nest_members = nullptr;
5828   _permitted_subclasses = nullptr;
5829   _loadable_descriptors = nullptr;
5830   _combined_annotations = nullptr;
5831   _class_annotations = _class_type_annotations = nullptr;
5832   _fields_annotations = _fields_type_annotations = nullptr;
5833   _record_components = nullptr;
5834   _inline_layout_info_array = nullptr;
5835 }
5836 
5837 // Destructor to clean up
5838 ClassFileParser::~ClassFileParser() {
5839   _class_name->decrement_refcount();
5840 
5841   if (_cp != nullptr) {
5842     MetadataFactory::free_metadata(_loader_data, _cp);
5843   }
5844 
5845   if (_fieldinfo_stream != nullptr) {
5846     MetadataFactory::free_array<u1>(_loader_data, _fieldinfo_stream);
5847   }
5848   MetadataFactory::free_array<u1>(_loader_data, _fieldinfo_search_table);
5849 
5850   if (_fields_status != nullptr) {
5851     MetadataFactory::free_array<FieldStatus>(_loader_data, _fields_status);
5852   }
5853 
5854   if (_inline_layout_info_array != nullptr) {
5855     MetadataFactory::free_array<InlineLayoutInfo>(_loader_data, _inline_layout_info_array);
5856   }
5857 
5858   if (_methods != nullptr) {
5859     // Free methods
5860     InstanceKlass::deallocate_methods(_loader_data, _methods);
5861   }
5862 
5863   // beware of the Universe::empty_blah_array!!
5864   if (_inner_classes != nullptr && _inner_classes != Universe::the_empty_short_array()) {
5865     MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
5866   }
5867 
5868   if (_nest_members != nullptr && _nest_members != Universe::the_empty_short_array()) {
5869     MetadataFactory::free_array<u2>(_loader_data, _nest_members);
5870   }
5871 
5872   if (_record_components != nullptr) {
5873     InstanceKlass::deallocate_record_components(_loader_data, _record_components);
5874   }
5875 
5876   if (_permitted_subclasses != nullptr && _permitted_subclasses != Universe::the_empty_short_array()) {
5877     MetadataFactory::free_array<u2>(_loader_data, _permitted_subclasses);
5878   }
5879 
5880   if (_loadable_descriptors != nullptr && _loadable_descriptors != Universe::the_empty_short_array()) {
5881     MetadataFactory::free_array<u2>(_loader_data, _loadable_descriptors);
5882   }
5883 
5884   // Free interfaces
5885   InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
5886                                        _local_interfaces, _transitive_interfaces);
5887 
5888   if (_combined_annotations != nullptr) {
5889     // After all annotations arrays have been created, they are installed into the
5890     // Annotations object that will be assigned to the InstanceKlass being created.
5891 
5892     // Deallocate the Annotations object and the installed annotations arrays.
5893     _combined_annotations->deallocate_contents(_loader_data);
5894 
5895     // If the _combined_annotations pointer is non-null,
5896     // then the other annotations fields should have been cleared.
5897     assert(_class_annotations       == nullptr, "Should have been cleared");
5898     assert(_class_type_annotations  == nullptr, "Should have been cleared");
5899     assert(_fields_annotations      == nullptr, "Should have been cleared");
5900     assert(_fields_type_annotations == nullptr, "Should have been cleared");
5901   } else {
5902     // If the annotations arrays were not installed into the Annotations object,
5903     // then they have to be deallocated explicitly.

5963 
5964   assert(cp_size == (u2)cp->length(), "invariant");
5965 
5966   // ACCESS FLAGS
5967   stream->guarantee_more(8, CHECK);  // flags, this_class, super_class, infs_len
5968 
5969   // Access flags
5970   u2 flags;
5971   // JVM_ACC_MODULE is defined in JDK-9 and later.
5972   if (_major_version >= JAVA_9_VERSION) {
5973     flags = stream->get_u2_fast() & (JVM_RECOGNIZED_CLASS_MODIFIERS | JVM_ACC_MODULE);
5974   } else {
5975     flags = stream->get_u2_fast() & JVM_RECOGNIZED_CLASS_MODIFIERS;
5976   }
5977 
5978   if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
5979     // Set abstract bit for old class files for backward compatibility
5980     flags |= JVM_ACC_ABSTRACT;
5981   }
5982 
5983   // Fixing ACC_SUPER/ACC_IDENTITY for old class files
5984   if (!supports_inline_types()) {
5985     const bool is_module = (flags & JVM_ACC_MODULE) != 0;
5986     const bool is_interface = (flags & JVM_ACC_INTERFACE) != 0;
5987     if (!is_module && !is_interface) {
5988       flags |= JVM_ACC_IDENTITY;
5989     }
5990   }
5991 
5992   verify_legal_class_modifiers(flags, nullptr, false, CHECK);
5993 
5994   short bad_constant = class_bad_constant_seen();
5995   if (bad_constant != 0) {
5996     // Do not throw CFE until after the access_flags are checked because if
5997     // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
5998     classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, THREAD);
5999     return;
6000   }
6001 
6002   _access_flags.set_flags(flags);
6003 
6004   // This class and superclass
6005   _this_class_index = stream->get_u2_fast();
6006   guarantee_property(
6007     valid_cp_range(_this_class_index, cp_size) &&
6008       cp->tag_at(_this_class_index).is_unresolved_klass(),
6009     "Invalid this class index %u in constant pool in class file %s",
6010     _this_class_index, CHECK);
6011 

6079 
6080   // SUPERKLASS
6081   _super_class_index = stream->get_u2_fast();
6082   check_super_class(cp,
6083                     _super_class_index,
6084                     _need_verify,
6085                     CHECK);
6086 
6087   // Interfaces
6088   _itfs_len = stream->get_u2_fast();
6089   parse_interfaces(stream,
6090                    _itfs_len,
6091                    cp,
6092                    &_has_nonstatic_concrete_methods,
6093                    CHECK);
6094 
6095   assert(_local_interfaces != nullptr, "invariant");
6096 
6097   // Fields (offsets are filled in later)
6098   parse_fields(stream,
6099                _access_flags,
6100                cp,
6101                cp_size,
6102                &_java_fields_count,
6103                CHECK);
6104 
6105   assert(_temp_field_info != nullptr, "invariant");
6106 
6107   // Methods
6108   parse_methods(stream,
6109                 _access_flags.is_interface(),
6110                 &_has_localvariable_table,
6111                 &_has_final_method,
6112                 &_declares_nonstatic_concrete_methods,
6113                 CHECK);
6114 
6115   assert(_methods != nullptr, "invariant");
6116 
6117   if (_declares_nonstatic_concrete_methods) {
6118     _has_nonstatic_concrete_methods = true;
6119   }

6199       // errors not checked yet.
6200       guarantee_property(super_class_name == vmSymbols::java_lang_Object(),
6201         "Interfaces must have java.lang.Object as superclass in class file %s",
6202         CHECK);
6203     }
6204     Handle loader(THREAD, _loader_data->class_loader());
6205     if (loader.is_null() && super_class_name == vmSymbols::java_lang_Object()) {
6206       // fast path to avoid lookup
6207       _super_klass = vmClasses::Object_klass();
6208     } else {
6209       _super_klass = (const InstanceKlass*)
6210                        SystemDictionary::resolve_super_or_fail(_class_name,
6211                                                                super_class_name,
6212                                                                loader,
6213                                                                true,
6214                                                                CHECK);
6215     }
6216   }
6217 
6218   if (_super_klass != nullptr) {
6219     if (_super_klass->is_interface()) {
6220       classfile_icce_error("class %s has interface %s as super class", _super_klass, THREAD);
6221       return;
6222     }
6223 
6224     if (_super_klass->is_final()) {
6225       classfile_icce_error("class %s cannot inherit from final class %s", _super_klass, THREAD);
6226       return;
6227     }
6228 
6229     if (Arguments::is_valhalla_enabled()) {
6230       // If this class is an value class, its super class cannot be an identity class unless it is java.lang.Object.
6231       if (_super_klass->access_flags().is_identity_class() && !access_flags().is_identity_class() &&
6232           _super_klass != vmClasses::Object_klass()) {
6233         ResourceMark rm(THREAD);
6234         THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
6235                   err_msg("Value type %s has an identity type as supertype", _class_name->as_C_string()));
6236       }
6237     }
6238 
6239     if (_super_klass->has_nonstatic_concrete_methods()) {
6240       _has_nonstatic_concrete_methods = true;
6241     }
6242   }
6243 
6244   if (_parsed_annotations->has_annotation(AnnotationCollector::_jdk_internal_LooselyConsistentValue) && _access_flags.is_identity_class()) {
6245     THROW_MSG(vmSymbols::java_lang_ClassFormatError(),
6246           err_msg("class %s cannot have annotation jdk.internal.vm.annotation.LooselyConsistentValue, because it is not a value class",
6247                   _class_name->as_klass_external_name()));
6248   }
6249 
6250   // Determining if the class allows tearing or not (default is not)
6251   if (Arguments::is_valhalla_enabled() && !_access_flags.is_identity_class()) {
6252     if (_parsed_annotations->has_annotation(ClassAnnotationCollector::_jdk_internal_LooselyConsistentValue)
6253         && (_super_klass == vmClasses::Object_klass() || !_super_klass->must_be_atomic())) {
6254       // Conditions above are not sufficient to determine atomicity requirements,
6255       // the presence of fields with atomic requirements could force the current class to have atomicy requirements too
6256       // Marking as not needing atomicity for now, can be updated when computing the fields layout
6257       // The InstanceKlass must be filled with the value from the FieldLayoutInfo returned by
6258       // the FieldLayoutBuilder, not with this _must_be_atomic field.
6259       _must_be_atomic = false;
6260     }
6261     // Apply VM options override
6262     if (*ForceNonTearable != '\0') {
6263       // Allow a command line switch to force the same atomicity property:
6264       const char* class_name_str = _class_name->as_C_string();
6265       if (StringUtils::class_list_match(ForceNonTearable, class_name_str)) {
6266         _must_be_atomic = true;
6267       }
6268     }
6269   }
6270 
6271   // Compute the transitive list of all unique interfaces implemented by this class
6272   _transitive_interfaces =
6273     compute_transitive_interfaces(_super_klass,
6274                                   _local_interfaces,
6275                                   _loader_data,
6276                                   CHECK);
6277 
6278   assert(_transitive_interfaces != nullptr, "invariant");
6279 
6280   // sort methods
6281   _method_ordering = sort_methods(_methods);
6282 
6283   _all_mirandas = new GrowableArray<Method*>(20);
6284 
6285   Handle loader(THREAD, _loader_data->class_loader());
6286   klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
6287                                                     &_num_miranda_methods,
6288                                                     _all_mirandas,
6289                                                     _super_klass,
6290                                                     _methods,
6291                                                     _access_flags,
6292                                                     _major_version,
6293                                                     loader,
6294                                                     _class_name,
6295                                                     _local_interfaces);
6296 
6297   // Size of Java itable (in words)
6298   _itable_size = is_interface() ? 0 :
6299     klassItable::compute_itable_size(_transitive_interfaces);
6300 
6301   assert(_parsed_annotations != nullptr, "invariant");
6302 
6303   if (Arguments::is_valhalla_enabled()) {
6304     fetch_field_classes(cp, CHECK);
6305   }
6306 
6307   _layout_info = new FieldLayoutInfo();
6308   FieldLayoutBuilder lb(class_name(), loader_data(), super_klass(), _cp, /*_fields*/ _temp_field_info,
6309       _parsed_annotations->is_contended(), is_inline_type(),
6310       access_flags().is_abstract() && !access_flags().is_identity_class() && !access_flags().is_interface(),
6311       _must_be_atomic, _layout_info, _inline_layout_info_array);
6312   lb.build_layout();
6313 
6314   // If it turned out that we didn't inline any of the fields, we deallocate
6315   // the array of InlineLayoutInfo since it isn't needed, and so it isn't
6316   // transferred to the allocated InstanceKlass.
6317   if (_inline_layout_info_array != nullptr && !_layout_info->_has_inlined_fields) {
6318     MetadataFactory::free_array<InlineLayoutInfo>(_loader_data, _inline_layout_info_array);
6319     _inline_layout_info_array = nullptr;
6320   }
6321 
6322   int injected_fields_count = _temp_field_info->length() - _java_fields_count;
6323   _fieldinfo_stream =
6324     FieldInfoStream::create_FieldInfoStream(_temp_field_info, _java_fields_count,
6325                                             injected_fields_count, loader_data(), CHECK);
6326   _fieldinfo_search_table = FieldInfoStream::create_search_table(_cp, _fieldinfo_stream, _loader_data, CHECK);
6327   _fields_status =
6328     MetadataFactory::new_array<FieldStatus>(_loader_data, _temp_field_info->length(),
6329                                             FieldStatus(0), CHECK);
6330 
6331   // Strict static fields track initialization status from the beginning of time.
6332   // After this class runs <clinit>, they will be verified as being "not unset".
6333   // See Step 8 of InstanceKlass::initialize_impl.
6334   if (_has_strict_static_fields) {
6335     bool found_one = false;
6336     for (int i = 0; i < _temp_field_info->length(); i++) {
6337       FieldInfo& fi = *_temp_field_info->adr_at(i);
6338       if (fi.access_flags().is_strict() && fi.access_flags().is_static()) {
6339         found_one = true;
6340         if (fi.initializer_index() != 0) {
6341           // skip strict static fields with ConstantValue attributes
6342         } else {
6343           _fields_status->adr_at(fi.index())->update_strict_static_unset(true);
6344           _fields_status->adr_at(fi.index())->update_strict_static_unread(true);
6345         }
6346       }
6347     }
6348     assert(found_one == _has_strict_static_fields,
6349            "correct prediction = %d", (int)_has_strict_static_fields);
6350   }
6351 }
6352 
6353 // In order to be able to optimize fields layouts by applying heap flattening,
6354 // the JVM needs to know the layout of the class of the fields, which implies
6355 // having these classes loaded. The strategy has two folds:
6356 //  1 - if the current class has a LoadableDescriptors attribute containing the
6357 //      name of the class of the field and PreloadClasses is true, the JVM will
6358 //      try to speculatively load this class. Failures to load the class are
6359 //      silently discarded, and loadings resulting in a non-optimizable class
6360 //      are ignored
6361 //  2 - if step 1 cannot be applied, the JVM will simply check if the class
6362 //      loader of the current class already knows these classes (no class
6363 //      loading triggered in this case). Note that the migrated value classes
6364 //      of the JDK are automatically registered to all class loaders, and
6365 //      are guaranteed to be found in this step even if the current class
6366 //      has not been recompiled with JEP 401 features enabled
6367 void ClassFileParser::fetch_field_classes(ConstantPool* cp, TRAPS) {
6368   for (int i = 0; i < _temp_field_info->length(); i++) {
6369     FieldInfo& fieldinfo = _temp_field_info->at(i);
6370     if (fieldinfo.access_flags().is_static()) continue;  // Only non-static fields are processed at load time
6371     Symbol* sig = fieldinfo.signature(cp);
6372     if (Signature::has_envelope(sig)) {
6373       TempNewSymbol name = Signature::strip_envelope(sig);
6374       if (name == _class_name) continue;
6375       if (PreloadClasses && is_class_in_loadable_descriptors_attribute(sig)) {
6376         log_info(class, preload)("Preloading of class %s during loading of class %s. "
6377                                  "Cause: field type in LoadableDescriptors attribute",
6378                                  name->as_C_string(), _class_name->as_C_string());
6379         oop loader = loader_data()->class_loader();
6380         InstanceKlass* klass = SystemDictionary::resolve_super_or_fail(_class_name, name,
6381                                                                        Handle(THREAD, loader),
6382                                                                        false, THREAD);
6383 
6384         assert((klass == nullptr) == HAS_PENDING_EXCEPTION, "Must be the same");
6385 
6386         if (klass != nullptr) {
6387           if (klass->is_inline_klass()) {
6388             set_inline_layout_info_klass(fieldinfo.index(), InlineKlass::cast(klass), CHECK);
6389             log_info(class, preload)("Preloading of class %s during loading of class %s "
6390                                      "(cause: field type in LoadableDescriptors attribute) succeeded",
6391                                      name->as_C_string(), _class_name->as_C_string());
6392           } else {
6393             // Non value class are allowed by the current spec, but it could be an indication of an issue so let's log this
6394             log_info(class, preload)("Preloading of class %s during loading of class %s "
6395                                      "(cause: field type in LoadableDescriptors attribute) but loaded class is not a value class",
6396                                      name->as_C_string(), _class_name->as_C_string());
6397             if (fieldinfo.field_flags().is_null_free_inline_type()) {
6398               log_warning(class, preload)("After preloading of class %s during loading of class %s "
6399                                      "field was annotated with @NullRestricted but loaded class is not a value class, "
6400                                      "the annotation is ignored",
6401                                      name->as_C_string(), _class_name->as_C_string());
6402               fieldinfo.field_flags_addr()->update_null_free_inline_type(false);
6403             }
6404           }
6405         } else {
6406           log_info(class, preload)("Preloading of class %s during loading of class %s "
6407                                    "(cause: field type in LoadableDescriptors attribute) failed : %s",
6408                                    name->as_C_string(), _class_name->as_C_string(),
6409                                    PENDING_EXCEPTION->klass()->name()->as_C_string());
6410           if (fieldinfo.field_flags().is_null_free_inline_type()) {
6411             log_warning(class, preload)("After preloading of class %s during loading of class %s failed,"
6412                                    "field was annotated with @NullRestricted but class is unknown, "
6413                                    "the annotation is ignored",
6414                                    name->as_C_string(), _class_name->as_C_string());
6415             fieldinfo.field_flags_addr()->update_null_free_inline_type(false);
6416           }
6417 
6418           // Loads triggered by the LoadableDescriptors attribute are speculative, failures must not
6419           // impact loading of current class.
6420           CLEAR_PENDING_EXCEPTION;
6421         }
6422       } else {
6423         oop loader = loader_data()->class_loader();
6424         InstanceKlass* klass = SystemDictionary::find_instance_klass(THREAD, name, Handle(THREAD, loader));
6425         if (klass != nullptr && klass->is_inline_klass()) {
6426           set_inline_layout_info_klass(fieldinfo.index(), InlineKlass::cast(klass), CHECK);
6427           log_info(class, preload)("During loading of class %s , class %s found in local system dictionary"
6428                                    "(field type not in LoadableDescriptors attribute)",
6429                                    _class_name->as_C_string(), name->as_C_string());
6430         } else if (fieldinfo.field_flags().is_null_free_inline_type()) {
6431           if (klass == nullptr) {
6432           log_warning(class, preload)("During loading of class %s, class %s is unknown, "
6433                                  "but a field of this type was annotated with @NullRestricted, "
6434                                  "the annotation is ignored",
6435                                  _class_name->as_C_string(), name->as_C_string());
6436           } else {
6437             log_warning(class, preload)("During loading of class %s, class %s was found in the local system dictionary "
6438                                  "and is not a concrete value class, but a field of this type was annotated with "
6439                                  "@NullRestricted, the annotation is ignored",
6440                                  _class_name->as_C_string(), name->as_C_string());
6441           }
6442           fieldinfo.field_flags_addr()->update_null_free_inline_type(false);
6443         }
6444       }
6445     }
6446   }
6447 }
6448 
6449 void ClassFileParser::set_klass(InstanceKlass* klass) {
6450 
6451 #ifdef ASSERT
6452   if (klass != nullptr) {
6453     assert(nullptr == _klass, "leaking?");
6454   }
6455 #endif
6456 
6457   _klass = klass;
6458 }
6459 
6460 void ClassFileParser::set_inline_layout_info_klass(int field_index, InlineKlass* ik, TRAPS) {
6461   assert(field_index >= 0 && field_index < java_fields_count(), "IOOB: 0 <= %d < %d", field_index, (int)java_fields_count());
6462 
6463   // The array of InlineLayoutInfo is allocated on demand. This way the array is
6464   // never allocated for an InstanceKlass which has no need for this information.
6465   if (_inline_layout_info_array == nullptr) {
6466     _inline_layout_info_array = MetadataFactory::new_array<InlineLayoutInfo>(_loader_data,
6467                                                                              java_fields_count(),
6468                                                                              CHECK);
6469   }
6470 
6471   // Set the Klass for the field's index
6472   _inline_layout_info_array->adr_at(field_index)->set_klass(ik);
6473 }
6474 
6475 void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) {
6476 
6477 #ifdef ASSERT
6478   if (klass != nullptr) {
6479     assert(nullptr == _klass_to_deallocate, "leaking?");
6480   }
6481 #endif
6482 
6483   _klass_to_deallocate = klass;
6484 }
6485 
6486 // Caller responsible for ResourceMark
6487 // clone stream with rewound position
6488 const ClassFileStream* ClassFileParser::clone_stream() const {
6489   assert(_stream != nullptr, "invariant");
6490 
6491   return _stream->clone();
6492 }
6493 
6494 ReferenceType ClassFileParser::super_reference_type() const {
< prev index next >