< prev index next >

src/hotspot/share/classfile/classFileParser.cpp

Print this page

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

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

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

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

 126 #define JAVA_11_VERSION                   55
 127 
 128 #define JAVA_12_VERSION                   56
 129 
 130 #define JAVA_13_VERSION                   57
 131 
 132 #define JAVA_14_VERSION                   58
 133 
 134 #define JAVA_15_VERSION                   59
 135 
 136 #define JAVA_16_VERSION                   60
 137 
 138 #define JAVA_17_VERSION                   61
 139 
 140 #define JAVA_18_VERSION                   62
 141 
 142 #define JAVA_19_VERSION                   63
 143 
 144 #define JAVA_20_VERSION                   64
 145 


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

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







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

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

 707           const unsigned int name_len = name->utf8_length();
 708           if (tag == JVM_CONSTANT_Methodref && name_len != 0 &&
 709               name->char_at(0) == JVM_SIGNATURE_SPECIAL) {
 710             if (name != vmSymbols::object_initializer_name()) {
 711               classfile_parse_error(
 712                 "Bad method name at constant pool index %u in class file %s",
 713                 name_ref_index, THREAD);
 714               return;
 715             } else if (!Signature::is_void_method(signature)) { // must have void signature.
 716               throwIllegalSignature("Method", name, signature, CHECK);




 717             }
 718           }
 719         }
 720         break;
 721       }
 722       case JVM_CONSTANT_MethodHandle: {
 723         const int ref_index = cp->method_handle_index_at(index);
 724         const int ref_kind = cp->method_handle_ref_kind_at(index);
 725         switch (ref_kind) {
 726           case JVM_REF_invokeVirtual:
 727           case JVM_REF_invokeStatic:
 728           case JVM_REF_invokeSpecial:
 729           case JVM_REF_newInvokeSpecial: {
 730             const int name_and_type_ref_index =
 731               cp->name_and_type_ref_index_at(ref_index);
 732             const int name_ref_index =
 733               cp->name_ref_index_at(name_and_type_ref_index);
 734             const Symbol* const name = cp->symbol_at(name_ref_index);
 735             if (ref_kind == JVM_REF_newInvokeSpecial) {
 736               if (name != vmSymbols::object_initializer_name()) {
 737                 classfile_parse_error(
 738                   "Bad constructor name at constant pool index %u in class file %s",
 739                     name_ref_index, THREAD);
 740                 return;
 741               }
 742             } else {
 743               if (name == vmSymbols::object_initializer_name()) {











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

 800   NameSigHash* entry = table[index];
 801   while (entry != NULL) {
 802     if (entry->_name == name && entry->_sig == sig) {
 803       return false;
 804     }
 805     entry = entry->_next;
 806   }
 807 
 808   // No duplicate is found, allocate a new entry and fill it.
 809   entry = new NameSigHash();
 810   entry->_name = name;
 811   entry->_sig = sig;
 812 
 813   // Insert into hash table
 814   entry->_next = table[index];
 815   table[index] = entry;
 816 
 817   return true;
 818 }
 819 
 820 // Side-effects: populates the _local_interfaces field
 821 void ClassFileParser::parse_interfaces(const ClassFileStream* const stream,
 822                                        const int itfs_len,
 823                                        ConstantPool* const cp,



























 824                                        bool* const has_nonstatic_concrete_methods,







 825                                        TRAPS) {
 826   assert(stream != NULL, "invariant");
 827   assert(cp != NULL, "invariant");
 828   assert(has_nonstatic_concrete_methods != NULL, "invariant");
 829 
 830   if (itfs_len == 0) {
 831     _local_interfaces = Universe::the_empty_instance_klass_array();

 832   } else {
 833     assert(itfs_len > 0, "only called for len>0");
 834     _local_interfaces = MetadataFactory::new_array<InstanceKlass*>(_loader_data, itfs_len, NULL, CHECK);
 835 
 836     int index;
 837     for (index = 0; index < itfs_len; index++) {
 838       const u2 interface_index = stream->get_u2(CHECK);
 839       Klass* interf;
 840       check_property(
 841         valid_klass_reference_at(interface_index),
 842         "Interface name has bad constant pool index %u in class file %s",
 843         interface_index, CHECK);
 844       if (cp->tag_at(interface_index).is_klass()) {
 845         interf = cp->resolved_klass_at(interface_index);
 846       } else {
 847         Symbol* const unresolved_klass  = cp->klass_name_at(interface_index);
 848 
 849         // Don't need to check legal name because it's checked when parsing constant pool.
 850         // But need to make sure it's not an array type.
 851         guarantee_property(unresolved_klass->char_at(0) != JVM_SIGNATURE_ARRAY,
 852                            "Bad interface name in class file %s", CHECK);
 853 
 854         // Call resolve_super so class circularity is checked
 855         interf = SystemDictionary::resolve_super_or_fail(
 856                                                   _class_name,
 857                                                   unresolved_klass,
 858                                                   Handle(THREAD, _loader_data->class_loader()),
 859                                                   _protection_domain,
 860                                                   false,
 861                                                   CHECK);
 862       }
 863 
 864       if (!interf->is_interface()) {
 865         THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
 866                   err_msg("class %s can not implement %s, because it is not an interface (%s)",
 867                           _class_name->as_klass_external_name(),
 868                           interf->external_name(),
 869                           interf->class_in_module_of_loader()));
 870       }
 871 
 872       if (InstanceKlass::cast(interf)->has_nonstatic_concrete_methods()) {
 873         *has_nonstatic_concrete_methods = true;
 874       }
 875       _local_interfaces->at_put(index, InstanceKlass::cast(interf));
 876     }
 877 
 878     if (!_need_verify || itfs_len <= 1) {
 879       return;
 880     }
 881 
 882     // Check if there's any duplicates in interfaces
 883     ResourceMark rm(THREAD);
 884     NameSigHash** interface_names = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD,
 885                                                                  NameSigHash*,
 886                                                                  HASH_ROW_SIZE);
 887     initialize_hashtable(interface_names);
 888     bool dup = false;
 889     const Symbol* name = NULL;
 890     {
 891       debug_only(NoSafepointVerifier nsv;)
 892       for (index = 0; index < itfs_len; index++) {
 893         const InstanceKlass* const k = _local_interfaces->at(index);
 894         name = k->name();
 895         // If no duplicates, add (name, NULL) in hashtable interface_names.
 896         if (!put_after_lookup(name, NULL, interface_names)) {
 897           dup = true;
 898           break;
 899         }
 900       }
 901     }
 902     if (dup) {
 903       classfile_parse_error("Duplicate interface name \"%s\" in class file %s",
 904                              name->as_C_string(), THREAD);
 905     }
 906   }
 907 }
 908 
 909 void ClassFileParser::verify_constantvalue(const ConstantPool* const cp,
 910                                            int constantvalue_index,
 911                                            int signature_index,
 912                                            TRAPS) const {
 913   // Make sure the constant pool entry is of a type appropriate to this field
 914   guarantee_property(

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

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

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

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

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



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

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




1486 
1487   // The field array starts with tuples of shorts
1488   // [access, name index, sig index, initial value index, byte offset].
1489   // A generic signature slot only exists for field with generic
1490   // signature attribute. And the access flag is set with
1491   // JVM_ACC_FIELD_HAS_GENERIC_SIGNATURE for that field. The generic
1492   // signature slots are at the end of the field array and after all
1493   // other fields data.
1494   //
1495   //   f1: [access, name index, sig index, initial value index, low_offset, high_offset]
1496   //   f2: [access, name index, sig index, initial value index, low_offset, high_offset]
1497   //       ...
1498   //   fn: [access, name index, sig index, initial value index, low_offset, high_offset]
1499   //       [generic signature index]
1500   //       [generic signature index]
1501   //       ...
1502   //
1503   // Allocate a temporary resource array for field data. For each field,
1504   // a slot is reserved in the temporary array for the generic signature
1505   // index. After parsing all fields, the data are copied to a permanent
1506   // array and any unused slots will be discarded.
1507   ResourceMark rm(THREAD);
1508   u2* const fa = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD,
1509                                               u2,
1510                                               total_fields * (FieldInfo::field_slots + 1));
1511 
1512   // The generic signature slots start after all other fields' data.
1513   int generic_signature_slot = total_fields * FieldInfo::field_slots;
1514   int num_generic_signature = 0;

1515   for (int n = 0; n < length; n++) {
1516     // access_flags, name_index, descriptor_index, attributes_count
1517     cfs->guarantee_more(8, CHECK);
1518 




1519     AccessFlags access_flags;
1520     const jint flags = cfs->get_u2_fast() & JVM_RECOGNIZED_FIELD_MODIFIERS;
1521     verify_legal_field_modifiers(flags, is_interface, CHECK);
1522     access_flags.set_flags(flags);
1523 
1524     const u2 name_index = cfs->get_u2_fast();
1525     check_property(valid_symbol_at(name_index),
1526       "Invalid constant pool index %u for field name in class file %s",
1527       name_index, CHECK);
1528     const Symbol* const name = cp->symbol_at(name_index);
1529     verify_legal_field_name(name, CHECK);
1530 
1531     const u2 signature_index = cfs->get_u2_fast();
1532     check_property(valid_symbol_at(signature_index),
1533       "Invalid constant pool index %u for field signature in class file %s",
1534       signature_index, CHECK);
1535     const Symbol* const sig = cp->symbol_at(signature_index);
1536     verify_legal_field_signature(name, sig, CHECK);

1537 
1538     u2 constantvalue_index = 0;
1539     bool is_synthetic = false;
1540     u2 generic_signature_index = 0;
1541     const bool is_static = access_flags.is_static();
1542     FieldAnnotationCollector parsed_annotations(_loader_data);
1543 
1544     const u2 attributes_count = cfs->get_u2_fast();
1545     if (attributes_count > 0) {
1546       parse_field_attributes(cfs,
1547                              attributes_count,
1548                              is_static,
1549                              signature_index,
1550                              &constantvalue_index,
1551                              &is_synthetic,
1552                              &generic_signature_index,
1553                              &parsed_annotations,
1554                              CHECK);
1555 
1556       if (parsed_annotations.field_annotations() != NULL) {

1576 
1577       if (is_synthetic) {
1578         access_flags.set_is_synthetic();
1579       }
1580       if (generic_signature_index != 0) {
1581         access_flags.set_field_has_generic_signature();
1582         fa[generic_signature_slot] = generic_signature_index;
1583         generic_signature_slot ++;
1584         num_generic_signature ++;
1585       }
1586     }
1587 
1588     FieldInfo* const field = FieldInfo::from_field_array(fa, n);
1589     field->initialize(access_flags.as_short(),
1590                       name_index,
1591                       signature_index,
1592                       constantvalue_index);
1593     const BasicType type = cp->basic_type_for_signature_at(signature_index);
1594 
1595     // Update FieldAllocationCount for this kind of field
1596     fac->update(is_static, type);
1597 
1598     // After field is initialized with type, we can augment it with aux info
1599     if (parsed_annotations.has_any_annotations()) {
1600       parsed_annotations.apply_to(field);
1601       if (field->is_contended()) {
1602         _has_contended_fields = true;
1603       }
1604     }
1605   }
1606 
1607   int index = length;
1608   if (num_injected != 0) {
1609     for (int n = 0; n < num_injected; n++) {
1610       // Check for duplicates
1611       if (injected[n].may_be_java) {
1612         const Symbol* const name      = injected[n].name();
1613         const Symbol* const signature = injected[n].signature();
1614         bool duplicate = false;
1615         for (int i = 0; i < length; i++) {
1616           const FieldInfo* const f = FieldInfo::from_field_array(fa, i);

1620             duplicate = true;
1621             break;
1622           }
1623         }
1624         if (duplicate) {
1625           // These will be removed from the field array at the end
1626           continue;
1627         }
1628       }
1629 
1630       // Injected field
1631       FieldInfo* const field = FieldInfo::from_field_array(fa, index);
1632       field->initialize((u2)JVM_ACC_FIELD_INTERNAL,
1633                         (u2)(injected[n].name_index),
1634                         (u2)(injected[n].signature_index),
1635                         0);
1636 
1637       const BasicType type = Signature::basic_type(injected[n].signature());
1638 
1639       // Update FieldAllocationCount for this kind of field
1640       fac->update(false, type);
1641       index++;
1642     }
1643   }
1644 



























1645   assert(NULL == _fields, "invariant");
1646 
1647   _fields =
1648     MetadataFactory::new_array<u2>(_loader_data,
1649                                    index * FieldInfo::field_slots + num_generic_signature,
1650                                    CHECK);
1651   // Sometimes injected fields already exist in the Java source so
1652   // the fields array could be too long.  In that case the
1653   // fields array is trimmed. Also unused slots that were reserved
1654   // for generic signature indexes are discarded.
1655   {
1656     int i = 0;
1657     for (; i < index * FieldInfo::field_slots; i++) {
1658       _fields->at_put(i, fa[i]);
1659     }
1660     for (int j = total_fields * FieldInfo::field_slots;
1661          j < generic_signature_slot; j++) {
1662       _fields->at_put(i++, fa[j]);
1663     }
1664     assert(_fields->length() == i, "");

1942         "Exception name has bad type at constant pool %u in class file %s",
1943         checked_exception, CHECK_NULL);
1944     }
1945   }
1946   // check exceptions attribute length
1947   if (_need_verify) {
1948     guarantee_property(method_attribute_length == (sizeof(*checked_exceptions_length) +
1949                                                    sizeof(u2) * size),
1950                       "Exceptions attribute has wrong length in class file %s", CHECK_NULL);
1951   }
1952   return checked_exceptions_start;
1953 }
1954 
1955 void ClassFileParser::throwIllegalSignature(const char* type,
1956                                             const Symbol* name,
1957                                             const Symbol* sig,
1958                                             TRAPS) const {
1959   assert(name != NULL, "invariant");
1960   assert(sig != NULL, "invariant");
1961 





1962   ResourceMark rm(THREAD);
1963   Exceptions::fthrow(THREAD_AND_LOCATION,
1964       vmSymbols::java_lang_ClassFormatError(),
1965       "%s \"%s\" in class %s has illegal signature \"%s\"", type,
1966       name->as_C_string(), _class_name->as_C_string(), sig->as_C_string());
1967 }
1968 
1969 AnnotationCollector::ID
1970 AnnotationCollector::annotation_index(const ClassLoaderData* loader_data,
1971                                       const Symbol* name,
1972                                       const bool can_access_vm_annotations) {
1973   const vmSymbolID sid = vmSymbols::find_sid(name);
1974   // Privileged code can use all annotations.  Other code silently drops some.
1975   const bool privileged = loader_data->is_boot_class_loader_data() ||
1976                           loader_data->is_platform_class_loader_data() ||
1977                           can_access_vm_annotations;
1978   switch (sid) {
1979     case VM_SYMBOL_ENUM_NAME(reflect_CallerSensitive_signature): {
1980       if (_location != _in_method)  break;  // only allow for methods
1981       if (!privileged)              break;  // only allow in privileged code
1982       return _method_CallerSensitive;
1983     }
1984     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ForceInline_signature): {
1985       if (_location != _in_method)  break;  // only allow for methods
1986       if (!privileged)              break;  // only allow in privileged code

2249                              runtime_visible_type_annotations_length,
2250                              runtime_invisible_type_annotations,
2251                              runtime_invisible_type_annotations_length,
2252                              CHECK);
2253     cm->set_type_annotations(a);
2254   }
2255 }
2256 
2257 
2258 // Note: the parse_method below is big and clunky because all parsing of the code and exceptions
2259 // attribute is inlined. This is cumbersome to avoid since we inline most of the parts in the
2260 // Method* to save footprint, so we only know the size of the resulting Method* when the
2261 // entire method attribute is parsed.
2262 //
2263 // The promoted_flags parameter is used to pass relevant access_flags
2264 // from the method back up to the containing klass. These flag values
2265 // are added to klass's access_flags.
2266 
2267 Method* ClassFileParser::parse_method(const ClassFileStream* const cfs,
2268                                       bool is_interface,


2269                                       const ConstantPool* cp,
2270                                       AccessFlags* const promoted_flags,
2271                                       TRAPS) {
2272   assert(cfs != NULL, "invariant");
2273   assert(cp != NULL, "invariant");
2274   assert(promoted_flags != NULL, "invariant");
2275 
2276   ResourceMark rm(THREAD);
2277   // Parse fixed parts:
2278   // access_flags, name_index, descriptor_index, attributes_count
2279   cfs->guarantee_more(8, CHECK_NULL);
2280 
2281   int flags = cfs->get_u2_fast();
2282   const u2 name_index = cfs->get_u2_fast();
2283   const int cp_size = cp->length();
2284   check_property(
2285     valid_symbol_at(name_index),
2286     "Illegal constant pool index %u for method name in class file %s",
2287     name_index, CHECK_NULL);
2288   const Symbol* const name = cp->symbol_at(name_index);

2290 
2291   const u2 signature_index = cfs->get_u2_fast();
2292   guarantee_property(
2293     valid_symbol_at(signature_index),
2294     "Illegal constant pool index %u for method signature in class file %s",
2295     signature_index, CHECK_NULL);
2296   const Symbol* const signature = cp->symbol_at(signature_index);
2297 
2298   if (name == vmSymbols::class_initializer_name()) {
2299     // We ignore the other access flags for a valid class initializer.
2300     // (JVM Spec 2nd ed., chapter 4.6)
2301     if (_major_version < 51) { // backward compatibility
2302       flags = JVM_ACC_STATIC;
2303     } else if ((flags & JVM_ACC_STATIC) == JVM_ACC_STATIC) {
2304       flags &= JVM_ACC_STATIC | (_major_version <= JAVA_16_VERSION ? JVM_ACC_STRICT : 0);
2305     } else {
2306       classfile_parse_error("Method <clinit> is not static in class file %s", THREAD);
2307       return NULL;
2308     }
2309   } else {
2310     verify_legal_method_modifiers(flags, is_interface, name, CHECK_NULL);
2311   }
2312 
2313   if (name == vmSymbols::object_initializer_name() && is_interface) {
2314     classfile_parse_error("Interface cannot have a method named <init>, class file %s", THREAD);
2315     return NULL;






















































2316   }
2317 
2318   int args_size = -1;  // only used when _need_verify is true
2319   if (_need_verify) {
2320     verify_legal_name_with_signature(name, signature, CHECK_NULL);
2321     args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) +
2322                  verify_legal_method_signature(name, signature, CHECK_NULL);
2323     if (args_size > MAX_ARGS_SIZE) {
2324       classfile_parse_error("Too many arguments in method signature in class file %s", THREAD);
2325       return NULL;
2326     }
2327   }
2328 
2329   AccessFlags access_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS);
2330 
2331   // Default values for code and exceptions attribute elements
2332   u2 max_stack = 0;
2333   u2 max_locals = 0;
2334   u4 code_length = 0;
2335   const u1* code_start = 0;

2865       _has_finalizer = true;
2866     }
2867   }
2868   if (name == vmSymbols::object_initializer_name() &&
2869       signature == vmSymbols::void_method_signature() &&
2870       m->is_vanilla_constructor()) {
2871     _has_vanilla_constructor = true;
2872   }
2873 
2874   NOT_PRODUCT(m->verify());
2875   return m;
2876 }
2877 
2878 
2879 // The promoted_flags parameter is used to pass relevant access_flags
2880 // from the methods back up to the containing klass. These flag values
2881 // are added to klass's access_flags.
2882 // Side-effects: populates the _methods field in the parser
2883 void ClassFileParser::parse_methods(const ClassFileStream* const cfs,
2884                                     bool is_interface,


2885                                     AccessFlags* promoted_flags,
2886                                     bool* has_final_method,
2887                                     bool* declares_nonstatic_concrete_methods,
2888                                     TRAPS) {
2889   assert(cfs != NULL, "invariant");
2890   assert(promoted_flags != NULL, "invariant");
2891   assert(has_final_method != NULL, "invariant");
2892   assert(declares_nonstatic_concrete_methods != NULL, "invariant");
2893 
2894   assert(NULL == _methods, "invariant");
2895 
2896   cfs->guarantee_more(2, CHECK);  // length
2897   const u2 length = cfs->get_u2_fast();
2898   if (length == 0) {
2899     _methods = Universe::the_empty_method_array();
2900   } else {
2901     _methods = MetadataFactory::new_array<Method*>(_loader_data,
2902                                                    length,
2903                                                    NULL,
2904                                                    CHECK);
2905 
2906     for (int index = 0; index < length; index++) {
2907       Method* method = parse_method(cfs,
2908                                     is_interface,


2909                                     _cp,
2910                                     promoted_flags,
2911                                     CHECK);
2912 
2913       if (method->is_final()) {
2914         *has_final_method = true;
2915       }
2916       // declares_nonstatic_concrete_methods: declares concrete instance methods, any access flags
2917       // used for interface initialization, and default method inheritance analysis
2918       if (is_interface && !(*declares_nonstatic_concrete_methods)
2919         && !method->is_abstract() && !method->is_static()) {
2920         *declares_nonstatic_concrete_methods = true;
2921       }
2922       _methods->at_put(index, method);
2923     }
2924 
2925     if (_need_verify && length > 1) {
2926       // Check duplicated methods
2927       ResourceMark rm(THREAD);
2928       NameSigHash** names_and_sigs = NEW_RESOURCE_ARRAY_IN_THREAD(

3165         valid_klass_reference_at(outer_class_info_index),
3166       "outer_class_info_index %u has bad constant type in class file %s",
3167       outer_class_info_index, CHECK_0);
3168 
3169     if (outer_class_info_index != 0) {
3170       const Symbol* const outer_class_name = cp->klass_name_at(outer_class_info_index);
3171       char* bytes = (char*)outer_class_name->bytes();
3172       guarantee_property(bytes[0] != JVM_SIGNATURE_ARRAY,
3173                          "Outer class is an array class in class file %s", CHECK_0);
3174     }
3175     // Inner class name
3176     const u2 inner_name_index = cfs->get_u2_fast();
3177     check_property(
3178       inner_name_index == 0 || valid_symbol_at(inner_name_index),
3179       "inner_name_index %u has bad constant type in class file %s",
3180       inner_name_index, CHECK_0);
3181     if (_need_verify) {
3182       guarantee_property(inner_class_info_index != outer_class_info_index,
3183                          "Class is both outer and inner class in class file %s", CHECK_0);
3184     }
3185     // Access flags
3186     jint flags;
3187     // JVM_ACC_MODULE is defined in JDK-9 and later.
3188     if (_major_version >= JAVA_9_VERSION) {
3189       flags = cfs->get_u2_fast() & (RECOGNIZED_INNER_CLASS_MODIFIERS | JVM_ACC_MODULE);
3190     } else {
3191       flags = cfs->get_u2_fast() & RECOGNIZED_INNER_CLASS_MODIFIERS;


3192     }




3193     if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
3194       // Set abstract bit for old class files for backward compatibility
3195       flags |= JVM_ACC_ABSTRACT;
3196     }
3197     verify_legal_class_modifiers(flags, CHECK_0);












3198     AccessFlags inner_access_flags(flags);
3199 
3200     inner_classes->at_put(index++, inner_class_info_index);
3201     inner_classes->at_put(index++, outer_class_info_index);
3202     inner_classes->at_put(index++, inner_name_index);
3203     inner_classes->at_put(index++, inner_access_flags.as_short());
3204   }
3205 
3206   // Check for circular and duplicate entries.
3207   bool has_circularity = false;
3208   if (_need_verify) {
3209     has_circularity = check_inner_classes_circularity(cp, length * 4, CHECK_0);
3210     if (has_circularity) {
3211       // If circularity check failed then ignore InnerClasses attribute.
3212       MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
3213       index = 0;
3214       if (parsed_enclosingmethod_attribute) {
3215         inner_classes = MetadataFactory::new_array<u2>(_loader_data, 2, CHECK_0);
3216         _inner_classes = inner_classes;
3217       } else {

3281   if (length > 0) {
3282     int index = 0;
3283     cfs->guarantee_more(2 * length, CHECK_0);
3284     for (int n = 0; n < length; n++) {
3285       const u2 class_info_index = cfs->get_u2_fast();
3286       check_property(
3287         valid_klass_reference_at(class_info_index),
3288         "Permitted subclass class_info_index %u has bad constant type in class file %s",
3289         class_info_index, CHECK_0);
3290       permitted_subclasses->at_put(index++, class_info_index);
3291     }
3292     assert(index == size, "wrong size");
3293   }
3294 
3295   // Restore buffer's current position.
3296   cfs->set_current(current_mark);
3297 
3298   return length;
3299 }
3300 

































3301 //  Record {
3302 //    u2 attribute_name_index;
3303 //    u4 attribute_length;
3304 //    u2 components_count;
3305 //    component_info components[components_count];
3306 //  }
3307 //  component_info {
3308 //    u2 name_index;
3309 //    u2 descriptor_index
3310 //    u2 attributes_count;
3311 //    attribute_info_attributes[attributes_count];
3312 //  }
3313 u2 ClassFileParser::parse_classfile_record_attribute(const ClassFileStream* const cfs,
3314                                                      const ConstantPool* cp,
3315                                                      const u1* const record_attribute_start,
3316                                                      TRAPS) {
3317   const u1* const current_mark = cfs->current();
3318   int components_count = 0;
3319   unsigned int calculate_attr_size = 0;
3320   if (record_attribute_start != NULL) {

3565   }
3566   guarantee_property(current_start + attribute_byte_length == cfs->current(),
3567                      "Bad length on BootstrapMethods in class file %s",
3568                      CHECK);
3569 }
3570 
3571 void ClassFileParser::parse_classfile_attributes(const ClassFileStream* const cfs,
3572                                                  ConstantPool* cp,
3573                  ClassFileParser::ClassAnnotationCollector* parsed_annotations,
3574                                                  TRAPS) {
3575   assert(cfs != NULL, "invariant");
3576   assert(cp != NULL, "invariant");
3577   assert(parsed_annotations != NULL, "invariant");
3578 
3579   // Set inner classes attribute to default sentinel
3580   _inner_classes = Universe::the_empty_short_array();
3581   // Set nest members attribute to default sentinel
3582   _nest_members = Universe::the_empty_short_array();
3583   // Set _permitted_subclasses attribute to default sentinel
3584   _permitted_subclasses = Universe::the_empty_short_array();


3585   cfs->guarantee_more(2, CHECK);  // attributes_count
3586   u2 attributes_count = cfs->get_u2_fast();
3587   bool parsed_sourcefile_attribute = false;
3588   bool parsed_innerclasses_attribute = false;
3589   bool parsed_nest_members_attribute = false;
3590   bool parsed_permitted_subclasses_attribute = false;

3591   bool parsed_nest_host_attribute = false;
3592   bool parsed_record_attribute = false;
3593   bool parsed_enclosingmethod_attribute = false;
3594   bool parsed_bootstrap_methods_attribute = false;
3595   const u1* runtime_visible_annotations = NULL;
3596   int runtime_visible_annotations_length = 0;
3597   const u1* runtime_invisible_annotations = NULL;
3598   int runtime_invisible_annotations_length = 0;
3599   const u1* runtime_visible_type_annotations = NULL;
3600   int runtime_visible_type_annotations_length = 0;
3601   const u1* runtime_invisible_type_annotations = NULL;
3602   int runtime_invisible_type_annotations_length = 0;
3603   bool runtime_invisible_type_annotations_exists = false;
3604   bool runtime_invisible_annotations_exists = false;
3605   bool parsed_source_debug_ext_annotations_exist = false;
3606   const u1* inner_classes_attribute_start = NULL;
3607   u4  inner_classes_attribute_length = 0;
3608   u2  enclosing_method_class_index = 0;
3609   u2  enclosing_method_method_index = 0;
3610   const u1* nest_members_attribute_start = NULL;
3611   u4  nest_members_attribute_length = 0;
3612   const u1* record_attribute_start = NULL;
3613   u4  record_attribute_length = 0;
3614   const u1* permitted_subclasses_attribute_start = NULL;
3615   u4  permitted_subclasses_attribute_length = 0;


3616 
3617   // Iterate over attributes
3618   while (attributes_count--) {
3619     cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
3620     const u2 attribute_name_index = cfs->get_u2_fast();
3621     const u4 attribute_length = cfs->get_u4_fast();
3622     check_property(
3623       valid_symbol_at(attribute_name_index),
3624       "Attribute name has bad constant pool index %u in class file %s",
3625       attribute_name_index, CHECK);
3626     const Symbol* const tag = cp->symbol_at(attribute_name_index);
3627     if (tag == vmSymbols::tag_source_file()) {
3628       // Check for SourceFile tag
3629       if (_need_verify) {
3630         guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
3631       }
3632       if (parsed_sourcefile_attribute) {
3633         classfile_parse_error("Multiple SourceFile attributes in class file %s", THREAD);
3634         return;
3635       } else {

3822               return;
3823             }
3824             parsed_record_attribute = true;
3825             record_attribute_start = cfs->current();
3826             record_attribute_length = attribute_length;
3827           } else if (_major_version >= JAVA_17_VERSION) {
3828             if (tag == vmSymbols::tag_permitted_subclasses()) {
3829               if (parsed_permitted_subclasses_attribute) {
3830                 classfile_parse_error("Multiple PermittedSubclasses attributes in class file %s", CHECK);
3831                 return;
3832               }
3833               // Classes marked ACC_FINAL cannot have a PermittedSubclasses attribute.
3834               if (_access_flags.is_final()) {
3835                 classfile_parse_error("PermittedSubclasses attribute in final class file %s", CHECK);
3836                 return;
3837               }
3838               parsed_permitted_subclasses_attribute = true;
3839               permitted_subclasses_attribute_start = cfs->current();
3840               permitted_subclasses_attribute_length = attribute_length;
3841             }









3842           }
3843           // Skip attribute_length for any attribute where major_verson >= JAVA_17_VERSION
3844           cfs->skip_u1(attribute_length, CHECK);
3845         } else {
3846           // Unknown attribute
3847           cfs->skip_u1(attribute_length, CHECK);
3848         }
3849       } else {
3850         // Unknown attribute
3851         cfs->skip_u1(attribute_length, CHECK);
3852       }
3853     } else {
3854       // Unknown attribute
3855       cfs->skip_u1(attribute_length, CHECK);
3856     }
3857   }
3858   _class_annotations = assemble_annotations(runtime_visible_annotations,
3859                                             runtime_visible_annotations_length,
3860                                             runtime_invisible_annotations,
3861                                             runtime_invisible_annotations_length,

3902                             CHECK);
3903     if (_need_verify) {
3904       guarantee_property(record_attribute_length == calculated_attr_length,
3905                          "Record attribute has wrong length in class file %s",
3906                          CHECK);
3907     }
3908   }
3909 
3910   if (parsed_permitted_subclasses_attribute) {
3911     const u2 num_subclasses = parse_classfile_permitted_subclasses_attribute(
3912                             cfs,
3913                             permitted_subclasses_attribute_start,
3914                             CHECK);
3915     if (_need_verify) {
3916       guarantee_property(
3917         permitted_subclasses_attribute_length == sizeof(num_subclasses) + sizeof(u2) * num_subclasses,
3918         "Wrong PermittedSubclasses attribute length in class file %s", CHECK);
3919     }
3920   }
3921 












3922   if (_max_bootstrap_specifier_index >= 0) {
3923     guarantee_property(parsed_bootstrap_methods_attribute,
3924                        "Missing BootstrapMethods attribute in class file %s", CHECK);
3925   }
3926 }
3927 
3928 void ClassFileParser::apply_parsed_class_attributes(InstanceKlass* k) {
3929   assert(k != NULL, "invariant");
3930 
3931   if (_synthetic_flag)
3932     k->set_is_synthetic();
3933   if (_sourcefile_index != 0) {
3934     k->set_source_file_name_index(_sourcefile_index);
3935   }
3936   if (_generic_signature_index != 0) {
3937     k->set_generic_signature_index(_generic_signature_index);
3938   }
3939   if (_sde_buffer != NULL) {
3940     k->set_source_debug_extension(_sde_buffer, _sde_length);
3941   }

3966     // _combined_annotations so these fields can now be cleared.
3967     _class_annotations       = NULL;
3968     _class_type_annotations  = NULL;
3969     _fields_annotations      = NULL;
3970     _fields_type_annotations = NULL;
3971 }
3972 
3973 // Transfer ownership of metadata allocated to the InstanceKlass.
3974 void ClassFileParser::apply_parsed_class_metadata(
3975                                             InstanceKlass* this_klass,
3976                                             int java_fields_count) {
3977   assert(this_klass != NULL, "invariant");
3978 
3979   _cp->set_pool_holder(this_klass);
3980   this_klass->set_constants(_cp);
3981   this_klass->set_fields(_fields, java_fields_count);
3982   this_klass->set_methods(_methods);
3983   this_klass->set_inner_classes(_inner_classes);
3984   this_klass->set_nest_members(_nest_members);
3985   this_klass->set_nest_host_index(_nest_host);

3986   this_klass->set_annotations(_combined_annotations);
3987   this_klass->set_permitted_subclasses(_permitted_subclasses);
3988   this_klass->set_record_components(_record_components);
3989   // Delay the setting of _local_interfaces and _transitive_interfaces until after
3990   // initialize_supers() in fill_instance_klass(). It is because the _local_interfaces could
3991   // be shared with _transitive_interfaces and _transitive_interfaces may be shared with
3992   // its _super. If an OOM occurs while loading the current klass, its _super field
3993   // may not have been set. When GC tries to free the klass, the _transitive_interfaces
3994   // may be deallocated mistakenly in InstanceKlass::deallocate_interfaces(). Subsequent
3995   // dereferences to the deallocated _transitive_interfaces will result in a crash.
3996 
3997   // Clear out these fields so they don't get deallocated by the destructor
3998   clear_class_metadata();
3999 }
4000 
4001 AnnotationArray* ClassFileParser::assemble_annotations(const u1* const runtime_visible_annotations,
4002                                                        int runtime_visible_annotations_length,
4003                                                        const u1* const runtime_invisible_annotations,
4004                                                        int runtime_invisible_annotations_length,
4005                                                        TRAPS) {

4017     }
4018     if (runtime_invisible_annotations != NULL) {
4019       for (int i = 0; i < runtime_invisible_annotations_length; i++) {
4020         int append = runtime_visible_annotations_length+i;
4021         annotations->at_put(append, runtime_invisible_annotations[i]);
4022       }
4023     }
4024   }
4025   return annotations;
4026 }
4027 
4028 const InstanceKlass* ClassFileParser::parse_super_class(ConstantPool* const cp,
4029                                                         const int super_class_index,
4030                                                         const bool need_verify,
4031                                                         TRAPS) {
4032   assert(cp != NULL, "invariant");
4033   const InstanceKlass* super_klass = NULL;
4034 
4035   if (super_class_index == 0) {
4036     check_property(_class_name == vmSymbols::java_lang_Object(),
4037                    "Invalid superclass index %u in class file %s",
4038                    super_class_index,
4039                    CHECK_NULL);
4040   } else {
4041     check_property(valid_klass_reference_at(super_class_index),
4042                    "Invalid superclass index %u in class file %s",
4043                    super_class_index,
4044                    CHECK_NULL);
4045     // The class name should be legal because it is checked when parsing constant pool.
4046     // However, make sure it is not an array type.
4047     bool is_array = false;
4048     if (cp->tag_at(super_class_index).is_klass()) {
4049       super_klass = InstanceKlass::cast(cp->resolved_klass_at(super_class_index));
4050       if (need_verify)
4051         is_array = super_klass->is_array_klass();
4052     } else if (need_verify) {
4053       is_array = (cp->klass_name_at(super_class_index)->char_at(0) == JVM_SIGNATURE_ARRAY);
4054     }
4055     if (need_verify) {

4056       guarantee_property(!is_array,
4057                         "Bad superclass name in class file %s", CHECK_NULL);
4058     }
4059   }
4060   return super_klass;
4061 }
4062 
4063 OopMapBlocksBuilder::OopMapBlocksBuilder(unsigned int max_blocks) {
4064   _max_nonstatic_oop_maps = max_blocks;
4065   _nonstatic_oop_map_count = 0;
4066   if (max_blocks == 0) {
4067     _nonstatic_oop_maps = NULL;
4068   } else {
4069     _nonstatic_oop_maps =
4070         NEW_RESOURCE_ARRAY(OopMapBlock, _max_nonstatic_oop_maps);
4071     memset(_nonstatic_oop_maps, 0, sizeof(OopMapBlock) * max_blocks);
4072   }
4073 }
4074 
4075 OopMapBlock* OopMapBlocksBuilder::last_oop_map() const {

4159 }
4160 
4161 void OopMapBlocksBuilder::print_on(outputStream* st) const {
4162   st->print_cr("  OopMapBlocks: %3d  /%3d", _nonstatic_oop_map_count, _max_nonstatic_oop_maps);
4163   if (_nonstatic_oop_map_count > 0) {
4164     OopMapBlock* map = _nonstatic_oop_maps;
4165     OopMapBlock* last_map = last_oop_map();
4166     assert(map <= last_map, "Last less than first");
4167     while (map <= last_map) {
4168       st->print_cr("    Offset: %3d  -%3d Count: %3d", map->offset(),
4169                    map->offset() + map->offset_span() - heapOopSize, map->count());
4170       map++;
4171     }
4172   }
4173 }
4174 
4175 void OopMapBlocksBuilder::print_value_on(outputStream* st) const {
4176   print_on(st);
4177 }
4178 



















4179 void ClassFileParser::set_precomputed_flags(InstanceKlass* ik) {
4180   assert(ik != NULL, "invariant");
4181 
4182   const Klass* const super = ik->super();
4183 
4184   // Check if this klass has an empty finalize method (i.e. one with return bytecode only),
4185   // in which case we don't have to register objects as finalizable
4186   if (!_has_empty_finalizer) {
4187     if (_has_finalizer ||
4188         (super != NULL && super->has_finalizer())) {
4189       ik->set_has_finalizer();
4190     }
4191   }
4192 
4193 #ifdef ASSERT
4194   bool f = false;
4195   const Method* const m = ik->lookup_method(vmSymbols::finalize_method_name(),
4196                                            vmSymbols::void_method_signature());
4197   if (InstanceKlass::is_finalization_enabled() &&
4198       (m != NULL) && !m->is_empty_method()) {
4199       f = true;
4200   }
4201 
4202   // Spec doesn't prevent agent from redefinition of empty finalizer.
4203   // Despite the fact that it's generally bad idea and redefined finalizer
4204   // will not work as expected we shouldn't abort vm in this case
4205   if (!ik->has_redefined_this_or_super()) {
4206     assert(ik->has_finalizer() == f, "inconsistent has_finalizer");
4207   }
4208 #endif
4209 
4210   // Check if this klass supports the java.lang.Cloneable interface
4211   if (vmClasses::Cloneable_klass_loaded()) {
4212     if (ik->is_subtype_of(vmClasses::Cloneable_klass())) {





4213       ik->set_is_cloneable();
4214     }
4215   }
4216 
4217   // Check if this klass has a vanilla default constructor
4218   if (super == NULL) {
4219     // java.lang.Object has empty default constructor
4220     ik->set_has_vanilla_constructor();
4221   } else {
4222     if (super->has_vanilla_constructor() &&
4223         _has_vanilla_constructor) {
4224       ik->set_has_vanilla_constructor();
4225     }
4226 #ifdef ASSERT
4227     bool v = false;
4228     if (super->has_vanilla_constructor()) {
4229       const Method* const constructor =
4230         ik->find_method(vmSymbols::object_initializer_name(),
4231                        vmSymbols::void_method_signature());
4232       if (constructor != NULL && constructor->is_vanilla_constructor()) {
4233         v = true;
4234       }
4235     }
4236     assert(v == ik->has_vanilla_constructor(), "inconsistent has_vanilla_constructor");
4237 #endif
4238   }
4239 
4240   // If it cannot be fast-path allocated, set a bit in the layout helper.
4241   // See documentation of InstanceKlass::can_be_fastpath_allocated().
4242   assert(ik->size_helper() > 0, "layout_helper is initialized");
4243   if ((!RegisterFinalizersAtInit && ik->has_finalizer())
4244       || ik->is_abstract() || ik->is_interface()
4245       || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == NULL)
4246       || ik->size_helper() >= FastAllocateSizeLimit) {
4247     // Forbid fast-path allocation.
4248     const jint lh = Klass::instance_layout_helper(ik->size_helper(), true);
4249     ik->set_layout_helper(lh);
4250   }
4251 }
4252 






4253 // utility methods for appending an array with check for duplicates
4254 
4255 static void append_interfaces(GrowableArray<InstanceKlass*>* result,
4256                               const Array<InstanceKlass*>* const ifs) {
4257   // iterate over new interfaces
4258   for (int i = 0; i < ifs->length(); i++) {
4259     InstanceKlass* const e = ifs->at(i);
4260     assert(e->is_klass() && e->is_interface(), "just checking");
4261     // add new interface
4262     result->append_if_missing(e);
4263   }
4264 }
4265 
4266 static Array<InstanceKlass*>* compute_transitive_interfaces(const InstanceKlass* super,
4267                                                             Array<InstanceKlass*>* local_ifs,
4268                                                             ClassLoaderData* loader_data,
4269                                                             TRAPS) {
4270   assert(local_ifs != NULL, "invariant");
4271   assert(loader_data != NULL, "invariant");
4272 

4276   // Add superclass transitive interfaces size
4277   if (super != NULL) {
4278     super_size = super->transitive_interfaces()->length();
4279     max_transitive_size += super_size;
4280   }
4281   // Add local interfaces' super interfaces
4282   const int local_size = local_ifs->length();
4283   for (int i = 0; i < local_size; i++) {
4284     InstanceKlass* const l = local_ifs->at(i);
4285     max_transitive_size += l->transitive_interfaces()->length();
4286   }
4287   // Finally add local interfaces
4288   max_transitive_size += local_size;
4289   // Construct array
4290   if (max_transitive_size == 0) {
4291     // no interfaces, use canonicalized array
4292     return Universe::the_empty_instance_klass_array();
4293   } else if (max_transitive_size == super_size) {
4294     // no new local interfaces added, share superklass' transitive interface array
4295     return super->transitive_interfaces();
4296   } else if (max_transitive_size == local_size) {
4297     // only local interfaces added, share local interface array
4298     return local_ifs;

4299   } else {
4300     ResourceMark rm;
4301     GrowableArray<InstanceKlass*>* const result = new GrowableArray<InstanceKlass*>(max_transitive_size);
4302 
4303     // Copy down from superclass
4304     if (super != NULL) {
4305       append_interfaces(result, super->transitive_interfaces());
4306     }
4307 
4308     // Copy down from local interfaces' superinterfaces
4309     for (int i = 0; i < local_size; i++) {
4310       InstanceKlass* const l = local_ifs->at(i);
4311       append_interfaces(result, l->transitive_interfaces());
4312     }
4313     // Finally add local interfaces
4314     append_interfaces(result, local_ifs);
4315 
4316     // length will be less than the max_transitive_size if duplicates were removed
4317     const int length = result->length();
4318     assert(length <= max_transitive_size, "just checking");

4319     Array<InstanceKlass*>* const new_result =
4320       MetadataFactory::new_array<InstanceKlass*>(loader_data, length, CHECK_NULL);
4321     for (int i = 0; i < length; i++) {
4322       InstanceKlass* const e = result->at(i);
4323       assert(e != NULL, "just checking");
4324       new_result->at_put(i, e);
4325     }
4326     return new_result;
4327   }
4328 }
4329 
4330 void ClassFileParser::check_super_class_access(const InstanceKlass* this_klass, TRAPS) {
4331   assert(this_klass != NULL, "invariant");
4332   const Klass* const super = this_klass->super();
4333 
4334   if (super != NULL) {
4335     const InstanceKlass* super_ik = InstanceKlass::cast(super);
4336 
4337     if (super->is_final()) {
4338       classfile_icce_error("class %s cannot inherit from final class %s", super_ik, THREAD);
4339       return;
4340     }
4341 
4342     if (super_ik->is_sealed() && !super_ik->has_as_permitted_subclass(this_klass)) {
4343       classfile_icce_error("class %s cannot inherit from sealed class %s", super_ik, THREAD);
4344       return;
4345     }
4346 










4347     // If the loader is not the boot loader then throw an exception if its
4348     // superclass is in package jdk.internal.reflect and its loader is not a
4349     // special reflection class loader
4350     if (!this_klass->class_loader_data()->is_the_null_class_loader_data()) {
4351       PackageEntry* super_package = super->package();
4352       if (super_package != NULL &&
4353           super_package->name()->fast_compare(vmSymbols::jdk_internal_reflect()) == 0 &&
4354           !java_lang_ClassLoader::is_reflection_class_loader(this_klass->class_loader())) {
4355         ResourceMark rm(THREAD);
4356         Exceptions::fthrow(
4357           THREAD_AND_LOCATION,
4358           vmSymbols::java_lang_IllegalAccessError(),
4359           "class %s loaded by %s cannot access jdk/internal/reflect superclass %s",
4360           this_klass->external_name(),
4361           this_klass->class_loader_data()->loader_name_and_id(),
4362           super->external_name());
4363         return;
4364       }
4365     }
4366 

4510 
4511   for (int index = 0; index < num_methods; index++) {
4512     const Method* const m = methods->at(index);
4513     // if m is static and not the init method, throw a verify error
4514     if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) {
4515       ResourceMark rm(THREAD);
4516       Exceptions::fthrow(
4517         THREAD_AND_LOCATION,
4518         vmSymbols::java_lang_VerifyError(),
4519         "Illegal static method %s in interface %s",
4520         m->name()->as_C_string(),
4521         this_klass->external_name()
4522       );
4523       return;
4524     }
4525   }
4526 }
4527 
4528 // utility methods for format checking
4529 
4530 void ClassFileParser::verify_legal_class_modifiers(jint flags, TRAPS) const {
4531   const bool is_module = (flags & JVM_ACC_MODULE) != 0;




4532   assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");


4533   if (is_module) {
4534     ResourceMark rm(THREAD);
4535     Exceptions::fthrow(
4536       THREAD_AND_LOCATION,
4537       vmSymbols::java_lang_NoClassDefFoundError(),
4538       "%s is not a class because access_flag ACC_MODULE is set",
4539       _class_name->as_C_string());
4540     return;
4541   }
4542 
4543   if (!_need_verify) { return; }














4544 
4545   const bool is_interface  = (flags & JVM_ACC_INTERFACE)  != 0;
4546   const bool is_abstract   = (flags & JVM_ACC_ABSTRACT)   != 0;
4547   const bool is_final      = (flags & JVM_ACC_FINAL)      != 0;
4548   const bool is_super      = (flags & JVM_ACC_SUPER)      != 0;
4549   const bool is_enum       = (flags & JVM_ACC_ENUM)       != 0;
4550   const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4551   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4552 
4553   if ((is_abstract && is_final) ||
4554       (is_interface && !is_abstract) ||
4555       (is_interface && major_gte_1_5 && (is_super || is_enum)) ||
4556       (!is_interface && major_gte_1_5 && is_annotation)) {




4557     ResourceMark rm(THREAD);
4558     Exceptions::fthrow(
4559       THREAD_AND_LOCATION,
4560       vmSymbols::java_lang_ClassFormatError(),
4561       "Illegal class modifiers in class %s: 0x%X",
4562       _class_name->as_C_string(), flags
4563     );
4564     return;














4565   }
4566 }
4567 
4568 static bool has_illegal_visibility(jint flags) {
4569   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4570   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4571   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4572 
4573   return ((is_public && is_protected) ||
4574           (is_public && is_private) ||
4575           (is_protected && is_private));
4576 }
4577 
4578 // A legal major_version.minor_version must be one of the following:
4579 //
4580 //  Major_version >= 45 and major_version < 56, any minor_version.
4581 //  Major_version >= 56 and major_version <= JVM_CLASSFILE_MAJOR_VERSION and minor_version = 0.
4582 //  Major_version = JVM_CLASSFILE_MAJOR_VERSION and minor_version = 65535 and --enable-preview is present.
4583 //
4584 void ClassFileParser::verify_class_version(u2 major, u2 minor, Symbol* class_name, TRAPS){

4610         THREAD_AND_LOCATION,
4611         vmSymbols::java_lang_UnsupportedClassVersionError(),
4612         "%s (class file version %u.%u) was compiled with preview features that are unsupported. "
4613         "This version of the Java Runtime only recognizes preview features for class file version %u.%u",
4614         class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION, JAVA_PREVIEW_MINOR_VERSION);
4615       return;
4616     }
4617 
4618     if (!Arguments::enable_preview()) {
4619       classfile_ucve_error("Preview features are not enabled for %s (class file version %u.%u). Try running with '--enable-preview'",
4620                            class_name, major, minor, THREAD);
4621       return;
4622     }
4623 
4624   } else { // minor != JAVA_PREVIEW_MINOR_VERSION
4625     classfile_ucve_error("%s (class file version %u.%u) was compiled with an invalid non-zero minor version",
4626                          class_name, major, minor, THREAD);
4627   }
4628 }
4629 
4630 void ClassFileParser::verify_legal_field_modifiers(jint flags,
4631                                                    bool is_interface,
4632                                                    TRAPS) const {
4633   if (!_need_verify) { return; }
4634 
4635   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4636   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4637   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4638   const bool is_static    = (flags & JVM_ACC_STATIC)    != 0;
4639   const bool is_final     = (flags & JVM_ACC_FINAL)     != 0;
4640   const bool is_volatile  = (flags & JVM_ACC_VOLATILE)  != 0;
4641   const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
4642   const bool is_enum      = (flags & JVM_ACC_ENUM)      != 0;
4643   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4644 





4645   bool is_illegal = false;
4646 
4647   if (is_interface) {
4648     if (!is_public || !is_static || !is_final || is_private ||
4649         is_protected || is_volatile || is_transient ||
4650         (major_gte_1_5 && is_enum)) {
4651       is_illegal = true;
4652     }
4653   } else { // not interface
4654     if (has_illegal_visibility(flags) || (is_final && is_volatile)) {
4655       is_illegal = true;






4656     }
4657   }
4658 
4659   if (is_illegal) {
4660     ResourceMark rm(THREAD);
4661     Exceptions::fthrow(
4662       THREAD_AND_LOCATION,
4663       vmSymbols::java_lang_ClassFormatError(),
4664       "Illegal field modifiers in class %s: 0x%X",
4665       _class_name->as_C_string(), flags);
4666     return;
4667   }
4668 }
4669 
4670 void ClassFileParser::verify_legal_method_modifiers(jint flags,
4671                                                     bool is_interface,
4672                                                     const Symbol* name,
4673                                                     TRAPS) const {
4674   if (!_need_verify) { return; }
4675 
4676   const bool is_public       = (flags & JVM_ACC_PUBLIC)       != 0;
4677   const bool is_private      = (flags & JVM_ACC_PRIVATE)      != 0;
4678   const bool is_static       = (flags & JVM_ACC_STATIC)       != 0;
4679   const bool is_final        = (flags & JVM_ACC_FINAL)        != 0;
4680   const bool is_native       = (flags & JVM_ACC_NATIVE)       != 0;
4681   const bool is_abstract     = (flags & JVM_ACC_ABSTRACT)     != 0;
4682   const bool is_bridge       = (flags & JVM_ACC_BRIDGE)       != 0;
4683   const bool is_strict       = (flags & JVM_ACC_STRICT)       != 0;
4684   const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
4685   const bool is_protected    = (flags & JVM_ACC_PROTECTED)    != 0;
4686   const bool major_gte_1_5   = _major_version >= JAVA_1_5_VERSION;
4687   const bool major_gte_8     = _major_version >= JAVA_8_VERSION;
4688   const bool major_gte_17    = _major_version >= JAVA_17_VERSION;
4689   const bool is_initializer  = (name == vmSymbols::object_initializer_name());




4690 
4691   bool is_illegal = false;
4692 

4693   if (is_interface) {
4694     if (major_gte_8) {
4695       // Class file version is JAVA_8_VERSION or later Methods of
4696       // interfaces may set any of the flags except ACC_PROTECTED,
4697       // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must
4698       // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.
4699       if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
4700           (is_native || is_protected || is_final || is_synchronized) ||
4701           // If a specific method of a class or interface has its
4702           // ACC_ABSTRACT flag set, it must not have any of its
4703           // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,
4704           // ACC_STRICT, or ACC_SYNCHRONIZED flags set.  No need to
4705           // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as
4706           // those flags are illegal irrespective of ACC_ABSTRACT being set or not.
4707           (is_abstract && (is_private || is_static || (!major_gte_17 && is_strict)))) {
4708         is_illegal = true;
4709       }
4710     } else if (major_gte_1_5) {
4711       // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)
4712       if (!is_public || is_private || is_protected || is_static || is_final ||
4713           is_synchronized || is_native || !is_abstract || is_strict) {
4714         is_illegal = true;
4715       }
4716     } else {
4717       // Class file version is pre-JAVA_1_5_VERSION
4718       if (!is_public || is_static || is_final || is_native || !is_abstract) {
4719         is_illegal = true;
4720       }
4721     }
4722   } else { // not interface
4723     if (has_illegal_visibility(flags)) {
4724       is_illegal = true;
4725     } else {
4726       if (is_initializer) {
4727         if (is_static || is_final || is_synchronized || is_native ||
4728             is_abstract || (major_gte_1_5 && is_bridge)) {
4729           is_illegal = true;
4730         }









4731       } else { // not initializer
4732         if (is_abstract) {
4733           if ((is_final || is_native || is_private || is_static ||
4734               (major_gte_1_5 && (is_synchronized || (!major_gte_17 && is_strict))))) {
4735             is_illegal = true;





4736           }
4737         }
4738       }
4739     }
4740   }
4741 
4742   if (is_illegal) {
4743     ResourceMark rm(THREAD);
4744     Exceptions::fthrow(
4745       THREAD_AND_LOCATION,
4746       vmSymbols::java_lang_ClassFormatError(),
4747       "Method %s in class %s has illegal modifiers: 0x%X",
4748       name->as_C_string(), _class_name->as_C_string(), flags);
4749     return;
4750   }
4751 }
4752 
4753 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer,
4754                                         int length,
4755                                         TRAPS) const {
4756   assert(_need_verify, "only called when _need_verify is true");
4757   if (!UTF8::is_legal_utf8(buffer, length, _major_version <= 47)) {
4758     classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", THREAD);
4759   }
4760 }
4761 
4762 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
4763 // In class names, '/' separates unqualified names.  This is verified in this function also.
4764 // Method names also may not contain the characters '<' or '>', unless <init>
4765 // or <clinit>.  Note that method names may not be <init> or <clinit> in this
4766 // method.  Because these names have been checked as special cases before
4767 // calling this method in verify_legal_method_name.
4768 //

4886 // be taken as a field signature. Allow "void" if void_ok.
4887 // Return a pointer to just past the signature.
4888 // Return NULL if no legal signature is found.
4889 const char* ClassFileParser::skip_over_field_signature(const char* signature,
4890                                                        bool void_ok,
4891                                                        unsigned int length,
4892                                                        TRAPS) const {
4893   unsigned int array_dim = 0;
4894   while (length > 0) {
4895     switch (signature[0]) {
4896     case JVM_SIGNATURE_VOID: if (!void_ok) { return NULL; }
4897     case JVM_SIGNATURE_BOOLEAN:
4898     case JVM_SIGNATURE_BYTE:
4899     case JVM_SIGNATURE_CHAR:
4900     case JVM_SIGNATURE_SHORT:
4901     case JVM_SIGNATURE_INT:
4902     case JVM_SIGNATURE_FLOAT:
4903     case JVM_SIGNATURE_LONG:
4904     case JVM_SIGNATURE_DOUBLE:
4905       return signature + 1;
4906     case JVM_SIGNATURE_CLASS: {











4907       if (_major_version < JAVA_1_5_VERSION) {
4908         // Skip over the class name if one is there
4909         const char* const p = skip_over_field_name(signature + 1, true, --length);
4910 
4911         // The next character better be a semicolon
4912         if (p && (p - signature) > 1 && p[0] == JVM_SIGNATURE_ENDCLASS) {
4913           return p + 1;
4914         }
4915       }
4916       else {
4917         // Skip leading 'L' and ignore first appearance of ';'
4918         signature++;
4919         const char* c = (const char*) memchr(signature, JVM_SIGNATURE_ENDCLASS, length - 1);
4920         // Format check signature
4921         if (c != NULL) {
4922           int newlen = c - (char*) signature;
4923           bool legal = verify_unqualified_name(signature, newlen, LegalClass);
4924           if (!legal) {
4925             classfile_parse_error("Class name is empty or contains illegal character "
4926                                   "in descriptor in class file %s",
4927                                   THREAD);
4928             return NULL;
4929           }
4930           return signature + newlen + 1;
4931         }
4932       }
4933       return NULL;
4934     }
4935     case JVM_SIGNATURE_ARRAY:
4936       array_dim++;
4937       if (array_dim > 255) {

4953 
4954 // Checks if name is a legal class name.
4955 void ClassFileParser::verify_legal_class_name(const Symbol* name, TRAPS) const {
4956   if (!_need_verify || _relax_verify) { return; }
4957 
4958   assert(name->refcount() > 0, "symbol must be kept alive");
4959   char* bytes = (char*)name->bytes();
4960   unsigned int length = name->utf8_length();
4961   bool legal = false;
4962 
4963   if (length > 0) {
4964     const char* p;
4965     if (bytes[0] == JVM_SIGNATURE_ARRAY) {
4966       p = skip_over_field_signature(bytes, false, length, CHECK);
4967       legal = (p != NULL) && ((p - bytes) == (int)length);
4968     } else if (_major_version < JAVA_1_5_VERSION) {
4969       if (bytes[0] != JVM_SIGNATURE_SPECIAL) {
4970         p = skip_over_field_name(bytes, true, length);
4971         legal = (p != NULL) && ((p - bytes) == (int)length);
4972       }




4973     } else {
4974       // 4900761: relax the constraints based on JSR202 spec
4975       // Class names may be drawn from the entire Unicode character set.
4976       // Identifiers between '/' must be unqualified names.
4977       // The utf8 string has been verified when parsing cpool entries.
4978       legal = verify_unqualified_name(bytes, length, LegalClass);
4979     }
4980   }
4981   if (!legal) {
4982     ResourceMark rm(THREAD);
4983     assert(_class_name != NULL, "invariant");
4984     Exceptions::fthrow(
4985       THREAD_AND_LOCATION,
4986       vmSymbols::java_lang_ClassFormatError(),
4987       "Illegal class name \"%.*s\" in class file %s", length, bytes,
4988       _class_name->as_C_string()
4989     );
4990     return;
4991   }
4992 }

5050 
5051   if (!legal) {
5052     ResourceMark rm(THREAD);
5053     assert(_class_name != NULL, "invariant");
5054     Exceptions::fthrow(
5055       THREAD_AND_LOCATION,
5056       vmSymbols::java_lang_ClassFormatError(),
5057       "Illegal method name \"%.*s\" in class %s", length, bytes,
5058       _class_name->as_C_string()
5059     );
5060     return;
5061   }
5062 }
5063 
5064 
5065 // Checks if signature is a legal field signature.
5066 void ClassFileParser::verify_legal_field_signature(const Symbol* name,
5067                                                    const Symbol* signature,
5068                                                    TRAPS) const {
5069   if (!_need_verify) { return; }



5070 
5071   const char* const bytes = (const char* const)signature->bytes();
5072   const unsigned int length = signature->utf8_length();
5073   const char* const p = skip_over_field_signature(bytes, false, length, CHECK);
5074 
5075   if (p == NULL || (p - bytes) != (int)length) {
5076     throwIllegalSignature("Field", name, signature, CHECK);
5077   }
5078 }
5079 
5080 // Check that the signature is compatible with the method name.  For example,
5081 // check that <init> has a void signature.
5082 void ClassFileParser::verify_legal_name_with_signature(const Symbol* name,
5083                                                        const Symbol* signature,
5084                                                        TRAPS) const {
5085   if (!_need_verify) {
5086     return;
5087   }
5088 
5089   // Class initializers cannot have args for class format version >= 51.
5090   if (name == vmSymbols::class_initializer_name() &&
5091       signature != vmSymbols::void_method_signature() &&
5092       _major_version >= JAVA_7_VERSION) {
5093     throwIllegalSignature("Method", name, signature, THREAD);
5094     return;
5095   }
5096 
5097   int sig_length = signature->utf8_length();
5098   if (name->utf8_length() > 0 &&

5099       name->char_at(0) == JVM_SIGNATURE_SPECIAL &&
5100       sig_length > 0 &&
5101       signature->char_at(sig_length - 1) != JVM_SIGNATURE_VOID) {
5102     throwIllegalSignature("Method", name, signature, THREAD);

5103   }
5104 }
5105 
5106 // Checks if signature is a legal method signature.
5107 // Returns number of parameters
5108 int ClassFileParser::verify_legal_method_signature(const Symbol* name,
5109                                                    const Symbol* signature,
5110                                                    TRAPS) const {
5111   if (!_need_verify) {
5112     // make sure caller's args_size will be less than 0 even for non-static
5113     // method so it will be recomputed in compute_size_of_parameters().
5114     return -2;
5115   }
5116 
5117   unsigned int args_size = 0;
5118   const char* p = (const char*)signature->bytes();
5119   unsigned int length = signature->utf8_length();
5120   const char* nextp;
5121 
5122   // The first character must be a '('

5258   }
5259 }
5260 
5261 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook,
5262                                                       const ClassInstanceInfo& cl_inst_info,
5263                                                       TRAPS) {
5264   if (_klass != NULL) {
5265     return _klass;
5266   }
5267 
5268   InstanceKlass* const ik =
5269     InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
5270 
5271   if (is_hidden()) {
5272     mangle_hidden_class_name(ik);
5273   }
5274 
5275   fill_instance_klass(ik, changed_by_loadhook, cl_inst_info, CHECK_NULL);
5276 
5277   assert(_klass == ik, "invariant");
5278 
5279   return ik;
5280 }
5281 
5282 void ClassFileParser::fill_instance_klass(InstanceKlass* ik,
5283                                           bool changed_by_loadhook,
5284                                           const ClassInstanceInfo& cl_inst_info,
5285                                           TRAPS) {
5286   assert(ik != NULL, "invariant");
5287 
5288   // Set name and CLD before adding to CLD
5289   ik->set_class_loader_data(_loader_data);
5290   ik->set_name(_class_name);
5291 
5292   // Add all classes to our internal class loader list here,
5293   // including classes in the bootstrap (NULL) class loader.
5294   const bool publicize = !is_internal();
5295 
5296   _loader_data->add_class(ik, publicize);
5297 
5298   set_klass_to_deallocate(ik);
5299 
5300   assert(_field_info != NULL, "invariant");
5301   assert(ik->static_field_size() == _field_info->_static_field_size, "sanity");
5302   assert(ik->nonstatic_oop_map_count() == _field_info->oop_map_blocks->_nonstatic_oop_map_count,
5303          "sanity");
5304 
5305   assert(ik->is_instance_klass(), "sanity");
5306   assert(ik->size_helper() == _field_info->_instance_size, "sanity");
5307 
5308   // Fill in information already parsed
5309   ik->set_should_verify_class(_need_verify);
5310 
5311   // Not yet: supers are done below to support the new subtype-checking fields
5312   ik->set_nonstatic_field_size(_field_info->_nonstatic_field_size);
5313   ik->set_has_nonstatic_fields(_field_info->_has_nonstatic_fields);










5314   assert(_fac != NULL, "invariant");
5315   ik->set_static_oop_field_count(_fac->count[STATIC_OOP]);
5316 
5317   // this transfers ownership of a lot of arrays from
5318   // the parser onto the InstanceKlass*
5319   apply_parsed_class_metadata(ik, _java_fields_count);
5320 
5321   // can only set dynamic nest-host after static nest information is set
5322   if (cl_inst_info.dynamic_nest_host() != NULL) {
5323     ik->set_nest_host(cl_inst_info.dynamic_nest_host());
5324   }
5325 
5326   // note that is not safe to use the fields in the parser from this point on
5327   assert(NULL == _cp, "invariant");
5328   assert(NULL == _fields, "invariant");
5329   assert(NULL == _methods, "invariant");
5330   assert(NULL == _inner_classes, "invariant");
5331   assert(NULL == _nest_members, "invariant");

5332   assert(NULL == _combined_annotations, "invariant");
5333   assert(NULL == _record_components, "invariant");
5334   assert(NULL == _permitted_subclasses, "invariant");
5335 
5336   if (_has_final_method) {
5337     ik->set_has_final_method();
5338   }
5339 
5340   ik->copy_method_ordering(_method_ordering, CHECK);
5341   // The InstanceKlass::_methods_jmethod_ids cache
5342   // is managed on the assumption that the initial cache
5343   // size is equal to the number of methods in the class. If
5344   // that changes, then InstanceKlass::idnum_can_increment()
5345   // has to be changed accordingly.
5346   ik->set_initial_method_idnum(ik->methods()->length());
5347 
5348   ik->set_this_class_index(_this_class_index);
5349 
5350   if (_is_hidden) {
5351     // _this_class_index is a CONSTANT_Class entry that refers to this
5352     // hidden class itself. If this class needs to refer to its own methods
5353     // or fields, it would use a CONSTANT_MethodRef, etc, which would reference
5354     // _this_class_index. However, because this class is hidden (it's
5355     // not stored in SystemDictionary), _this_class_index cannot be resolved
5356     // with ConstantPool::klass_at_impl, which does a SystemDictionary lookup.
5357     // Therefore, we must eagerly resolve _this_class_index now.
5358     ik->constants()->klass_at_put(_this_class_index, ik);
5359   }
5360 
5361   ik->set_minor_version(_minor_version);
5362   ik->set_major_version(_major_version);
5363   ik->set_has_nonstatic_concrete_methods(_has_nonstatic_concrete_methods);
5364   ik->set_declares_nonstatic_concrete_methods(_declares_nonstatic_concrete_methods);



5365 
5366   if (_is_hidden) {
5367     ik->set_is_hidden();
5368   }
5369 
5370   // Set PackageEntry for this_klass
5371   oop cl = ik->class_loader();
5372   Handle clh = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(cl));
5373   ClassLoaderData* cld = ClassLoaderData::class_loader_data_or_null(clh());
5374   ik->set_package(cld, NULL, CHECK);
5375 
5376   const Array<Method*>* const methods = ik->methods();
5377   assert(methods != NULL, "invariant");
5378   const int methods_len = methods->length();
5379 
5380   check_methods_for_intrinsics(ik, methods);
5381 
5382   // Fill in field values obtained by parse_classfile_attributes
5383   if (_parsed_annotations->has_any_annotations()) {
5384     _parsed_annotations->apply_to(ik);

5452 
5453   assert(_all_mirandas != NULL, "invariant");
5454 
5455   // Generate any default methods - default methods are public interface methods
5456   // that have a default implementation.  This is new with Java 8.
5457   if (_has_nonstatic_concrete_methods) {
5458     DefaultMethods::generate_default_methods(ik,
5459                                              _all_mirandas,
5460                                              CHECK);
5461   }
5462 
5463   // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5464   if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5465       !module_entry->has_default_read_edges()) {
5466     if (!module_entry->set_has_default_read_edges()) {
5467       // We won a potential race
5468       JvmtiExport::add_default_read_edges(module_handle, THREAD);
5469     }
5470   }
5471 



























5472   ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5473 
5474   if (!is_internal()) {
5475     ik->print_class_load_logging(_loader_data, module_entry, _stream);
5476 
5477     if (ik->minor_version() == JAVA_PREVIEW_MINOR_VERSION &&
5478         ik->major_version() == JVM_CLASSFILE_MAJOR_VERSION &&
5479         log_is_enabled(Info, class, preview)) {
5480       ResourceMark rm;
5481       log_info(class, preview)("Loading class %s that depends on preview features (class file version %d.65535)",
5482                                ik->external_name(), JVM_CLASSFILE_MAJOR_VERSION);
5483     }
5484 
5485     if (log_is_enabled(Debug, class, resolve))  {
5486       ResourceMark rm;
5487       // print out the superclass.
5488       const char * from = ik->external_name();
5489       if (ik->java_super() != NULL) {
5490         log_debug(class, resolve)("%s %s (super)",
5491                    from,

5542 ClassFileParser::ClassFileParser(ClassFileStream* stream,
5543                                  Symbol* name,
5544                                  ClassLoaderData* loader_data,
5545                                  const ClassLoadInfo* cl_info,
5546                                  Publicity pub_level,
5547                                  TRAPS) :
5548   _stream(stream),
5549   _class_name(NULL),
5550   _loader_data(loader_data),
5551   _is_hidden(cl_info->is_hidden()),
5552   _can_access_vm_annotations(cl_info->can_access_vm_annotations()),
5553   _orig_cp_size(0),
5554   _super_klass(),
5555   _cp(NULL),
5556   _fields(NULL),
5557   _methods(NULL),
5558   _inner_classes(NULL),
5559   _nest_members(NULL),
5560   _nest_host(0),
5561   _permitted_subclasses(NULL),

5562   _record_components(NULL),
5563   _local_interfaces(NULL),

5564   _transitive_interfaces(NULL),
5565   _combined_annotations(NULL),
5566   _class_annotations(NULL),
5567   _class_type_annotations(NULL),
5568   _fields_annotations(NULL),
5569   _fields_type_annotations(NULL),
5570   _klass(NULL),
5571   _klass_to_deallocate(NULL),
5572   _parsed_annotations(NULL),
5573   _fac(NULL),
5574   _field_info(NULL),

5575   _method_ordering(NULL),
5576   _all_mirandas(NULL),
5577   _vtable_size(0),
5578   _itable_size(0),
5579   _num_miranda_methods(0),
5580   _protection_domain(cl_info->protection_domain()),
5581   _access_flags(),
5582   _pub_level(pub_level),
5583   _bad_constant_seen(0),
5584   _synthetic_flag(false),
5585   _sde_length(false),
5586   _sde_buffer(NULL),
5587   _sourcefile_index(0),
5588   _generic_signature_index(0),
5589   _major_version(0),
5590   _minor_version(0),
5591   _this_class_index(0),
5592   _super_class_index(0),
5593   _itfs_len(0),
5594   _java_fields_count(0),
5595   _need_verify(false),
5596   _relax_verify(false),
5597   _has_nonstatic_concrete_methods(false),
5598   _declares_nonstatic_concrete_methods(false),
5599   _has_final_method(false),
5600   _has_contended_fields(false),







5601   _has_finalizer(false),
5602   _has_empty_finalizer(false),
5603   _has_vanilla_constructor(false),
5604   _max_bootstrap_specifier_index(-1) {
5605 
5606   _class_name = name != NULL ? name : vmSymbols::unknown_class_name();
5607   _class_name->increment_refcount();
5608 
5609   assert(_loader_data != NULL, "invariant");
5610   assert(stream != NULL, "invariant");
5611   assert(_stream != NULL, "invariant");
5612   assert(_stream->buffer() == _stream->current(), "invariant");
5613   assert(_class_name != NULL, "invariant");
5614   assert(0 == _access_flags.as_int(), "invariant");
5615 
5616   // Figure out whether we can skip format checking (matching classic VM behavior)
5617   if (DumpSharedSpaces) {
5618     // verify == true means it's a 'remote' class (i.e., non-boot class)
5619     // Verification decision is based on BytecodeVerificationRemote flag
5620     // for those classes.

5630   stream->set_verify(_need_verify);
5631 
5632   // Check if verification needs to be relaxed for this class file
5633   // Do not restrict it to jdk1.0 or jdk1.1 to maintain backward compatibility (4982376)
5634   _relax_verify = relax_format_check_for(_loader_data);
5635 
5636   parse_stream(stream, CHECK);
5637 
5638   post_process_parsed_stream(stream, _cp, CHECK);
5639 }
5640 
5641 void ClassFileParser::clear_class_metadata() {
5642   // metadata created before the instance klass is created.  Must be
5643   // deallocated if classfile parsing returns an error.
5644   _cp = NULL;
5645   _fields = NULL;
5646   _methods = NULL;
5647   _inner_classes = NULL;
5648   _nest_members = NULL;
5649   _permitted_subclasses = NULL;

5650   _combined_annotations = NULL;
5651   _class_annotations = _class_type_annotations = NULL;
5652   _fields_annotations = _fields_type_annotations = NULL;
5653   _record_components = NULL;
5654 }
5655 
5656 // Destructor to clean up
5657 ClassFileParser::~ClassFileParser() {
5658   _class_name->decrement_refcount();
5659 
5660   if (_cp != NULL) {
5661     MetadataFactory::free_metadata(_loader_data, _cp);
5662   }
5663   if (_fields != NULL) {
5664     MetadataFactory::free_array<u2>(_loader_data, _fields);
5665   }
5666 




5667   if (_methods != NULL) {
5668     // Free methods
5669     InstanceKlass::deallocate_methods(_loader_data, _methods);
5670   }
5671 
5672   // beware of the Universe::empty_blah_array!!
5673   if (_inner_classes != NULL && _inner_classes != Universe::the_empty_short_array()) {
5674     MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
5675   }
5676 
5677   if (_nest_members != NULL && _nest_members != Universe::the_empty_short_array()) {
5678     MetadataFactory::free_array<u2>(_loader_data, _nest_members);
5679   }
5680 
5681   if (_record_components != NULL) {
5682     InstanceKlass::deallocate_record_components(_loader_data, _record_components);
5683   }
5684 
5685   if (_permitted_subclasses != NULL && _permitted_subclasses != Universe::the_empty_short_array()) {
5686     MetadataFactory::free_array<u2>(_loader_data, _permitted_subclasses);
5687   }
5688 




5689   // Free interfaces
5690   InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
5691                                        _local_interfaces, _transitive_interfaces);
5692 
5693   if (_combined_annotations != NULL) {
5694     // After all annotations arrays have been created, they are installed into the
5695     // Annotations object that will be assigned to the InstanceKlass being created.
5696 
5697     // Deallocate the Annotations object and the installed annotations arrays.
5698     _combined_annotations->deallocate_contents(_loader_data);
5699 
5700     // If the _combined_annotations pointer is non-NULL,
5701     // then the other annotations fields should have been cleared.
5702     assert(_class_annotations       == NULL, "Should have been cleared");
5703     assert(_class_type_annotations  == NULL, "Should have been cleared");
5704     assert(_fields_annotations      == NULL, "Should have been cleared");
5705     assert(_fields_type_annotations == NULL, "Should have been cleared");
5706   } else {
5707     // If the annotations arrays were not installed into the Annotations object,
5708     // then they have to be deallocated explicitly.

5753     cp_size, CHECK);
5754 
5755   _orig_cp_size = cp_size;
5756   if (is_hidden()) { // Add a slot for hidden class name.
5757     cp_size++;
5758   }
5759 
5760   _cp = ConstantPool::allocate(_loader_data,
5761                                cp_size,
5762                                CHECK);
5763 
5764   ConstantPool* const cp = _cp;
5765 
5766   parse_constant_pool(stream, cp, _orig_cp_size, CHECK);
5767 
5768   assert(cp_size == (const u2)cp->length(), "invariant");
5769 
5770   // ACCESS FLAGS
5771   stream->guarantee_more(8, CHECK);  // flags, this_class, super_class, infs_len
5772 
5773   // Access flags
5774   jint flags;
5775   // JVM_ACC_MODULE is defined in JDK-9 and later.
5776   if (_major_version >= JAVA_9_VERSION) {
5777     flags = stream->get_u2_fast() & (JVM_RECOGNIZED_CLASS_MODIFIERS | JVM_ACC_MODULE);
5778   } else {
5779     flags = stream->get_u2_fast() & JVM_RECOGNIZED_CLASS_MODIFIERS;


5780   }
5781 



5782   if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
5783     // Set abstract bit for old class files for backward compatibility
5784     flags |= JVM_ACC_ABSTRACT;
5785   }
5786 
5787   verify_legal_class_modifiers(flags, CHECK);
5788 
5789   short bad_constant = class_bad_constant_seen();
5790   if (bad_constant != 0) {
5791     // Do not throw CFE until after the access_flags are checked because if
5792     // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
5793     classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, THREAD);
5794     return;
5795   }
5796 
5797   _access_flags.set_flags(flags);
5798 
5799   // This class and superclass
5800   _this_class_index = stream->get_u2_fast();
5801   check_property(
5802     valid_cp_range(_this_class_index, cp_size) &&
5803       cp->tag_at(_this_class_index).is_unresolved_klass(),
5804     "Invalid this class index %u in constant pool in class file %s",
5805     _this_class_index, CHECK);
5806 
5807   Symbol* const class_name_in_cp = cp->klass_name_at(_this_class_index);
5808   assert(class_name_in_cp != NULL, "class_name can't be null");
5809 
































5810   // Don't need to check whether this class name is legal or not.
5811   // It has been checked when constant pool is parsed.
5812   // However, make sure it is not an array type.
5813   if (_need_verify) {
5814     guarantee_property(class_name_in_cp->char_at(0) != JVM_SIGNATURE_ARRAY,
5815                        "Bad class name in class file %s",
5816                        CHECK);
5817   }
5818 
5819 #ifdef ASSERT
5820   // Basic sanity checks
5821   if (_is_hidden) {
5822     assert(_class_name != vmSymbols::unknown_class_name(), "hidden classes should have a special name");
5823   }
5824 #endif
5825 
5826   // Update the _class_name as needed depending on whether this is a named, un-named, or hidden class.
5827 
5828   if (_is_hidden) {
5829     assert(_class_name != NULL, "Unexpected null _class_name");

5867       if (stream->source() != NULL) {
5868         ls.print(" source: %s", stream->source());
5869       }
5870       ls.cr();
5871     }
5872   }
5873 
5874   // SUPERKLASS
5875   _super_class_index = stream->get_u2_fast();
5876   _super_klass = parse_super_class(cp,
5877                                    _super_class_index,
5878                                    _need_verify,
5879                                    CHECK);
5880 
5881   // Interfaces
5882   _itfs_len = stream->get_u2_fast();
5883   parse_interfaces(stream,
5884                    _itfs_len,
5885                    cp,
5886                    &_has_nonstatic_concrete_methods,

5887                    CHECK);
5888 
5889   assert(_local_interfaces != NULL, "invariant");
5890 
5891   // Fields (offsets are filled in later)
5892   _fac = new FieldAllocationCount();
5893   parse_fields(stream,
5894                _access_flags.is_interface(),
5895                _fac,
5896                cp,
5897                cp_size,
5898                &_java_fields_count,
5899                CHECK);
5900 
5901   assert(_fields != NULL, "invariant");
5902 
5903   // Methods
5904   AccessFlags promoted_flags;
5905   parse_methods(stream,
5906                 _access_flags.is_interface(),


5907                 &promoted_flags,
5908                 &_has_final_method,
5909                 &_declares_nonstatic_concrete_methods,
5910                 CHECK);
5911 
5912   assert(_methods != NULL, "invariant");
5913 
5914   // promote flags from parse_methods() to the klass' flags
5915   _access_flags.add_promoted_flags(promoted_flags.as_int());
5916 
5917   if (_declares_nonstatic_concrete_methods) {
5918     _has_nonstatic_concrete_methods = true;
5919   }
5920 
5921   // Additional attributes/annotations
5922   _parsed_annotations = new ClassAnnotationCollector();
5923   parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK);
5924 
5925   assert(_inner_classes != NULL, "invariant");
5926 

5969   // Update this_class_index's slot in the constant pool with the new Utf8 entry.
5970   // We have to update the resolved_klass_index and the name_index together
5971   // so extract the existing resolved_klass_index first.
5972   CPKlassSlot cp_klass_slot = _cp->klass_slot_at(_this_class_index);
5973   int resolved_klass_index = cp_klass_slot.resolved_klass_index();
5974   _cp->unresolved_klass_at_put(_this_class_index, hidden_index, resolved_klass_index);
5975   assert(_cp->klass_slot_at(_this_class_index).name_index() == _orig_cp_size,
5976          "Bad name_index");
5977 }
5978 
5979 void ClassFileParser::post_process_parsed_stream(const ClassFileStream* const stream,
5980                                                  ConstantPool* cp,
5981                                                  TRAPS) {
5982   assert(stream != NULL, "invariant");
5983   assert(stream->at_eos(), "invariant");
5984   assert(cp != NULL, "invariant");
5985   assert(_loader_data != NULL, "invariant");
5986 
5987   if (_class_name == vmSymbols::java_lang_Object()) {
5988     check_property(_local_interfaces == Universe::the_empty_instance_klass_array(),
5989                    "java.lang.Object cannot implement an interface in class file %s",
5990                    CHECK);
5991   }
5992   // We check super class after class file is parsed and format is checked
5993   if (_super_class_index > 0 && NULL == _super_klass) {
5994     Symbol* const super_class_name = cp->klass_name_at(_super_class_index);
5995     if (_access_flags.is_interface()) {
5996       // Before attempting to resolve the superclass, check for class format
5997       // errors not checked yet.
5998       guarantee_property(super_class_name == vmSymbols::java_lang_Object(),
5999         "Interfaces must have java.lang.Object as superclass in class file %s",
6000         CHECK);
6001     }
6002     Handle loader(THREAD, _loader_data->class_loader());
6003     _super_klass = (const InstanceKlass*)
6004                        SystemDictionary::resolve_super_or_fail(_class_name,
6005                                                                super_class_name,
6006                                                                loader,
6007                                                                _protection_domain,
6008                                                                true,
6009                                                                CHECK);
6010   }
6011 
6012   if (_super_klass != NULL) {









6013     if (_super_klass->has_nonstatic_concrete_methods()) {
6014       _has_nonstatic_concrete_methods = true;
6015     }




6016 
6017     if (_super_klass->is_interface()) {
6018       classfile_icce_error("class %s has interface %s as super class", _super_klass, THREAD);
6019       return;























































6020     }
6021   }

6022 
6023   // Compute the transitive list of all unique interfaces implemented by this class
6024   _transitive_interfaces =
6025     compute_transitive_interfaces(_super_klass,
6026                                   _local_interfaces,
6027                                   _loader_data,
6028                                   CHECK);
6029 
6030   assert(_transitive_interfaces != NULL, "invariant");
6031 
6032   // sort methods
6033   _method_ordering = sort_methods(_methods);
6034 
6035   _all_mirandas = new GrowableArray<Method*>(20);
6036 
6037   Handle loader(THREAD, _loader_data->class_loader());
6038   klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
6039                                                     &_num_miranda_methods,
6040                                                     _all_mirandas,
6041                                                     _super_klass,
6042                                                     _methods,
6043                                                     _access_flags,
6044                                                     _major_version,
6045                                                     loader,
6046                                                     _class_name,
6047                                                     _local_interfaces);
6048 
6049   // Size of Java itable (in words)
6050   _itable_size = _access_flags.is_interface() ? 0 :
6051     klassItable::compute_itable_size(_transitive_interfaces);
6052 
6053   assert(_fac != NULL, "invariant");
6054   assert(_parsed_annotations != NULL, "invariant");
6055 


























6056   _field_info = new FieldLayoutInfo();
6057   FieldLayoutBuilder lb(class_name(), super_klass(), _cp, _fields,
6058                         _parsed_annotations->is_contended(), _field_info);
6059   lb.build_layout();







6060 }
6061 
6062 void ClassFileParser::set_klass(InstanceKlass* klass) {
6063 
6064 #ifdef ASSERT
6065   if (klass != NULL) {
6066     assert(NULL == _klass, "leaking?");
6067   }
6068 #endif
6069 
6070   _klass = klass;
6071 }
6072 
6073 void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) {
6074 
6075 #ifdef ASSERT
6076   if (klass != NULL) {
6077     assert(NULL == _klass_to_deallocate, "leaking?");
6078   }
6079 #endif

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

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

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

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

 828   NameSigHash* entry = table[index];
 829   while (entry != NULL) {
 830     if (entry->_name == name && entry->_sig == sig) {
 831       return false;
 832     }
 833     entry = entry->_next;
 834   }
 835 
 836   // No duplicate is found, allocate a new entry and fill it.
 837   entry = new NameSigHash();
 838   entry->_name = name;
 839   entry->_sig = sig;
 840 
 841   // Insert into hash table
 842   entry->_next = table[index];
 843   table[index] = entry;
 844 
 845   return true;
 846 }
 847 
 848 static void check_identity_and_value_modifiers(ClassFileParser* current, const InstanceKlass* super_type, TRAPS) {
 849   assert(super_type != NULL,"Method doesn't support null super type");
 850   if (super_type->carries_identity_modifier()) {
 851     if (current->carries_value_modifier()) {
 852         ResourceMark rm(THREAD);
 853         Exceptions::fthrow(
 854           THREAD_AND_LOCATION,
 855           vmSymbols::java_lang_IncompatibleClassChangeError(),
 856           "Value type %s has an identity type as supertype",
 857           current->class_name()->as_klass_external_name());
 858         return;
 859       }
 860     current->set_carries_identity_modifier();
 861   }
 862   if (super_type->carries_value_modifier()) {
 863     if (current->carries_identity_modifier()) {
 864       ResourceMark rm(THREAD);
 865       Exceptions::fthrow(
 866         THREAD_AND_LOCATION,
 867         vmSymbols::java_lang_IncompatibleClassChangeError(),
 868         "Identity type %s has a value type as supertype",
 869         current->class_name()->as_klass_external_name());
 870       return;
 871     }
 872     current->set_carries_value_modifier();
 873   }
 874 }
 875 
 876 void ClassFileParser::parse_interfaces(const ClassFileStream* stream,
 877                                        int itfs_len,
 878                                        ConstantPool* cp,
 879                                        bool* const has_nonstatic_concrete_methods,
 880                                        // FIXME: lots of these functions
 881                                        // declare their parameters as const,
 882                                        // which adds only noise to the code.
 883                                        // Remove the spurious const modifiers.
 884                                        // Many are of the form "const int x"
 885                                        // or "T* const x".
 886                                        bool* const is_declared_atomic,
 887                                        TRAPS) {
 888   assert(stream != NULL, "invariant");
 889   assert(cp != NULL, "invariant");
 890   assert(has_nonstatic_concrete_methods != NULL, "invariant");
 891 
 892   if (itfs_len == 0) {
 893     _local_interfaces = Universe::the_empty_instance_klass_array();
 894 
 895   } else {
 896     assert(itfs_len > 0, "only called for len>0");
 897     _local_interface_indexes = new GrowableArray<u2>(itfs_len, mtNone);
 898     int index = 0;

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

 901       check_property(
 902         valid_klass_reference_at(interface_index),
 903         "Interface name has bad constant pool index %u in class file %s",
 904         interface_index, CHECK);
 905       _local_interface_indexes->at_put_grow(index, interface_index);































 906     }
 907 
 908     if (!_need_verify || itfs_len <= 1) {
 909       return;
 910     }
 911 
 912     // Check if there's any duplicates in interfaces
 913     ResourceMark rm(THREAD);
 914     NameSigHash** interface_names = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD,
 915                                                                  NameSigHash*,
 916                                                                  HASH_ROW_SIZE);
 917     initialize_hashtable(interface_names);
 918     bool dup = false;
 919     const Symbol* name = NULL;
 920     {
 921       debug_only(NoSafepointVerifier nsv;)
 922       for (index = 0; index < itfs_len; index++) {
 923         name = cp->klass_name_at(_local_interface_indexes->at(index));

 924         // If no duplicates, add (name, NULL) in hashtable interface_names.
 925         if (!put_after_lookup(name, NULL, interface_names)) {
 926           dup = true;
 927           break;
 928         }
 929       }
 930     }
 931     if (dup) {
 932       classfile_parse_error("Duplicate interface name \"%s\" in class file %s",
 933                              name->as_C_string(), THREAD);
 934     }
 935   }
 936 }
 937 
 938 void ClassFileParser::verify_constantvalue(const ConstantPool* const cp,
 939                                            int constantvalue_index,
 940                                            int signature_index,
 941                                            TRAPS) const {
 942   // Make sure the constant pool entry is of a type appropriate to this field
 943   guarantee_property(

1389                                             CHECK);
1390   parsed_annotations->set_field_annotations(a);
1391   a = assemble_annotations(runtime_visible_type_annotations,
1392                            runtime_visible_type_annotations_length,
1393                            runtime_invisible_type_annotations,
1394                            runtime_invisible_type_annotations_length,
1395                            CHECK);
1396   parsed_annotations->set_field_type_annotations(a);
1397   return;
1398 }
1399 
1400 
1401 // Field allocation types. Used for computing field offsets.
1402 
1403 enum FieldAllocationType {
1404   STATIC_OOP,           // Oops
1405   STATIC_BYTE,          // Boolean, Byte, char
1406   STATIC_SHORT,         // shorts
1407   STATIC_WORD,          // ints
1408   STATIC_DOUBLE,        // aligned long or double
1409   STATIC_INLINE,        // inline type field
1410   NONSTATIC_OOP,
1411   NONSTATIC_BYTE,
1412   NONSTATIC_SHORT,
1413   NONSTATIC_WORD,
1414   NONSTATIC_DOUBLE,
1415   NONSTATIC_INLINE,
1416   MAX_FIELD_ALLOCATION_TYPE,
1417   BAD_ALLOCATION_TYPE = -1
1418 };
1419 
1420 static FieldAllocationType _basic_type_to_atype[2 * (T_CONFLICT + 1)] = {
1421   BAD_ALLOCATION_TYPE, // 0
1422   BAD_ALLOCATION_TYPE, // 1
1423   BAD_ALLOCATION_TYPE, // 2
1424   BAD_ALLOCATION_TYPE, // 3
1425   NONSTATIC_BYTE ,     // T_BOOLEAN     =  4,
1426   NONSTATIC_SHORT,     // T_CHAR        =  5,
1427   NONSTATIC_WORD,      // T_FLOAT       =  6,
1428   NONSTATIC_DOUBLE,    // T_DOUBLE      =  7,
1429   NONSTATIC_BYTE,      // T_BYTE        =  8,
1430   NONSTATIC_SHORT,     // T_SHORT       =  9,
1431   NONSTATIC_WORD,      // T_INT         = 10,
1432   NONSTATIC_DOUBLE,    // T_LONG        = 11,
1433   NONSTATIC_OOP,       // T_OBJECT      = 12,
1434   NONSTATIC_OOP,       // T_ARRAY       = 13,
1435   NONSTATIC_OOP,       // T_PRIMITIVE_OBJECT = 14,
1436   BAD_ALLOCATION_TYPE, // T_VOID        = 15,
1437   BAD_ALLOCATION_TYPE, // T_ADDRESS     = 16,
1438   BAD_ALLOCATION_TYPE, // T_NARROWOOP   = 17,
1439   BAD_ALLOCATION_TYPE, // T_METADATA    = 18,
1440   BAD_ALLOCATION_TYPE, // T_NARROWKLASS = 19,
1441   BAD_ALLOCATION_TYPE, // T_CONFLICT    = 20,
1442   BAD_ALLOCATION_TYPE, // 0
1443   BAD_ALLOCATION_TYPE, // 1
1444   BAD_ALLOCATION_TYPE, // 2
1445   BAD_ALLOCATION_TYPE, // 3
1446   STATIC_BYTE ,        // T_BOOLEAN     =  4,
1447   STATIC_SHORT,        // T_CHAR        =  5,
1448   STATIC_WORD,         // T_FLOAT       =  6,
1449   STATIC_DOUBLE,       // T_DOUBLE      =  7,
1450   STATIC_BYTE,         // T_BYTE        =  8,
1451   STATIC_SHORT,        // T_SHORT       =  9,
1452   STATIC_WORD,         // T_INT         = 10,
1453   STATIC_DOUBLE,       // T_LONG        = 11,
1454   STATIC_OOP,          // T_OBJECT      = 12,
1455   STATIC_OOP,          // T_ARRAY       = 13,
1456   STATIC_OOP,          // T_PRIMITIVE_OBJECT = 14,
1457   BAD_ALLOCATION_TYPE, // T_VOID        = 15,
1458   BAD_ALLOCATION_TYPE, // T_ADDRESS     = 16,
1459   BAD_ALLOCATION_TYPE, // T_NARROWOOP   = 17,
1460   BAD_ALLOCATION_TYPE, // T_METADATA    = 18,
1461   BAD_ALLOCATION_TYPE, // T_NARROWKLASS = 19,
1462   BAD_ALLOCATION_TYPE, // T_CONFLICT    = 20
1463 };
1464 
1465 static FieldAllocationType basic_type_to_atype(bool is_static, BasicType type, bool is_inline_type) {
1466   assert(type >= T_BOOLEAN && type < T_VOID, "only allowable values");
1467   FieldAllocationType result = _basic_type_to_atype[type + (is_static ? (T_CONFLICT + 1) : 0)];
1468   assert(result != BAD_ALLOCATION_TYPE, "bad type");
1469   if (is_inline_type) {
1470     result = is_static ? STATIC_INLINE : NONSTATIC_INLINE;
1471   }
1472   return result;
1473 }
1474 
1475 class ClassFileParser::FieldAllocationCount : public ResourceObj {
1476  public:
1477   u2 count[MAX_FIELD_ALLOCATION_TYPE];
1478 
1479   FieldAllocationCount() {
1480     for (int i = 0; i < MAX_FIELD_ALLOCATION_TYPE; i++) {
1481       count[i] = 0;
1482     }
1483   }
1484 
1485   void update(bool is_static, BasicType type, bool is_inline_type) {
1486     FieldAllocationType atype = basic_type_to_atype(is_static, type, is_inline_type);
1487     if (atype != BAD_ALLOCATION_TYPE) {
1488       // Make sure there is no overflow with injected fields.
1489       assert(count[atype] < 0xFFFF, "More than 65535 fields");
1490       count[atype]++;
1491     }
1492   }
1493 };
1494 
1495 // Side-effects: populates the _fields, _fields_annotations,
1496 // _fields_type_annotations fields
1497 void ClassFileParser::parse_fields(const ClassFileStream* const cfs,
1498                                    AccessFlags class_access_flags,
1499                                    FieldAllocationCount* const fac,
1500                                    ConstantPool* cp,
1501                                    const int cp_size,
1502                                    u2* const java_fields_count_ptr,
1503                                    TRAPS) {
1504 
1505   assert(cfs != NULL, "invariant");
1506   assert(fac != NULL, "invariant");
1507   assert(cp != NULL, "invariant");
1508   assert(java_fields_count_ptr != NULL, "invariant");
1509 
1510   assert(NULL == _fields, "invariant");
1511   assert(NULL == _fields_annotations, "invariant");
1512   assert(NULL == _fields_type_annotations, "invariant");
1513 
1514   bool is_inline_type = class_access_flags.is_value_class() && !class_access_flags.is_abstract();
1515   cfs->guarantee_more(2, CHECK);  // length
1516   const u2 length = cfs->get_u2_fast();
1517   *java_fields_count_ptr = length;
1518 
1519   int num_injected = 0;
1520   const InjectedField* const injected = JavaClasses::get_injected(_class_name,
1521                                                                   &num_injected);
1522 
1523   // two more slots are required for inline classes:
1524   // one for the static field with a reference to the pre-allocated default value
1525   // one for the field the JVM injects when detecting an empty inline class
1526   const int total_fields = length + num_injected + (is_inline_type ? 2 : 0);
1527 
1528   // The field array starts with tuples of shorts
1529   // [access, name index, sig index, initial value index, byte offset].
1530   // A generic signature slot only exists for field with generic
1531   // signature attribute. And the access flag is set with
1532   // JVM_ACC_FIELD_HAS_GENERIC_SIGNATURE for that field. The generic
1533   // signature slots are at the end of the field array and after all
1534   // other fields data.
1535   //
1536   //   f1: [access, name index, sig index, initial value index, low_offset, high_offset]
1537   //   f2: [access, name index, sig index, initial value index, low_offset, high_offset]
1538   //       ...
1539   //   fn: [access, name index, sig index, initial value index, low_offset, high_offset]
1540   //       [generic signature index]
1541   //       [generic signature index]
1542   //       ...
1543   //
1544   // Allocate a temporary resource array for field data. For each field,
1545   // a slot is reserved in the temporary array for the generic signature
1546   // index. After parsing all fields, the data are copied to a permanent
1547   // array and any unused slots will be discarded.
1548   ResourceMark rm(THREAD);
1549   u2* const fa = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD,
1550                                               u2,
1551                                               total_fields * (FieldInfo::field_slots + 1));
1552 
1553   // The generic signature slots start after all other fields' data.
1554   int generic_signature_slot = total_fields * FieldInfo::field_slots;
1555   int num_generic_signature = 0;
1556   int instance_fields_count = 0;
1557   for (int n = 0; n < length; n++) {
1558     // access_flags, name_index, descriptor_index, attributes_count
1559     cfs->guarantee_more(8, CHECK);
1560 
1561     jint recognized_modifiers = JVM_RECOGNIZED_FIELD_MODIFIERS;
1562 
1563     const jint flags = cfs->get_u2_fast() & recognized_modifiers;
1564     verify_legal_field_modifiers(flags, class_access_flags, CHECK);
1565     AccessFlags access_flags;


1566     access_flags.set_flags(flags);
1567 
1568     const u2 name_index = cfs->get_u2_fast();
1569     check_property(valid_symbol_at(name_index),
1570       "Invalid constant pool index %u for field name in class file %s",
1571       name_index, CHECK);
1572     const Symbol* const name = cp->symbol_at(name_index);
1573     verify_legal_field_name(name, CHECK);
1574 
1575     const u2 signature_index = cfs->get_u2_fast();
1576     check_property(valid_symbol_at(signature_index),
1577       "Invalid constant pool index %u for field signature in class file %s",
1578       signature_index, CHECK);
1579     const Symbol* const sig = cp->symbol_at(signature_index);
1580     verify_legal_field_signature(name, sig, CHECK);
1581     if (!access_flags.is_static()) instance_fields_count++;
1582 
1583     u2 constantvalue_index = 0;
1584     bool is_synthetic = false;
1585     u2 generic_signature_index = 0;
1586     const bool is_static = access_flags.is_static();
1587     FieldAnnotationCollector parsed_annotations(_loader_data);
1588 
1589     const u2 attributes_count = cfs->get_u2_fast();
1590     if (attributes_count > 0) {
1591       parse_field_attributes(cfs,
1592                              attributes_count,
1593                              is_static,
1594                              signature_index,
1595                              &constantvalue_index,
1596                              &is_synthetic,
1597                              &generic_signature_index,
1598                              &parsed_annotations,
1599                              CHECK);
1600 
1601       if (parsed_annotations.field_annotations() != NULL) {

1621 
1622       if (is_synthetic) {
1623         access_flags.set_is_synthetic();
1624       }
1625       if (generic_signature_index != 0) {
1626         access_flags.set_field_has_generic_signature();
1627         fa[generic_signature_slot] = generic_signature_index;
1628         generic_signature_slot ++;
1629         num_generic_signature ++;
1630       }
1631     }
1632 
1633     FieldInfo* const field = FieldInfo::from_field_array(fa, n);
1634     field->initialize(access_flags.as_short(),
1635                       name_index,
1636                       signature_index,
1637                       constantvalue_index);
1638     const BasicType type = cp->basic_type_for_signature_at(signature_index);
1639 
1640     // Update FieldAllocationCount for this kind of field
1641     fac->update(is_static, type, type == T_PRIMITIVE_OBJECT);
1642 
1643     // After field is initialized with type, we can augment it with aux info
1644     if (parsed_annotations.has_any_annotations()) {
1645       parsed_annotations.apply_to(field);
1646       if (field->is_contended()) {
1647         _has_contended_fields = true;
1648       }
1649     }
1650   }
1651 
1652   int index = length;
1653   if (num_injected != 0) {
1654     for (int n = 0; n < num_injected; n++) {
1655       // Check for duplicates
1656       if (injected[n].may_be_java) {
1657         const Symbol* const name      = injected[n].name();
1658         const Symbol* const signature = injected[n].signature();
1659         bool duplicate = false;
1660         for (int i = 0; i < length; i++) {
1661           const FieldInfo* const f = FieldInfo::from_field_array(fa, i);

1665             duplicate = true;
1666             break;
1667           }
1668         }
1669         if (duplicate) {
1670           // These will be removed from the field array at the end
1671           continue;
1672         }
1673       }
1674 
1675       // Injected field
1676       FieldInfo* const field = FieldInfo::from_field_array(fa, index);
1677       field->initialize((u2)JVM_ACC_FIELD_INTERNAL,
1678                         (u2)(injected[n].name_index),
1679                         (u2)(injected[n].signature_index),
1680                         0);
1681 
1682       const BasicType type = Signature::basic_type(injected[n].signature());
1683 
1684       // Update FieldAllocationCount for this kind of field
1685       fac->update(false, type, false);
1686       index++;
1687     }
1688   }
1689 
1690   if (is_inline_type) {
1691     FieldInfo* const field = FieldInfo::from_field_array(fa, index);
1692     field->initialize(JVM_ACC_FIELD_INTERNAL | JVM_ACC_STATIC,
1693                       (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(default_value_name)),
1694                       (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(object_signature)),
1695                       0);
1696     const BasicType type = Signature::basic_type(vmSymbols::object_signature());
1697     fac->update(true, type, false);
1698     index++;
1699   }
1700 
1701   if (is_inline_type && instance_fields_count == 0) {
1702     _is_empty_inline_type = true;
1703     FieldInfo* const field = FieldInfo::from_field_array(fa, index);
1704     field->initialize(JVM_ACC_FIELD_INTERNAL,
1705         (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(empty_marker_name)),
1706         (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(byte_signature)),
1707         0);
1708     const BasicType type = Signature::basic_type(vmSymbols::byte_signature());
1709     fac->update(false, type, false);
1710     index++;
1711   }
1712 
1713   if (instance_fields_count > 0) {
1714     _has_nonstatic_fields = true;
1715   }
1716 
1717   assert(NULL == _fields, "invariant");
1718 
1719   _fields =
1720     MetadataFactory::new_array<u2>(_loader_data,
1721                                    index * FieldInfo::field_slots + num_generic_signature,
1722                                    CHECK);
1723   // Sometimes injected fields already exist in the Java source so
1724   // the fields array could be too long.  In that case the
1725   // fields array is trimmed. Also unused slots that were reserved
1726   // for generic signature indexes are discarded.
1727   {
1728     int i = 0;
1729     for (; i < index * FieldInfo::field_slots; i++) {
1730       _fields->at_put(i, fa[i]);
1731     }
1732     for (int j = total_fields * FieldInfo::field_slots;
1733          j < generic_signature_slot; j++) {
1734       _fields->at_put(i++, fa[j]);
1735     }
1736     assert(_fields->length() == i, "");

2014         "Exception name has bad type at constant pool %u in class file %s",
2015         checked_exception, CHECK_NULL);
2016     }
2017   }
2018   // check exceptions attribute length
2019   if (_need_verify) {
2020     guarantee_property(method_attribute_length == (sizeof(*checked_exceptions_length) +
2021                                                    sizeof(u2) * size),
2022                       "Exceptions attribute has wrong length in class file %s", CHECK_NULL);
2023   }
2024   return checked_exceptions_start;
2025 }
2026 
2027 void ClassFileParser::throwIllegalSignature(const char* type,
2028                                             const Symbol* name,
2029                                             const Symbol* sig,
2030                                             TRAPS) const {
2031   assert(name != NULL, "invariant");
2032   assert(sig != NULL, "invariant");
2033 
2034   const char* class_note = "";
2035   if (is_inline_type() && name == vmSymbols::object_initializer_name()) {
2036     class_note = " (an inline class)";
2037   }
2038 
2039   ResourceMark rm(THREAD);
2040   Exceptions::fthrow(THREAD_AND_LOCATION,
2041       vmSymbols::java_lang_ClassFormatError(),
2042       "%s \"%s\" in class %s%s has illegal signature \"%s\"", type,
2043       name->as_C_string(), _class_name->as_C_string(), class_note, sig->as_C_string());
2044 }
2045 
2046 AnnotationCollector::ID
2047 AnnotationCollector::annotation_index(const ClassLoaderData* loader_data,
2048                                       const Symbol* name,
2049                                       const bool can_access_vm_annotations) {
2050   const vmSymbolID sid = vmSymbols::find_sid(name);
2051   // Privileged code can use all annotations.  Other code silently drops some.
2052   const bool privileged = loader_data->is_boot_class_loader_data() ||
2053                           loader_data->is_platform_class_loader_data() ||
2054                           can_access_vm_annotations;
2055   switch (sid) {
2056     case VM_SYMBOL_ENUM_NAME(reflect_CallerSensitive_signature): {
2057       if (_location != _in_method)  break;  // only allow for methods
2058       if (!privileged)              break;  // only allow in privileged code
2059       return _method_CallerSensitive;
2060     }
2061     case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ForceInline_signature): {
2062       if (_location != _in_method)  break;  // only allow for methods
2063       if (!privileged)              break;  // only allow in privileged code

2326                              runtime_visible_type_annotations_length,
2327                              runtime_invisible_type_annotations,
2328                              runtime_invisible_type_annotations_length,
2329                              CHECK);
2330     cm->set_type_annotations(a);
2331   }
2332 }
2333 
2334 
2335 // Note: the parse_method below is big and clunky because all parsing of the code and exceptions
2336 // attribute is inlined. This is cumbersome to avoid since we inline most of the parts in the
2337 // Method* to save footprint, so we only know the size of the resulting Method* when the
2338 // entire method attribute is parsed.
2339 //
2340 // The promoted_flags parameter is used to pass relevant access_flags
2341 // from the method back up to the containing klass. These flag values
2342 // are added to klass's access_flags.
2343 
2344 Method* ClassFileParser::parse_method(const ClassFileStream* const cfs,
2345                                       bool is_interface,
2346                                       bool is_value_class,
2347                                       bool is_abstract_class,
2348                                       const ConstantPool* cp,
2349                                       AccessFlags* const promoted_flags,
2350                                       TRAPS) {
2351   assert(cfs != NULL, "invariant");
2352   assert(cp != NULL, "invariant");
2353   assert(promoted_flags != NULL, "invariant");
2354 
2355   ResourceMark rm(THREAD);
2356   // Parse fixed parts:
2357   // access_flags, name_index, descriptor_index, attributes_count
2358   cfs->guarantee_more(8, CHECK_NULL);
2359 
2360   int flags = cfs->get_u2_fast();
2361   const u2 name_index = cfs->get_u2_fast();
2362   const int cp_size = cp->length();
2363   check_property(
2364     valid_symbol_at(name_index),
2365     "Illegal constant pool index %u for method name in class file %s",
2366     name_index, CHECK_NULL);
2367   const Symbol* const name = cp->symbol_at(name_index);

2369 
2370   const u2 signature_index = cfs->get_u2_fast();
2371   guarantee_property(
2372     valid_symbol_at(signature_index),
2373     "Illegal constant pool index %u for method signature in class file %s",
2374     signature_index, CHECK_NULL);
2375   const Symbol* const signature = cp->symbol_at(signature_index);
2376 
2377   if (name == vmSymbols::class_initializer_name()) {
2378     // We ignore the other access flags for a valid class initializer.
2379     // (JVM Spec 2nd ed., chapter 4.6)
2380     if (_major_version < 51) { // backward compatibility
2381       flags = JVM_ACC_STATIC;
2382     } else if ((flags & JVM_ACC_STATIC) == JVM_ACC_STATIC) {
2383       flags &= JVM_ACC_STATIC | (_major_version <= JAVA_16_VERSION ? JVM_ACC_STRICT : 0);
2384     } else {
2385       classfile_parse_error("Method <clinit> is not static in class file %s", THREAD);
2386       return NULL;
2387     }
2388   } else {
2389     verify_legal_method_modifiers(flags, access_flags() , name, CHECK_NULL);
2390   }
2391 
2392   if (name == vmSymbols::object_initializer_name()) {
2393     if (is_interface) {
2394       classfile_parse_error("Interface cannot have a method named <init>, class file %s", THREAD);
2395       return NULL;
2396     } else if ((!is_value_class || is_abstract_class) && signature->is_void_method_signature()) {
2397       // OK, a constructor
2398     } else if (is_value_class && !signature->is_void_method_signature()) {
2399       // also OK, a static factory, as long as the return value is good
2400       bool ok = false;
2401       SignatureStream ss((Symbol*) signature, true);
2402       while (!ss.at_return_type())  ss.next();
2403       if (ss.is_reference()) {
2404         Symbol* ret = ss.as_symbol();
2405         const Symbol* required = class_name();
2406         if (is_hidden()) {
2407           // The original class name in hidden classes gets changed.  So using
2408           // the original name in the return type is no longer valid.
2409           // Note that expecting the return type for inline hidden class factory
2410           // methods to be java.lang.Object works around a JVM Spec issue for
2411           // hidden classes.
2412           required = vmSymbols::java_lang_Object();
2413         }
2414         ok = (ret == required);
2415       }
2416       if (!ok) {
2417         throwIllegalSignature("Method", name, signature, CHECK_0);
2418       }
2419     } else {
2420       // not OK, so throw the same error as in verify_legal_method_signature.
2421       throwIllegalSignature("Method", name, signature, CHECK_0);
2422     }
2423     // A declared <init> method must always be either a non-static
2424     // object constructor, with a void return, or else it must be a
2425     // static factory method, with a non-void return.  No other
2426     // definition of <init> is possible.
2427     //
2428     // The verifier (in verify_invoke_instructions) will inspect the
2429     // signature of any attempt to invoke <init>, and ensures that it
2430     // returns non-void if and only if it is being invoked by
2431     // invokestatic, and void if and only if it is being invoked by
2432     // invokespecial.
2433     //
2434     // When a symbolic reference to <init> is resolved for a
2435     // particular invocation mode (special or static), the mode is
2436     // matched to the JVM_ACC_STATIC modifier of the <init> method.
2437     // Thus, it is impossible to statically invoke a constructor, and
2438     // impossible to "new + invokespecial" a static factory, either
2439     // through bytecode or through reflection.
2440   }
2441 
2442   if (EnableValhalla) {
2443     if (((flags & JVM_ACC_SYNCHRONIZED) == JVM_ACC_SYNCHRONIZED)
2444         && ((flags & JVM_ACC_STATIC) == 0 )
2445         && !carries_identity_modifier()) {
2446       classfile_parse_error("Invalid synchronized method in non-identity class %s", THREAD);
2447         return NULL;
2448     }
2449   }
2450 
2451   int args_size = -1;  // only used when _need_verify is true
2452   if (_need_verify) {
2453     verify_legal_name_with_signature(name, signature, CHECK_NULL);
2454     args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) +
2455                  verify_legal_method_signature(name, signature, CHECK_NULL);
2456     if (args_size > MAX_ARGS_SIZE) {
2457       classfile_parse_error("Too many arguments in method signature in class file %s", THREAD);
2458       return NULL;
2459     }
2460   }
2461 
2462   AccessFlags access_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS);
2463 
2464   // Default values for code and exceptions attribute elements
2465   u2 max_stack = 0;
2466   u2 max_locals = 0;
2467   u4 code_length = 0;
2468   const u1* code_start = 0;

2998       _has_finalizer = true;
2999     }
3000   }
3001   if (name == vmSymbols::object_initializer_name() &&
3002       signature == vmSymbols::void_method_signature() &&
3003       m->is_vanilla_constructor()) {
3004     _has_vanilla_constructor = true;
3005   }
3006 
3007   NOT_PRODUCT(m->verify());
3008   return m;
3009 }
3010 
3011 
3012 // The promoted_flags parameter is used to pass relevant access_flags
3013 // from the methods back up to the containing klass. These flag values
3014 // are added to klass's access_flags.
3015 // Side-effects: populates the _methods field in the parser
3016 void ClassFileParser::parse_methods(const ClassFileStream* const cfs,
3017                                     bool is_interface,
3018                                     bool is_value_class,
3019                                     bool is_abstract_type,
3020                                     AccessFlags* promoted_flags,
3021                                     bool* has_final_method,
3022                                     bool* declares_nonstatic_concrete_methods,
3023                                     TRAPS) {
3024   assert(cfs != NULL, "invariant");
3025   assert(promoted_flags != NULL, "invariant");
3026   assert(has_final_method != NULL, "invariant");
3027   assert(declares_nonstatic_concrete_methods != NULL, "invariant");
3028 
3029   assert(NULL == _methods, "invariant");
3030 
3031   cfs->guarantee_more(2, CHECK);  // length
3032   const u2 length = cfs->get_u2_fast();
3033   if (length == 0) {
3034     _methods = Universe::the_empty_method_array();
3035   } else {
3036     _methods = MetadataFactory::new_array<Method*>(_loader_data,
3037                                                    length,
3038                                                    NULL,
3039                                                    CHECK);
3040 
3041     for (int index = 0; index < length; index++) {
3042       Method* method = parse_method(cfs,
3043                                     is_interface,
3044                                     is_value_class,
3045                                     is_abstract_type,
3046                                     _cp,
3047                                     promoted_flags,
3048                                     CHECK);
3049 
3050       if (method->is_final()) {
3051         *has_final_method = true;
3052       }
3053       // declares_nonstatic_concrete_methods: declares concrete instance methods, any access flags
3054       // used for interface initialization, and default method inheritance analysis
3055       if (is_interface && !(*declares_nonstatic_concrete_methods)
3056         && !method->is_abstract() && !method->is_static()) {
3057         *declares_nonstatic_concrete_methods = true;
3058       }
3059       _methods->at_put(index, method);
3060     }
3061 
3062     if (_need_verify && length > 1) {
3063       // Check duplicated methods
3064       ResourceMark rm(THREAD);
3065       NameSigHash** names_and_sigs = NEW_RESOURCE_ARRAY_IN_THREAD(

3302         valid_klass_reference_at(outer_class_info_index),
3303       "outer_class_info_index %u has bad constant type in class file %s",
3304       outer_class_info_index, CHECK_0);
3305 
3306     if (outer_class_info_index != 0) {
3307       const Symbol* const outer_class_name = cp->klass_name_at(outer_class_info_index);
3308       char* bytes = (char*)outer_class_name->bytes();
3309       guarantee_property(bytes[0] != JVM_SIGNATURE_ARRAY,
3310                          "Outer class is an array class in class file %s", CHECK_0);
3311     }
3312     // Inner class name
3313     const u2 inner_name_index = cfs->get_u2_fast();
3314     check_property(
3315       inner_name_index == 0 || valid_symbol_at(inner_name_index),
3316       "inner_name_index %u has bad constant type in class file %s",
3317       inner_name_index, CHECK_0);
3318     if (_need_verify) {
3319       guarantee_property(inner_class_info_index != outer_class_info_index,
3320                          "Class is both outer and inner class in class file %s", CHECK_0);
3321     }
3322 
3323     jint recognized_modifiers = RECOGNIZED_INNER_CLASS_MODIFIERS;
3324     // JVM_ACC_MODULE is defined in JDK-9 and later.
3325     if (_major_version >= JAVA_9_VERSION) {
3326       recognized_modifiers |= JVM_ACC_MODULE;
3327     }
3328     // JVM_ACC_VALUE, JVM_ACC_PRIMITIVE, and JVM_ACC_IDENTITY are defined for class file version 62 and later
3329     if (supports_inline_types()) {
3330       recognized_modifiers |= JVM_ACC_PRIMITIVE | JVM_ACC_VALUE | JVM_ACC_IDENTITY;
3331     }
3332 
3333     // Access flags
3334     jint flags = cfs->get_u2_fast() & recognized_modifiers;
3335 
3336     if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
3337       // Set abstract bit for old class files for backward compatibility
3338       flags |= JVM_ACC_ABSTRACT;
3339     }
3340 
3341     if (EnableValhalla) {
3342       if (!supports_inline_types()) {
3343         const bool is_module = (flags & JVM_ACC_MODULE) != 0;
3344         const bool is_interface = (flags & JVM_ACC_INTERFACE) != 0;
3345         if (!is_module && !is_interface) {
3346           flags |= JVM_ACC_IDENTITY;
3347         }
3348       }
3349     }
3350 
3351     const char* name = inner_name_index == 0 ? "unnamed" : cp->symbol_at(inner_name_index)->as_utf8();
3352     verify_legal_class_modifiers(flags, name, false, CHECK_0);
3353     AccessFlags inner_access_flags(flags);
3354 
3355     inner_classes->at_put(index++, inner_class_info_index);
3356     inner_classes->at_put(index++, outer_class_info_index);
3357     inner_classes->at_put(index++, inner_name_index);
3358     inner_classes->at_put(index++, inner_access_flags.as_short());
3359   }
3360 
3361   // Check for circular and duplicate entries.
3362   bool has_circularity = false;
3363   if (_need_verify) {
3364     has_circularity = check_inner_classes_circularity(cp, length * 4, CHECK_0);
3365     if (has_circularity) {
3366       // If circularity check failed then ignore InnerClasses attribute.
3367       MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
3368       index = 0;
3369       if (parsed_enclosingmethod_attribute) {
3370         inner_classes = MetadataFactory::new_array<u2>(_loader_data, 2, CHECK_0);
3371         _inner_classes = inner_classes;
3372       } else {

3436   if (length > 0) {
3437     int index = 0;
3438     cfs->guarantee_more(2 * length, CHECK_0);
3439     for (int n = 0; n < length; n++) {
3440       const u2 class_info_index = cfs->get_u2_fast();
3441       check_property(
3442         valid_klass_reference_at(class_info_index),
3443         "Permitted subclass class_info_index %u has bad constant type in class file %s",
3444         class_info_index, CHECK_0);
3445       permitted_subclasses->at_put(index++, class_info_index);
3446     }
3447     assert(index == size, "wrong size");
3448   }
3449 
3450   // Restore buffer's current position.
3451   cfs->set_current(current_mark);
3452 
3453   return length;
3454 }
3455 
3456 u2 ClassFileParser::parse_classfile_preload_attribute(const ClassFileStream* const cfs,
3457                                                                    const u1* const preload_attribute_start,
3458                                                                    TRAPS) {
3459   const u1* const current_mark = cfs->current();
3460   u2 length = 0;
3461   if (preload_attribute_start != NULL) {
3462     cfs->set_current(preload_attribute_start);
3463     cfs->guarantee_more(2, CHECK_0);  // length
3464     length = cfs->get_u2_fast();
3465   }
3466   const int size = length;
3467   Array<u2>* const preload_classes = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
3468   _preload_classes = preload_classes;
3469   if (length > 0) {
3470     int index = 0;
3471     cfs->guarantee_more(2 * length, CHECK_0);
3472     for (int n = 0; n < length; n++) {
3473       const u2 class_info_index = cfs->get_u2_fast();
3474       check_property(
3475         valid_klass_reference_at(class_info_index),
3476         "Preload class_info_index %u has bad constant type in class file %s",
3477         class_info_index, CHECK_0);
3478       preload_classes->at_put(index++, class_info_index);
3479     }
3480     assert(index == size, "wrong size");
3481   }
3482 
3483   // Restore buffer's current position.
3484   cfs->set_current(current_mark);
3485 
3486   return length;
3487 }
3488 
3489 //  Record {
3490 //    u2 attribute_name_index;
3491 //    u4 attribute_length;
3492 //    u2 components_count;
3493 //    component_info components[components_count];
3494 //  }
3495 //  component_info {
3496 //    u2 name_index;
3497 //    u2 descriptor_index
3498 //    u2 attributes_count;
3499 //    attribute_info_attributes[attributes_count];
3500 //  }
3501 u2 ClassFileParser::parse_classfile_record_attribute(const ClassFileStream* const cfs,
3502                                                      const ConstantPool* cp,
3503                                                      const u1* const record_attribute_start,
3504                                                      TRAPS) {
3505   const u1* const current_mark = cfs->current();
3506   int components_count = 0;
3507   unsigned int calculate_attr_size = 0;
3508   if (record_attribute_start != NULL) {

3753   }
3754   guarantee_property(current_start + attribute_byte_length == cfs->current(),
3755                      "Bad length on BootstrapMethods in class file %s",
3756                      CHECK);
3757 }
3758 
3759 void ClassFileParser::parse_classfile_attributes(const ClassFileStream* const cfs,
3760                                                  ConstantPool* cp,
3761                  ClassFileParser::ClassAnnotationCollector* parsed_annotations,
3762                                                  TRAPS) {
3763   assert(cfs != NULL, "invariant");
3764   assert(cp != NULL, "invariant");
3765   assert(parsed_annotations != NULL, "invariant");
3766 
3767   // Set inner classes attribute to default sentinel
3768   _inner_classes = Universe::the_empty_short_array();
3769   // Set nest members attribute to default sentinel
3770   _nest_members = Universe::the_empty_short_array();
3771   // Set _permitted_subclasses attribute to default sentinel
3772   _permitted_subclasses = Universe::the_empty_short_array();
3773   // Set _preload_classes attribute to default sentinel
3774   _preload_classes = Universe::the_empty_short_array();
3775   cfs->guarantee_more(2, CHECK);  // attributes_count
3776   u2 attributes_count = cfs->get_u2_fast();
3777   bool parsed_sourcefile_attribute = false;
3778   bool parsed_innerclasses_attribute = false;
3779   bool parsed_nest_members_attribute = false;
3780   bool parsed_permitted_subclasses_attribute = false;
3781   bool parsed_preload_attribute = false;
3782   bool parsed_nest_host_attribute = false;
3783   bool parsed_record_attribute = false;
3784   bool parsed_enclosingmethod_attribute = false;
3785   bool parsed_bootstrap_methods_attribute = false;
3786   const u1* runtime_visible_annotations = NULL;
3787   int runtime_visible_annotations_length = 0;
3788   const u1* runtime_invisible_annotations = NULL;
3789   int runtime_invisible_annotations_length = 0;
3790   const u1* runtime_visible_type_annotations = NULL;
3791   int runtime_visible_type_annotations_length = 0;
3792   const u1* runtime_invisible_type_annotations = NULL;
3793   int runtime_invisible_type_annotations_length = 0;
3794   bool runtime_invisible_type_annotations_exists = false;
3795   bool runtime_invisible_annotations_exists = false;
3796   bool parsed_source_debug_ext_annotations_exist = false;
3797   const u1* inner_classes_attribute_start = NULL;
3798   u4  inner_classes_attribute_length = 0;
3799   u2  enclosing_method_class_index = 0;
3800   u2  enclosing_method_method_index = 0;
3801   const u1* nest_members_attribute_start = NULL;
3802   u4  nest_members_attribute_length = 0;
3803   const u1* record_attribute_start = NULL;
3804   u4  record_attribute_length = 0;
3805   const u1* permitted_subclasses_attribute_start = NULL;
3806   u4  permitted_subclasses_attribute_length = 0;
3807   const u1* preload_attribute_start = NULL;
3808   u4  preload_attribute_length = 0;
3809 
3810   // Iterate over attributes
3811   while (attributes_count--) {
3812     cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
3813     const u2 attribute_name_index = cfs->get_u2_fast();
3814     const u4 attribute_length = cfs->get_u4_fast();
3815     check_property(
3816       valid_symbol_at(attribute_name_index),
3817       "Attribute name has bad constant pool index %u in class file %s",
3818       attribute_name_index, CHECK);
3819     const Symbol* const tag = cp->symbol_at(attribute_name_index);
3820     if (tag == vmSymbols::tag_source_file()) {
3821       // Check for SourceFile tag
3822       if (_need_verify) {
3823         guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
3824       }
3825       if (parsed_sourcefile_attribute) {
3826         classfile_parse_error("Multiple SourceFile attributes in class file %s", THREAD);
3827         return;
3828       } else {

4015               return;
4016             }
4017             parsed_record_attribute = true;
4018             record_attribute_start = cfs->current();
4019             record_attribute_length = attribute_length;
4020           } else if (_major_version >= JAVA_17_VERSION) {
4021             if (tag == vmSymbols::tag_permitted_subclasses()) {
4022               if (parsed_permitted_subclasses_attribute) {
4023                 classfile_parse_error("Multiple PermittedSubclasses attributes in class file %s", CHECK);
4024                 return;
4025               }
4026               // Classes marked ACC_FINAL cannot have a PermittedSubclasses attribute.
4027               if (_access_flags.is_final()) {
4028                 classfile_parse_error("PermittedSubclasses attribute in final class file %s", CHECK);
4029                 return;
4030               }
4031               parsed_permitted_subclasses_attribute = true;
4032               permitted_subclasses_attribute_start = cfs->current();
4033               permitted_subclasses_attribute_length = attribute_length;
4034             }
4035             if (EnableValhalla && tag == vmSymbols::tag_preload()) {
4036               if (parsed_preload_attribute) {
4037                 classfile_parse_error("Multiple Preload attributes in class file %s", CHECK);
4038                 return;
4039               }
4040               parsed_preload_attribute = true;
4041               preload_attribute_start = cfs->current();
4042               preload_attribute_length = attribute_length;
4043             }
4044           }
4045           // Skip attribute_length for any attribute where major_verson >= JAVA_17_VERSION
4046           cfs->skip_u1(attribute_length, CHECK);
4047         } else {
4048           // Unknown attribute
4049           cfs->skip_u1(attribute_length, CHECK);
4050         }
4051       } else {
4052         // Unknown attribute
4053         cfs->skip_u1(attribute_length, CHECK);
4054       }
4055     } else {
4056       // Unknown attribute
4057       cfs->skip_u1(attribute_length, CHECK);
4058     }
4059   }
4060   _class_annotations = assemble_annotations(runtime_visible_annotations,
4061                                             runtime_visible_annotations_length,
4062                                             runtime_invisible_annotations,
4063                                             runtime_invisible_annotations_length,

4104                             CHECK);
4105     if (_need_verify) {
4106       guarantee_property(record_attribute_length == calculated_attr_length,
4107                          "Record attribute has wrong length in class file %s",
4108                          CHECK);
4109     }
4110   }
4111 
4112   if (parsed_permitted_subclasses_attribute) {
4113     const u2 num_subclasses = parse_classfile_permitted_subclasses_attribute(
4114                             cfs,
4115                             permitted_subclasses_attribute_start,
4116                             CHECK);
4117     if (_need_verify) {
4118       guarantee_property(
4119         permitted_subclasses_attribute_length == sizeof(num_subclasses) + sizeof(u2) * num_subclasses,
4120         "Wrong PermittedSubclasses attribute length in class file %s", CHECK);
4121     }
4122   }
4123 
4124   if (parsed_preload_attribute) {
4125     const u2 num_classes = parse_classfile_preload_attribute(
4126                             cfs,
4127                             preload_attribute_start,
4128                             CHECK);
4129     if (_need_verify) {
4130       guarantee_property(
4131         preload_attribute_length == sizeof(num_classes) + sizeof(u2) * num_classes,
4132         "Wrong Preload attribute length in class file %s", CHECK);
4133     }
4134   }
4135 
4136   if (_max_bootstrap_specifier_index >= 0) {
4137     guarantee_property(parsed_bootstrap_methods_attribute,
4138                        "Missing BootstrapMethods attribute in class file %s", CHECK);
4139   }
4140 }
4141 
4142 void ClassFileParser::apply_parsed_class_attributes(InstanceKlass* k) {
4143   assert(k != NULL, "invariant");
4144 
4145   if (_synthetic_flag)
4146     k->set_is_synthetic();
4147   if (_sourcefile_index != 0) {
4148     k->set_source_file_name_index(_sourcefile_index);
4149   }
4150   if (_generic_signature_index != 0) {
4151     k->set_generic_signature_index(_generic_signature_index);
4152   }
4153   if (_sde_buffer != NULL) {
4154     k->set_source_debug_extension(_sde_buffer, _sde_length);
4155   }

4180     // _combined_annotations so these fields can now be cleared.
4181     _class_annotations       = NULL;
4182     _class_type_annotations  = NULL;
4183     _fields_annotations      = NULL;
4184     _fields_type_annotations = NULL;
4185 }
4186 
4187 // Transfer ownership of metadata allocated to the InstanceKlass.
4188 void ClassFileParser::apply_parsed_class_metadata(
4189                                             InstanceKlass* this_klass,
4190                                             int java_fields_count) {
4191   assert(this_klass != NULL, "invariant");
4192 
4193   _cp->set_pool_holder(this_klass);
4194   this_klass->set_constants(_cp);
4195   this_klass->set_fields(_fields, java_fields_count);
4196   this_klass->set_methods(_methods);
4197   this_klass->set_inner_classes(_inner_classes);
4198   this_klass->set_nest_members(_nest_members);
4199   this_klass->set_nest_host_index(_nest_host);
4200   this_klass->set_preload_classes(_preload_classes);
4201   this_klass->set_annotations(_combined_annotations);
4202   this_klass->set_permitted_subclasses(_permitted_subclasses);
4203   this_klass->set_record_components(_record_components);
4204   // Delay the setting of _local_interfaces and _transitive_interfaces until after
4205   // initialize_supers() in fill_instance_klass(). It is because the _local_interfaces could
4206   // be shared with _transitive_interfaces and _transitive_interfaces may be shared with
4207   // its _super. If an OOM occurs while loading the current klass, its _super field
4208   // may not have been set. When GC tries to free the klass, the _transitive_interfaces
4209   // may be deallocated mistakenly in InstanceKlass::deallocate_interfaces(). Subsequent
4210   // dereferences to the deallocated _transitive_interfaces will result in a crash.
4211 
4212   // Clear out these fields so they don't get deallocated by the destructor
4213   clear_class_metadata();
4214 }
4215 
4216 AnnotationArray* ClassFileParser::assemble_annotations(const u1* const runtime_visible_annotations,
4217                                                        int runtime_visible_annotations_length,
4218                                                        const u1* const runtime_invisible_annotations,
4219                                                        int runtime_invisible_annotations_length,
4220                                                        TRAPS) {

4232     }
4233     if (runtime_invisible_annotations != NULL) {
4234       for (int i = 0; i < runtime_invisible_annotations_length; i++) {
4235         int append = runtime_visible_annotations_length+i;
4236         annotations->at_put(append, runtime_invisible_annotations[i]);
4237       }
4238     }
4239   }
4240   return annotations;
4241 }
4242 
4243 const InstanceKlass* ClassFileParser::parse_super_class(ConstantPool* const cp,
4244                                                         const int super_class_index,
4245                                                         const bool need_verify,
4246                                                         TRAPS) {
4247   assert(cp != NULL, "invariant");
4248   const InstanceKlass* super_klass = NULL;
4249 
4250   if (super_class_index == 0) {
4251     check_property(_class_name == vmSymbols::java_lang_Object(),
4252                    "Invalid superclass index 0 in class file %s",

4253                    CHECK_NULL);
4254   } else {
4255     check_property(valid_klass_reference_at(super_class_index),
4256                    "Invalid superclass index %u in class file %s",
4257                    super_class_index,
4258                    CHECK_NULL);
4259     // The class name should be legal because it is checked when parsing constant pool.
4260     // However, make sure it is not an array type.

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




4263     }
4264     if (need_verify) {
4265       bool is_array = (cp->klass_name_at(super_class_index)->char_at(0) == JVM_SIGNATURE_ARRAY);
4266       guarantee_property(!is_array,
4267                         "Bad superclass name in class file %s", CHECK_NULL);
4268     }
4269   }
4270   return super_klass;
4271 }
4272 
4273 OopMapBlocksBuilder::OopMapBlocksBuilder(unsigned int max_blocks) {
4274   _max_nonstatic_oop_maps = max_blocks;
4275   _nonstatic_oop_map_count = 0;
4276   if (max_blocks == 0) {
4277     _nonstatic_oop_maps = NULL;
4278   } else {
4279     _nonstatic_oop_maps =
4280         NEW_RESOURCE_ARRAY(OopMapBlock, _max_nonstatic_oop_maps);
4281     memset(_nonstatic_oop_maps, 0, sizeof(OopMapBlock) * max_blocks);
4282   }
4283 }
4284 
4285 OopMapBlock* OopMapBlocksBuilder::last_oop_map() const {

4369 }
4370 
4371 void OopMapBlocksBuilder::print_on(outputStream* st) const {
4372   st->print_cr("  OopMapBlocks: %3d  /%3d", _nonstatic_oop_map_count, _max_nonstatic_oop_maps);
4373   if (_nonstatic_oop_map_count > 0) {
4374     OopMapBlock* map = _nonstatic_oop_maps;
4375     OopMapBlock* last_map = last_oop_map();
4376     assert(map <= last_map, "Last less than first");
4377     while (map <= last_map) {
4378       st->print_cr("    Offset: %3d  -%3d Count: %3d", map->offset(),
4379                    map->offset() + map->offset_span() - heapOopSize, map->count());
4380       map++;
4381     }
4382   }
4383 }
4384 
4385 void OopMapBlocksBuilder::print_value_on(outputStream* st) const {
4386   print_on(st);
4387 }
4388 
4389 void ClassFileParser::throwInlineTypeLimitation(THREAD_AND_LOCATION_DECL,
4390                                                 const char* msg,
4391                                                 const Symbol* name,
4392                                                 const Symbol* sig) const {
4393 
4394   ResourceMark rm(THREAD);
4395   if (name == NULL || sig == NULL) {
4396     Exceptions::fthrow(THREAD_AND_LOCATION_ARGS,
4397         vmSymbols::java_lang_ClassFormatError(),
4398         "class: %s - %s", _class_name->as_C_string(), msg);
4399   }
4400   else {
4401     Exceptions::fthrow(THREAD_AND_LOCATION_ARGS,
4402         vmSymbols::java_lang_ClassFormatError(),
4403         "\"%s\" sig: \"%s\" class: %s - %s", name->as_C_string(), sig->as_C_string(),
4404         _class_name->as_C_string(), msg);
4405   }
4406 }
4407 
4408 void ClassFileParser::set_precomputed_flags(InstanceKlass* ik) {
4409   assert(ik != NULL, "invariant");
4410 
4411   const Klass* const super = ik->super();
4412 
4413   // Check if this klass has an empty finalize method (i.e. one with return bytecode only),
4414   // in which case we don't have to register objects as finalizable
4415   if (!_has_empty_finalizer) {
4416     if (_has_finalizer ||
4417         (super != NULL && super->has_finalizer())) {
4418       ik->set_has_finalizer();
4419     }
4420   }
4421 
4422 #ifdef ASSERT
4423   bool f = false;
4424   const Method* const m = ik->lookup_method(vmSymbols::finalize_method_name(),
4425                                            vmSymbols::void_method_signature());
4426   if (InstanceKlass::is_finalization_enabled() &&
4427       (m != NULL) && !m->is_empty_method()) {
4428       f = true;
4429   }
4430 
4431   // Spec doesn't prevent agent from redefinition of empty finalizer.
4432   // Despite the fact that it's generally bad idea and redefined finalizer
4433   // will not work as expected we shouldn't abort vm in this case
4434   if (!ik->has_redefined_this_or_super()) {
4435     assert(ik->has_finalizer() == f, "inconsistent has_finalizer");
4436   }
4437 #endif
4438 
4439   // Check if this klass supports the java.lang.Cloneable interface
4440   if (vmClasses::Cloneable_klass_loaded()) {
4441     if (ik->is_subtype_of(vmClasses::Cloneable_klass())) {
4442       if (ik->is_inline_klass()) {
4443         JavaThread *THREAD = JavaThread::current();
4444         throwInlineTypeLimitation(THREAD_AND_LOCATION, "Inline Types do not support Cloneable");
4445         return;
4446       }
4447       ik->set_is_cloneable();
4448     }
4449   }
4450 
4451   // Check if this klass has a vanilla default constructor
4452   if (super == NULL) {
4453     // java.lang.Object has empty default constructor
4454     ik->set_has_vanilla_constructor();
4455   } else {
4456     if (super->has_vanilla_constructor() &&
4457         _has_vanilla_constructor) {
4458       ik->set_has_vanilla_constructor();
4459     }
4460 #ifdef ASSERT
4461     bool v = false;
4462     if (super->has_vanilla_constructor()) {
4463       const Method* const constructor =
4464         ik->find_method(vmSymbols::object_initializer_name(),
4465                        vmSymbols::void_method_signature());
4466       if (constructor != NULL && constructor->is_vanilla_constructor()) {
4467         v = true;
4468       }
4469     }
4470     assert(v == ik->has_vanilla_constructor(), "inconsistent has_vanilla_constructor");
4471 #endif
4472   }
4473 
4474   // If it cannot be fast-path allocated, set a bit in the layout helper.
4475   // See documentation of InstanceKlass::can_be_fastpath_allocated().
4476   assert(ik->size_helper() > 0, "layout_helper is initialized");
4477   if ((!RegisterFinalizersAtInit && ik->has_finalizer())
4478       || ik->is_abstract() || ik->is_interface()
4479       || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == NULL)
4480       || ik->size_helper() >= FastAllocateSizeLimit) {
4481     // Forbid fast-path allocation.
4482     const jint lh = Klass::instance_layout_helper(ik->size_helper(), true);
4483     ik->set_layout_helper(lh);
4484   }
4485 }
4486 
4487 bool ClassFileParser::supports_inline_types() const {
4488   // Inline types are only supported by class file version 61.65535 and later
4489   return _major_version > JAVA_20_VERSION ||
4490          (_major_version == JAVA_20_VERSION /*&& _minor_version == JAVA_PREVIEW_MINOR_VERSION*/); // JAVA_PREVIEW_MINOR_VERSION not yet implemented by javac, check JVMS draft
4491 }
4492 
4493 // utility methods for appending an array with check for duplicates
4494 
4495 static void append_interfaces(GrowableArray<InstanceKlass*>* result,
4496                               const Array<InstanceKlass*>* const ifs) {
4497   // iterate over new interfaces
4498   for (int i = 0; i < ifs->length(); i++) {
4499     InstanceKlass* const e = ifs->at(i);
4500     assert(e->is_klass() && e->is_interface(), "just checking");
4501     // add new interface
4502     result->append_if_missing(e);
4503   }
4504 }
4505 
4506 static Array<InstanceKlass*>* compute_transitive_interfaces(const InstanceKlass* super,
4507                                                             Array<InstanceKlass*>* local_ifs,
4508                                                             ClassLoaderData* loader_data,
4509                                                             TRAPS) {
4510   assert(local_ifs != NULL, "invariant");
4511   assert(loader_data != NULL, "invariant");
4512 

4516   // Add superclass transitive interfaces size
4517   if (super != NULL) {
4518     super_size = super->transitive_interfaces()->length();
4519     max_transitive_size += super_size;
4520   }
4521   // Add local interfaces' super interfaces
4522   const int local_size = local_ifs->length();
4523   for (int i = 0; i < local_size; i++) {
4524     InstanceKlass* const l = local_ifs->at(i);
4525     max_transitive_size += l->transitive_interfaces()->length();
4526   }
4527   // Finally add local interfaces
4528   max_transitive_size += local_size;
4529   // Construct array
4530   if (max_transitive_size == 0) {
4531     // no interfaces, use canonicalized array
4532     return Universe::the_empty_instance_klass_array();
4533   } else if (max_transitive_size == super_size) {
4534     // no new local interfaces added, share superklass' transitive interface array
4535     return super->transitive_interfaces();
4536     // The three lines below are commented to work around bug JDK-8245487
4537 //  } else if (max_transitive_size == local_size) {
4538 //    // only local interfaces added, share local interface array
4539 //    return local_ifs;
4540   } else {
4541     ResourceMark rm;
4542     GrowableArray<InstanceKlass*>* const result = new GrowableArray<InstanceKlass*>(max_transitive_size);
4543 
4544     // Copy down from superclass
4545     if (super != NULL) {
4546       append_interfaces(result, super->transitive_interfaces());
4547     }
4548 
4549     // Copy down from local interfaces' superinterfaces
4550     for (int i = 0; i < local_size; i++) {
4551       InstanceKlass* const l = local_ifs->at(i);
4552       append_interfaces(result, l->transitive_interfaces());
4553     }
4554     // Finally add local interfaces
4555     append_interfaces(result, local_ifs);
4556 
4557     // length will be less than the max_transitive_size if duplicates were removed
4558     const int length = result->length();
4559     assert(length <= max_transitive_size, "just checking");
4560 
4561     Array<InstanceKlass*>* const new_result =
4562       MetadataFactory::new_array<InstanceKlass*>(loader_data, length, CHECK_NULL);
4563     for (int i = 0; i < length; i++) {
4564       InstanceKlass* const e = result->at(i);
4565       assert(e != NULL, "just checking");
4566       new_result->at_put(i, e);
4567     }
4568     return new_result;
4569   }
4570 }
4571 
4572 void ClassFileParser::check_super_class_access(const InstanceKlass* this_klass, TRAPS) {
4573   assert(this_klass != NULL, "invariant");
4574   const Klass* const super = this_klass->super();
4575 
4576   if (super != NULL) {
4577     const InstanceKlass* super_ik = InstanceKlass::cast(super);
4578 
4579     if (super->is_final()) {
4580       classfile_icce_error("class %s cannot inherit from final class %s", super_ik, THREAD);
4581       return;
4582     }
4583 
4584     if (super_ik->is_sealed() && !super_ik->has_as_permitted_subclass(this_klass)) {
4585       classfile_icce_error("class %s cannot inherit from sealed class %s", super_ik, THREAD);
4586       return;
4587     }
4588 
4589     // The JVMS says that super classes for value types must not have the ACC_IDENTITY
4590     // flag set. But, java.lang.Object must still be allowed to be a direct super class
4591     // for a value classes.  So, it is treated as a special case for now.
4592     if (this_klass->access_flags().is_value_class() &&
4593         super_ik->name() != vmSymbols::java_lang_Object() &&
4594         super_ik->is_identity_class()) {
4595       classfile_icce_error("value class %s cannot inherit from class %s", super_ik, THREAD);
4596       return;
4597     }
4598 
4599     // If the loader is not the boot loader then throw an exception if its
4600     // superclass is in package jdk.internal.reflect and its loader is not a
4601     // special reflection class loader
4602     if (!this_klass->class_loader_data()->is_the_null_class_loader_data()) {
4603       PackageEntry* super_package = super->package();
4604       if (super_package != NULL &&
4605           super_package->name()->fast_compare(vmSymbols::jdk_internal_reflect()) == 0 &&
4606           !java_lang_ClassLoader::is_reflection_class_loader(this_klass->class_loader())) {
4607         ResourceMark rm(THREAD);
4608         Exceptions::fthrow(
4609           THREAD_AND_LOCATION,
4610           vmSymbols::java_lang_IllegalAccessError(),
4611           "class %s loaded by %s cannot access jdk/internal/reflect superclass %s",
4612           this_klass->external_name(),
4613           this_klass->class_loader_data()->loader_name_and_id(),
4614           super->external_name());
4615         return;
4616       }
4617     }
4618 

4762 
4763   for (int index = 0; index < num_methods; index++) {
4764     const Method* const m = methods->at(index);
4765     // if m is static and not the init method, throw a verify error
4766     if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) {
4767       ResourceMark rm(THREAD);
4768       Exceptions::fthrow(
4769         THREAD_AND_LOCATION,
4770         vmSymbols::java_lang_VerifyError(),
4771         "Illegal static method %s in interface %s",
4772         m->name()->as_C_string(),
4773         this_klass->external_name()
4774       );
4775       return;
4776     }
4777   }
4778 }
4779 
4780 // utility methods for format checking
4781 
4782 void ClassFileParser::verify_legal_class_modifiers(jint flags, const char* name, bool is_Object, TRAPS) const {
4783   const bool is_module = (flags & JVM_ACC_MODULE) != 0;
4784   const bool is_value_class = (flags & JVM_ACC_VALUE) != 0;
4785   const bool is_primitive_class = (flags & JVM_ACC_PRIMITIVE) != 0;
4786   const bool is_identity_class = (flags & JVM_ACC_IDENTITY) != 0;
4787   const bool is_inner_class = name != NULL;
4788   assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");
4789   assert(supports_inline_types() || !is_value_class, "JVM_ACC_VALUE should not be set");
4790   assert(supports_inline_types() || !is_primitive_class, "JVM_ACC_PRIMITIVE should not be set");
4791   if (is_module) {
4792     ResourceMark rm(THREAD);
4793     Exceptions::fthrow(
4794       THREAD_AND_LOCATION,
4795       vmSymbols::java_lang_NoClassDefFoundError(),
4796       "%s is not a class because access_flag ACC_MODULE is set",
4797       _class_name->as_C_string());
4798     return;
4799   }
4800 
4801   if (!EnableValhalla) {
4802     if (is_value_class || is_primitive_class) {
4803       const char* bad_flag = is_primitive_class ? "ACC_PRIMITIVE" : "ACC_VALUE";
4804       ResourceMark rm(THREAD);
4805       Exceptions::fthrow(
4806         THREAD_AND_LOCATION,
4807         vmSymbols::java_lang_ClassFormatError(),
4808         "Class modifier %s in class %s requires option -XX:+EnableValhalla",
4809         bad_flag, _class_name->as_C_string()
4810       );
4811     }
4812     return;
4813   }
4814 
4815   // if (!_need_verify) { return; }
4816 
4817   const bool is_interface  = (flags & JVM_ACC_INTERFACE)  != 0;
4818   const bool is_abstract   = (flags & JVM_ACC_ABSTRACT)   != 0;
4819   const bool is_final      = (flags & JVM_ACC_FINAL)      != 0;
4820   const bool is_super      = (flags & JVM_ACC_SUPER)      != 0;
4821   const bool is_enum       = (flags & JVM_ACC_ENUM)       != 0;
4822   const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4823   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4824 
4825   if ((is_abstract && is_final) ||
4826       (is_interface && !is_abstract) ||
4827       (is_interface && major_gte_1_5 && ((is_super && !supports_inline_types()) || is_enum)) ||   //  ACC_SUPER (now ACC_IDENTITY) was illegal for interfaces
4828       (!is_interface && major_gte_1_5 && is_annotation) ||
4829       (is_value_class && is_enum) ||
4830       (is_identity_class && is_value_class) ||
4831       (supports_inline_types() && !is_module && !is_abstract && !is_Object && !(is_identity_class || is_value_class) && !is_inner_class) ||
4832       (supports_inline_types() && is_primitive_class && (!is_value_class || !is_final || is_interface || is_abstract))) {
4833     ResourceMark rm(THREAD);
4834     const char* class_note = "";
4835     if (is_value_class)  class_note = " (a value class)";
4836     if (is_primitive_class)  class_note = " (a primitive class)";
4837     if (is_value_class && is_identity_class) class_note = " (a value and identity class)";
4838     if (name == NULL) { // Not an inner class
4839       Exceptions::fthrow(
4840         THREAD_AND_LOCATION,
4841         vmSymbols::java_lang_ClassFormatError(),
4842         "Illegal class modifiers in class %s%s: 0x%X",
4843         _class_name->as_C_string(), class_note, flags
4844       );
4845       return;
4846     } else {
4847       Exceptions::fthrow(
4848         THREAD_AND_LOCATION,
4849         vmSymbols::java_lang_ClassFormatError(),
4850         "Illegal class modifiers in declaration of inner class %s%s of class %s: 0x%X",
4851         name, class_note, _class_name->as_C_string(), flags
4852       );
4853       return;
4854     }
4855   }
4856 }
4857 
4858 static bool has_illegal_visibility(jint flags) {
4859   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4860   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4861   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4862 
4863   return ((is_public && is_protected) ||
4864           (is_public && is_private) ||
4865           (is_protected && is_private));
4866 }
4867 
4868 // A legal major_version.minor_version must be one of the following:
4869 //
4870 //  Major_version >= 45 and major_version < 56, any minor_version.
4871 //  Major_version >= 56 and major_version <= JVM_CLASSFILE_MAJOR_VERSION and minor_version = 0.
4872 //  Major_version = JVM_CLASSFILE_MAJOR_VERSION and minor_version = 65535 and --enable-preview is present.
4873 //
4874 void ClassFileParser::verify_class_version(u2 major, u2 minor, Symbol* class_name, TRAPS){

4900         THREAD_AND_LOCATION,
4901         vmSymbols::java_lang_UnsupportedClassVersionError(),
4902         "%s (class file version %u.%u) was compiled with preview features that are unsupported. "
4903         "This version of the Java Runtime only recognizes preview features for class file version %u.%u",
4904         class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION, JAVA_PREVIEW_MINOR_VERSION);
4905       return;
4906     }
4907 
4908     if (!Arguments::enable_preview()) {
4909       classfile_ucve_error("Preview features are not enabled for %s (class file version %u.%u). Try running with '--enable-preview'",
4910                            class_name, major, minor, THREAD);
4911       return;
4912     }
4913 
4914   } else { // minor != JAVA_PREVIEW_MINOR_VERSION
4915     classfile_ucve_error("%s (class file version %u.%u) was compiled with an invalid non-zero minor version",
4916                          class_name, major, minor, THREAD);
4917   }
4918 }
4919 
4920 void ClassFileParser:: verify_legal_field_modifiers(jint flags,
4921                                                    AccessFlags class_access_flags,
4922                                                    TRAPS) const {
4923   if (!_need_verify) { return; }
4924 
4925   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4926   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4927   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4928   const bool is_static    = (flags & JVM_ACC_STATIC)    != 0;
4929   const bool is_final     = (flags & JVM_ACC_FINAL)     != 0;
4930   const bool is_volatile  = (flags & JVM_ACC_VOLATILE)  != 0;
4931   const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
4932   const bool is_enum      = (flags & JVM_ACC_ENUM)      != 0;
4933   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4934 
4935   const bool is_interface = class_access_flags.is_interface();
4936   const bool is_abstract = class_access_flags.is_abstract();
4937   const bool is_value_class = class_access_flags.is_value_class();
4938   const bool is_identity_class = class_access_flags.is_identity_class();
4939 
4940   bool is_illegal = false;
4941 
4942   if (is_interface) {
4943     if (!is_public || !is_static || !is_final || is_private ||
4944         is_protected || is_volatile || is_transient ||
4945         (major_gte_1_5 && is_enum)) {
4946       is_illegal = true;
4947     }
4948   } else { // not interface
4949     if (has_illegal_visibility(flags) || (is_final && is_volatile)) {
4950       is_illegal = true;
4951     } else {
4952       if (is_value_class && !is_abstract && !is_static && !is_final) {
4953         is_illegal = true;
4954       } else if (is_abstract && !is_identity_class && !is_static) {
4955         is_illegal = true;
4956       }
4957     }
4958   }
4959 
4960   if (is_illegal) {
4961     ResourceMark rm(THREAD);
4962     Exceptions::fthrow(
4963       THREAD_AND_LOCATION,
4964       vmSymbols::java_lang_ClassFormatError(),
4965       "Illegal field modifiers in class %s: 0x%X",
4966       _class_name->as_C_string(), flags);
4967     return;
4968   }
4969 }
4970 
4971 void ClassFileParser::verify_legal_method_modifiers(jint flags,
4972                                                     AccessFlags class_access_flags,
4973                                                     const Symbol* name,
4974                                                     TRAPS) const {
4975   if (!_need_verify) { return; }
4976 
4977   const bool is_public       = (flags & JVM_ACC_PUBLIC)       != 0;
4978   const bool is_private      = (flags & JVM_ACC_PRIVATE)      != 0;
4979   const bool is_static       = (flags & JVM_ACC_STATIC)       != 0;
4980   const bool is_final        = (flags & JVM_ACC_FINAL)        != 0;
4981   const bool is_native       = (flags & JVM_ACC_NATIVE)       != 0;
4982   const bool is_abstract     = (flags & JVM_ACC_ABSTRACT)     != 0;
4983   const bool is_bridge       = (flags & JVM_ACC_BRIDGE)       != 0;
4984   const bool is_strict       = (flags & JVM_ACC_STRICT)       != 0;
4985   const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
4986   const bool is_protected    = (flags & JVM_ACC_PROTECTED)    != 0;
4987   const bool major_gte_1_5   = _major_version >= JAVA_1_5_VERSION;
4988   const bool major_gte_8     = _major_version >= JAVA_8_VERSION;
4989   const bool major_gte_17    = _major_version >= JAVA_17_VERSION;
4990   const bool is_initializer  = (name == vmSymbols::object_initializer_name());
4991   const bool is_interface    = class_access_flags.is_interface();
4992   const bool is_value_class  = class_access_flags.is_value_class();
4993   const bool is_identity_class = class_access_flags.is_identity_class();
4994   const bool is_abstract_class = class_access_flags.is_abstract();
4995 
4996   bool is_illegal = false;
4997 
4998   const char* class_note = "";
4999   if (is_interface) {
5000     if (major_gte_8) {
5001       // Class file version is JAVA_8_VERSION or later Methods of
5002       // interfaces may set any of the flags except ACC_PROTECTED,
5003       // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must
5004       // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.
5005       if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
5006           (is_native || is_protected || is_final || is_synchronized) ||
5007           // If a specific method of a class or interface has its
5008           // ACC_ABSTRACT flag set, it must not have any of its
5009           // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,
5010           // ACC_STRICT, or ACC_SYNCHRONIZED flags set.  No need to
5011           // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as
5012           // those flags are illegal irrespective of ACC_ABSTRACT being set or not.
5013           (is_abstract && (is_private || is_static || (!major_gte_17 && is_strict)))) {
5014         is_illegal = true;
5015       }
5016     } else if (major_gte_1_5) {
5017       // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)
5018       if (!is_public || is_private || is_protected || is_static || is_final ||
5019           is_synchronized || is_native || !is_abstract || is_strict) {
5020         is_illegal = true;
5021       }
5022     } else {
5023       // Class file version is pre-JAVA_1_5_VERSION
5024       if (!is_public || is_static || is_final || is_native || !is_abstract) {
5025         is_illegal = true;
5026       }
5027     }
5028   } else { // not interface
5029     if (has_illegal_visibility(flags)) {
5030       is_illegal = true;
5031     } else {
5032       if (is_initializer) {
5033         if (is_final || is_synchronized || is_native ||
5034             is_abstract || (major_gte_1_5 && is_bridge)) {
5035           is_illegal = true;
5036         }
5037         if (!is_static && (!is_value_class || is_abstract_class)) {
5038           // OK, an object constructor in a regular class or an abstract value class
5039         } else if (is_static && is_value_class) {
5040           // OK, a static init factory in an inline class
5041         } else {
5042           // but no other combinations are allowed
5043           is_illegal = true;
5044           class_note = (is_value_class ? " (a value class)" : " (not a value class)");
5045         }
5046       } else { // not initializer
5047         if (!is_identity_class && is_synchronized && !is_static) {
5048           is_illegal = true;
5049           class_note = " (not an identity class)";
5050         } else {
5051           if (is_abstract) {
5052             if ((is_final || is_native || is_private || is_static ||
5053                 (major_gte_1_5 && (is_synchronized || (!major_gte_17 && is_strict))))) {
5054               is_illegal = true;
5055             }
5056           }
5057         }
5058       }
5059     }
5060   }
5061 
5062   if (is_illegal) {
5063     ResourceMark rm(THREAD);
5064     Exceptions::fthrow(
5065       THREAD_AND_LOCATION,
5066       vmSymbols::java_lang_ClassFormatError(),
5067       "Method %s in class %s%s has illegal modifiers: 0x%X",
5068       name->as_C_string(), _class_name->as_C_string(), class_note, flags);
5069     return;
5070   }
5071 }
5072 
5073 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer,
5074                                         int length,
5075                                         TRAPS) const {
5076   assert(_need_verify, "only called when _need_verify is true");
5077   if (!UTF8::is_legal_utf8(buffer, length, _major_version <= 47)) {
5078     classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", THREAD);
5079   }
5080 }
5081 
5082 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
5083 // In class names, '/' separates unqualified names.  This is verified in this function also.
5084 // Method names also may not contain the characters '<' or '>', unless <init>
5085 // or <clinit>.  Note that method names may not be <init> or <clinit> in this
5086 // method.  Because these names have been checked as special cases before
5087 // calling this method in verify_legal_method_name.
5088 //

5206 // be taken as a field signature. Allow "void" if void_ok.
5207 // Return a pointer to just past the signature.
5208 // Return NULL if no legal signature is found.
5209 const char* ClassFileParser::skip_over_field_signature(const char* signature,
5210                                                        bool void_ok,
5211                                                        unsigned int length,
5212                                                        TRAPS) const {
5213   unsigned int array_dim = 0;
5214   while (length > 0) {
5215     switch (signature[0]) {
5216     case JVM_SIGNATURE_VOID: if (!void_ok) { return NULL; }
5217     case JVM_SIGNATURE_BOOLEAN:
5218     case JVM_SIGNATURE_BYTE:
5219     case JVM_SIGNATURE_CHAR:
5220     case JVM_SIGNATURE_SHORT:
5221     case JVM_SIGNATURE_INT:
5222     case JVM_SIGNATURE_FLOAT:
5223     case JVM_SIGNATURE_LONG:
5224     case JVM_SIGNATURE_DOUBLE:
5225       return signature + 1;
5226     case JVM_SIGNATURE_PRIMITIVE_OBJECT:
5227       // Can't enable this check fully until JDK upgrades the bytecode generators.
5228       // For now, compare to class file version 51 so old verifier doesn't see Q signatures.
5229       if (_major_version < 51 /* CONSTANT_CLASS_DESCRIPTORS */ ) {
5230         classfile_parse_error("Class name contains illegal Q-signature "
5231                               "in descriptor in class file %s",
5232                               CHECK_0);
5233         return NULL;
5234       }
5235       // fall through
5236     case JVM_SIGNATURE_CLASS:
5237     {
5238       if (_major_version < JAVA_1_5_VERSION) {
5239         // Skip over the class name if one is there
5240         const char* const p = skip_over_field_name(signature + 1, true, --length);
5241 
5242         // The next character better be a semicolon
5243         if (p && (p - signature) > 1 && p[0] == JVM_SIGNATURE_ENDCLASS) {
5244           return p + 1;
5245         }
5246       }
5247       else {
5248         // Skip leading 'L' or 'Q' and ignore first appearance of ';'
5249         signature++;
5250         const char* c = (const char*) memchr(signature, JVM_SIGNATURE_ENDCLASS, length - 1);
5251         // Format check signature
5252         if (c != NULL) {
5253           int newlen = c - (char*) signature;
5254           bool legal = verify_unqualified_name(signature, newlen, LegalClass);
5255           if (!legal) {
5256             classfile_parse_error("Class name is empty or contains illegal character "
5257                                   "in descriptor in class file %s",
5258                                   THREAD);
5259             return NULL;
5260           }
5261           return signature + newlen + 1;
5262         }
5263       }
5264       return NULL;
5265     }
5266     case JVM_SIGNATURE_ARRAY:
5267       array_dim++;
5268       if (array_dim > 255) {

5284 
5285 // Checks if name is a legal class name.
5286 void ClassFileParser::verify_legal_class_name(const Symbol* name, TRAPS) const {
5287   if (!_need_verify || _relax_verify) { return; }
5288 
5289   assert(name->refcount() > 0, "symbol must be kept alive");
5290   char* bytes = (char*)name->bytes();
5291   unsigned int length = name->utf8_length();
5292   bool legal = false;
5293 
5294   if (length > 0) {
5295     const char* p;
5296     if (bytes[0] == JVM_SIGNATURE_ARRAY) {
5297       p = skip_over_field_signature(bytes, false, length, CHECK);
5298       legal = (p != NULL) && ((p - bytes) == (int)length);
5299     } else if (_major_version < JAVA_1_5_VERSION) {
5300       if (bytes[0] != JVM_SIGNATURE_SPECIAL) {
5301         p = skip_over_field_name(bytes, true, length);
5302         legal = (p != NULL) && ((p - bytes) == (int)length);
5303       }
5304     } else if ((_major_version >= CONSTANT_CLASS_DESCRIPTORS || _class_name->starts_with("jdk/internal/reflect/"))
5305                    && bytes[length - 1] == ';' ) {
5306       // Support for L...; and Q...; descriptors
5307       legal = verify_unqualified_name(bytes + 1, length - 2, LegalClass);
5308     } else {
5309       // 4900761: relax the constraints based on JSR202 spec
5310       // Class names may be drawn from the entire Unicode character set.
5311       // Identifiers between '/' must be unqualified names.
5312       // The utf8 string has been verified when parsing cpool entries.
5313       legal = verify_unqualified_name(bytes, length, LegalClass);
5314     }
5315   }
5316   if (!legal) {
5317     ResourceMark rm(THREAD);
5318     assert(_class_name != NULL, "invariant");
5319     Exceptions::fthrow(
5320       THREAD_AND_LOCATION,
5321       vmSymbols::java_lang_ClassFormatError(),
5322       "Illegal class name \"%.*s\" in class file %s", length, bytes,
5323       _class_name->as_C_string()
5324     );
5325     return;
5326   }
5327 }

5385 
5386   if (!legal) {
5387     ResourceMark rm(THREAD);
5388     assert(_class_name != NULL, "invariant");
5389     Exceptions::fthrow(
5390       THREAD_AND_LOCATION,
5391       vmSymbols::java_lang_ClassFormatError(),
5392       "Illegal method name \"%.*s\" in class %s", length, bytes,
5393       _class_name->as_C_string()
5394     );
5395     return;
5396   }
5397 }
5398 
5399 
5400 // Checks if signature is a legal field signature.
5401 void ClassFileParser::verify_legal_field_signature(const Symbol* name,
5402                                                    const Symbol* signature,
5403                                                    TRAPS) const {
5404   if (!_need_verify) { return; }
5405   if (!supports_inline_types() && (signature->is_Q_signature() || signature->is_Q_array_signature())) {
5406     throwIllegalSignature("Field", name, signature, CHECK);
5407   }
5408 
5409   const char* const bytes = (const char* const)signature->bytes();
5410   const unsigned int length = signature->utf8_length();
5411   const char* const p = skip_over_field_signature(bytes, false, length, CHECK);
5412 
5413   if (p == NULL || (p - bytes) != (int)length) {
5414     throwIllegalSignature("Field", name, signature, CHECK);
5415   }
5416 }
5417 
5418 // Check that the signature is compatible with the method name.  For example,
5419 // check that <init> has a void signature.
5420 void ClassFileParser::verify_legal_name_with_signature(const Symbol* name,
5421                                                        const Symbol* signature,
5422                                                        TRAPS) const {
5423   if (!_need_verify) {
5424     return;
5425   }
5426 
5427   // Class initializers cannot have args for class format version >= 51.
5428   if (name == vmSymbols::class_initializer_name() &&
5429       signature != vmSymbols::void_method_signature() &&
5430       _major_version >= JAVA_7_VERSION) {
5431     throwIllegalSignature("Method", name, signature, THREAD);
5432     return;
5433   }
5434 
5435   if (!is_value_class()) {
5436     int sig_length = signature->utf8_length();
5437     if (name->utf8_length() > 0 &&
5438       name->char_at(0) == JVM_SIGNATURE_SPECIAL &&
5439       sig_length > 0 &&
5440       signature->char_at(sig_length - 1) != JVM_SIGNATURE_VOID) {
5441       throwIllegalSignature("Method", name, signature, THREAD);
5442     }
5443   }
5444 }
5445 
5446 // Checks if signature is a legal method signature.
5447 // Returns number of parameters
5448 int ClassFileParser::verify_legal_method_signature(const Symbol* name,
5449                                                    const Symbol* signature,
5450                                                    TRAPS) const {
5451   if (!_need_verify) {
5452     // make sure caller's args_size will be less than 0 even for non-static
5453     // method so it will be recomputed in compute_size_of_parameters().
5454     return -2;
5455   }
5456 
5457   unsigned int args_size = 0;
5458   const char* p = (const char*)signature->bytes();
5459   unsigned int length = signature->utf8_length();
5460   const char* nextp;
5461 
5462   // The first character must be a '('

5598   }
5599 }
5600 
5601 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook,
5602                                                       const ClassInstanceInfo& cl_inst_info,
5603                                                       TRAPS) {
5604   if (_klass != NULL) {
5605     return _klass;
5606   }
5607 
5608   InstanceKlass* const ik =
5609     InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
5610 
5611   if (is_hidden()) {
5612     mangle_hidden_class_name(ik);
5613   }
5614 
5615   fill_instance_klass(ik, changed_by_loadhook, cl_inst_info, CHECK_NULL);
5616 
5617   assert(_klass == ik, "invariant");

5618   return ik;
5619 }
5620 
5621 void ClassFileParser::fill_instance_klass(InstanceKlass* ik,
5622                                           bool changed_by_loadhook,
5623                                           const ClassInstanceInfo& cl_inst_info,
5624                                           TRAPS) {
5625   assert(ik != NULL, "invariant");
5626 
5627   // Set name and CLD before adding to CLD
5628   ik->set_class_loader_data(_loader_data);
5629   ik->set_name(_class_name);
5630 
5631   // Add all classes to our internal class loader list here,
5632   // including classes in the bootstrap (NULL) class loader.
5633   const bool publicize = !is_internal();
5634 
5635   _loader_data->add_class(ik, publicize);
5636 
5637   set_klass_to_deallocate(ik);
5638 
5639   assert(_field_info != NULL, "invariant");
5640   assert(ik->static_field_size() == _field_info->_static_field_size, "sanity");
5641   assert(ik->nonstatic_oop_map_count() == _field_info->oop_map_blocks->_nonstatic_oop_map_count,
5642          "sanity");
5643 
5644   assert(ik->is_instance_klass(), "sanity");
5645   assert(ik->size_helper() == _field_info->_instance_size, "sanity");
5646 
5647   // Fill in information already parsed
5648   ik->set_should_verify_class(_need_verify);
5649 
5650   // Not yet: supers are done below to support the new subtype-checking fields
5651   ik->set_nonstatic_field_size(_field_info->_nonstatic_field_size);
5652   ik->set_has_nonstatic_fields(_field_info->_has_nonstatic_fields);
5653   if (_field_info->_is_naturally_atomic && ik->is_inline_klass()) {
5654     ik->set_is_naturally_atomic();
5655   }
5656 
5657   if (carries_identity_modifier()) {
5658     ik->set_carries_identity_modifier();
5659   } else if (carries_value_modifier()) {
5660     ik->set_carries_value_modifier();
5661   }
5662 
5663   assert(_fac != NULL, "invariant");
5664   ik->set_static_oop_field_count(_fac->count[STATIC_OOP] + _fac->count[STATIC_INLINE]);
5665 
5666   // this transfers ownership of a lot of arrays from
5667   // the parser onto the InstanceKlass*
5668   apply_parsed_class_metadata(ik, _java_fields_count);
5669 
5670   // can only set dynamic nest-host after static nest information is set
5671   if (cl_inst_info.dynamic_nest_host() != NULL) {
5672     ik->set_nest_host(cl_inst_info.dynamic_nest_host());
5673   }
5674 
5675   // note that is not safe to use the fields in the parser from this point on
5676   assert(NULL == _cp, "invariant");
5677   assert(NULL == _fields, "invariant");
5678   assert(NULL == _methods, "invariant");
5679   assert(NULL == _inner_classes, "invariant");
5680   assert(NULL == _nest_members, "invariant");
5681   assert(NULL == _preload_classes, "invariant");
5682   assert(NULL == _combined_annotations, "invariant");
5683   assert(NULL == _record_components, "invariant");
5684   assert(NULL == _permitted_subclasses, "invariant");
5685 
5686   if (_has_final_method) {
5687     ik->set_has_final_method();
5688   }
5689 
5690   ik->copy_method_ordering(_method_ordering, CHECK);
5691   // The InstanceKlass::_methods_jmethod_ids cache
5692   // is managed on the assumption that the initial cache
5693   // size is equal to the number of methods in the class. If
5694   // that changes, then InstanceKlass::idnum_can_increment()
5695   // has to be changed accordingly.
5696   ik->set_initial_method_idnum(ik->methods()->length());
5697 
5698   ik->set_this_class_index(_this_class_index);
5699 
5700   if (_is_hidden) {
5701     // _this_class_index is a CONSTANT_Class entry that refers to this
5702     // hidden class itself. If this class needs to refer to its own methods
5703     // or fields, it would use a CONSTANT_MethodRef, etc, which would reference
5704     // _this_class_index. However, because this class is hidden (it's
5705     // not stored in SystemDictionary), _this_class_index cannot be resolved
5706     // with ConstantPool::klass_at_impl, which does a SystemDictionary lookup.
5707     // Therefore, we must eagerly resolve _this_class_index now.
5708     ik->constants()->klass_at_put(_this_class_index, ik);
5709   }
5710 
5711   ik->set_minor_version(_minor_version);
5712   ik->set_major_version(_major_version);
5713   ik->set_has_nonstatic_concrete_methods(_has_nonstatic_concrete_methods);
5714   ik->set_declares_nonstatic_concrete_methods(_declares_nonstatic_concrete_methods);
5715   if (_is_declared_atomic) {
5716     ik->set_is_declared_atomic();
5717   }
5718 
5719   if (_is_hidden) {
5720     ik->set_is_hidden();
5721   }
5722 
5723   // Set PackageEntry for this_klass
5724   oop cl = ik->class_loader();
5725   Handle clh = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(cl));
5726   ClassLoaderData* cld = ClassLoaderData::class_loader_data_or_null(clh());
5727   ik->set_package(cld, NULL, CHECK);
5728 
5729   const Array<Method*>* const methods = ik->methods();
5730   assert(methods != NULL, "invariant");
5731   const int methods_len = methods->length();
5732 
5733   check_methods_for_intrinsics(ik, methods);
5734 
5735   // Fill in field values obtained by parse_classfile_attributes
5736   if (_parsed_annotations->has_any_annotations()) {
5737     _parsed_annotations->apply_to(ik);

5805 
5806   assert(_all_mirandas != NULL, "invariant");
5807 
5808   // Generate any default methods - default methods are public interface methods
5809   // that have a default implementation.  This is new with Java 8.
5810   if (_has_nonstatic_concrete_methods) {
5811     DefaultMethods::generate_default_methods(ik,
5812                                              _all_mirandas,
5813                                              CHECK);
5814   }
5815 
5816   // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5817   if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5818       !module_entry->has_default_read_edges()) {
5819     if (!module_entry->set_has_default_read_edges()) {
5820       // We won a potential race
5821       JvmtiExport::add_default_read_edges(module_handle, THREAD);
5822     }
5823   }
5824 
5825   bool all_fields_empty = true;
5826   for (AllFieldStream fs(ik->fields(), ik->constants()); !fs.done(); fs.next()) {
5827     if (!fs.access_flags().is_static()) {
5828       if (fs.field_descriptor().is_inline_type()) {
5829         Klass* k = _inline_type_field_klasses->at(fs.index());
5830         ik->set_inline_type_field_klass(fs.index(), k);
5831         if (!InlineKlass::cast(k)->is_empty_inline_type()) { all_fields_empty = false; }
5832       } else {
5833         all_fields_empty = false;
5834       }
5835     } else if (is_inline_type() && (fs.name() == vmSymbols::default_value_name())) {
5836       InlineKlass::cast(ik)->set_default_value_offset(ik->field_offset(fs.index()));
5837     }
5838   }
5839 
5840   if (_is_empty_inline_type || (is_inline_type() && all_fields_empty)) {
5841     ik->set_is_empty_inline_type();
5842   }
5843 
5844   if (is_inline_type()) {
5845     InlineKlass* vk = InlineKlass::cast(ik);
5846     vk->set_alignment(_alignment);
5847     vk->set_first_field_offset(_first_field_offset);
5848     vk->set_exact_size_in_bytes(_exact_size_in_bytes);
5849     InlineKlass::cast(ik)->initialize_calling_convention(CHECK);
5850   }
5851 
5852   ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5853 
5854   if (!is_internal()) {
5855     ik->print_class_load_logging(_loader_data, module_entry, _stream);
5856 
5857     if (ik->minor_version() == JAVA_PREVIEW_MINOR_VERSION &&
5858         ik->major_version() == JVM_CLASSFILE_MAJOR_VERSION &&
5859         log_is_enabled(Info, class, preview)) {
5860       ResourceMark rm;
5861       log_info(class, preview)("Loading class %s that depends on preview features (class file version %d.65535)",
5862                                ik->external_name(), JVM_CLASSFILE_MAJOR_VERSION);
5863     }
5864 
5865     if (log_is_enabled(Debug, class, resolve))  {
5866       ResourceMark rm;
5867       // print out the superclass.
5868       const char * from = ik->external_name();
5869       if (ik->java_super() != NULL) {
5870         log_debug(class, resolve)("%s %s (super)",
5871                    from,

5922 ClassFileParser::ClassFileParser(ClassFileStream* stream,
5923                                  Symbol* name,
5924                                  ClassLoaderData* loader_data,
5925                                  const ClassLoadInfo* cl_info,
5926                                  Publicity pub_level,
5927                                  TRAPS) :
5928   _stream(stream),
5929   _class_name(NULL),
5930   _loader_data(loader_data),
5931   _is_hidden(cl_info->is_hidden()),
5932   _can_access_vm_annotations(cl_info->can_access_vm_annotations()),
5933   _orig_cp_size(0),
5934   _super_klass(),
5935   _cp(NULL),
5936   _fields(NULL),
5937   _methods(NULL),
5938   _inner_classes(NULL),
5939   _nest_members(NULL),
5940   _nest_host(0),
5941   _permitted_subclasses(NULL),
5942   _preload_classes(NULL),
5943   _record_components(NULL),
5944   _local_interfaces(NULL),
5945   _local_interface_indexes(NULL),
5946   _transitive_interfaces(NULL),
5947   _combined_annotations(NULL),
5948   _class_annotations(NULL),
5949   _class_type_annotations(NULL),
5950   _fields_annotations(NULL),
5951   _fields_type_annotations(NULL),
5952   _klass(NULL),
5953   _klass_to_deallocate(NULL),
5954   _parsed_annotations(NULL),
5955   _fac(NULL),
5956   _field_info(NULL),
5957   _inline_type_field_klasses(NULL),
5958   _method_ordering(NULL),
5959   _all_mirandas(NULL),
5960   _vtable_size(0),
5961   _itable_size(0),
5962   _num_miranda_methods(0),
5963   _protection_domain(cl_info->protection_domain()),
5964   _access_flags(),
5965   _pub_level(pub_level),
5966   _bad_constant_seen(0),
5967   _synthetic_flag(false),
5968   _sde_length(false),
5969   _sde_buffer(NULL),
5970   _sourcefile_index(0),
5971   _generic_signature_index(0),
5972   _major_version(0),
5973   _minor_version(0),
5974   _this_class_index(0),
5975   _super_class_index(0),
5976   _itfs_len(0),
5977   _java_fields_count(0),
5978   _need_verify(false),
5979   _relax_verify(false),
5980   _has_nonstatic_concrete_methods(false),
5981   _declares_nonstatic_concrete_methods(false),
5982   _has_final_method(false),
5983   _has_contended_fields(false),
5984   _has_inline_type_fields(false),
5985   _has_nonstatic_fields(false),
5986   _is_empty_inline_type(false),
5987   _is_naturally_atomic(false),
5988   _is_declared_atomic(false),
5989   _carries_value_modifier(false),
5990   _carries_identity_modifier(false),
5991   _has_finalizer(false),
5992   _has_empty_finalizer(false),
5993   _has_vanilla_constructor(false),
5994   _max_bootstrap_specifier_index(-1) {
5995 
5996   _class_name = name != NULL ? name : vmSymbols::unknown_class_name();
5997   _class_name->increment_refcount();
5998 
5999   assert(_loader_data != NULL, "invariant");
6000   assert(stream != NULL, "invariant");
6001   assert(_stream != NULL, "invariant");
6002   assert(_stream->buffer() == _stream->current(), "invariant");
6003   assert(_class_name != NULL, "invariant");
6004   assert(0 == _access_flags.as_int(), "invariant");
6005 
6006   // Figure out whether we can skip format checking (matching classic VM behavior)
6007   if (DumpSharedSpaces) {
6008     // verify == true means it's a 'remote' class (i.e., non-boot class)
6009     // Verification decision is based on BytecodeVerificationRemote flag
6010     // for those classes.

6020   stream->set_verify(_need_verify);
6021 
6022   // Check if verification needs to be relaxed for this class file
6023   // Do not restrict it to jdk1.0 or jdk1.1 to maintain backward compatibility (4982376)
6024   _relax_verify = relax_format_check_for(_loader_data);
6025 
6026   parse_stream(stream, CHECK);
6027 
6028   post_process_parsed_stream(stream, _cp, CHECK);
6029 }
6030 
6031 void ClassFileParser::clear_class_metadata() {
6032   // metadata created before the instance klass is created.  Must be
6033   // deallocated if classfile parsing returns an error.
6034   _cp = NULL;
6035   _fields = NULL;
6036   _methods = NULL;
6037   _inner_classes = NULL;
6038   _nest_members = NULL;
6039   _permitted_subclasses = NULL;
6040   _preload_classes = NULL;
6041   _combined_annotations = NULL;
6042   _class_annotations = _class_type_annotations = NULL;
6043   _fields_annotations = _fields_type_annotations = NULL;
6044   _record_components = NULL;
6045 }
6046 
6047 // Destructor to clean up
6048 ClassFileParser::~ClassFileParser() {
6049   _class_name->decrement_refcount();
6050 
6051   if (_cp != NULL) {
6052     MetadataFactory::free_metadata(_loader_data, _cp);
6053   }
6054   if (_fields != NULL) {
6055     MetadataFactory::free_array<u2>(_loader_data, _fields);
6056   }
6057 
6058   if (_inline_type_field_klasses != NULL) {
6059      MetadataFactory::free_array<InlineKlass*>(_loader_data, _inline_type_field_klasses);
6060   }
6061 
6062   if (_methods != NULL) {
6063     // Free methods
6064     InstanceKlass::deallocate_methods(_loader_data, _methods);
6065   }
6066 
6067   // beware of the Universe::empty_blah_array!!
6068   if (_inner_classes != NULL && _inner_classes != Universe::the_empty_short_array()) {
6069     MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
6070   }
6071 
6072   if (_nest_members != NULL && _nest_members != Universe::the_empty_short_array()) {
6073     MetadataFactory::free_array<u2>(_loader_data, _nest_members);
6074   }
6075 
6076   if (_record_components != NULL) {
6077     InstanceKlass::deallocate_record_components(_loader_data, _record_components);
6078   }
6079 
6080   if (_permitted_subclasses != NULL && _permitted_subclasses != Universe::the_empty_short_array()) {
6081     MetadataFactory::free_array<u2>(_loader_data, _permitted_subclasses);
6082   }
6083 
6084   if (_preload_classes != NULL && _preload_classes != Universe::the_empty_short_array()) {
6085     MetadataFactory::free_array<u2>(_loader_data, _preload_classes);
6086   }
6087 
6088   // Free interfaces
6089   InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
6090                                        _local_interfaces, _transitive_interfaces);
6091 
6092   if (_combined_annotations != NULL) {
6093     // After all annotations arrays have been created, they are installed into the
6094     // Annotations object that will be assigned to the InstanceKlass being created.
6095 
6096     // Deallocate the Annotations object and the installed annotations arrays.
6097     _combined_annotations->deallocate_contents(_loader_data);
6098 
6099     // If the _combined_annotations pointer is non-NULL,
6100     // then the other annotations fields should have been cleared.
6101     assert(_class_annotations       == NULL, "Should have been cleared");
6102     assert(_class_type_annotations  == NULL, "Should have been cleared");
6103     assert(_fields_annotations      == NULL, "Should have been cleared");
6104     assert(_fields_type_annotations == NULL, "Should have been cleared");
6105   } else {
6106     // If the annotations arrays were not installed into the Annotations object,
6107     // then they have to be deallocated explicitly.

6152     cp_size, CHECK);
6153 
6154   _orig_cp_size = cp_size;
6155   if (is_hidden()) { // Add a slot for hidden class name.
6156     cp_size++;
6157   }
6158 
6159   _cp = ConstantPool::allocate(_loader_data,
6160                                cp_size,
6161                                CHECK);
6162 
6163   ConstantPool* const cp = _cp;
6164 
6165   parse_constant_pool(stream, cp, _orig_cp_size, CHECK);
6166 
6167   assert(cp_size == (const u2)cp->length(), "invariant");
6168 
6169   // ACCESS FLAGS
6170   stream->guarantee_more(8, CHECK);  // flags, this_class, super_class, infs_len
6171 
6172   jint recognized_modifiers = JVM_RECOGNIZED_CLASS_MODIFIERS;

6173   // JVM_ACC_MODULE is defined in JDK-9 and later.
6174   if (_major_version >= JAVA_9_VERSION) {
6175     recognized_modifiers |= JVM_ACC_MODULE;
6176   }
6177   // JVM_ACC_VALUE and JVM_ACC_PRIMITIVE are defined for class file version 55 and later
6178   if (supports_inline_types()) {
6179     recognized_modifiers |= JVM_ACC_PRIMITIVE | JVM_ACC_VALUE;
6180   }
6181 
6182   // Access flags
6183   jint flags = stream->get_u2_fast() & recognized_modifiers;
6184 
6185   if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
6186     // Set abstract bit for old class files for backward compatibility
6187     flags |= JVM_ACC_ABSTRACT;
6188   }
6189 












6190   // This class and superclass
6191   _this_class_index = stream->get_u2_fast();
6192   check_property(
6193     valid_cp_range(_this_class_index, cp_size) &&
6194       cp->tag_at(_this_class_index).is_unresolved_klass(),
6195     "Invalid this class index %u in constant pool in class file %s",
6196     _this_class_index, CHECK);
6197 
6198   Symbol* const class_name_in_cp = cp->klass_name_at(_this_class_index);
6199   assert(class_name_in_cp != NULL, "class_name can't be null");
6200 
6201   bool is_java_lang_Object = class_name_in_cp == vmSymbols::java_lang_Object();
6202 
6203   verify_legal_class_modifiers(flags, NULL, is_java_lang_Object, CHECK);
6204 
6205   if (EnableValhalla) {
6206     if(!supports_inline_types()) {
6207       const bool is_module = (flags & JVM_ACC_MODULE) != 0;
6208       const bool is_interface = (flags & JVM_ACC_INTERFACE) != 0;
6209       if (!is_module && !is_interface && !is_java_lang_Object) {
6210         flags |= JVM_ACC_IDENTITY;
6211       }
6212     }
6213   }
6214 
6215   _access_flags.set_flags(flags);
6216 
6217   if (EnableValhalla) {
6218     if (_access_flags.is_identity_class()) set_carries_identity_modifier();
6219     if (_access_flags.is_value_class()) set_carries_value_modifier();
6220     if (carries_identity_modifier() && carries_value_modifier()) {
6221       classfile_parse_error("Class %s has both ACC_IDENTITY and ACC_VALUE modifiers", THREAD);
6222     }
6223   }
6224 
6225   short bad_constant = class_bad_constant_seen();
6226   if (bad_constant != 0) {
6227     // Do not throw CFE until after the access_flags are checked because if
6228     // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
6229     classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, THREAD);
6230     return;
6231   }
6232 
6233   // Don't need to check whether this class name is legal or not.
6234   // It has been checked when constant pool is parsed.
6235   // However, make sure it is not an array type.
6236   if (_need_verify) {
6237     guarantee_property(class_name_in_cp->char_at(0) != JVM_SIGNATURE_ARRAY,
6238                        "Bad class name in class file %s",
6239                        CHECK);
6240   }
6241 
6242 #ifdef ASSERT
6243   // Basic sanity checks
6244   if (_is_hidden) {
6245     assert(_class_name != vmSymbols::unknown_class_name(), "hidden classes should have a special name");
6246   }
6247 #endif
6248 
6249   // Update the _class_name as needed depending on whether this is a named, un-named, or hidden class.
6250 
6251   if (_is_hidden) {
6252     assert(_class_name != NULL, "Unexpected null _class_name");

6290       if (stream->source() != NULL) {
6291         ls.print(" source: %s", stream->source());
6292       }
6293       ls.cr();
6294     }
6295   }
6296 
6297   // SUPERKLASS
6298   _super_class_index = stream->get_u2_fast();
6299   _super_klass = parse_super_class(cp,
6300                                    _super_class_index,
6301                                    _need_verify,
6302                                    CHECK);
6303 
6304   // Interfaces
6305   _itfs_len = stream->get_u2_fast();
6306   parse_interfaces(stream,
6307                    _itfs_len,
6308                    cp,
6309                    &_has_nonstatic_concrete_methods,
6310                    &_is_declared_atomic,
6311                    CHECK);
6312 


6313   // Fields (offsets are filled in later)
6314   _fac = new FieldAllocationCount();
6315   parse_fields(stream,
6316                _access_flags,
6317                _fac,
6318                cp,
6319                cp_size,
6320                &_java_fields_count,
6321                CHECK);
6322 
6323   assert(_fields != NULL, "invariant");
6324 
6325   // Methods
6326   AccessFlags promoted_flags;
6327   parse_methods(stream,
6328                 is_interface(),
6329                 is_value_class(),
6330                 is_abstract_class(),
6331                 &promoted_flags,
6332                 &_has_final_method,
6333                 &_declares_nonstatic_concrete_methods,
6334                 CHECK);
6335 
6336   assert(_methods != NULL, "invariant");
6337 
6338   // promote flags from parse_methods() to the klass' flags
6339   _access_flags.add_promoted_flags(promoted_flags.as_int());
6340 
6341   if (_declares_nonstatic_concrete_methods) {
6342     _has_nonstatic_concrete_methods = true;
6343   }
6344 
6345   // Additional attributes/annotations
6346   _parsed_annotations = new ClassAnnotationCollector();
6347   parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK);
6348 
6349   assert(_inner_classes != NULL, "invariant");
6350 

6393   // Update this_class_index's slot in the constant pool with the new Utf8 entry.
6394   // We have to update the resolved_klass_index and the name_index together
6395   // so extract the existing resolved_klass_index first.
6396   CPKlassSlot cp_klass_slot = _cp->klass_slot_at(_this_class_index);
6397   int resolved_klass_index = cp_klass_slot.resolved_klass_index();
6398   _cp->unresolved_klass_at_put(_this_class_index, hidden_index, resolved_klass_index);
6399   assert(_cp->klass_slot_at(_this_class_index).name_index() == _orig_cp_size,
6400          "Bad name_index");
6401 }
6402 
6403 void ClassFileParser::post_process_parsed_stream(const ClassFileStream* const stream,
6404                                                  ConstantPool* cp,
6405                                                  TRAPS) {
6406   assert(stream != NULL, "invariant");
6407   assert(stream->at_eos(), "invariant");
6408   assert(cp != NULL, "invariant");
6409   assert(_loader_data != NULL, "invariant");
6410 
6411   if (_class_name == vmSymbols::java_lang_Object()) {
6412     check_property(_local_interfaces == Universe::the_empty_instance_klass_array(),
6413         "java.lang.Object cannot implement an interface in class file %s",
6414         CHECK);
6415   }
6416   // We check super class after class file is parsed and format is checked
6417   if (_super_class_index > 0 && NULL == _super_klass) {
6418     Symbol* const super_class_name = cp->klass_name_at(_super_class_index);
6419     if (is_interface()) {
6420       // Before attempting to resolve the superclass, check for class format
6421       // errors not checked yet.
6422       guarantee_property(super_class_name == vmSymbols::java_lang_Object(),
6423         "Interfaces must have java.lang.Object as superclass in class file %s",
6424         CHECK);
6425     }
6426     Handle loader(THREAD, _loader_data->class_loader());
6427     _super_klass = (const InstanceKlass*)
6428                        SystemDictionary::resolve_super_or_fail(_class_name,
6429                                                                super_class_name,
6430                                                                loader,
6431                                                                _protection_domain,
6432                                                                true,
6433                                                                CHECK);
6434   }
6435 
6436   if (_super_klass != NULL) {
6437     if (_super_klass->is_interface()) {
6438       classfile_icce_error("class %s has interface %s as super class", _super_klass, THREAD);
6439       return;
6440     }
6441 
6442     if (EnableValhalla) {
6443       check_identity_and_value_modifiers(this, _super_klass, CHECK);
6444     }
6445 
6446     if (_super_klass->has_nonstatic_concrete_methods()) {
6447       _has_nonstatic_concrete_methods = true;
6448     }
6449     if (_super_klass->is_declared_atomic()) {
6450       _is_declared_atomic = true;
6451     }
6452   }
6453 
6454   if (_class_name == vmSymbols::java_lang_NonTearable() && _loader_data->class_loader() == NULL) {
6455     // This is the original source of this condition.
6456     // It propagates by inheritance, as if testing "instanceof NonTearable".
6457     _is_declared_atomic = true;
6458   } else if (*ForceNonTearable != '\0') {
6459     // Allow a command line switch to force the same atomicity property:
6460     const char* class_name_str = _class_name->as_C_string();
6461     if (StringUtils::class_list_match(ForceNonTearable, class_name_str)) {
6462       _is_declared_atomic = true;
6463     }
6464   }
6465 
6466   int itfs_len = _local_interface_indexes == NULL ? 0 : _local_interface_indexes->length();
6467   _local_interfaces = MetadataFactory::new_array<InstanceKlass*>(_loader_data, itfs_len, NULL, CHECK);
6468   if (_local_interface_indexes != NULL) {
6469     for (int i = 0; i < _local_interface_indexes->length(); i++) {
6470       u2 interface_index = _local_interface_indexes->at(i);
6471       Klass* interf;
6472       if (cp->tag_at(interface_index).is_klass()) {
6473         interf = cp->resolved_klass_at(interface_index);
6474       } else {
6475         Symbol* const unresolved_klass  = cp->klass_name_at(interface_index);
6476 
6477         // Don't need to check legal name because it's checked when parsing constant pool.
6478         // But need to make sure it's not an array type.
6479         guarantee_property(unresolved_klass->char_at(0) != JVM_SIGNATURE_ARRAY,
6480                             "Bad interface name in class file %s", CHECK);
6481 
6482         // Call resolve_super so class circularity is checked
6483         interf = SystemDictionary::resolve_super_or_fail(
6484                                                   _class_name,
6485                                                   unresolved_klass,
6486                                                   Handle(THREAD, _loader_data->class_loader()),
6487                                                   _protection_domain,
6488                                                   false,
6489                                                   CHECK);
6490       }
6491 
6492       if (!interf->is_interface()) {
6493         THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
6494                   err_msg("class %s can not implement %s, because it is not an interface (%s)",
6495                           _class_name->as_klass_external_name(),
6496                           interf->external_name(),
6497                           interf->class_in_module_of_loader()));
6498       }
6499 
6500       if (EnableValhalla) {
6501         // Check modifiers and set carries_identity_modifier/carries_value_modifier flags
6502         check_identity_and_value_modifiers(this, InstanceKlass::cast(interf), CHECK);
6503       }
6504 
6505       if (InstanceKlass::cast(interf)->has_nonstatic_concrete_methods()) {
6506         _has_nonstatic_concrete_methods = true;
6507       }
6508       if (InstanceKlass::cast(interf)->is_declared_atomic()) {
6509         _is_declared_atomic = true;
6510       }
6511       _local_interfaces->at_put(i, InstanceKlass::cast(interf));
6512     }
6513   }
6514   assert(_local_interfaces != NULL, "invariant");
6515 
6516   // Compute the transitive list of all unique interfaces implemented by this class
6517   _transitive_interfaces =
6518     compute_transitive_interfaces(_super_klass,
6519                                   _local_interfaces,
6520                                   _loader_data,
6521                                   CHECK);
6522 
6523   assert(_transitive_interfaces != NULL, "invariant");
6524 
6525   // sort methods
6526   _method_ordering = sort_methods(_methods);
6527 
6528   _all_mirandas = new GrowableArray<Method*>(20);
6529 
6530   Handle loader(THREAD, _loader_data->class_loader());
6531   klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
6532                                                     &_num_miranda_methods,
6533                                                     _all_mirandas,
6534                                                     _super_klass,
6535                                                     _methods,
6536                                                     _access_flags,
6537                                                     _major_version,
6538                                                     loader,
6539                                                     _class_name,
6540                                                     _local_interfaces);
6541 
6542   // Size of Java itable (in words)
6543   _itable_size = is_interface() ? 0 :
6544     klassItable::compute_itable_size(_transitive_interfaces);
6545 
6546   assert(_fac != NULL, "invariant");
6547   assert(_parsed_annotations != NULL, "invariant");
6548 
6549 
6550   if (EnableValhalla) {
6551     _inline_type_field_klasses = MetadataFactory::new_array<InlineKlass*>(_loader_data,
6552                                                    java_fields_count(),
6553                                                    NULL,
6554                                                    CHECK);
6555     for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
6556       if (Signature::basic_type(fs.signature()) == T_PRIMITIVE_OBJECT && !fs.access_flags().is_static()) {
6557         // Pre-load inline class
6558         Klass* klass = SystemDictionary::resolve_inline_type_field_or_fail(&fs,
6559             Handle(THREAD, _loader_data->class_loader()),
6560             _protection_domain, true, CHECK);
6561         assert(klass != NULL, "Sanity check");
6562         if (!klass->access_flags().is_value_class()) {
6563           assert(klass->is_instance_klass(), "Sanity check");
6564           ResourceMark rm(THREAD);
6565             THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
6566                       err_msg("Class %s expects class %s to be an inline type, but it is not",
6567                       _class_name->as_C_string(),
6568                       InstanceKlass::cast(klass)->external_name()));
6569         }
6570         _inline_type_field_klasses->at_put(fs.index(), InlineKlass::cast(klass));
6571       }
6572     }
6573   }
6574 
6575   _field_info = new FieldLayoutInfo();
6576   FieldLayoutBuilder lb(class_name(), super_klass(), _cp, _fields,
6577       _parsed_annotations->is_contended(), is_inline_type(),
6578       _field_info, _inline_type_field_klasses);
6579   lb.build_layout(CHECK);
6580   if (is_inline_type()) {
6581     _alignment = lb.get_alignment();
6582     _first_field_offset = lb.get_first_field_offset();
6583     _exact_size_in_bytes = lb.get_exact_size_in_byte();
6584   }
6585   _has_inline_type_fields = _field_info->_has_inline_fields;
6586 }
6587 
6588 void ClassFileParser::set_klass(InstanceKlass* klass) {
6589 
6590 #ifdef ASSERT
6591   if (klass != NULL) {
6592     assert(NULL == _klass, "leaking?");
6593   }
6594 #endif
6595 
6596   _klass = klass;
6597 }
6598 
6599 void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) {
6600 
6601 #ifdef ASSERT
6602   if (klass != NULL) {
6603     assert(NULL == _klass_to_deallocate, "leaking?");
6604   }
6605 #endif
< prev index next >