4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24 #include "precompiled.hpp"
25 #include "cds/cdsConfig.hpp"
26 #include "classfile/classFileParser.hpp"
27 #include "classfile/classFileStream.hpp"
28 #include "classfile/classLoader.hpp"
29 #include "classfile/classLoaderData.inline.hpp"
30 #include "classfile/classLoadInfo.hpp"
31 #include "classfile/defaultMethods.hpp"
32 #include "classfile/fieldLayoutBuilder.hpp"
33 #include "classfile/javaClasses.inline.hpp"
34 #include "classfile/moduleEntry.hpp"
35 #include "classfile/packageEntry.hpp"
36 #include "classfile/symbolTable.hpp"
37 #include "classfile/systemDictionary.hpp"
38 #include "classfile/verificationType.hpp"
39 #include "classfile/verifier.hpp"
40 #include "classfile/vmClasses.hpp"
41 #include "classfile/vmSymbols.hpp"
42 #include "jvm.h"
43 #include "logging/log.hpp"
44 #include "logging/logStream.hpp"
45 #include "memory/allocation.hpp"
46 #include "memory/metadataFactory.hpp"
47 #include "memory/oopFactory.hpp"
48 #include "memory/resourceArea.hpp"
49 #include "memory/universe.hpp"
50 #include "oops/annotations.hpp"
51 #include "oops/constantPool.inline.hpp"
52 #include "oops/fieldInfo.hpp"
53 #include "oops/fieldStreams.inline.hpp"
54 #include "oops/instanceKlass.inline.hpp"
55 #include "oops/instanceMirrorKlass.hpp"
56 #include "oops/klass.inline.hpp"
57 #include "oops/klassVtable.hpp"
58 #include "oops/metadata.hpp"
59 #include "oops/method.inline.hpp"
60 #include "oops/oop.inline.hpp"
61 #include "oops/recordComponent.hpp"
62 #include "oops/symbol.hpp"
63 #include "prims/jvmtiExport.hpp"
64 #include "prims/jvmtiThreadState.hpp"
65 #include "runtime/arguments.hpp"
66 #include "runtime/fieldDescriptor.inline.hpp"
67 #include "runtime/handles.inline.hpp"
68 #include "runtime/javaCalls.hpp"
69 #include "runtime/os.hpp"
70 #include "runtime/perfData.hpp"
71 #include "runtime/reflection.hpp"
72 #include "runtime/safepointVerifiers.hpp"
73 #include "runtime/signature.hpp"
74 #include "runtime/timer.hpp"
75 #include "services/classLoadingService.hpp"
76 #include "services/threadService.hpp"
77 #include "utilities/align.hpp"
78 #include "utilities/bitMap.inline.hpp"
79 #include "utilities/checkedCast.hpp"
80 #include "utilities/copy.hpp"
81 #include "utilities/formatBuffer.hpp"
82 #include "utilities/exceptions.hpp"
83 #include "utilities/globalDefinitions.hpp"
84 #include "utilities/growableArray.hpp"
85 #include "utilities/macros.hpp"
86 #include "utilities/ostream.hpp"
87 #include "utilities/resourceHash.hpp"
88 #include "utilities/utf8.hpp"
89 #if INCLUDE_CDS
90 #include "classfile/systemDictionaryShared.hpp"
91 #endif
92 #if INCLUDE_JFR
93 #include "jfr/support/jfrTraceIdExtension.hpp"
94 #endif
95
96 // We generally try to create the oops directly when parsing, rather than
97 // allocating temporary data structures and copying the bytes twice. A
98 // temporary area is only needed when parsing utf8 entries in the constant
99 // pool and when parsing line number tables.
100
101 // We add assert in debug mode when class format is not checked.
102
103 #define JAVA_CLASSFILE_MAGIC 0xCAFEBABE
104 #define JAVA_MIN_SUPPORTED_VERSION 45
105 #define JAVA_PREVIEW_MINOR_VERSION 65535
106
107 // Used for two backward compatibility reasons:
132 #define JAVA_13_VERSION 57
133
134 #define JAVA_14_VERSION 58
135
136 #define JAVA_15_VERSION 59
137
138 #define JAVA_16_VERSION 60
139
140 #define JAVA_17_VERSION 61
141
142 #define JAVA_18_VERSION 62
143
144 #define JAVA_19_VERSION 63
145
146 #define JAVA_20_VERSION 64
147
148 #define JAVA_21_VERSION 65
149
150 #define JAVA_22_VERSION 66
151
152 #define JAVA_23_VERSION 67
153
154 void ClassFileParser::set_class_bad_constant_seen(short bad_constant) {
155 assert((bad_constant == JVM_CONSTANT_Module ||
156 bad_constant == JVM_CONSTANT_Package) && _major_version >= JAVA_9_VERSION,
157 "Unexpected bad constant pool entry");
158 if (_bad_constant_seen == 0) _bad_constant_seen = bad_constant;
159 }
160
161 void ClassFileParser::parse_constant_pool_entries(const ClassFileStream* const stream,
162 ConstantPool* cp,
163 const int length,
164 TRAPS) {
165 assert(stream != nullptr, "invariant");
166 assert(cp != nullptr, "invariant");
167
168 // Use a local copy of ClassFileStream. It helps the C++ compiler to optimize
169 // this function (_current can be allocated in a register, with scalar
170 // replacement of aggregates). The _current pointer is copied back to
171 // stream() when this function returns. DON'T call another method within
172 // this method that uses stream().
173 const ClassFileStream cfs1 = *stream;
174 const ClassFileStream* const cfs = &cfs1;
175
176 debug_only(const u1* const old_current = stream->current();)
177
178 // Used for batching symbol allocations.
179 const char* names[SymbolTable::symbol_alloc_batch_size];
180 int lengths[SymbolTable::symbol_alloc_batch_size];
181 int indices[SymbolTable::symbol_alloc_batch_size];
182 unsigned int hashValues[SymbolTable::symbol_alloc_batch_size];
183 int names_count = 0;
184
185 // parsing Index 0 is unused
186 for (int index = 1; index < length; index++) {
187 // Each of the following case guarantees one more byte in the stream
188 // for the following tag or the access_flags following constant pool,
189 // so we don't need bounds-check for reading tag.
190 const u1 tag = cfs->get_u1_fast();
191 switch (tag) {
192 case JVM_CONSTANT_Class : {
193 cfs->guarantee_more(3, CHECK); // name_index, tag/access_flags
194 const u2 name_index = cfs->get_u2_fast();
195 cp->klass_index_at_put(index, name_index);
196 break;
197 }
198 case JVM_CONSTANT_Fieldref: {
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->field_at_put(index, class_index, name_and_type_index);
203 break;
204 }
205 case JVM_CONSTANT_Methodref: {
206 cfs->guarantee_more(5, CHECK); // class_index, name_and_type_index, tag/access_flags
207 const u2 class_index = cfs->get_u2_fast();
208 const u2 name_and_type_index = cfs->get_u2_fast();
209 cp->method_at_put(index, class_index, name_and_type_index);
210 break;
211 }
212 case JVM_CONSTANT_InterfaceMethodref: {
493 check_property(valid_symbol_at(name_ref_index),
494 "Invalid constant pool index %u in class file %s",
495 name_ref_index, CHECK);
496 check_property(valid_symbol_at(signature_ref_index),
497 "Invalid constant pool index %u in class file %s",
498 signature_ref_index, CHECK);
499 break;
500 }
501 case JVM_CONSTANT_Utf8:
502 break;
503 case JVM_CONSTANT_UnresolvedClass: // fall-through
504 case JVM_CONSTANT_UnresolvedClassInError: {
505 ShouldNotReachHere(); // Only JVM_CONSTANT_ClassIndex should be present
506 break;
507 }
508 case JVM_CONSTANT_ClassIndex: {
509 const int class_index = cp->klass_index_at(index);
510 check_property(valid_symbol_at(class_index),
511 "Invalid constant pool index %u in class file %s",
512 class_index, CHECK);
513 cp->unresolved_klass_at_put(index, class_index, num_klasses++);
514 break;
515 }
516 case JVM_CONSTANT_StringIndex: {
517 const int string_index = cp->string_index_at(index);
518 check_property(valid_symbol_at(string_index),
519 "Invalid constant pool index %u in class file %s",
520 string_index, CHECK);
521 Symbol* const sym = cp->symbol_at(string_index);
522 cp->unresolved_string_at_put(index, sym);
523 break;
524 }
525 case JVM_CONSTANT_MethodHandle: {
526 const int ref_index = cp->method_handle_index_at(index);
527 check_property(valid_cp_range(ref_index, length),
528 "Invalid constant pool index %u in class file %s",
529 ref_index, CHECK);
530 const constantTag tag = cp->tag_at(ref_index);
531 const int ref_kind = cp->method_handle_ref_kind_at(index);
532
702 }
703 }
704 } else {
705 if (_need_verify) {
706 // Method name and signature are individually verified above, when iterating
707 // NameAndType_info. Need to check here that signature is non-zero length and
708 // the right type.
709 if (!Signature::is_method(signature)) {
710 throwIllegalSignature("Method", name, signature, CHECK);
711 }
712 }
713 // If a class method name begins with '<', it must be "<init>" and have void signature.
714 const unsigned int name_len = name->utf8_length();
715 if (tag == JVM_CONSTANT_Methodref && name_len != 0 &&
716 name->char_at(0) == JVM_SIGNATURE_SPECIAL) {
717 if (name != vmSymbols::object_initializer_name()) {
718 classfile_parse_error(
719 "Bad method name at constant pool index %u in class file %s",
720 name_ref_index, THREAD);
721 return;
722 } else if (!Signature::is_void_method(signature)) { // must have void signature.
723 throwIllegalSignature("Method", name, signature, CHECK);
724 }
725 }
726 }
727 break;
728 }
729 case JVM_CONSTANT_MethodHandle: {
730 const int ref_index = cp->method_handle_index_at(index);
731 const int ref_kind = cp->method_handle_ref_kind_at(index);
732 switch (ref_kind) {
733 case JVM_REF_invokeVirtual:
734 case JVM_REF_invokeStatic:
735 case JVM_REF_invokeSpecial:
736 case JVM_REF_newInvokeSpecial: {
737 const int name_and_type_ref_index =
738 cp->uncached_name_and_type_ref_index_at(ref_index);
739 const int name_ref_index =
740 cp->name_ref_index_at(name_and_type_ref_index);
741 const Symbol* const name = cp->symbol_at(name_ref_index);
742 if (ref_kind == JVM_REF_newInvokeSpecial) {
743 if (name != vmSymbols::object_initializer_name()) {
744 classfile_parse_error(
745 "Bad constructor name at constant pool index %u in class file %s",
746 name_ref_index, THREAD);
747 return;
748 }
749 } else {
750 if (name == vmSymbols::object_initializer_name()) {
751 classfile_parse_error(
752 "Bad method name at constant pool index %u in class file %s",
753 name_ref_index, THREAD);
754 return;
755 }
756 }
757 break;
758 }
759 // Other ref_kinds are already fully checked in previous pass.
760 } // switch(ref_kind)
761 break;
762 }
763 case JVM_CONSTANT_MethodType: {
764 const Symbol* const no_name = vmSymbols::type_name(); // place holder
765 const Symbol* const signature = cp->method_type_signature_at(index);
766 verify_legal_method_signature(no_name, signature, CHECK);
767 break;
768 }
769 case JVM_CONSTANT_Utf8: {
770 assert(cp->symbol_at(index)->refcount() != 0, "count corrupted");
782
783 NameSigHash(Symbol* name, Symbol* sig) :
784 _name(name),
785 _sig(sig) {}
786
787 static unsigned int hash(NameSigHash const& namesig) {
788 return namesig._name->identity_hash() ^ namesig._sig->identity_hash();
789 }
790
791 static bool equals(NameSigHash const& e0, NameSigHash const& e1) {
792 return (e0._name == e1._name) &&
793 (e0._sig == e1._sig);
794 }
795 };
796
797 using NameSigHashtable = ResourceHashtable<NameSigHash, int,
798 NameSigHash::HASH_ROW_SIZE,
799 AnyObj::RESOURCE_AREA, mtInternal,
800 &NameSigHash::hash, &NameSigHash::equals>;
801
802 // Side-effects: populates the _local_interfaces field
803 void ClassFileParser::parse_interfaces(const ClassFileStream* const stream,
804 const int itfs_len,
805 ConstantPool* const cp,
806 bool* const has_nonstatic_concrete_methods,
807 TRAPS) {
808 assert(stream != nullptr, "invariant");
809 assert(cp != nullptr, "invariant");
810 assert(has_nonstatic_concrete_methods != nullptr, "invariant");
811
812 if (itfs_len == 0) {
813 _local_interfaces = Universe::the_empty_instance_klass_array();
814 } else {
815 assert(itfs_len > 0, "only called for len>0");
816 _local_interfaces = MetadataFactory::new_array<InstanceKlass*>(_loader_data, itfs_len, nullptr, CHECK);
817
818 int index;
819 for (index = 0; index < itfs_len; index++) {
820 const u2 interface_index = stream->get_u2(CHECK);
821 Klass* interf;
822 check_property(
823 valid_klass_reference_at(interface_index),
824 "Interface name has bad constant pool index %u in class file %s",
825 interface_index, CHECK);
826 if (cp->tag_at(interface_index).is_klass()) {
827 interf = cp->resolved_klass_at(interface_index);
828 } else {
829 Symbol* const unresolved_klass = cp->klass_name_at(interface_index);
830
831 // Don't need to check legal name because it's checked when parsing constant pool.
832 // But need to make sure it's not an array type.
833 guarantee_property(unresolved_klass->char_at(0) != JVM_SIGNATURE_ARRAY,
834 "Bad interface name in class file %s", CHECK);
835
836 // Call resolve_super so class circularity is checked
837 interf = SystemDictionary::resolve_super_or_fail(
838 _class_name,
839 unresolved_klass,
840 Handle(THREAD, _loader_data->class_loader()),
841 _protection_domain,
842 false,
843 CHECK);
844 }
845
846 if (!interf->is_interface()) {
847 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
848 err_msg("class %s can not implement %s, because it is not an interface (%s)",
849 _class_name->as_klass_external_name(),
850 interf->external_name(),
851 interf->class_in_module_of_loader()));
852 }
853
854 if (InstanceKlass::cast(interf)->has_nonstatic_concrete_methods()) {
855 *has_nonstatic_concrete_methods = true;
856 }
857 _local_interfaces->at_put(index, InstanceKlass::cast(interf));
858 }
859
860 if (!_need_verify || itfs_len <= 1) {
861 return;
862 }
863
864 // Check if there's any duplicates in interfaces
865 ResourceMark rm(THREAD);
866 // Set containing interface names
867 ResourceHashtable<Symbol*, int>* interface_names = new ResourceHashtable<Symbol*, int>();
868 for (index = 0; index < itfs_len; index++) {
869 const InstanceKlass* const k = _local_interfaces->at(index);
870 Symbol* interface_name = k->name();
871 // If no duplicates, add (name, nullptr) in hashtable interface_names.
872 if (!interface_names->put(interface_name, 0)) {
873 classfile_parse_error("Duplicate interface name \"%s\" in class file %s",
874 interface_name->as_C_string(), THREAD);
875 return;
876 }
877 }
878 }
879 }
880
881 void ClassFileParser::verify_constantvalue(const ConstantPool* const cp,
882 int constantvalue_index,
883 int signature_index,
884 TRAPS) const {
885 // Make sure the constant pool entry is of a type appropriate to this field
886 guarantee_property(
887 (constantvalue_index > 0 &&
888 constantvalue_index < cp->length()),
889 "Bad initial value index %u in ConstantValue attribute in class file %s",
890 constantvalue_index, CHECK);
936
937 class AnnotationCollector : public ResourceObj{
938 public:
939 enum Location { _in_field, _in_method, _in_class };
940 enum ID {
941 _unknown = 0,
942 _method_CallerSensitive,
943 _method_ForceInline,
944 _method_DontInline,
945 _method_ChangesCurrentThread,
946 _method_JvmtiMountTransition,
947 _method_InjectedProfile,
948 _method_LambdaForm_Compiled,
949 _method_Hidden,
950 _method_Scoped,
951 _method_IntrinsicCandidate,
952 _jdk_internal_vm_annotation_Contended,
953 _field_Stable,
954 _jdk_internal_vm_annotation_ReservedStackAccess,
955 _jdk_internal_ValueBased,
956 _java_lang_Deprecated,
957 _java_lang_Deprecated_for_removal,
958 _annotation_LIMIT
959 };
960 const Location _location;
961 int _annotations_present;
962 u2 _contended_group;
963
964 AnnotationCollector(Location location)
965 : _location(location), _annotations_present(0), _contended_group(0)
966 {
967 assert((int)_annotation_LIMIT <= (int)sizeof(_annotations_present) * BitsPerByte, "");
968 }
969 // If this annotation name has an ID, report it (or _none).
970 ID annotation_index(const ClassLoaderData* loader_data, const Symbol* name, bool can_access_vm_annotations);
971 // Set the annotation name:
972 void set_annotation(ID id) {
973 assert((int)id >= 0 && (int)id < (int)_annotation_LIMIT, "oob");
974 _annotations_present |= (int)nth_bit((int)id);
975 }
1361 CHECK);
1362 parsed_annotations->set_field_annotations(a);
1363 a = assemble_annotations(runtime_visible_type_annotations,
1364 runtime_visible_type_annotations_length,
1365 runtime_invisible_type_annotations,
1366 runtime_invisible_type_annotations_length,
1367 CHECK);
1368 parsed_annotations->set_field_type_annotations(a);
1369 return;
1370 }
1371
1372
1373 // Field allocation types. Used for computing field offsets.
1374
1375 enum FieldAllocationType {
1376 STATIC_OOP, // Oops
1377 STATIC_BYTE, // Boolean, Byte, char
1378 STATIC_SHORT, // shorts
1379 STATIC_WORD, // ints
1380 STATIC_DOUBLE, // aligned long or double
1381 NONSTATIC_OOP,
1382 NONSTATIC_BYTE,
1383 NONSTATIC_SHORT,
1384 NONSTATIC_WORD,
1385 NONSTATIC_DOUBLE,
1386 MAX_FIELD_ALLOCATION_TYPE,
1387 BAD_ALLOCATION_TYPE = -1
1388 };
1389
1390 static FieldAllocationType _basic_type_to_atype[2 * (T_CONFLICT + 1)] = {
1391 BAD_ALLOCATION_TYPE, // 0
1392 BAD_ALLOCATION_TYPE, // 1
1393 BAD_ALLOCATION_TYPE, // 2
1394 BAD_ALLOCATION_TYPE, // 3
1395 NONSTATIC_BYTE , // T_BOOLEAN = 4,
1396 NONSTATIC_SHORT, // T_CHAR = 5,
1397 NONSTATIC_WORD, // T_FLOAT = 6,
1398 NONSTATIC_DOUBLE, // T_DOUBLE = 7,
1399 NONSTATIC_BYTE, // T_BYTE = 8,
1400 NONSTATIC_SHORT, // T_SHORT = 9,
1401 NONSTATIC_WORD, // T_INT = 10,
1402 NONSTATIC_DOUBLE, // T_LONG = 11,
1403 NONSTATIC_OOP, // T_OBJECT = 12,
1404 NONSTATIC_OOP, // T_ARRAY = 13,
1405 BAD_ALLOCATION_TYPE, // T_VOID = 14,
1406 BAD_ALLOCATION_TYPE, // T_ADDRESS = 15,
1407 BAD_ALLOCATION_TYPE, // T_NARROWOOP = 16,
1408 BAD_ALLOCATION_TYPE, // T_METADATA = 17,
1409 BAD_ALLOCATION_TYPE, // T_NARROWKLASS = 18,
1410 BAD_ALLOCATION_TYPE, // T_CONFLICT = 19,
1411 BAD_ALLOCATION_TYPE, // 0
1412 BAD_ALLOCATION_TYPE, // 1
1413 BAD_ALLOCATION_TYPE, // 2
1414 BAD_ALLOCATION_TYPE, // 3
1415 STATIC_BYTE , // T_BOOLEAN = 4,
1416 STATIC_SHORT, // T_CHAR = 5,
1417 STATIC_WORD, // T_FLOAT = 6,
1418 STATIC_DOUBLE, // T_DOUBLE = 7,
1419 STATIC_BYTE, // T_BYTE = 8,
1420 STATIC_SHORT, // T_SHORT = 9,
1421 STATIC_WORD, // T_INT = 10,
1422 STATIC_DOUBLE, // T_LONG = 11,
1423 STATIC_OOP, // T_OBJECT = 12,
1424 STATIC_OOP, // T_ARRAY = 13,
1425 BAD_ALLOCATION_TYPE, // T_VOID = 14,
1426 BAD_ALLOCATION_TYPE, // T_ADDRESS = 15,
1427 BAD_ALLOCATION_TYPE, // T_NARROWOOP = 16,
1428 BAD_ALLOCATION_TYPE, // T_METADATA = 17,
1429 BAD_ALLOCATION_TYPE, // T_NARROWKLASS = 18,
1430 BAD_ALLOCATION_TYPE, // T_CONFLICT = 19,
1431 };
1432
1433 static FieldAllocationType basic_type_to_atype(bool is_static, BasicType type) {
1434 assert(type >= T_BOOLEAN && type < T_VOID, "only allowable values");
1435 FieldAllocationType result = _basic_type_to_atype[type + (is_static ? (T_CONFLICT + 1) : 0)];
1436 assert(result != BAD_ALLOCATION_TYPE, "bad type");
1437 return result;
1438 }
1439
1440 class ClassFileParser::FieldAllocationCount : public ResourceObj {
1441 public:
1442 u2 count[MAX_FIELD_ALLOCATION_TYPE];
1443
1444 FieldAllocationCount() {
1445 for (int i = 0; i < MAX_FIELD_ALLOCATION_TYPE; i++) {
1446 count[i] = 0;
1447 }
1448 }
1449
1450 void update(bool is_static, BasicType type) {
1451 FieldAllocationType atype = basic_type_to_atype(is_static, type);
1452 if (atype != BAD_ALLOCATION_TYPE) {
1453 // Make sure there is no overflow with injected fields.
1454 assert(count[atype] < 0xFFFF, "More than 65535 fields");
1455 count[atype]++;
1456 }
1457 }
1458 };
1459
1460 // Side-effects: populates the _fields, _fields_annotations,
1461 // _fields_type_annotations fields
1462 void ClassFileParser::parse_fields(const ClassFileStream* const cfs,
1463 bool is_interface,
1464 FieldAllocationCount* const fac,
1465 ConstantPool* cp,
1466 const int cp_size,
1467 u2* const java_fields_count_ptr,
1468 TRAPS) {
1469
1470 assert(cfs != nullptr, "invariant");
1471 assert(fac != nullptr, "invariant");
1472 assert(cp != nullptr, "invariant");
1473 assert(java_fields_count_ptr != nullptr, "invariant");
1474
1475 assert(nullptr == _fields_annotations, "invariant");
1476 assert(nullptr == _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 // Allocate a temporary resource array to collect field data.
1488 // After parsing all fields, data are stored in a UNSIGNED5 compressed stream.
1489 _temp_field_info = new GrowableArray<FieldInfo>(total_fields);
1490
1491 ResourceMark rm(THREAD);
1492 for (int n = 0; n < length; n++) {
1493 // access_flags, name_index, descriptor_index, attributes_count
1494 cfs->guarantee_more(8, CHECK);
1495
1496 AccessFlags access_flags;
1497 const jint flags = cfs->get_u2_fast() & JVM_RECOGNIZED_FIELD_MODIFIERS;
1498 verify_legal_field_modifiers(flags, is_interface, CHECK);
1499 access_flags.set_flags(flags);
1500 FieldInfo::FieldFlags fieldFlags(0);
1501
1502 const u2 name_index = cfs->get_u2_fast();
1503 check_property(valid_symbol_at(name_index),
1504 "Invalid constant pool index %u for field name in class file %s",
1505 name_index, CHECK);
1506 const Symbol* const name = cp->symbol_at(name_index);
1507 verify_legal_field_name(name, CHECK);
1508
1509 const u2 signature_index = cfs->get_u2_fast();
1510 check_property(valid_symbol_at(signature_index),
1511 "Invalid constant pool index %u for field signature in class file %s",
1512 signature_index, CHECK);
1513 const Symbol* const sig = cp->symbol_at(signature_index);
1514 verify_legal_field_signature(name, sig, CHECK);
1515
1516 u2 constantvalue_index = 0;
1517 bool is_synthetic = false;
1518 u2 generic_signature_index = 0;
1519 const bool is_static = access_flags.is_static();
1520 FieldAnnotationCollector parsed_annotations(_loader_data);
1521
1522 const u2 attributes_count = cfs->get_u2_fast();
1523 if (attributes_count > 0) {
1524 parse_field_attributes(cfs,
1525 attributes_count,
1526 is_static,
1527 signature_index,
1528 &constantvalue_index,
1529 &is_synthetic,
1530 &generic_signature_index,
1531 &parsed_annotations,
1532 CHECK);
1533
1534 if (parsed_annotations.field_annotations() != nullptr) {
1535 if (_fields_annotations == nullptr) {
1536 _fields_annotations = MetadataFactory::new_array<AnnotationArray*>(
1537 _loader_data, length, nullptr,
1538 CHECK);
1539 }
1540 _fields_annotations->at_put(n, parsed_annotations.field_annotations());
1541 parsed_annotations.set_field_annotations(nullptr);
1542 }
1543 if (parsed_annotations.field_type_annotations() != nullptr) {
1544 if (_fields_type_annotations == nullptr) {
1545 _fields_type_annotations =
1546 MetadataFactory::new_array<AnnotationArray*>(_loader_data,
1547 length,
1548 nullptr,
1549 CHECK);
1550 }
1551 _fields_type_annotations->at_put(n, parsed_annotations.field_type_annotations());
1552 parsed_annotations.set_field_type_annotations(nullptr);
1553 }
1554
1555 if (is_synthetic) {
1556 access_flags.set_is_synthetic();
1557 }
1558 if (generic_signature_index != 0) {
1559 fieldFlags.update_generic(true);
1560 }
1561 }
1562
1563 const BasicType type = cp->basic_type_for_signature_at(signature_index);
1564
1565 // Update FieldAllocationCount for this kind of field
1566 fac->update(is_static, type);
1567
1568 FieldInfo fi(access_flags, name_index, signature_index, constantvalue_index, fieldFlags);
1569 fi.set_index(n);
1570 if (fieldFlags.is_generic()) {
1571 fi.set_generic_signature_index(generic_signature_index);
1572 }
1573 parsed_annotations.apply_to(&fi);
1574 if (fi.field_flags().is_contended()) {
1575 _has_contended_fields = true;
1576 }
1577 _temp_field_info->append(fi);
1578 }
1579 assert(_temp_field_info->length() == length, "Must be");
1580
1581 int index = length;
1582 if (num_injected != 0) {
1583 for (int n = 0; n < num_injected; n++) {
1584 // Check for duplicates
1585 if (injected[n].may_be_java) {
1586 const Symbol* const name = injected[n].name();
1594 duplicate = true;
1595 break;
1596 }
1597 }
1598 if (duplicate) {
1599 // These will be removed from the field array at the end
1600 continue;
1601 }
1602 }
1603
1604 // Injected field
1605 FieldInfo::FieldFlags fflags(0);
1606 fflags.update_injected(true);
1607 AccessFlags aflags;
1608 FieldInfo fi(aflags, (u2)(injected[n].name_index), (u2)(injected[n].signature_index), 0, fflags);
1609 fi.set_index(index);
1610 _temp_field_info->append(fi);
1611
1612 // Update FieldAllocationCount for this kind of field
1613 const BasicType type = Signature::basic_type(injected[n].signature());
1614 fac->update(false, type);
1615 index++;
1616 }
1617 }
1618
1619 assert(_temp_field_info->length() == index, "Must be");
1620
1621 if (_need_verify && length > 1) {
1622 // Check duplicated fields
1623 ResourceMark rm(THREAD);
1624 // Set containing name-signature pairs
1625 NameSigHashtable* names_and_sigs = new NameSigHashtable();
1626 for (int i = 0; i < _temp_field_info->length(); i++) {
1627 NameSigHash name_and_sig(_temp_field_info->adr_at(i)->name(_cp),
1628 _temp_field_info->adr_at(i)->signature(_cp));
1629 // If no duplicates, add name/signature in hashtable names_and_sigs.
1630 if(!names_and_sigs->put(name_and_sig, 0)) {
1631 classfile_parse_error("Duplicate field name \"%s\" with signature \"%s\" in class file %s",
1632 name_and_sig._name->as_C_string(), name_and_sig._sig->as_klass_external_name(), THREAD);
1633 return;
1634 }
1635 }
1636 }
1637 }
1638
1973 }
1974 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Contended_signature): {
1975 if (_location != _in_field && _location != _in_class) {
1976 break; // only allow for fields and classes
1977 }
1978 if (!EnableContended || (RestrictContended && !privileged)) {
1979 break; // honor privileges
1980 }
1981 return _jdk_internal_vm_annotation_Contended;
1982 }
1983 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ReservedStackAccess_signature): {
1984 if (_location != _in_method) break; // only allow for methods
1985 if (RestrictReservedStack && !privileged) break; // honor privileges
1986 return _jdk_internal_vm_annotation_ReservedStackAccess;
1987 }
1988 case VM_SYMBOL_ENUM_NAME(jdk_internal_ValueBased_signature): {
1989 if (_location != _in_class) break; // only allow for classes
1990 if (!privileged) break; // only allow in privileged code
1991 return _jdk_internal_ValueBased;
1992 }
1993 case VM_SYMBOL_ENUM_NAME(java_lang_Deprecated): {
1994 return _java_lang_Deprecated;
1995 }
1996 default: {
1997 break;
1998 }
1999 }
2000 return AnnotationCollector::_unknown;
2001 }
2002
2003 void ClassFileParser::FieldAnnotationCollector::apply_to(FieldInfo* f) {
2004 if (is_contended())
2005 // Setting the contended group also sets the contended bit in field flags
2006 f->set_contended_group(contended_group());
2007 if (is_stable())
2008 (f->field_flags_addr())->update_stable(true);
2009 }
2010
2011 ClassFileParser::FieldAnnotationCollector::~FieldAnnotationCollector() {
2012 // If there's an error deallocate metadata for field annotations
2211 runtime_invisible_type_annotations_length > 0) {
2212 a = assemble_annotations(runtime_visible_type_annotations,
2213 runtime_visible_type_annotations_length,
2214 runtime_invisible_type_annotations,
2215 runtime_invisible_type_annotations_length,
2216 CHECK);
2217 cm->set_type_annotations(a);
2218 }
2219 }
2220
2221
2222 // Note: the parse_method below is big and clunky because all parsing of the code and exceptions
2223 // attribute is inlined. This is cumbersome to avoid since we inline most of the parts in the
2224 // Method* to save footprint, so we only know the size of the resulting Method* when the
2225 // entire method attribute is parsed.
2226 //
2227 // The has_localvariable_table parameter is used to pass up the value to InstanceKlass.
2228
2229 Method* ClassFileParser::parse_method(const ClassFileStream* const cfs,
2230 bool is_interface,
2231 const ConstantPool* cp,
2232 bool* const has_localvariable_table,
2233 TRAPS) {
2234 assert(cfs != nullptr, "invariant");
2235 assert(cp != nullptr, "invariant");
2236 assert(has_localvariable_table != nullptr, "invariant");
2237
2238 ResourceMark rm(THREAD);
2239 // Parse fixed parts:
2240 // access_flags, name_index, descriptor_index, attributes_count
2241 cfs->guarantee_more(8, CHECK_NULL);
2242
2243 int flags = cfs->get_u2_fast();
2244 const u2 name_index = cfs->get_u2_fast();
2245 const int cp_size = cp->length();
2246 check_property(
2247 valid_symbol_at(name_index),
2248 "Illegal constant pool index %u for method name in class file %s",
2249 name_index, CHECK_NULL);
2250 const Symbol* const name = cp->symbol_at(name_index);
2252
2253 const u2 signature_index = cfs->get_u2_fast();
2254 guarantee_property(
2255 valid_symbol_at(signature_index),
2256 "Illegal constant pool index %u for method signature in class file %s",
2257 signature_index, CHECK_NULL);
2258 const Symbol* const signature = cp->symbol_at(signature_index);
2259
2260 if (name == vmSymbols::class_initializer_name()) {
2261 // We ignore the other access flags for a valid class initializer.
2262 // (JVM Spec 2nd ed., chapter 4.6)
2263 if (_major_version < 51) { // backward compatibility
2264 flags = JVM_ACC_STATIC;
2265 } else if ((flags & JVM_ACC_STATIC) == JVM_ACC_STATIC) {
2266 flags &= JVM_ACC_STATIC | (_major_version <= JAVA_16_VERSION ? JVM_ACC_STRICT : 0);
2267 } else {
2268 classfile_parse_error("Method <clinit> is not static in class file %s", THREAD);
2269 return nullptr;
2270 }
2271 } else {
2272 verify_legal_method_modifiers(flags, is_interface, name, CHECK_NULL);
2273 }
2274
2275 if (name == vmSymbols::object_initializer_name() && is_interface) {
2276 classfile_parse_error("Interface cannot have a method named <init>, class file %s", THREAD);
2277 return nullptr;
2278 }
2279
2280 int args_size = -1; // only used when _need_verify is true
2281 if (_need_verify) {
2282 verify_legal_name_with_signature(name, signature, CHECK_NULL);
2283 args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) +
2284 verify_legal_method_signature(name, signature, CHECK_NULL);
2285 if (args_size > MAX_ARGS_SIZE) {
2286 classfile_parse_error("Too many arguments in method signature in class file %s", THREAD);
2287 return nullptr;
2288 }
2289 }
2290
2291 AccessFlags access_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS);
2292
2293 // Default values for code and exceptions attribute elements
2294 u2 max_stack = 0;
2295 u2 max_locals = 0;
2296 u4 code_length = 0;
2297 const u1* code_start = 0;
2298 u2 exception_table_length = 0;
2299 const unsafe_u2* exception_table_start = nullptr; // (potentially unaligned) pointer to array of u2 elements
2824 if (m->is_empty_method()) {
2825 _has_empty_finalizer = true;
2826 } else {
2827 _has_finalizer = true;
2828 }
2829 }
2830 if (name == vmSymbols::object_initializer_name() &&
2831 signature == vmSymbols::void_method_signature() &&
2832 m->is_vanilla_constructor()) {
2833 _has_vanilla_constructor = true;
2834 }
2835
2836 NOT_PRODUCT(m->verify());
2837 return m;
2838 }
2839
2840
2841 // Side-effects: populates the _methods field in the parser
2842 void ClassFileParser::parse_methods(const ClassFileStream* const cfs,
2843 bool is_interface,
2844 bool* const has_localvariable_table,
2845 bool* has_final_method,
2846 bool* declares_nonstatic_concrete_methods,
2847 TRAPS) {
2848 assert(cfs != nullptr, "invariant");
2849 assert(has_localvariable_table != nullptr, "invariant");
2850 assert(has_final_method != nullptr, "invariant");
2851 assert(declares_nonstatic_concrete_methods != nullptr, "invariant");
2852
2853 assert(nullptr == _methods, "invariant");
2854
2855 cfs->guarantee_more(2, CHECK); // length
2856 const u2 length = cfs->get_u2_fast();
2857 if (length == 0) {
2858 _methods = Universe::the_empty_method_array();
2859 } else {
2860 _methods = MetadataFactory::new_array<Method*>(_loader_data,
2861 length,
2862 nullptr,
2863 CHECK);
2864
2865 for (int index = 0; index < length; index++) {
2866 Method* method = parse_method(cfs,
2867 is_interface,
2868 _cp,
2869 has_localvariable_table,
2870 CHECK);
2871
2872 if (method->is_final()) {
2873 *has_final_method = true;
2874 }
2875 // declares_nonstatic_concrete_methods: declares concrete instance methods, any access flags
2876 // used for interface initialization, and default method inheritance analysis
2877 if (is_interface && !(*declares_nonstatic_concrete_methods)
2878 && !method->is_abstract() && !method->is_static()) {
2879 *declares_nonstatic_concrete_methods = true;
2880 }
2881 _methods->at_put(index, method);
2882 }
2883
2884 if (_need_verify && length > 1) {
2885 // Check duplicated methods
2886 ResourceMark rm(THREAD);
2887 // Set containing name-signature pairs
3113 valid_klass_reference_at(outer_class_info_index),
3114 "outer_class_info_index %u has bad constant type in class file %s",
3115 outer_class_info_index, CHECK_0);
3116
3117 if (outer_class_info_index != 0) {
3118 const Symbol* const outer_class_name = cp->klass_name_at(outer_class_info_index);
3119 char* bytes = (char*)outer_class_name->bytes();
3120 guarantee_property(bytes[0] != JVM_SIGNATURE_ARRAY,
3121 "Outer class is an array class in class file %s", CHECK_0);
3122 }
3123 // Inner class name
3124 const u2 inner_name_index = cfs->get_u2_fast();
3125 check_property(
3126 inner_name_index == 0 || valid_symbol_at(inner_name_index),
3127 "inner_name_index %u has bad constant type in class file %s",
3128 inner_name_index, CHECK_0);
3129 if (_need_verify) {
3130 guarantee_property(inner_class_info_index != outer_class_info_index,
3131 "Class is both outer and inner class in class file %s", CHECK_0);
3132 }
3133 // Access flags
3134 jint flags;
3135 // JVM_ACC_MODULE is defined in JDK-9 and later.
3136 if (_major_version >= JAVA_9_VERSION) {
3137 flags = cfs->get_u2_fast() & (RECOGNIZED_INNER_CLASS_MODIFIERS | JVM_ACC_MODULE);
3138 } else {
3139 flags = cfs->get_u2_fast() & RECOGNIZED_INNER_CLASS_MODIFIERS;
3140 }
3141 if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
3142 // Set abstract bit for old class files for backward compatibility
3143 flags |= JVM_ACC_ABSTRACT;
3144 }
3145 verify_legal_class_modifiers(flags, CHECK_0);
3146 AccessFlags inner_access_flags(flags);
3147
3148 inner_classes->at_put(index++, inner_class_info_index);
3149 inner_classes->at_put(index++, outer_class_info_index);
3150 inner_classes->at_put(index++, inner_name_index);
3151 inner_classes->at_put(index++, inner_access_flags.as_short());
3152 }
3153
3154 // Check for circular and duplicate entries.
3155 bool has_circularity = false;
3156 if (_need_verify) {
3157 has_circularity = check_inner_classes_circularity(cp, length * 4, CHECK_0);
3158 if (has_circularity) {
3159 // If circularity check failed then ignore InnerClasses attribute.
3160 MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
3161 index = 0;
3162 if (parsed_enclosingmethod_attribute) {
3163 inner_classes = MetadataFactory::new_array<u2>(_loader_data, 2, CHECK_0);
3164 _inner_classes = inner_classes;
3165 } else {
3229 if (length > 0) {
3230 int index = 0;
3231 cfs->guarantee_more(2 * length, CHECK_0);
3232 for (int n = 0; n < length; n++) {
3233 const u2 class_info_index = cfs->get_u2_fast();
3234 check_property(
3235 valid_klass_reference_at(class_info_index),
3236 "Permitted subclass class_info_index %u has bad constant type in class file %s",
3237 class_info_index, CHECK_0);
3238 permitted_subclasses->at_put(index++, class_info_index);
3239 }
3240 assert(index == size, "wrong size");
3241 }
3242
3243 // Restore buffer's current position.
3244 cfs->set_current(current_mark);
3245
3246 return length;
3247 }
3248
3249 // Record {
3250 // u2 attribute_name_index;
3251 // u4 attribute_length;
3252 // u2 components_count;
3253 // component_info components[components_count];
3254 // }
3255 // component_info {
3256 // u2 name_index;
3257 // u2 descriptor_index
3258 // u2 attributes_count;
3259 // attribute_info_attributes[attributes_count];
3260 // }
3261 u4 ClassFileParser::parse_classfile_record_attribute(const ClassFileStream* const cfs,
3262 const ConstantPool* cp,
3263 const u1* const record_attribute_start,
3264 TRAPS) {
3265 const u1* const current_mark = cfs->current();
3266 int components_count = 0;
3267 unsigned int calculate_attr_size = 0;
3268 if (record_attribute_start != nullptr) {
3513 }
3514 guarantee_property(current_start + attribute_byte_length == cfs->current(),
3515 "Bad length on BootstrapMethods in class file %s",
3516 CHECK);
3517 }
3518
3519 void ClassFileParser::parse_classfile_attributes(const ClassFileStream* const cfs,
3520 ConstantPool* cp,
3521 ClassFileParser::ClassAnnotationCollector* parsed_annotations,
3522 TRAPS) {
3523 assert(cfs != nullptr, "invariant");
3524 assert(cp != nullptr, "invariant");
3525 assert(parsed_annotations != nullptr, "invariant");
3526
3527 // Set inner classes attribute to default sentinel
3528 _inner_classes = Universe::the_empty_short_array();
3529 // Set nest members attribute to default sentinel
3530 _nest_members = Universe::the_empty_short_array();
3531 // Set _permitted_subclasses attribute to default sentinel
3532 _permitted_subclasses = Universe::the_empty_short_array();
3533 cfs->guarantee_more(2, CHECK); // attributes_count
3534 u2 attributes_count = cfs->get_u2_fast();
3535 bool parsed_sourcefile_attribute = false;
3536 bool parsed_innerclasses_attribute = false;
3537 bool parsed_nest_members_attribute = false;
3538 bool parsed_permitted_subclasses_attribute = false;
3539 bool parsed_nest_host_attribute = false;
3540 bool parsed_record_attribute = false;
3541 bool parsed_enclosingmethod_attribute = false;
3542 bool parsed_bootstrap_methods_attribute = false;
3543 const u1* runtime_visible_annotations = nullptr;
3544 int runtime_visible_annotations_length = 0;
3545 const u1* runtime_invisible_annotations = nullptr;
3546 int runtime_invisible_annotations_length = 0;
3547 const u1* runtime_visible_type_annotations = nullptr;
3548 int runtime_visible_type_annotations_length = 0;
3549 const u1* runtime_invisible_type_annotations = nullptr;
3550 int runtime_invisible_type_annotations_length = 0;
3551 bool runtime_invisible_type_annotations_exists = false;
3552 bool runtime_invisible_annotations_exists = false;
3553 bool parsed_source_debug_ext_annotations_exist = false;
3554 const u1* inner_classes_attribute_start = nullptr;
3555 u4 inner_classes_attribute_length = 0;
3556 u2 enclosing_method_class_index = 0;
3557 u2 enclosing_method_method_index = 0;
3558 const u1* nest_members_attribute_start = nullptr;
3559 u4 nest_members_attribute_length = 0;
3560 const u1* record_attribute_start = nullptr;
3561 u4 record_attribute_length = 0;
3562 const u1* permitted_subclasses_attribute_start = nullptr;
3563 u4 permitted_subclasses_attribute_length = 0;
3564
3565 // Iterate over attributes
3566 while (attributes_count--) {
3567 cfs->guarantee_more(6, CHECK); // attribute_name_index, attribute_length
3568 const u2 attribute_name_index = cfs->get_u2_fast();
3569 const u4 attribute_length = cfs->get_u4_fast();
3570 check_property(
3571 valid_symbol_at(attribute_name_index),
3572 "Attribute name has bad constant pool index %u in class file %s",
3573 attribute_name_index, CHECK);
3574 const Symbol* const tag = cp->symbol_at(attribute_name_index);
3575 if (tag == vmSymbols::tag_source_file()) {
3576 // Check for SourceFile tag
3577 if (_need_verify) {
3578 guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
3579 }
3580 if (parsed_sourcefile_attribute) {
3581 classfile_parse_error("Multiple SourceFile attributes in class file %s", THREAD);
3582 return;
3583 } else {
3770 return;
3771 }
3772 parsed_record_attribute = true;
3773 record_attribute_start = cfs->current();
3774 record_attribute_length = attribute_length;
3775 } else if (_major_version >= JAVA_17_VERSION) {
3776 if (tag == vmSymbols::tag_permitted_subclasses()) {
3777 if (parsed_permitted_subclasses_attribute) {
3778 classfile_parse_error("Multiple PermittedSubclasses attributes in class file %s", CHECK);
3779 return;
3780 }
3781 // Classes marked ACC_FINAL cannot have a PermittedSubclasses attribute.
3782 if (_access_flags.is_final()) {
3783 classfile_parse_error("PermittedSubclasses attribute in final class file %s", CHECK);
3784 return;
3785 }
3786 parsed_permitted_subclasses_attribute = true;
3787 permitted_subclasses_attribute_start = cfs->current();
3788 permitted_subclasses_attribute_length = attribute_length;
3789 }
3790 }
3791 // Skip attribute_length for any attribute where major_verson >= JAVA_17_VERSION
3792 cfs->skip_u1(attribute_length, CHECK);
3793 } else {
3794 // Unknown attribute
3795 cfs->skip_u1(attribute_length, CHECK);
3796 }
3797 } else {
3798 // Unknown attribute
3799 cfs->skip_u1(attribute_length, CHECK);
3800 }
3801 } else {
3802 // Unknown attribute
3803 cfs->skip_u1(attribute_length, CHECK);
3804 }
3805 }
3806 _class_annotations = assemble_annotations(runtime_visible_annotations,
3807 runtime_visible_annotations_length,
3808 runtime_invisible_annotations,
3809 runtime_invisible_annotations_length,
3850 CHECK);
3851 if (_need_verify) {
3852 guarantee_property(record_attribute_length == calculated_attr_length,
3853 "Record attribute has wrong length in class file %s",
3854 CHECK);
3855 }
3856 }
3857
3858 if (parsed_permitted_subclasses_attribute) {
3859 const u2 num_subclasses = parse_classfile_permitted_subclasses_attribute(
3860 cfs,
3861 permitted_subclasses_attribute_start,
3862 CHECK);
3863 if (_need_verify) {
3864 guarantee_property(
3865 permitted_subclasses_attribute_length == sizeof(num_subclasses) + sizeof(u2) * num_subclasses,
3866 "Wrong PermittedSubclasses attribute length in class file %s", CHECK);
3867 }
3868 }
3869
3870 if (_max_bootstrap_specifier_index >= 0) {
3871 guarantee_property(parsed_bootstrap_methods_attribute,
3872 "Missing BootstrapMethods attribute in class file %s", CHECK);
3873 }
3874 }
3875
3876 void ClassFileParser::apply_parsed_class_attributes(InstanceKlass* k) {
3877 assert(k != nullptr, "invariant");
3878
3879 if (_synthetic_flag)
3880 k->set_is_synthetic();
3881 if (_sourcefile_index != 0) {
3882 k->set_source_file_name_index(_sourcefile_index);
3883 }
3884 if (_generic_signature_index != 0) {
3885 k->set_generic_signature_index(_generic_signature_index);
3886 }
3887 if (_sde_buffer != nullptr) {
3888 k->set_source_debug_extension(_sde_buffer, _sde_length);
3889 }
3915 _class_annotations = nullptr;
3916 _class_type_annotations = nullptr;
3917 _fields_annotations = nullptr;
3918 _fields_type_annotations = nullptr;
3919 }
3920
3921 // Transfer ownership of metadata allocated to the InstanceKlass.
3922 void ClassFileParser::apply_parsed_class_metadata(
3923 InstanceKlass* this_klass,
3924 int java_fields_count) {
3925 assert(this_klass != nullptr, "invariant");
3926
3927 _cp->set_pool_holder(this_klass);
3928 this_klass->set_constants(_cp);
3929 this_klass->set_fieldinfo_stream(_fieldinfo_stream);
3930 this_klass->set_fields_status(_fields_status);
3931 this_klass->set_methods(_methods);
3932 this_klass->set_inner_classes(_inner_classes);
3933 this_klass->set_nest_members(_nest_members);
3934 this_klass->set_nest_host_index(_nest_host);
3935 this_klass->set_annotations(_combined_annotations);
3936 this_klass->set_permitted_subclasses(_permitted_subclasses);
3937 this_klass->set_record_components(_record_components);
3938 // Delay the setting of _local_interfaces and _transitive_interfaces until after
3939 // initialize_supers() in fill_instance_klass(). It is because the _local_interfaces could
3940 // be shared with _transitive_interfaces and _transitive_interfaces may be shared with
3941 // its _super. If an OOM occurs while loading the current klass, its _super field
3942 // may not have been set. When GC tries to free the klass, the _transitive_interfaces
3943 // may be deallocated mistakenly in InstanceKlass::deallocate_interfaces(). Subsequent
3944 // dereferences to the deallocated _transitive_interfaces will result in a crash.
3945
3946 // Clear out these fields so they don't get deallocated by the destructor
3947 clear_class_metadata();
3948 }
3949
3950 AnnotationArray* ClassFileParser::assemble_annotations(const u1* const runtime_visible_annotations,
3951 int runtime_visible_annotations_length,
3952 const u1* const runtime_invisible_annotations,
3953 int runtime_invisible_annotations_length,
3954 TRAPS) {
3955 AnnotationArray* annotations = nullptr;
3956 if (runtime_visible_annotations != nullptr ||
3957 runtime_invisible_annotations != nullptr) {
3966 }
3967 if (runtime_invisible_annotations != nullptr) {
3968 for (int i = 0; i < runtime_invisible_annotations_length; i++) {
3969 int append = runtime_visible_annotations_length+i;
3970 annotations->at_put(append, runtime_invisible_annotations[i]);
3971 }
3972 }
3973 }
3974 return annotations;
3975 }
3976
3977 const InstanceKlass* ClassFileParser::parse_super_class(ConstantPool* const cp,
3978 const int super_class_index,
3979 const bool need_verify,
3980 TRAPS) {
3981 assert(cp != nullptr, "invariant");
3982 const InstanceKlass* super_klass = nullptr;
3983
3984 if (super_class_index == 0) {
3985 check_property(_class_name == vmSymbols::java_lang_Object(),
3986 "Invalid superclass index %u in class file %s",
3987 super_class_index,
3988 CHECK_NULL);
3989 } else {
3990 check_property(valid_klass_reference_at(super_class_index),
3991 "Invalid superclass index %u in class file %s",
3992 super_class_index,
3993 CHECK_NULL);
3994 // The class name should be legal because it is checked when parsing constant pool.
3995 // However, make sure it is not an array type.
3996 bool is_array = false;
3997 if (cp->tag_at(super_class_index).is_klass()) {
3998 super_klass = InstanceKlass::cast(cp->resolved_klass_at(super_class_index));
3999 if (need_verify)
4000 is_array = super_klass->is_array_klass();
4001 } else if (need_verify) {
4002 is_array = (cp->klass_name_at(super_class_index)->char_at(0) == JVM_SIGNATURE_ARRAY);
4003 }
4004 if (need_verify) {
4005 guarantee_property(!is_array,
4006 "Bad superclass name in class file %s", CHECK_NULL);
4007 }
4008 }
4009 return super_klass;
4010 }
4011
4012 OopMapBlocksBuilder::OopMapBlocksBuilder(unsigned int max_blocks) {
4013 _max_nonstatic_oop_maps = max_blocks;
4014 _nonstatic_oop_map_count = 0;
4015 if (max_blocks == 0) {
4016 _nonstatic_oop_maps = nullptr;
4017 } else {
4018 _nonstatic_oop_maps =
4019 NEW_RESOURCE_ARRAY(OopMapBlock, _max_nonstatic_oop_maps);
4020 memset(_nonstatic_oop_maps, 0, sizeof(OopMapBlock) * max_blocks);
4021 }
4022 }
4023
4024 OopMapBlock* OopMapBlocksBuilder::last_oop_map() const {
4182 v = true;
4183 }
4184 }
4185 assert(v == ik->has_vanilla_constructor(), "inconsistent has_vanilla_constructor");
4186 #endif
4187 }
4188
4189 // If it cannot be fast-path allocated, set a bit in the layout helper.
4190 // See documentation of InstanceKlass::can_be_fastpath_allocated().
4191 assert(ik->size_helper() > 0, "layout_helper is initialized");
4192 if ((!RegisterFinalizersAtInit && ik->has_finalizer())
4193 || ik->is_abstract() || ik->is_interface()
4194 || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == nullptr)
4195 || ik->size_helper() >= FastAllocateSizeLimit) {
4196 // Forbid fast-path allocation.
4197 const jint lh = Klass::instance_layout_helper(ik->size_helper(), true);
4198 ik->set_layout_helper(lh);
4199 }
4200 }
4201
4202 // utility methods for appending an array with check for duplicates
4203
4204 static void append_interfaces(GrowableArray<InstanceKlass*>* result,
4205 const Array<InstanceKlass*>* const ifs) {
4206 // iterate over new interfaces
4207 for (int i = 0; i < ifs->length(); i++) {
4208 InstanceKlass* const e = ifs->at(i);
4209 assert(e->is_klass() && e->is_interface(), "just checking");
4210 // add new interface
4211 result->append_if_missing(e);
4212 }
4213 }
4214
4215 static Array<InstanceKlass*>* compute_transitive_interfaces(const InstanceKlass* super,
4216 Array<InstanceKlass*>* local_ifs,
4217 ClassLoaderData* loader_data,
4218 TRAPS) {
4219 assert(local_ifs != nullptr, "invariant");
4220 assert(loader_data != nullptr, "invariant");
4221
4225 // Add superclass transitive interfaces size
4226 if (super != nullptr) {
4227 super_size = super->transitive_interfaces()->length();
4228 max_transitive_size += super_size;
4229 }
4230 // Add local interfaces' super interfaces
4231 const int local_size = local_ifs->length();
4232 for (int i = 0; i < local_size; i++) {
4233 InstanceKlass* const l = local_ifs->at(i);
4234 max_transitive_size += l->transitive_interfaces()->length();
4235 }
4236 // Finally add local interfaces
4237 max_transitive_size += local_size;
4238 // Construct array
4239 if (max_transitive_size == 0) {
4240 // no interfaces, use canonicalized array
4241 return Universe::the_empty_instance_klass_array();
4242 } else if (max_transitive_size == super_size) {
4243 // no new local interfaces added, share superklass' transitive interface array
4244 return super->transitive_interfaces();
4245 } else if (max_transitive_size == local_size) {
4246 // only local interfaces added, share local interface array
4247 return local_ifs;
4248 } else {
4249 ResourceMark rm;
4250 GrowableArray<InstanceKlass*>* const result = new GrowableArray<InstanceKlass*>(max_transitive_size);
4251
4252 // Copy down from superclass
4253 if (super != nullptr) {
4254 append_interfaces(result, super->transitive_interfaces());
4255 }
4256
4257 // Copy down from local interfaces' superinterfaces
4258 for (int i = 0; i < local_size; i++) {
4259 InstanceKlass* const l = local_ifs->at(i);
4260 append_interfaces(result, l->transitive_interfaces());
4261 }
4262 // Finally add local interfaces
4263 append_interfaces(result, local_ifs);
4264
4265 // length will be less than the max_transitive_size if duplicates were removed
4266 const int length = result->length();
4267 assert(length <= max_transitive_size, "just checking");
4268 Array<InstanceKlass*>* const new_result =
4269 MetadataFactory::new_array<InstanceKlass*>(loader_data, length, CHECK_NULL);
4270 for (int i = 0; i < length; i++) {
4271 InstanceKlass* const e = result->at(i);
4272 assert(e != nullptr, "just checking");
4273 new_result->at_put(i, e);
4274 }
4275 return new_result;
4276 }
4277 }
4278
4279 void ClassFileParser::check_super_class_access(const InstanceKlass* this_klass, TRAPS) {
4280 assert(this_klass != nullptr, "invariant");
4281 const Klass* const super = this_klass->super();
4282
4283 if (super != nullptr) {
4284 const InstanceKlass* super_ik = InstanceKlass::cast(super);
4285
4286 if (super->is_final()) {
4287 classfile_icce_error("class %s cannot inherit from final class %s", super_ik, THREAD);
4288 return;
4289 }
4290
4291 if (super_ik->is_sealed() && !super_ik->has_as_permitted_subclass(this_klass)) {
4292 classfile_icce_error("class %s cannot inherit from sealed class %s", super_ik, THREAD);
4293 return;
4294 }
4295
4296 // If the loader is not the boot loader then throw an exception if its
4297 // superclass is in package jdk.internal.reflect and its loader is not a
4298 // special reflection class loader
4299 if (!this_klass->class_loader_data()->is_the_null_class_loader_data()) {
4300 PackageEntry* super_package = super->package();
4301 if (super_package != nullptr &&
4302 super_package->name()->fast_compare(vmSymbols::jdk_internal_reflect()) == 0 &&
4303 !java_lang_ClassLoader::is_reflection_class_loader(this_klass->class_loader())) {
4304 ResourceMark rm(THREAD);
4305 Exceptions::fthrow(
4306 THREAD_AND_LOCATION,
4307 vmSymbols::java_lang_IllegalAccessError(),
4308 "class %s loaded by %s cannot access jdk/internal/reflect superclass %s",
4309 this_klass->external_name(),
4310 this_klass->class_loader_data()->loader_name_and_id(),
4311 super->external_name());
4312 return;
4313 }
4314 }
4315
4461
4462 for (int index = 0; index < num_methods; index++) {
4463 const Method* const m = methods->at(index);
4464 // if m is static and not the init method, throw a verify error
4465 if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) {
4466 ResourceMark rm(THREAD);
4467 Exceptions::fthrow(
4468 THREAD_AND_LOCATION,
4469 vmSymbols::java_lang_VerifyError(),
4470 "Illegal static method %s in interface %s",
4471 m->name()->as_C_string(),
4472 this_klass->external_name()
4473 );
4474 return;
4475 }
4476 }
4477 }
4478
4479 // utility methods for format checking
4480
4481 void ClassFileParser::verify_legal_class_modifiers(jint flags, TRAPS) const {
4482 const bool is_module = (flags & JVM_ACC_MODULE) != 0;
4483 assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");
4484 if (is_module) {
4485 ResourceMark rm(THREAD);
4486 Exceptions::fthrow(
4487 THREAD_AND_LOCATION,
4488 vmSymbols::java_lang_NoClassDefFoundError(),
4489 "%s is not a class because access_flag ACC_MODULE is set",
4490 _class_name->as_C_string());
4491 return;
4492 }
4493
4494 if (!_need_verify) { return; }
4495
4496 const bool is_interface = (flags & JVM_ACC_INTERFACE) != 0;
4497 const bool is_abstract = (flags & JVM_ACC_ABSTRACT) != 0;
4498 const bool is_final = (flags & JVM_ACC_FINAL) != 0;
4499 const bool is_super = (flags & JVM_ACC_SUPER) != 0;
4500 const bool is_enum = (flags & JVM_ACC_ENUM) != 0;
4501 const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4502 const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4503
4504 if ((is_abstract && is_final) ||
4505 (is_interface && !is_abstract) ||
4506 (is_interface && major_gte_1_5 && (is_super || is_enum)) ||
4507 (!is_interface && major_gte_1_5 && is_annotation)) {
4508 ResourceMark rm(THREAD);
4509 Exceptions::fthrow(
4510 THREAD_AND_LOCATION,
4511 vmSymbols::java_lang_ClassFormatError(),
4512 "Illegal class modifiers in class %s: 0x%X",
4513 _class_name->as_C_string(), flags
4514 );
4515 return;
4516 }
4517 }
4518
4519 static bool has_illegal_visibility(jint flags) {
4520 const bool is_public = (flags & JVM_ACC_PUBLIC) != 0;
4521 const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4522 const bool is_private = (flags & JVM_ACC_PRIVATE) != 0;
4523
4524 return ((is_public && is_protected) ||
4525 (is_public && is_private) ||
4526 (is_protected && is_private));
4527 }
4528
4529 // A legal major_version.minor_version must be one of the following:
4530 //
4531 // Major_version >= 45 and major_version < 56, any minor_version.
4532 // Major_version >= 56 and major_version <= JVM_CLASSFILE_MAJOR_VERSION and minor_version = 0.
4533 // Major_version = JVM_CLASSFILE_MAJOR_VERSION and minor_version = 65535 and --enable-preview is present.
4534 //
4535 void ClassFileParser::verify_class_version(u2 major, u2 minor, Symbol* class_name, TRAPS){
4561 THREAD_AND_LOCATION,
4562 vmSymbols::java_lang_UnsupportedClassVersionError(),
4563 "%s (class file version %u.%u) was compiled with preview features that are unsupported. "
4564 "This version of the Java Runtime only recognizes preview features for class file version %u.%u",
4565 class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION, JAVA_PREVIEW_MINOR_VERSION);
4566 return;
4567 }
4568
4569 if (!Arguments::enable_preview()) {
4570 classfile_ucve_error("Preview features are not enabled for %s (class file version %u.%u). Try running with '--enable-preview'",
4571 class_name, major, minor, THREAD);
4572 return;
4573 }
4574
4575 } else { // minor != JAVA_PREVIEW_MINOR_VERSION
4576 classfile_ucve_error("%s (class file version %u.%u) was compiled with an invalid non-zero minor version",
4577 class_name, major, minor, THREAD);
4578 }
4579 }
4580
4581 void ClassFileParser::verify_legal_field_modifiers(jint flags,
4582 bool is_interface,
4583 TRAPS) const {
4584 if (!_need_verify) { return; }
4585
4586 const bool is_public = (flags & JVM_ACC_PUBLIC) != 0;
4587 const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4588 const bool is_private = (flags & JVM_ACC_PRIVATE) != 0;
4589 const bool is_static = (flags & JVM_ACC_STATIC) != 0;
4590 const bool is_final = (flags & JVM_ACC_FINAL) != 0;
4591 const bool is_volatile = (flags & JVM_ACC_VOLATILE) != 0;
4592 const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
4593 const bool is_enum = (flags & JVM_ACC_ENUM) != 0;
4594 const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4595
4596 bool is_illegal = false;
4597
4598 if (is_interface) {
4599 if (!is_public || !is_static || !is_final || is_private ||
4600 is_protected || is_volatile || is_transient ||
4601 (major_gte_1_5 && is_enum)) {
4602 is_illegal = true;
4603 }
4604 } else { // not interface
4605 if (has_illegal_visibility(flags) || (is_final && is_volatile)) {
4606 is_illegal = true;
4607 }
4608 }
4609
4610 if (is_illegal) {
4611 ResourceMark rm(THREAD);
4612 Exceptions::fthrow(
4613 THREAD_AND_LOCATION,
4614 vmSymbols::java_lang_ClassFormatError(),
4615 "Illegal field modifiers in class %s: 0x%X",
4616 _class_name->as_C_string(), flags);
4617 return;
4618 }
4619 }
4620
4621 void ClassFileParser::verify_legal_method_modifiers(jint flags,
4622 bool is_interface,
4623 const Symbol* name,
4624 TRAPS) const {
4625 if (!_need_verify) { return; }
4626
4627 const bool is_public = (flags & JVM_ACC_PUBLIC) != 0;
4628 const bool is_private = (flags & JVM_ACC_PRIVATE) != 0;
4629 const bool is_static = (flags & JVM_ACC_STATIC) != 0;
4630 const bool is_final = (flags & JVM_ACC_FINAL) != 0;
4631 const bool is_native = (flags & JVM_ACC_NATIVE) != 0;
4632 const bool is_abstract = (flags & JVM_ACC_ABSTRACT) != 0;
4633 const bool is_bridge = (flags & JVM_ACC_BRIDGE) != 0;
4634 const bool is_strict = (flags & JVM_ACC_STRICT) != 0;
4635 const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
4636 const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4637 const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4638 const bool major_gte_8 = _major_version >= JAVA_8_VERSION;
4639 const bool major_gte_17 = _major_version >= JAVA_17_VERSION;
4640 const bool is_initializer = (name == vmSymbols::object_initializer_name());
4641
4642 bool is_illegal = false;
4643
4644 if (is_interface) {
4645 if (major_gte_8) {
4646 // Class file version is JAVA_8_VERSION or later Methods of
4647 // interfaces may set any of the flags except ACC_PROTECTED,
4648 // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must
4649 // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.
4650 if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
4651 (is_native || is_protected || is_final || is_synchronized) ||
4652 // If a specific method of a class or interface has its
4653 // ACC_ABSTRACT flag set, it must not have any of its
4654 // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,
4655 // ACC_STRICT, or ACC_SYNCHRONIZED flags set. No need to
4656 // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as
4657 // those flags are illegal irrespective of ACC_ABSTRACT being set or not.
4658 (is_abstract && (is_private || is_static || (!major_gte_17 && is_strict)))) {
4659 is_illegal = true;
4660 }
4661 } else if (major_gte_1_5) {
4662 // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)
4663 if (!is_public || is_private || is_protected || is_static || is_final ||
4664 is_synchronized || is_native || !is_abstract || is_strict) {
4665 is_illegal = true;
4666 }
4667 } else {
4668 // Class file version is pre-JAVA_1_5_VERSION
4669 if (!is_public || is_static || is_final || is_native || !is_abstract) {
4670 is_illegal = true;
4671 }
4672 }
4673 } else { // not interface
4674 if (has_illegal_visibility(flags)) {
4675 is_illegal = true;
4676 } else {
4677 if (is_initializer) {
4678 if (is_static || is_final || is_synchronized || is_native ||
4679 is_abstract || (major_gte_1_5 && is_bridge)) {
4680 is_illegal = true;
4681 }
4682 } else { // not initializer
4683 if (is_abstract) {
4684 if ((is_final || is_native || is_private || is_static ||
4685 (major_gte_1_5 && (is_synchronized || (!major_gte_17 && is_strict))))) {
4686 is_illegal = true;
4687 }
4688 }
4689 }
4690 }
4691 }
4692
4693 if (is_illegal) {
4694 ResourceMark rm(THREAD);
4695 Exceptions::fthrow(
4696 THREAD_AND_LOCATION,
4697 vmSymbols::java_lang_ClassFormatError(),
4698 "Method %s in class %s has illegal modifiers: 0x%X",
4699 name->as_C_string(), _class_name->as_C_string(), flags);
4700 return;
4701 }
4702 }
4703
4704 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer,
4705 int length,
4706 TRAPS) const {
4707 assert(_need_verify, "only called when _need_verify is true");
4708 if (!UTF8::is_legal_utf8(buffer, length, _major_version <= 47)) {
4709 classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", THREAD);
4710 }
4711 }
4712
4713 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
4714 // In class names, '/' separates unqualified names. This is verified in this function also.
4715 // Method names also may not contain the characters '<' or '>', unless <init>
4716 // or <clinit>. Note that method names may not be <init> or <clinit> in this
4717 // method. Because these names have been checked as special cases before
4718 // calling this method in verify_legal_method_name.
4719 //
4736 if (type == ClassFileParser::LegalClass) {
4737 if (p == name || p+1 >= name+length ||
4738 *(p+1) == JVM_SIGNATURE_SLASH) {
4739 return false;
4740 }
4741 } else {
4742 return false; // do not permit '/' unless it's class name
4743 }
4744 break;
4745 case JVM_SIGNATURE_SPECIAL:
4746 case JVM_SIGNATURE_ENDSPECIAL:
4747 // do not permit '<' or '>' in method names
4748 if (type == ClassFileParser::LegalMethod) {
4749 return false;
4750 }
4751 }
4752 }
4753 return true;
4754 }
4755
4756 // Take pointer to a UTF8 byte string (not NUL-terminated).
4757 // Skip over the longest part of the string that could
4758 // be taken as a fieldname. Allow non-trailing '/'s if slash_ok is true.
4759 // Return a pointer to just past the fieldname.
4760 // Return null if no fieldname at all was found, or in the case of slash_ok
4761 // being true, we saw consecutive slashes (meaning we were looking for a
4762 // qualified path but found something that was badly-formed).
4763 static const char* skip_over_field_name(const char* const name,
4764 bool slash_ok,
4765 unsigned int length) {
4766 const char* p;
4767 jboolean last_is_slash = false;
4768 jboolean not_first_ch = false;
4769
4770 for (p = name; p != name + length; not_first_ch = true) {
4771 const char* old_p = p;
4772 jchar ch = *p;
4773 if (ch < 128) {
4774 p++;
4775 // quick check for ascii
4837 // be taken as a field signature. Allow "void" if void_ok.
4838 // Return a pointer to just past the signature.
4839 // Return null if no legal signature is found.
4840 const char* ClassFileParser::skip_over_field_signature(const char* signature,
4841 bool void_ok,
4842 unsigned int length,
4843 TRAPS) const {
4844 unsigned int array_dim = 0;
4845 while (length > 0) {
4846 switch (signature[0]) {
4847 case JVM_SIGNATURE_VOID: if (!void_ok) { return nullptr; }
4848 case JVM_SIGNATURE_BOOLEAN:
4849 case JVM_SIGNATURE_BYTE:
4850 case JVM_SIGNATURE_CHAR:
4851 case JVM_SIGNATURE_SHORT:
4852 case JVM_SIGNATURE_INT:
4853 case JVM_SIGNATURE_FLOAT:
4854 case JVM_SIGNATURE_LONG:
4855 case JVM_SIGNATURE_DOUBLE:
4856 return signature + 1;
4857 case JVM_SIGNATURE_CLASS: {
4858 if (_major_version < JAVA_1_5_VERSION) {
4859 // Skip over the class name if one is there
4860 const char* const p = skip_over_field_name(signature + 1, true, --length);
4861
4862 // The next character better be a semicolon
4863 if (p && (p - signature) > 1 && p[0] == JVM_SIGNATURE_ENDCLASS) {
4864 return p + 1;
4865 }
4866 }
4867 else {
4868 // Skip leading 'L' and ignore first appearance of ';'
4869 signature++;
4870 const char* c = (const char*) memchr(signature, JVM_SIGNATURE_ENDCLASS, length - 1);
4871 // Format check signature
4872 if (c != nullptr) {
4873 int newlen = pointer_delta_as_int(c, (char*) signature);
4874 bool legal = verify_unqualified_name(signature, newlen, LegalClass);
4875 if (!legal) {
4876 classfile_parse_error("Class name is empty or contains illegal character "
4877 "in descriptor in class file %s",
4878 THREAD);
4879 return nullptr;
4880 }
4881 return signature + newlen + 1;
4882 }
4883 }
4884 return nullptr;
4885 }
4886 case JVM_SIGNATURE_ARRAY:
4887 array_dim++;
4888 if (array_dim > 255) {
4904
4905 // Checks if name is a legal class name.
4906 void ClassFileParser::verify_legal_class_name(const Symbol* name, TRAPS) const {
4907 if (!_need_verify || _relax_verify) { return; }
4908
4909 assert(name->refcount() > 0, "symbol must be kept alive");
4910 char* bytes = (char*)name->bytes();
4911 unsigned int length = name->utf8_length();
4912 bool legal = false;
4913
4914 if (length > 0) {
4915 const char* p;
4916 if (bytes[0] == JVM_SIGNATURE_ARRAY) {
4917 p = skip_over_field_signature(bytes, false, length, CHECK);
4918 legal = (p != nullptr) && ((p - bytes) == (int)length);
4919 } else if (_major_version < JAVA_1_5_VERSION) {
4920 if (bytes[0] != JVM_SIGNATURE_SPECIAL) {
4921 p = skip_over_field_name(bytes, true, length);
4922 legal = (p != nullptr) && ((p - bytes) == (int)length);
4923 }
4924 } else {
4925 // 4900761: relax the constraints based on JSR202 spec
4926 // Class names may be drawn from the entire Unicode character set.
4927 // Identifiers between '/' must be unqualified names.
4928 // The utf8 string has been verified when parsing cpool entries.
4929 legal = verify_unqualified_name(bytes, length, LegalClass);
4930 }
4931 }
4932 if (!legal) {
4933 ResourceMark rm(THREAD);
4934 assert(_class_name != nullptr, "invariant");
4935 Exceptions::fthrow(
4936 THREAD_AND_LOCATION,
4937 vmSymbols::java_lang_ClassFormatError(),
4938 "Illegal class name \"%.*s\" in class file %s", length, bytes,
4939 _class_name->as_C_string()
4940 );
4941 return;
4942 }
4943 }
4969 THREAD_AND_LOCATION,
4970 vmSymbols::java_lang_ClassFormatError(),
4971 "Illegal field name \"%.*s\" in class %s", length, bytes,
4972 _class_name->as_C_string()
4973 );
4974 return;
4975 }
4976 }
4977
4978 // Checks if name is a legal method name.
4979 void ClassFileParser::verify_legal_method_name(const Symbol* name, TRAPS) const {
4980 if (!_need_verify || _relax_verify) { return; }
4981
4982 assert(name != nullptr, "method name is null");
4983 char* bytes = (char*)name->bytes();
4984 unsigned int length = name->utf8_length();
4985 bool legal = false;
4986
4987 if (length > 0) {
4988 if (bytes[0] == JVM_SIGNATURE_SPECIAL) {
4989 if (name == vmSymbols::object_initializer_name() || name == vmSymbols::class_initializer_name()) {
4990 legal = true;
4991 }
4992 } else if (_major_version < JAVA_1_5_VERSION) {
4993 const char* p;
4994 p = skip_over_field_name(bytes, false, length);
4995 legal = (p != nullptr) && ((p - bytes) == (int)length);
4996 } else {
4997 // 4881221: relax the constraints based on JSR202 spec
4998 legal = verify_unqualified_name(bytes, length, LegalMethod);
4999 }
5000 }
5001
5002 if (!legal) {
5003 ResourceMark rm(THREAD);
5004 assert(_class_name != nullptr, "invariant");
5005 Exceptions::fthrow(
5006 THREAD_AND_LOCATION,
5007 vmSymbols::java_lang_ClassFormatError(),
5008 "Illegal method name \"%.*s\" in class %s", length, bytes,
5009 _class_name->as_C_string()
5010 );
5011 return;
5012 }
5013 }
5014
5015
5016 // Checks if signature is a legal field signature.
5017 void ClassFileParser::verify_legal_field_signature(const Symbol* name,
5018 const Symbol* signature,
5019 TRAPS) const {
5020 if (!_need_verify) { return; }
5021
5022 const char* const bytes = (const char*)signature->bytes();
5023 const unsigned int length = signature->utf8_length();
5024 const char* const p = skip_over_field_signature(bytes, false, length, CHECK);
5025
5026 if (p == nullptr || (p - bytes) != (int)length) {
5027 throwIllegalSignature("Field", name, signature, CHECK);
5028 }
5029 }
5030
5031 // Check that the signature is compatible with the method name. For example,
5032 // check that <init> has a void signature.
5033 void ClassFileParser::verify_legal_name_with_signature(const Symbol* name,
5034 const Symbol* signature,
5035 TRAPS) const {
5036 if (!_need_verify) {
5037 return;
5038 }
5039
5040 // Class initializers cannot have args for class format version >= 51.
5041 if (name == vmSymbols::class_initializer_name() &&
5042 signature != vmSymbols::void_method_signature() &&
5043 _major_version >= JAVA_7_VERSION) {
5044 throwIllegalSignature("Method", name, signature, THREAD);
5045 return;
5046 }
5047
5048 int sig_length = signature->utf8_length();
5049 if (name->utf8_length() > 0 &&
5050 name->char_at(0) == JVM_SIGNATURE_SPECIAL &&
5051 sig_length > 0 &&
5052 signature->char_at(sig_length - 1) != JVM_SIGNATURE_VOID) {
5053 throwIllegalSignature("Method", name, signature, THREAD);
5054 }
5055 }
5056
5057 // Checks if signature is a legal method signature.
5058 // Returns number of parameters
5059 int ClassFileParser::verify_legal_method_signature(const Symbol* name,
5060 const Symbol* signature,
5061 TRAPS) const {
5062 if (!_need_verify) {
5063 // make sure caller's args_size will be less than 0 even for non-static
5064 // method so it will be recomputed in compute_size_of_parameters().
5065 return -2;
5066 }
5067
5068 unsigned int args_size = 0;
5069 const char* p = (const char*)signature->bytes();
5070 unsigned int length = signature->utf8_length();
5071 const char* nextp;
5072
5209 }
5210 }
5211
5212 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook,
5213 const ClassInstanceInfo& cl_inst_info,
5214 TRAPS) {
5215 if (_klass != nullptr) {
5216 return _klass;
5217 }
5218
5219 InstanceKlass* const ik =
5220 InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
5221
5222 if (is_hidden()) {
5223 mangle_hidden_class_name(ik);
5224 }
5225
5226 fill_instance_klass(ik, changed_by_loadhook, cl_inst_info, CHECK_NULL);
5227
5228 assert(_klass == ik, "invariant");
5229
5230 return ik;
5231 }
5232
5233 void ClassFileParser::fill_instance_klass(InstanceKlass* ik,
5234 bool changed_by_loadhook,
5235 const ClassInstanceInfo& cl_inst_info,
5236 TRAPS) {
5237 assert(ik != nullptr, "invariant");
5238
5239 // Set name and CLD before adding to CLD
5240 ik->set_class_loader_data(_loader_data);
5241 ik->set_name(_class_name);
5242
5243 // Add all classes to our internal class loader list here,
5244 // including classes in the bootstrap (null) class loader.
5245 const bool publicize = !is_internal();
5246
5247 _loader_data->add_class(ik, publicize);
5248
5249 set_klass_to_deallocate(ik);
5250
5251 assert(_field_info != nullptr, "invariant");
5252 assert(ik->static_field_size() == _field_info->_static_field_size, "sanity");
5253 assert(ik->nonstatic_oop_map_count() == _field_info->oop_map_blocks->_nonstatic_oop_map_count,
5254 "sanity");
5255
5256 assert(ik->is_instance_klass(), "sanity");
5257 assert(ik->size_helper() == _field_info->_instance_size, "sanity");
5258
5259 // Fill in information already parsed
5260 ik->set_should_verify_class(_need_verify);
5261
5262 // Not yet: supers are done below to support the new subtype-checking fields
5263 ik->set_nonstatic_field_size(_field_info->_nonstatic_field_size);
5264 ik->set_has_nonstatic_fields(_field_info->_has_nonstatic_fields);
5265 assert(_fac != nullptr, "invariant");
5266 ik->set_static_oop_field_count(_fac->count[STATIC_OOP]);
5267
5268 // this transfers ownership of a lot of arrays from
5269 // the parser onto the InstanceKlass*
5270 apply_parsed_class_metadata(ik, _java_fields_count);
5271
5272 // can only set dynamic nest-host after static nest information is set
5273 if (cl_inst_info.dynamic_nest_host() != nullptr) {
5274 ik->set_nest_host(cl_inst_info.dynamic_nest_host());
5275 }
5276
5277 // note that is not safe to use the fields in the parser from this point on
5278 assert(nullptr == _cp, "invariant");
5279 assert(nullptr == _fieldinfo_stream, "invariant");
5280 assert(nullptr == _fields_status, "invariant");
5281 assert(nullptr == _methods, "invariant");
5282 assert(nullptr == _inner_classes, "invariant");
5283 assert(nullptr == _nest_members, "invariant");
5284 assert(nullptr == _combined_annotations, "invariant");
5285 assert(nullptr == _record_components, "invariant");
5286 assert(nullptr == _permitted_subclasses, "invariant");
5287
5288 if (_has_localvariable_table) {
5289 ik->set_has_localvariable_table(true);
5290 }
5291
5292 if (_has_final_method) {
5293 ik->set_has_final_method();
5294 }
5295
5296 ik->copy_method_ordering(_method_ordering, CHECK);
5297 // The InstanceKlass::_methods_jmethod_ids cache
5298 // is managed on the assumption that the initial cache
5299 // size is equal to the number of methods in the class. If
5300 // that changes, then InstanceKlass::idnum_can_increment()
5301 // has to be changed accordingly.
5302 ik->set_initial_method_idnum(checked_cast<u2>(ik->methods()->length()));
5303
5304 ik->set_this_class_index(_this_class_index);
5305
5306 if (_is_hidden) {
5307 // _this_class_index is a CONSTANT_Class entry that refers to this
5308 // hidden class itself. If this class needs to refer to its own methods
5309 // or fields, it would use a CONSTANT_MethodRef, etc, which would reference
5310 // _this_class_index. However, because this class is hidden (it's
5311 // not stored in SystemDictionary), _this_class_index cannot be resolved
5312 // with ConstantPool::klass_at_impl, which does a SystemDictionary lookup.
5313 // Therefore, we must eagerly resolve _this_class_index now.
5314 ik->constants()->klass_at_put(_this_class_index, ik);
5315 }
5316
5317 ik->set_minor_version(_minor_version);
5318 ik->set_major_version(_major_version);
5319 ik->set_has_nonstatic_concrete_methods(_has_nonstatic_concrete_methods);
5320 ik->set_declares_nonstatic_concrete_methods(_declares_nonstatic_concrete_methods);
5321
5322 if (_is_hidden) {
5323 ik->set_is_hidden();
5324 }
5325
5326 // Set PackageEntry for this_klass
5327 oop cl = ik->class_loader();
5328 Handle clh = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(cl));
5329 ClassLoaderData* cld = ClassLoaderData::class_loader_data_or_null(clh());
5330 ik->set_package(cld, nullptr, CHECK);
5331
5332 const Array<Method*>* const methods = ik->methods();
5333 assert(methods != nullptr, "invariant");
5334 const int methods_len = methods->length();
5335
5336 check_methods_for_intrinsics(ik, methods);
5337
5338 // Fill in field values obtained by parse_classfile_attributes
5339 if (_parsed_annotations->has_any_annotations()) {
5340 _parsed_annotations->apply_to(ik);
5341 }
5408
5409 assert(_all_mirandas != nullptr, "invariant");
5410
5411 // Generate any default methods - default methods are public interface methods
5412 // that have a default implementation. This is new with Java 8.
5413 if (_has_nonstatic_concrete_methods) {
5414 DefaultMethods::generate_default_methods(ik,
5415 _all_mirandas,
5416 CHECK);
5417 }
5418
5419 // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5420 if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5421 !module_entry->has_default_read_edges()) {
5422 if (!module_entry->set_has_default_read_edges()) {
5423 // We won a potential race
5424 JvmtiExport::add_default_read_edges(module_handle, THREAD);
5425 }
5426 }
5427
5428 ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5429
5430 if (!is_internal()) {
5431 ik->print_class_load_logging(_loader_data, module_entry, _stream);
5432
5433 if (ik->minor_version() == JAVA_PREVIEW_MINOR_VERSION &&
5434 ik->major_version() == JVM_CLASSFILE_MAJOR_VERSION &&
5435 log_is_enabled(Info, class, preview)) {
5436 ResourceMark rm;
5437 log_info(class, preview)("Loading class %s that depends on preview features (class file version %d.65535)",
5438 ik->external_name(), JVM_CLASSFILE_MAJOR_VERSION);
5439 }
5440
5441 if (log_is_enabled(Debug, class, resolve)) {
5442 ResourceMark rm;
5443 // print out the superclass.
5444 const char * from = ik->external_name();
5445 if (ik->java_super() != nullptr) {
5446 log_debug(class, resolve)("%s %s (super)",
5447 from,
5499 Symbol* name,
5500 ClassLoaderData* loader_data,
5501 const ClassLoadInfo* cl_info,
5502 Publicity pub_level,
5503 TRAPS) :
5504 _stream(stream),
5505 _class_name(nullptr),
5506 _loader_data(loader_data),
5507 _is_hidden(cl_info->is_hidden()),
5508 _can_access_vm_annotations(cl_info->can_access_vm_annotations()),
5509 _orig_cp_size(0),
5510 _super_klass(),
5511 _cp(nullptr),
5512 _fieldinfo_stream(nullptr),
5513 _fields_status(nullptr),
5514 _methods(nullptr),
5515 _inner_classes(nullptr),
5516 _nest_members(nullptr),
5517 _nest_host(0),
5518 _permitted_subclasses(nullptr),
5519 _record_components(nullptr),
5520 _local_interfaces(nullptr),
5521 _transitive_interfaces(nullptr),
5522 _combined_annotations(nullptr),
5523 _class_annotations(nullptr),
5524 _class_type_annotations(nullptr),
5525 _fields_annotations(nullptr),
5526 _fields_type_annotations(nullptr),
5527 _klass(nullptr),
5528 _klass_to_deallocate(nullptr),
5529 _parsed_annotations(nullptr),
5530 _fac(nullptr),
5531 _field_info(nullptr),
5532 _temp_field_info(nullptr),
5533 _method_ordering(nullptr),
5534 _all_mirandas(nullptr),
5535 _vtable_size(0),
5536 _itable_size(0),
5537 _num_miranda_methods(0),
5538 _protection_domain(cl_info->protection_domain()),
5539 _access_flags(),
5540 _pub_level(pub_level),
5541 _bad_constant_seen(0),
5542 _synthetic_flag(false),
5543 _sde_length(false),
5544 _sde_buffer(nullptr),
5545 _sourcefile_index(0),
5546 _generic_signature_index(0),
5547 _major_version(0),
5548 _minor_version(0),
5549 _this_class_index(0),
5550 _super_class_index(0),
5551 _itfs_len(0),
5552 _java_fields_count(0),
5553 _need_verify(false),
5554 _relax_verify(false),
5555 _has_nonstatic_concrete_methods(false),
5556 _declares_nonstatic_concrete_methods(false),
5557 _has_localvariable_table(false),
5558 _has_final_method(false),
5559 _has_contended_fields(false),
5560 _has_finalizer(false),
5561 _has_empty_finalizer(false),
5562 _has_vanilla_constructor(false),
5563 _max_bootstrap_specifier_index(-1) {
5564
5565 _class_name = name != nullptr ? name : vmSymbols::unknown_class_name();
5566 _class_name->increment_refcount();
5567
5568 assert(_loader_data != nullptr, "invariant");
5569 assert(stream != nullptr, "invariant");
5570 assert(_stream != nullptr, "invariant");
5571 assert(_stream->buffer() == _stream->current(), "invariant");
5572 assert(_class_name != nullptr, "invariant");
5573 assert(0 == _access_flags.as_int(), "invariant");
5574
5575 // Figure out whether we can skip format checking (matching classic VM behavior)
5576 if (CDSConfig::is_dumping_static_archive()) {
5577 // verify == true means it's a 'remote' class (i.e., non-boot class)
5578 // Verification decision is based on BytecodeVerificationRemote flag
5579 // for those classes.
5590
5591 // Check if verification needs to be relaxed for this class file
5592 // Do not restrict it to jdk1.0 or jdk1.1 to maintain backward compatibility (4982376)
5593 _relax_verify = relax_format_check_for(_loader_data);
5594
5595 parse_stream(stream, CHECK);
5596
5597 post_process_parsed_stream(stream, _cp, CHECK);
5598 }
5599
5600 void ClassFileParser::clear_class_metadata() {
5601 // metadata created before the instance klass is created. Must be
5602 // deallocated if classfile parsing returns an error.
5603 _cp = nullptr;
5604 _fieldinfo_stream = nullptr;
5605 _fields_status = nullptr;
5606 _methods = nullptr;
5607 _inner_classes = nullptr;
5608 _nest_members = nullptr;
5609 _permitted_subclasses = nullptr;
5610 _combined_annotations = nullptr;
5611 _class_annotations = _class_type_annotations = nullptr;
5612 _fields_annotations = _fields_type_annotations = nullptr;
5613 _record_components = nullptr;
5614 }
5615
5616 // Destructor to clean up
5617 ClassFileParser::~ClassFileParser() {
5618 _class_name->decrement_refcount();
5619
5620 if (_cp != nullptr) {
5621 MetadataFactory::free_metadata(_loader_data, _cp);
5622 }
5623
5624 if (_fieldinfo_stream != nullptr) {
5625 MetadataFactory::free_array<u1>(_loader_data, _fieldinfo_stream);
5626 }
5627
5628 if (_fields_status != nullptr) {
5629 MetadataFactory::free_array<FieldStatus>(_loader_data, _fields_status);
5630 }
5631
5632 if (_methods != nullptr) {
5633 // Free methods
5634 InstanceKlass::deallocate_methods(_loader_data, _methods);
5635 }
5636
5637 // beware of the Universe::empty_blah_array!!
5638 if (_inner_classes != nullptr && _inner_classes != Universe::the_empty_short_array()) {
5639 MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
5640 }
5641
5642 if (_nest_members != nullptr && _nest_members != Universe::the_empty_short_array()) {
5643 MetadataFactory::free_array<u2>(_loader_data, _nest_members);
5644 }
5645
5646 if (_record_components != nullptr) {
5647 InstanceKlass::deallocate_record_components(_loader_data, _record_components);
5648 }
5649
5650 if (_permitted_subclasses != nullptr && _permitted_subclasses != Universe::the_empty_short_array()) {
5651 MetadataFactory::free_array<u2>(_loader_data, _permitted_subclasses);
5652 }
5653
5654 // Free interfaces
5655 InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
5656 _local_interfaces, _transitive_interfaces);
5657
5658 if (_combined_annotations != nullptr) {
5659 // After all annotations arrays have been created, they are installed into the
5660 // Annotations object that will be assigned to the InstanceKlass being created.
5661
5662 // Deallocate the Annotations object and the installed annotations arrays.
5663 _combined_annotations->deallocate_contents(_loader_data);
5664
5665 // If the _combined_annotations pointer is non-null,
5666 // then the other annotations fields should have been cleared.
5667 assert(_class_annotations == nullptr, "Should have been cleared");
5668 assert(_class_type_annotations == nullptr, "Should have been cleared");
5669 assert(_fields_annotations == nullptr, "Should have been cleared");
5670 assert(_fields_type_annotations == nullptr, "Should have been cleared");
5671 } else {
5672 // If the annotations arrays were not installed into the Annotations object,
5673 // then they have to be deallocated explicitly.
5718 cp_size, CHECK);
5719
5720 _orig_cp_size = cp_size;
5721 if (is_hidden()) { // Add a slot for hidden class name.
5722 cp_size++;
5723 }
5724
5725 _cp = ConstantPool::allocate(_loader_data,
5726 cp_size,
5727 CHECK);
5728
5729 ConstantPool* const cp = _cp;
5730
5731 parse_constant_pool(stream, cp, _orig_cp_size, CHECK);
5732
5733 assert(cp_size == (u2)cp->length(), "invariant");
5734
5735 // ACCESS FLAGS
5736 stream->guarantee_more(8, CHECK); // flags, this_class, super_class, infs_len
5737
5738 // Access flags
5739 jint flags;
5740 // JVM_ACC_MODULE is defined in JDK-9 and later.
5741 if (_major_version >= JAVA_9_VERSION) {
5742 flags = stream->get_u2_fast() & (JVM_RECOGNIZED_CLASS_MODIFIERS | JVM_ACC_MODULE);
5743 } else {
5744 flags = stream->get_u2_fast() & JVM_RECOGNIZED_CLASS_MODIFIERS;
5745 }
5746
5747 if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
5748 // Set abstract bit for old class files for backward compatibility
5749 flags |= JVM_ACC_ABSTRACT;
5750 }
5751
5752 verify_legal_class_modifiers(flags, CHECK);
5753
5754 short bad_constant = class_bad_constant_seen();
5755 if (bad_constant != 0) {
5756 // Do not throw CFE until after the access_flags are checked because if
5757 // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
5758 classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, THREAD);
5759 return;
5760 }
5761
5762 _access_flags.set_flags(flags);
5763
5764 // This class and superclass
5765 _this_class_index = stream->get_u2_fast();
5766 check_property(
5767 valid_cp_range(_this_class_index, cp_size) &&
5768 cp->tag_at(_this_class_index).is_unresolved_klass(),
5769 "Invalid this class index %u in constant pool in class file %s",
5770 _this_class_index, CHECK);
5771
5772 Symbol* const class_name_in_cp = cp->klass_name_at(_this_class_index);
5773 assert(class_name_in_cp != nullptr, "class_name can't be null");
5774
5775 // Don't need to check whether this class name is legal or not.
5776 // It has been checked when constant pool is parsed.
5777 // However, make sure it is not an array type.
5778 if (_need_verify) {
5779 guarantee_property(class_name_in_cp->char_at(0) != JVM_SIGNATURE_ARRAY,
5780 "Bad class name in class file %s",
5781 CHECK);
5782 }
5783
5784 #ifdef ASSERT
5785 // Basic sanity checks
5786 if (_is_hidden) {
5787 assert(_class_name != vmSymbols::unknown_class_name(), "hidden classes should have a special name");
5788 }
5789 #endif
5790
5791 // Update the _class_name as needed depending on whether this is a named, un-named, or hidden class.
5792
5793 if (_is_hidden) {
5794 assert(_class_name != nullptr, "Unexpected null _class_name");
5834 }
5835 ls.cr();
5836 }
5837 }
5838
5839 // SUPERKLASS
5840 _super_class_index = stream->get_u2_fast();
5841 _super_klass = parse_super_class(cp,
5842 _super_class_index,
5843 _need_verify,
5844 CHECK);
5845
5846 // Interfaces
5847 _itfs_len = stream->get_u2_fast();
5848 parse_interfaces(stream,
5849 _itfs_len,
5850 cp,
5851 &_has_nonstatic_concrete_methods,
5852 CHECK);
5853
5854 assert(_local_interfaces != nullptr, "invariant");
5855
5856 // Fields (offsets are filled in later)
5857 _fac = new FieldAllocationCount();
5858 parse_fields(stream,
5859 _access_flags.is_interface(),
5860 _fac,
5861 cp,
5862 cp_size,
5863 &_java_fields_count,
5864 CHECK);
5865
5866 assert(_temp_field_info != nullptr, "invariant");
5867
5868 // Methods
5869 parse_methods(stream,
5870 _access_flags.is_interface(),
5871 &_has_localvariable_table,
5872 &_has_final_method,
5873 &_declares_nonstatic_concrete_methods,
5874 CHECK);
5875
5876 assert(_methods != nullptr, "invariant");
5877
5878 if (_declares_nonstatic_concrete_methods) {
5879 _has_nonstatic_concrete_methods = true;
5880 }
5881
5882 // Additional attributes/annotations
5883 _parsed_annotations = new ClassAnnotationCollector();
5884 parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK);
5885
5886 assert(_inner_classes != nullptr, "invariant");
5887
5888 // Finalize the Annotations metadata object,
5889 // now that all annotation arrays have been created.
5890 create_combined_annotations(CHECK);
5930 // Update this_class_index's slot in the constant pool with the new Utf8 entry.
5931 // We have to update the resolved_klass_index and the name_index together
5932 // so extract the existing resolved_klass_index first.
5933 CPKlassSlot cp_klass_slot = _cp->klass_slot_at(_this_class_index);
5934 int resolved_klass_index = cp_klass_slot.resolved_klass_index();
5935 _cp->unresolved_klass_at_put(_this_class_index, hidden_index, resolved_klass_index);
5936 assert(_cp->klass_slot_at(_this_class_index).name_index() == _orig_cp_size,
5937 "Bad name_index");
5938 }
5939
5940 void ClassFileParser::post_process_parsed_stream(const ClassFileStream* const stream,
5941 ConstantPool* cp,
5942 TRAPS) {
5943 assert(stream != nullptr, "invariant");
5944 assert(stream->at_eos(), "invariant");
5945 assert(cp != nullptr, "invariant");
5946 assert(_loader_data != nullptr, "invariant");
5947
5948 if (_class_name == vmSymbols::java_lang_Object()) {
5949 check_property(_local_interfaces == Universe::the_empty_instance_klass_array(),
5950 "java.lang.Object cannot implement an interface in class file %s",
5951 CHECK);
5952 }
5953 // We check super class after class file is parsed and format is checked
5954 if (_super_class_index > 0 && nullptr == _super_klass) {
5955 Symbol* const super_class_name = cp->klass_name_at(_super_class_index);
5956 if (_access_flags.is_interface()) {
5957 // Before attempting to resolve the superclass, check for class format
5958 // errors not checked yet.
5959 guarantee_property(super_class_name == vmSymbols::java_lang_Object(),
5960 "Interfaces must have java.lang.Object as superclass in class file %s",
5961 CHECK);
5962 }
5963 Handle loader(THREAD, _loader_data->class_loader());
5964 if (loader.is_null() && super_class_name == vmSymbols::java_lang_Object()) {
5965 _super_klass = vmClasses::Object_klass();
5966 } else {
5967 _super_klass = (const InstanceKlass*)
5968 SystemDictionary::resolve_super_or_fail(_class_name,
5969 super_class_name,
5970 loader,
5971 _protection_domain,
5972 true,
5973 CHECK);
5974 }
5975 }
5976
5977 if (_super_klass != nullptr) {
5978 if (_super_klass->has_nonstatic_concrete_methods()) {
5979 _has_nonstatic_concrete_methods = true;
5980 }
5981
5982 if (_super_klass->is_interface()) {
5983 classfile_icce_error("class %s has interface %s as super class", _super_klass, THREAD);
5984 return;
5985 }
5986 }
5987
5988 // Compute the transitive list of all unique interfaces implemented by this class
5989 _transitive_interfaces =
5990 compute_transitive_interfaces(_super_klass,
5991 _local_interfaces,
5992 _loader_data,
5993 CHECK);
5994
5995 assert(_transitive_interfaces != nullptr, "invariant");
5996
5997 // sort methods
5998 _method_ordering = sort_methods(_methods);
5999
6000 _all_mirandas = new GrowableArray<Method*>(20);
6001
6002 Handle loader(THREAD, _loader_data->class_loader());
6003 klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
6004 &_num_miranda_methods,
6005 _all_mirandas,
6006 _super_klass,
6007 _methods,
6008 _access_flags,
6009 _major_version,
6010 loader,
6011 _class_name,
6012 _local_interfaces);
6013
6014 // Size of Java itable (in words)
6015 _itable_size = _access_flags.is_interface() ? 0 :
6016 klassItable::compute_itable_size(_transitive_interfaces);
6017
6018 assert(_fac != nullptr, "invariant");
6019 assert(_parsed_annotations != nullptr, "invariant");
6020
6021 _field_info = new FieldLayoutInfo();
6022 FieldLayoutBuilder lb(class_name(), super_klass(), _cp, /*_fields*/ _temp_field_info,
6023 _parsed_annotations->is_contended(), _field_info);
6024 lb.build_layout();
6025
6026 int injected_fields_count = _temp_field_info->length() - _java_fields_count;
6027 _fieldinfo_stream =
6028 FieldInfoStream::create_FieldInfoStream(_temp_field_info, _java_fields_count,
6029 injected_fields_count, loader_data(), CHECK);
6030 _fields_status =
6031 MetadataFactory::new_array<FieldStatus>(_loader_data, _temp_field_info->length(),
6032 FieldStatus(0), CHECK);
6033 }
6034
6035 void ClassFileParser::set_klass(InstanceKlass* klass) {
6036
6037 #ifdef ASSERT
6038 if (klass != nullptr) {
6039 assert(nullptr == _klass, "leaking?");
6040 }
6041 #endif
6042
6043 _klass = klass;
6044 }
6045
6046 void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) {
6047
6048 #ifdef ASSERT
6049 if (klass != nullptr) {
6050 assert(nullptr == _klass_to_deallocate, "leaking?");
6051 }
6052 #endif
|
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "oops/inlineKlass.hpp"
26 #include "precompiled.hpp"
27 #include "cds/cdsConfig.hpp"
28 #include "classfile/classFileParser.hpp"
29 #include "classfile/classFileStream.hpp"
30 #include "classfile/classLoader.hpp"
31 #include "classfile/classLoaderData.inline.hpp"
32 #include "classfile/classLoadInfo.hpp"
33 #include "classfile/defaultMethods.hpp"
34 #include "classfile/fieldLayoutBuilder.hpp"
35 #include "classfile/javaClasses.inline.hpp"
36 #include "classfile/moduleEntry.hpp"
37 #include "classfile/packageEntry.hpp"
38 #include "classfile/symbolTable.hpp"
39 #include "classfile/systemDictionary.hpp"
40 #include "classfile/verificationType.hpp"
41 #include "classfile/verifier.hpp"
42 #include "classfile/vmClasses.hpp"
43 #include "classfile/vmSymbols.hpp"
44 #include "jvm.h"
45 #include "logging/log.hpp"
46 #include "logging/logStream.hpp"
47 #include "memory/allocation.hpp"
48 #include "memory/metadataFactory.hpp"
49 #include "memory/oopFactory.hpp"
50 #include "memory/resourceArea.hpp"
51 #include "memory/universe.hpp"
52 #include "oops/annotations.hpp"
53 #include "oops/constantPool.inline.hpp"
54 #include "oops/fieldInfo.hpp"
55 #include "oops/fieldStreams.inline.hpp"
56 #include "oops/inlineKlass.inline.hpp"
57 #include "oops/instanceKlass.inline.hpp"
58 #include "oops/instanceMirrorKlass.hpp"
59 #include "oops/klass.inline.hpp"
60 #include "oops/klassVtable.hpp"
61 #include "oops/metadata.hpp"
62 #include "oops/method.inline.hpp"
63 #include "oops/oop.inline.hpp"
64 #include "oops/recordComponent.hpp"
65 #include "oops/symbol.hpp"
66 #include "prims/jvmtiExport.hpp"
67 #include "prims/jvmtiThreadState.hpp"
68 #include "runtime/arguments.hpp"
69 #include "runtime/fieldDescriptor.inline.hpp"
70 #include "runtime/handles.inline.hpp"
71 #include "runtime/javaCalls.hpp"
72 #include "runtime/os.hpp"
73 #include "runtime/perfData.hpp"
74 #include "runtime/reflection.hpp"
75 #include "runtime/safepointVerifiers.hpp"
76 #include "runtime/signature.hpp"
77 #include "runtime/timer.hpp"
78 #include "services/classLoadingService.hpp"
79 #include "services/threadService.hpp"
80 #include "utilities/align.hpp"
81 #include "utilities/bitMap.inline.hpp"
82 #include "utilities/checkedCast.hpp"
83 #include "utilities/copy.hpp"
84 #include "utilities/formatBuffer.hpp"
85 #include "utilities/exceptions.hpp"
86 #include "utilities/globalDefinitions.hpp"
87 #include "utilities/growableArray.hpp"
88 #include "utilities/macros.hpp"
89 #include "utilities/ostream.hpp"
90 #include "utilities/resourceHash.hpp"
91 #include "utilities/stringUtils.hpp"
92 #include "utilities/utf8.hpp"
93 #if INCLUDE_CDS
94 #include "classfile/systemDictionaryShared.hpp"
95 #endif
96 #if INCLUDE_JFR
97 #include "jfr/support/jfrTraceIdExtension.hpp"
98 #endif
99
100 // We generally try to create the oops directly when parsing, rather than
101 // allocating temporary data structures and copying the bytes twice. A
102 // temporary area is only needed when parsing utf8 entries in the constant
103 // pool and when parsing line number tables.
104
105 // We add assert in debug mode when class format is not checked.
106
107 #define JAVA_CLASSFILE_MAGIC 0xCAFEBABE
108 #define JAVA_MIN_SUPPORTED_VERSION 45
109 #define JAVA_PREVIEW_MINOR_VERSION 65535
110
111 // Used for two backward compatibility reasons:
136 #define JAVA_13_VERSION 57
137
138 #define JAVA_14_VERSION 58
139
140 #define JAVA_15_VERSION 59
141
142 #define JAVA_16_VERSION 60
143
144 #define JAVA_17_VERSION 61
145
146 #define JAVA_18_VERSION 62
147
148 #define JAVA_19_VERSION 63
149
150 #define JAVA_20_VERSION 64
151
152 #define JAVA_21_VERSION 65
153
154 #define JAVA_22_VERSION 66
155
156 #define CONSTANT_CLASS_DESCRIPTORS 67
157
158 #define JAVA_23_VERSION 67
159
160 void ClassFileParser::set_class_bad_constant_seen(short bad_constant) {
161 assert((bad_constant == JVM_CONSTANT_Module ||
162 bad_constant == JVM_CONSTANT_Package) && _major_version >= JAVA_9_VERSION,
163 "Unexpected bad constant pool entry");
164 if (_bad_constant_seen == 0) _bad_constant_seen = bad_constant;
165 }
166
167 void ClassFileParser::parse_constant_pool_entries(const ClassFileStream* const stream,
168 ConstantPool* cp,
169 const int length,
170 TRAPS) {
171 assert(stream != nullptr, "invariant");
172 assert(cp != nullptr, "invariant");
173
174 // Use a local copy of ClassFileStream. It helps the C++ compiler to optimize
175 // this function (_current can be allocated in a register, with scalar
176 // replacement of aggregates). The _current pointer is copied back to
177 // stream() when this function returns. DON'T call another method within
178 // this method that uses stream().
179 const ClassFileStream cfs1 = *stream;
180 const ClassFileStream* const cfs = &cfs1;
181
182 debug_only(const u1* const old_current = stream->current();)
183
184 // Used for batching symbol allocations.
185 const char* names[SymbolTable::symbol_alloc_batch_size];
186 int lengths[SymbolTable::symbol_alloc_batch_size];
187 int indices[SymbolTable::symbol_alloc_batch_size];
188 unsigned int hashValues[SymbolTable::symbol_alloc_batch_size];
189 int names_count = 0;
190
191 // parsing Index 0 is unused
192 for (int index = 1; index < length; index++) {
193 // Each of the following case guarantees one more byte in the stream
194 // for the following tag or the access_flags following constant pool,
195 // so we don't need bounds-check for reading tag.
196 const u1 tag = cfs->get_u1_fast();
197 switch (tag) {
198 case JVM_CONSTANT_Class: {
199 cfs->guarantee_more(3, CHECK); // name_index, tag/access_flags
200 const u2 name_index = cfs->get_u2_fast();
201 cp->klass_index_at_put(index, name_index);
202 break;
203 }
204 case JVM_CONSTANT_Fieldref: {
205 cfs->guarantee_more(5, CHECK); // class_index, name_and_type_index, tag/access_flags
206 const u2 class_index = cfs->get_u2_fast();
207 const u2 name_and_type_index = cfs->get_u2_fast();
208 cp->field_at_put(index, class_index, name_and_type_index);
209 break;
210 }
211 case JVM_CONSTANT_Methodref: {
212 cfs->guarantee_more(5, CHECK); // class_index, name_and_type_index, tag/access_flags
213 const u2 class_index = cfs->get_u2_fast();
214 const u2 name_and_type_index = cfs->get_u2_fast();
215 cp->method_at_put(index, class_index, name_and_type_index);
216 break;
217 }
218 case JVM_CONSTANT_InterfaceMethodref: {
499 check_property(valid_symbol_at(name_ref_index),
500 "Invalid constant pool index %u in class file %s",
501 name_ref_index, CHECK);
502 check_property(valid_symbol_at(signature_ref_index),
503 "Invalid constant pool index %u in class file %s",
504 signature_ref_index, CHECK);
505 break;
506 }
507 case JVM_CONSTANT_Utf8:
508 break;
509 case JVM_CONSTANT_UnresolvedClass: // fall-through
510 case JVM_CONSTANT_UnresolvedClassInError: {
511 ShouldNotReachHere(); // Only JVM_CONSTANT_ClassIndex should be present
512 break;
513 }
514 case JVM_CONSTANT_ClassIndex: {
515 const int class_index = cp->klass_index_at(index);
516 check_property(valid_symbol_at(class_index),
517 "Invalid constant pool index %u in class file %s",
518 class_index, CHECK);
519
520 Symbol* const name = cp->symbol_at(class_index);
521 const unsigned int name_len = name->utf8_length();
522 cp->unresolved_klass_at_put(index, class_index, num_klasses++);
523 break;
524 }
525 case JVM_CONSTANT_StringIndex: {
526 const int string_index = cp->string_index_at(index);
527 check_property(valid_symbol_at(string_index),
528 "Invalid constant pool index %u in class file %s",
529 string_index, CHECK);
530 Symbol* const sym = cp->symbol_at(string_index);
531 cp->unresolved_string_at_put(index, sym);
532 break;
533 }
534 case JVM_CONSTANT_MethodHandle: {
535 const int ref_index = cp->method_handle_index_at(index);
536 check_property(valid_cp_range(ref_index, length),
537 "Invalid constant pool index %u in class file %s",
538 ref_index, CHECK);
539 const constantTag tag = cp->tag_at(ref_index);
540 const int ref_kind = cp->method_handle_ref_kind_at(index);
541
711 }
712 }
713 } else {
714 if (_need_verify) {
715 // Method name and signature are individually verified above, when iterating
716 // NameAndType_info. Need to check here that signature is non-zero length and
717 // the right type.
718 if (!Signature::is_method(signature)) {
719 throwIllegalSignature("Method", name, signature, CHECK);
720 }
721 }
722 // If a class method name begins with '<', it must be "<init>" and have void signature.
723 const unsigned int name_len = name->utf8_length();
724 if (tag == JVM_CONSTANT_Methodref && name_len != 0 &&
725 name->char_at(0) == JVM_SIGNATURE_SPECIAL) {
726 if (name != vmSymbols::object_initializer_name()) {
727 classfile_parse_error(
728 "Bad method name at constant pool index %u in class file %s",
729 name_ref_index, THREAD);
730 return;
731 } else if (!Signature::is_void_method(signature)) { // must have void signature.
732 throwIllegalSignature("Method", name, signature, CHECK);
733 }
734 }
735 }
736 break;
737 }
738 case JVM_CONSTANT_MethodHandle: {
739 const int ref_index = cp->method_handle_index_at(index);
740 const int ref_kind = cp->method_handle_ref_kind_at(index);
741 switch (ref_kind) {
742 case JVM_REF_invokeVirtual:
743 case JVM_REF_invokeStatic:
744 case JVM_REF_invokeSpecial:
745 case JVM_REF_newInvokeSpecial: {
746 const int name_and_type_ref_index =
747 cp->uncached_name_and_type_ref_index_at(ref_index);
748 const int name_ref_index =
749 cp->name_ref_index_at(name_and_type_ref_index);
750 const Symbol* const name = cp->symbol_at(name_ref_index);
751
752 if (name != vmSymbols::object_initializer_name()) { // !<init>
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 { // <init>
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 {
769 classfile_parse_error(
770 "Bad method name at constant pool index %u in class file %s",
771 name_ref_index, THREAD);
772 return;
773 }
774 }
775 break;
776 }
777 // Other ref_kinds are already fully checked in previous pass.
778 } // switch(ref_kind)
779 break;
780 }
781 case JVM_CONSTANT_MethodType: {
782 const Symbol* const no_name = vmSymbols::type_name(); // place holder
783 const Symbol* const signature = cp->method_type_signature_at(index);
784 verify_legal_method_signature(no_name, signature, CHECK);
785 break;
786 }
787 case JVM_CONSTANT_Utf8: {
788 assert(cp->symbol_at(index)->refcount() != 0, "count corrupted");
800
801 NameSigHash(Symbol* name, Symbol* sig) :
802 _name(name),
803 _sig(sig) {}
804
805 static unsigned int hash(NameSigHash const& namesig) {
806 return namesig._name->identity_hash() ^ namesig._sig->identity_hash();
807 }
808
809 static bool equals(NameSigHash const& e0, NameSigHash const& e1) {
810 return (e0._name == e1._name) &&
811 (e0._sig == e1._sig);
812 }
813 };
814
815 using NameSigHashtable = ResourceHashtable<NameSigHash, int,
816 NameSigHash::HASH_ROW_SIZE,
817 AnyObj::RESOURCE_AREA, mtInternal,
818 &NameSigHash::hash, &NameSigHash::equals>;
819
820 static void check_identity_and_value_modifiers(ClassFileParser* current, const InstanceKlass* super_type, TRAPS) {
821 assert(super_type != nullptr,"Method doesn't support null super type");
822 if (super_type->access_flags().is_identity_class() && !current->access_flags().is_identity_class()
823 && super_type->name() != vmSymbols::java_lang_Object()) {
824 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
825 err_msg("Value type %s has an identity type as supertype",
826 current->class_name()->as_klass_external_name()));
827 }
828 }
829
830 void ClassFileParser::parse_interfaces(const ClassFileStream* stream,
831 int itfs_len,
832 ConstantPool* cp,
833 bool* const has_nonstatic_concrete_methods,
834 // FIXME: lots of these functions
835 // declare their parameters as const,
836 // which adds only noise to the code.
837 // Remove the spurious const modifiers.
838 // Many are of the form "const int x"
839 // or "T* const x".
840 TRAPS) {
841 assert(stream != nullptr, "invariant");
842 assert(cp != nullptr, "invariant");
843 assert(has_nonstatic_concrete_methods != nullptr, "invariant");
844
845 if (itfs_len == 0) {
846 _local_interfaces = Universe::the_empty_instance_klass_array();
847
848 } else {
849 assert(itfs_len > 0, "only called for len>0");
850 _local_interface_indexes = new GrowableArray<u2>(itfs_len);
851 int index = 0;
852 for (index = 0; index < itfs_len; index++) {
853 const u2 interface_index = stream->get_u2(CHECK);
854 check_property(
855 valid_klass_reference_at(interface_index),
856 "Interface name has bad constant pool index %u in class file %s",
857 interface_index, CHECK);
858 _local_interface_indexes->at_put_grow(index, interface_index);
859 }
860
861 if (!_need_verify || itfs_len <= 1) {
862 return;
863 }
864
865 // Check if there's any duplicates in interfaces
866 ResourceMark rm(THREAD);
867 // Set containing interface names
868 ResourceHashtable<Symbol*, int>* interface_names = new ResourceHashtable<Symbol*, int>();
869 for (index = 0; index < itfs_len; index++) {
870 Symbol* interface_name = cp->klass_name_at(_local_interface_indexes->at(index));
871 // If no duplicates, add (name, nullptr) in hashtable interface_names.
872 if (!interface_names->put(interface_name, 0)) {
873 classfile_parse_error("Duplicate interface name \"%s\" in class file %s",
874 interface_name->as_C_string(), THREAD);
875 return;
876 }
877 }
878 }
879 }
880
881 void ClassFileParser::verify_constantvalue(const ConstantPool* const cp,
882 int constantvalue_index,
883 int signature_index,
884 TRAPS) const {
885 // Make sure the constant pool entry is of a type appropriate to this field
886 guarantee_property(
887 (constantvalue_index > 0 &&
888 constantvalue_index < cp->length()),
889 "Bad initial value index %u in ConstantValue attribute in class file %s",
890 constantvalue_index, CHECK);
936
937 class AnnotationCollector : public ResourceObj{
938 public:
939 enum Location { _in_field, _in_method, _in_class };
940 enum ID {
941 _unknown = 0,
942 _method_CallerSensitive,
943 _method_ForceInline,
944 _method_DontInline,
945 _method_ChangesCurrentThread,
946 _method_JvmtiMountTransition,
947 _method_InjectedProfile,
948 _method_LambdaForm_Compiled,
949 _method_Hidden,
950 _method_Scoped,
951 _method_IntrinsicCandidate,
952 _jdk_internal_vm_annotation_Contended,
953 _field_Stable,
954 _jdk_internal_vm_annotation_ReservedStackAccess,
955 _jdk_internal_ValueBased,
956 _jdk_internal_ImplicitlyConstructible,
957 _jdk_internal_LooselyConsistentValue,
958 _jdk_internal_NullRestricted,
959 _java_lang_Deprecated,
960 _java_lang_Deprecated_for_removal,
961 _annotation_LIMIT
962 };
963 const Location _location;
964 int _annotations_present;
965 u2 _contended_group;
966
967 AnnotationCollector(Location location)
968 : _location(location), _annotations_present(0), _contended_group(0)
969 {
970 assert((int)_annotation_LIMIT <= (int)sizeof(_annotations_present) * BitsPerByte, "");
971 }
972 // If this annotation name has an ID, report it (or _none).
973 ID annotation_index(const ClassLoaderData* loader_data, const Symbol* name, bool can_access_vm_annotations);
974 // Set the annotation name:
975 void set_annotation(ID id) {
976 assert((int)id >= 0 && (int)id < (int)_annotation_LIMIT, "oob");
977 _annotations_present |= (int)nth_bit((int)id);
978 }
1364 CHECK);
1365 parsed_annotations->set_field_annotations(a);
1366 a = assemble_annotations(runtime_visible_type_annotations,
1367 runtime_visible_type_annotations_length,
1368 runtime_invisible_type_annotations,
1369 runtime_invisible_type_annotations_length,
1370 CHECK);
1371 parsed_annotations->set_field_type_annotations(a);
1372 return;
1373 }
1374
1375
1376 // Field allocation types. Used for computing field offsets.
1377
1378 enum FieldAllocationType {
1379 STATIC_OOP, // Oops
1380 STATIC_BYTE, // Boolean, Byte, char
1381 STATIC_SHORT, // shorts
1382 STATIC_WORD, // ints
1383 STATIC_DOUBLE, // aligned long or double
1384 STATIC_INLINE, // inline type field
1385 NONSTATIC_OOP,
1386 NONSTATIC_BYTE,
1387 NONSTATIC_SHORT,
1388 NONSTATIC_WORD,
1389 NONSTATIC_DOUBLE,
1390 NONSTATIC_INLINE,
1391 MAX_FIELD_ALLOCATION_TYPE,
1392 BAD_ALLOCATION_TYPE = -1
1393 };
1394
1395 static FieldAllocationType _basic_type_to_atype[2 * (T_CONFLICT + 1)] = {
1396 BAD_ALLOCATION_TYPE, // 0
1397 BAD_ALLOCATION_TYPE, // 1
1398 BAD_ALLOCATION_TYPE, // 2
1399 BAD_ALLOCATION_TYPE, // 3
1400 NONSTATIC_BYTE , // T_BOOLEAN = 4,
1401 NONSTATIC_SHORT, // T_CHAR = 5,
1402 NONSTATIC_WORD, // T_FLOAT = 6,
1403 NONSTATIC_DOUBLE, // T_DOUBLE = 7,
1404 NONSTATIC_BYTE, // T_BYTE = 8,
1405 NONSTATIC_SHORT, // T_SHORT = 9,
1406 NONSTATIC_WORD, // T_INT = 10,
1407 NONSTATIC_DOUBLE, // T_LONG = 11,
1408 NONSTATIC_OOP, // T_OBJECT = 12,
1409 NONSTATIC_OOP, // T_ARRAY = 13,
1410 NONSTATIC_OOP, // T_PRIMITIVE_OBJECT = 14,
1411 BAD_ALLOCATION_TYPE, // T_VOID = 15,
1412 BAD_ALLOCATION_TYPE, // T_ADDRESS = 16,
1413 BAD_ALLOCATION_TYPE, // T_NARROWOOP = 17,
1414 BAD_ALLOCATION_TYPE, // T_METADATA = 18,
1415 BAD_ALLOCATION_TYPE, // T_NARROWKLASS = 19,
1416 BAD_ALLOCATION_TYPE, // T_CONFLICT = 20,
1417 BAD_ALLOCATION_TYPE, // 0
1418 BAD_ALLOCATION_TYPE, // 1
1419 BAD_ALLOCATION_TYPE, // 2
1420 BAD_ALLOCATION_TYPE, // 3
1421 STATIC_BYTE , // T_BOOLEAN = 4,
1422 STATIC_SHORT, // T_CHAR = 5,
1423 STATIC_WORD, // T_FLOAT = 6,
1424 STATIC_DOUBLE, // T_DOUBLE = 7,
1425 STATIC_BYTE, // T_BYTE = 8,
1426 STATIC_SHORT, // T_SHORT = 9,
1427 STATIC_WORD, // T_INT = 10,
1428 STATIC_DOUBLE, // T_LONG = 11,
1429 STATIC_OOP, // T_OBJECT = 12,
1430 STATIC_OOP, // T_ARRAY = 13,
1431 STATIC_OOP, // T_PRIMITIVE_OBJECT = 14,
1432 BAD_ALLOCATION_TYPE, // T_VOID = 15,
1433 BAD_ALLOCATION_TYPE, // T_ADDRESS = 16,
1434 BAD_ALLOCATION_TYPE, // T_NARROWOOP = 17,
1435 BAD_ALLOCATION_TYPE, // T_METADATA = 18,
1436 BAD_ALLOCATION_TYPE, // T_NARROWKLASS = 19,
1437 BAD_ALLOCATION_TYPE, // T_CONFLICT = 20
1438 };
1439
1440 static FieldAllocationType basic_type_to_atype(bool is_static, BasicType type, bool is_inline_type) {
1441 assert(type >= T_BOOLEAN && type < T_VOID, "only allowable values");
1442 FieldAllocationType result = _basic_type_to_atype[type + (is_static ? (T_CONFLICT + 1) : 0)];
1443 assert(result != BAD_ALLOCATION_TYPE, "bad type");
1444 if (is_inline_type) {
1445 result = is_static ? STATIC_INLINE : NONSTATIC_INLINE;
1446 }
1447 return result;
1448 }
1449
1450 class ClassFileParser::FieldAllocationCount : public ResourceObj {
1451 public:
1452 u2 count[MAX_FIELD_ALLOCATION_TYPE];
1453
1454 FieldAllocationCount() {
1455 for (int i = 0; i < MAX_FIELD_ALLOCATION_TYPE; i++) {
1456 count[i] = 0;
1457 }
1458 }
1459
1460 void update(bool is_static, BasicType type, bool is_inline_type) {
1461 FieldAllocationType atype = basic_type_to_atype(is_static, type, is_inline_type);
1462 if (atype != BAD_ALLOCATION_TYPE) {
1463 // Make sure there is no overflow with injected fields.
1464 assert(count[atype] < 0xFFFF, "More than 65535 fields");
1465 count[atype]++;
1466 }
1467 }
1468 };
1469
1470 // Side-effects: populates the _fields, _fields_annotations,
1471 // _fields_type_annotations fields
1472 void ClassFileParser::parse_fields(const ClassFileStream* const cfs,
1473 AccessFlags class_access_flags,
1474 FieldAllocationCount* const fac,
1475 ConstantPool* cp,
1476 const int cp_size,
1477 u2* const java_fields_count_ptr,
1478 TRAPS) {
1479
1480 assert(cfs != nullptr, "invariant");
1481 assert(fac != nullptr, "invariant");
1482 assert(cp != nullptr, "invariant");
1483 assert(java_fields_count_ptr != nullptr, "invariant");
1484
1485 assert(nullptr == _fields_annotations, "invariant");
1486 assert(nullptr == _fields_type_annotations, "invariant");
1487
1488 bool is_inline_type = !class_access_flags.is_identity_class() && !class_access_flags.is_abstract();
1489 cfs->guarantee_more(2, CHECK); // length
1490 const u2 length = cfs->get_u2_fast();
1491 *java_fields_count_ptr = length;
1492
1493 int num_injected = 0;
1494 const InjectedField* const injected = JavaClasses::get_injected(_class_name,
1495 &num_injected);
1496
1497 // two more slots are required for inline classes:
1498 // one for the static field with a reference to the pre-allocated default value
1499 // one for the field the JVM injects when detecting an empty inline class
1500 const int total_fields = length + num_injected + (is_inline_type ? 2 : 0);
1501
1502 // Allocate a temporary resource array to collect field data.
1503 // After parsing all fields, data are stored in a UNSIGNED5 compressed stream.
1504 _temp_field_info = new GrowableArray<FieldInfo>(total_fields);
1505
1506 int instance_fields_count = 0;
1507 ResourceMark rm(THREAD);
1508 for (int n = 0; n < length; n++) {
1509 // access_flags, name_index, descriptor_index, attributes_count
1510 cfs->guarantee_more(8, CHECK);
1511
1512 jint recognized_modifiers = JVM_RECOGNIZED_FIELD_MODIFIERS;
1513 if (!supports_inline_types()) {
1514 recognized_modifiers &= ~JVM_ACC_STRICT;
1515 }
1516
1517 const jint flags = cfs->get_u2_fast() & recognized_modifiers;
1518 verify_legal_field_modifiers(flags, class_access_flags, CHECK);
1519 AccessFlags access_flags;
1520 access_flags.set_flags(flags);
1521 FieldInfo::FieldFlags fieldFlags(0);
1522
1523 const u2 name_index = cfs->get_u2_fast();
1524 check_property(valid_symbol_at(name_index),
1525 "Invalid constant pool index %u for field name in class file %s",
1526 name_index, CHECK);
1527 const Symbol* const name = cp->symbol_at(name_index);
1528 verify_legal_field_name(name, CHECK);
1529
1530 const u2 signature_index = cfs->get_u2_fast();
1531 check_property(valid_symbol_at(signature_index),
1532 "Invalid constant pool index %u for field signature in class file %s",
1533 signature_index, CHECK);
1534 const Symbol* const sig = cp->symbol_at(signature_index);
1535 verify_legal_field_signature(name, sig, CHECK);
1536 if (!access_flags.is_static()) instance_fields_count++;
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 bool is_null_restricted = false;
1545
1546 const u2 attributes_count = cfs->get_u2_fast();
1547 if (attributes_count > 0) {
1548 parse_field_attributes(cfs,
1549 attributes_count,
1550 is_static,
1551 signature_index,
1552 &constantvalue_index,
1553 &is_synthetic,
1554 &generic_signature_index,
1555 &parsed_annotations,
1556 CHECK);
1557
1558 if (parsed_annotations.field_annotations() != nullptr) {
1559 if (_fields_annotations == nullptr) {
1560 _fields_annotations = MetadataFactory::new_array<AnnotationArray*>(
1561 _loader_data, length, nullptr,
1562 CHECK);
1563 }
1564 _fields_annotations->at_put(n, parsed_annotations.field_annotations());
1565 if (parsed_annotations.has_annotation(AnnotationCollector::_jdk_internal_NullRestricted)) {
1566 if (!Signature::has_envelope(sig)) {
1567 Exceptions::fthrow(
1568 THREAD_AND_LOCATION,
1569 vmSymbols::java_lang_ClassFormatError(),
1570 "Illegal use of @jdk.internal.vm.annotation.NullRestricted annotation on field %s with signature %s (primitive types can never be null)",
1571 name->as_C_string(), sig->as_C_string());
1572 }
1573 is_null_restricted = true;
1574 }
1575 parsed_annotations.set_field_annotations(nullptr);
1576 }
1577 if (parsed_annotations.field_type_annotations() != nullptr) {
1578 if (_fields_type_annotations == nullptr) {
1579 _fields_type_annotations =
1580 MetadataFactory::new_array<AnnotationArray*>(_loader_data,
1581 length,
1582 nullptr,
1583 CHECK);
1584 }
1585 _fields_type_annotations->at_put(n, parsed_annotations.field_type_annotations());
1586 parsed_annotations.set_field_type_annotations(nullptr);
1587 }
1588
1589 if (is_synthetic) {
1590 access_flags.set_is_synthetic();
1591 }
1592 if (generic_signature_index != 0) {
1593 fieldFlags.update_generic(true);
1594 }
1595 }
1596
1597 const BasicType type = cp->basic_type_for_signature_at(signature_index);
1598
1599 // Update FieldAllocationCount for this kind of field
1600 // This use of T_PRIMITIVE_OBJECT is not valid anymore => FIXME (relate to cleanup (removal?) of FiedAllocationCount
1601 fac->update(is_static, type, type == T_PRIMITIVE_OBJECT);
1602
1603 if (is_null_restricted) fieldFlags.update_null_free_inline_type(true);
1604
1605 FieldInfo fi(access_flags, name_index, signature_index, constantvalue_index, fieldFlags);
1606 fi.set_index(n);
1607 if (fieldFlags.is_generic()) {
1608 fi.set_generic_signature_index(generic_signature_index);
1609 }
1610 parsed_annotations.apply_to(&fi);
1611 if (fi.field_flags().is_contended()) {
1612 _has_contended_fields = true;
1613 }
1614 _temp_field_info->append(fi);
1615 }
1616 assert(_temp_field_info->length() == length, "Must be");
1617
1618 int index = length;
1619 if (num_injected != 0) {
1620 for (int n = 0; n < num_injected; n++) {
1621 // Check for duplicates
1622 if (injected[n].may_be_java) {
1623 const Symbol* const name = injected[n].name();
1631 duplicate = true;
1632 break;
1633 }
1634 }
1635 if (duplicate) {
1636 // These will be removed from the field array at the end
1637 continue;
1638 }
1639 }
1640
1641 // Injected field
1642 FieldInfo::FieldFlags fflags(0);
1643 fflags.update_injected(true);
1644 AccessFlags aflags;
1645 FieldInfo fi(aflags, (u2)(injected[n].name_index), (u2)(injected[n].signature_index), 0, fflags);
1646 fi.set_index(index);
1647 _temp_field_info->append(fi);
1648
1649 // Update FieldAllocationCount for this kind of field
1650 const BasicType type = Signature::basic_type(injected[n].signature());
1651 fac->update(false, type, false);
1652 index++;
1653 }
1654 }
1655
1656 if (is_inline_type) {
1657 // Inject static ".default" field
1658 FieldInfo::FieldFlags fflags(0);
1659 fflags.update_injected(true);
1660 AccessFlags aflags(JVM_ACC_STATIC);
1661 FieldInfo fi(aflags,
1662 (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(default_value_name)),
1663 (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(object_signature)),
1664 0,
1665 fflags);
1666 fi.set_index(index);
1667 _temp_field_info->append(fi);
1668
1669 const BasicType type = Signature::basic_type(vmSymbols::object_signature());
1670 fac->update(true, type, false);
1671 index++;
1672 }
1673
1674 if (is_inline_type && instance_fields_count == 0) {
1675 // Inject ".empty" dummy field
1676 _is_empty_inline_type = true;
1677
1678 FieldInfo::FieldFlags fflags(0);
1679 fflags.update_injected(true);
1680 AccessFlags aflags;
1681 FieldInfo fi(aflags,
1682 (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(empty_marker_name)),
1683 (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(byte_signature)),
1684 0,
1685 fflags);
1686 fi.set_index(index);
1687 _temp_field_info->append(fi);
1688
1689 const BasicType type = Signature::basic_type(vmSymbols::byte_signature());
1690 fac->update(false, type, false);
1691 index++;
1692 }
1693
1694 if (instance_fields_count > 0) {
1695 _has_nonstatic_fields = true;
1696 }
1697
1698 assert(_temp_field_info->length() == index, "Must be");
1699
1700 if (_need_verify && length > 1) {
1701 // Check duplicated fields
1702 ResourceMark rm(THREAD);
1703 // Set containing name-signature pairs
1704 NameSigHashtable* names_and_sigs = new NameSigHashtable();
1705 for (int i = 0; i < _temp_field_info->length(); i++) {
1706 NameSigHash name_and_sig(_temp_field_info->adr_at(i)->name(_cp),
1707 _temp_field_info->adr_at(i)->signature(_cp));
1708 // If no duplicates, add name/signature in hashtable names_and_sigs.
1709 if(!names_and_sigs->put(name_and_sig, 0)) {
1710 classfile_parse_error("Duplicate field name \"%s\" with signature \"%s\" in class file %s",
1711 name_and_sig._name->as_C_string(), name_and_sig._sig->as_klass_external_name(), THREAD);
1712 return;
1713 }
1714 }
1715 }
1716 }
1717
2052 }
2053 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Contended_signature): {
2054 if (_location != _in_field && _location != _in_class) {
2055 break; // only allow for fields and classes
2056 }
2057 if (!EnableContended || (RestrictContended && !privileged)) {
2058 break; // honor privileges
2059 }
2060 return _jdk_internal_vm_annotation_Contended;
2061 }
2062 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ReservedStackAccess_signature): {
2063 if (_location != _in_method) break; // only allow for methods
2064 if (RestrictReservedStack && !privileged) break; // honor privileges
2065 return _jdk_internal_vm_annotation_ReservedStackAccess;
2066 }
2067 case VM_SYMBOL_ENUM_NAME(jdk_internal_ValueBased_signature): {
2068 if (_location != _in_class) break; // only allow for classes
2069 if (!privileged) break; // only allow in privileged code
2070 return _jdk_internal_ValueBased;
2071 }
2072 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ImplicitlyConstructible_signature): {
2073 if (_location != _in_class) break; // only allow for classes
2074 return _jdk_internal_ImplicitlyConstructible;
2075 }
2076 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_LooselyConsistentValue_signature): {
2077 if (_location != _in_class) break; // only allow for classes
2078 return _jdk_internal_LooselyConsistentValue;
2079 }
2080 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_NullRestricted_signature): {
2081 if (_location != _in_field) break; // only allow for fields
2082 return _jdk_internal_NullRestricted;
2083 }
2084 case VM_SYMBOL_ENUM_NAME(java_lang_Deprecated): {
2085 return _java_lang_Deprecated;
2086 }
2087 default: {
2088 break;
2089 }
2090 }
2091 return AnnotationCollector::_unknown;
2092 }
2093
2094 void ClassFileParser::FieldAnnotationCollector::apply_to(FieldInfo* f) {
2095 if (is_contended())
2096 // Setting the contended group also sets the contended bit in field flags
2097 f->set_contended_group(contended_group());
2098 if (is_stable())
2099 (f->field_flags_addr())->update_stable(true);
2100 }
2101
2102 ClassFileParser::FieldAnnotationCollector::~FieldAnnotationCollector() {
2103 // If there's an error deallocate metadata for field annotations
2302 runtime_invisible_type_annotations_length > 0) {
2303 a = assemble_annotations(runtime_visible_type_annotations,
2304 runtime_visible_type_annotations_length,
2305 runtime_invisible_type_annotations,
2306 runtime_invisible_type_annotations_length,
2307 CHECK);
2308 cm->set_type_annotations(a);
2309 }
2310 }
2311
2312
2313 // Note: the parse_method below is big and clunky because all parsing of the code and exceptions
2314 // attribute is inlined. This is cumbersome to avoid since we inline most of the parts in the
2315 // Method* to save footprint, so we only know the size of the resulting Method* when the
2316 // entire method attribute is parsed.
2317 //
2318 // The has_localvariable_table parameter is used to pass up the value to InstanceKlass.
2319
2320 Method* ClassFileParser::parse_method(const ClassFileStream* const cfs,
2321 bool is_interface,
2322 bool is_value_class,
2323 bool is_abstract_class,
2324 const ConstantPool* cp,
2325 bool* const has_localvariable_table,
2326 TRAPS) {
2327 assert(cfs != nullptr, "invariant");
2328 assert(cp != nullptr, "invariant");
2329 assert(has_localvariable_table != nullptr, "invariant");
2330
2331 ResourceMark rm(THREAD);
2332 // Parse fixed parts:
2333 // access_flags, name_index, descriptor_index, attributes_count
2334 cfs->guarantee_more(8, CHECK_NULL);
2335
2336 int flags = cfs->get_u2_fast();
2337 const u2 name_index = cfs->get_u2_fast();
2338 const int cp_size = cp->length();
2339 check_property(
2340 valid_symbol_at(name_index),
2341 "Illegal constant pool index %u for method name in class file %s",
2342 name_index, CHECK_NULL);
2343 const Symbol* const name = cp->symbol_at(name_index);
2345
2346 const u2 signature_index = cfs->get_u2_fast();
2347 guarantee_property(
2348 valid_symbol_at(signature_index),
2349 "Illegal constant pool index %u for method signature in class file %s",
2350 signature_index, CHECK_NULL);
2351 const Symbol* const signature = cp->symbol_at(signature_index);
2352
2353 if (name == vmSymbols::class_initializer_name()) {
2354 // We ignore the other access flags for a valid class initializer.
2355 // (JVM Spec 2nd ed., chapter 4.6)
2356 if (_major_version < 51) { // backward compatibility
2357 flags = JVM_ACC_STATIC;
2358 } else if ((flags & JVM_ACC_STATIC) == JVM_ACC_STATIC) {
2359 flags &= JVM_ACC_STATIC | (_major_version <= JAVA_16_VERSION ? JVM_ACC_STRICT : 0);
2360 } else {
2361 classfile_parse_error("Method <clinit> is not static in class file %s", THREAD);
2362 return nullptr;
2363 }
2364 } else {
2365 verify_legal_method_modifiers(flags, access_flags() , name, CHECK_NULL);
2366 }
2367
2368 if (name == vmSymbols::object_initializer_name() && is_interface) {
2369 classfile_parse_error("Interface cannot have a method named <init>, class file %s", THREAD);
2370 return nullptr;
2371 }
2372
2373 if (EnableValhalla) {
2374 if (((flags & JVM_ACC_SYNCHRONIZED) == JVM_ACC_SYNCHRONIZED)
2375 && ((flags & JVM_ACC_STATIC) == 0 )
2376 && !_access_flags.is_identity_class()) {
2377 classfile_parse_error("Invalid synchronized method in non-identity class %s", THREAD);
2378 return nullptr;
2379 }
2380 }
2381
2382 int args_size = -1; // only used when _need_verify is true
2383 if (_need_verify) {
2384 verify_legal_name_with_signature(name, signature, CHECK_NULL);
2385 args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) +
2386 verify_legal_method_signature(name, signature, CHECK_NULL);
2387 if (args_size > MAX_ARGS_SIZE) {
2388 classfile_parse_error("Too many arguments in method signature in class file %s", THREAD);
2389 return nullptr;
2390 }
2391 }
2392
2393 AccessFlags access_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS);
2394
2395 // Default values for code and exceptions attribute elements
2396 u2 max_stack = 0;
2397 u2 max_locals = 0;
2398 u4 code_length = 0;
2399 const u1* code_start = 0;
2400 u2 exception_table_length = 0;
2401 const unsafe_u2* exception_table_start = nullptr; // (potentially unaligned) pointer to array of u2 elements
2926 if (m->is_empty_method()) {
2927 _has_empty_finalizer = true;
2928 } else {
2929 _has_finalizer = true;
2930 }
2931 }
2932 if (name == vmSymbols::object_initializer_name() &&
2933 signature == vmSymbols::void_method_signature() &&
2934 m->is_vanilla_constructor()) {
2935 _has_vanilla_constructor = true;
2936 }
2937
2938 NOT_PRODUCT(m->verify());
2939 return m;
2940 }
2941
2942
2943 // Side-effects: populates the _methods field in the parser
2944 void ClassFileParser::parse_methods(const ClassFileStream* const cfs,
2945 bool is_interface,
2946 bool is_value_class,
2947 bool is_abstract_type,
2948 bool* const has_localvariable_table,
2949 bool* has_final_method,
2950 bool* declares_nonstatic_concrete_methods,
2951 TRAPS) {
2952 assert(cfs != nullptr, "invariant");
2953 assert(has_localvariable_table != nullptr, "invariant");
2954 assert(has_final_method != nullptr, "invariant");
2955 assert(declares_nonstatic_concrete_methods != nullptr, "invariant");
2956
2957 assert(nullptr == _methods, "invariant");
2958
2959 cfs->guarantee_more(2, CHECK); // length
2960 const u2 length = cfs->get_u2_fast();
2961 if (length == 0) {
2962 _methods = Universe::the_empty_method_array();
2963 } else {
2964 _methods = MetadataFactory::new_array<Method*>(_loader_data,
2965 length,
2966 nullptr,
2967 CHECK);
2968
2969 for (int index = 0; index < length; index++) {
2970 Method* method = parse_method(cfs,
2971 is_interface,
2972 is_value_class,
2973 is_abstract_type,
2974 _cp,
2975 has_localvariable_table,
2976 CHECK);
2977
2978 if (method->is_final()) {
2979 *has_final_method = true;
2980 }
2981 // declares_nonstatic_concrete_methods: declares concrete instance methods, any access flags
2982 // used for interface initialization, and default method inheritance analysis
2983 if (is_interface && !(*declares_nonstatic_concrete_methods)
2984 && !method->is_abstract() && !method->is_static()) {
2985 *declares_nonstatic_concrete_methods = true;
2986 }
2987 _methods->at_put(index, method);
2988 }
2989
2990 if (_need_verify && length > 1) {
2991 // Check duplicated methods
2992 ResourceMark rm(THREAD);
2993 // Set containing name-signature pairs
3219 valid_klass_reference_at(outer_class_info_index),
3220 "outer_class_info_index %u has bad constant type in class file %s",
3221 outer_class_info_index, CHECK_0);
3222
3223 if (outer_class_info_index != 0) {
3224 const Symbol* const outer_class_name = cp->klass_name_at(outer_class_info_index);
3225 char* bytes = (char*)outer_class_name->bytes();
3226 guarantee_property(bytes[0] != JVM_SIGNATURE_ARRAY,
3227 "Outer class is an array class in class file %s", CHECK_0);
3228 }
3229 // Inner class name
3230 const u2 inner_name_index = cfs->get_u2_fast();
3231 check_property(
3232 inner_name_index == 0 || valid_symbol_at(inner_name_index),
3233 "inner_name_index %u has bad constant type in class file %s",
3234 inner_name_index, CHECK_0);
3235 if (_need_verify) {
3236 guarantee_property(inner_class_info_index != outer_class_info_index,
3237 "Class is both outer and inner class in class file %s", CHECK_0);
3238 }
3239
3240 jint recognized_modifiers = RECOGNIZED_INNER_CLASS_MODIFIERS;
3241 // JVM_ACC_MODULE is defined in JDK-9 and later.
3242 if (_major_version >= JAVA_9_VERSION) {
3243 recognized_modifiers |= JVM_ACC_MODULE;
3244 }
3245
3246 // Access flags
3247 jint flags = cfs->get_u2_fast() & recognized_modifiers;
3248
3249 if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
3250 // Set abstract bit for old class files for backward compatibility
3251 flags |= JVM_ACC_ABSTRACT;
3252 }
3253
3254 if (!supports_inline_types()) {
3255 const bool is_module = (flags & JVM_ACC_MODULE) != 0;
3256 const bool is_interface = (flags & JVM_ACC_INTERFACE) != 0;
3257 if (!is_module && !is_interface) {
3258 flags |= JVM_ACC_IDENTITY;
3259 }
3260 }
3261
3262 const char* name = inner_name_index == 0 ? "unnamed" : cp->symbol_at(inner_name_index)->as_utf8();
3263 verify_legal_class_modifiers(flags, name, false, CHECK_0);
3264 AccessFlags inner_access_flags(flags);
3265
3266 inner_classes->at_put(index++, inner_class_info_index);
3267 inner_classes->at_put(index++, outer_class_info_index);
3268 inner_classes->at_put(index++, inner_name_index);
3269 inner_classes->at_put(index++, inner_access_flags.as_short());
3270 }
3271
3272 // Check for circular and duplicate entries.
3273 bool has_circularity = false;
3274 if (_need_verify) {
3275 has_circularity = check_inner_classes_circularity(cp, length * 4, CHECK_0);
3276 if (has_circularity) {
3277 // If circularity check failed then ignore InnerClasses attribute.
3278 MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
3279 index = 0;
3280 if (parsed_enclosingmethod_attribute) {
3281 inner_classes = MetadataFactory::new_array<u2>(_loader_data, 2, CHECK_0);
3282 _inner_classes = inner_classes;
3283 } else {
3347 if (length > 0) {
3348 int index = 0;
3349 cfs->guarantee_more(2 * length, CHECK_0);
3350 for (int n = 0; n < length; n++) {
3351 const u2 class_info_index = cfs->get_u2_fast();
3352 check_property(
3353 valid_klass_reference_at(class_info_index),
3354 "Permitted subclass class_info_index %u has bad constant type in class file %s",
3355 class_info_index, CHECK_0);
3356 permitted_subclasses->at_put(index++, class_info_index);
3357 }
3358 assert(index == size, "wrong size");
3359 }
3360
3361 // Restore buffer's current position.
3362 cfs->set_current(current_mark);
3363
3364 return length;
3365 }
3366
3367 u2 ClassFileParser::parse_classfile_loadable_descriptors_attribute(const ClassFileStream* const cfs,
3368 const u1* const loadable_descriptors_attribute_start,
3369 TRAPS) {
3370 const u1* const current_mark = cfs->current();
3371 u2 length = 0;
3372 if (loadable_descriptors_attribute_start != nullptr) {
3373 cfs->set_current(loadable_descriptors_attribute_start);
3374 cfs->guarantee_more(2, CHECK_0); // length
3375 length = cfs->get_u2_fast();
3376 }
3377 const int size = length;
3378 Array<u2>* const loadable_descriptors = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
3379 _loadable_descriptors = loadable_descriptors;
3380 if (length > 0) {
3381 int index = 0;
3382 cfs->guarantee_more(2 * length, CHECK_0);
3383 for (int n = 0; n < length; n++) {
3384 const u2 descriptor_index = cfs->get_u2_fast();
3385 check_property(
3386 valid_symbol_at(descriptor_index),
3387 "LoadableDescriptors descriptor_index %u has bad constant type in class file %s",
3388 descriptor_index, CHECK_0);
3389 Symbol* descriptor = _cp->symbol_at(descriptor_index);
3390 bool valid = legal_field_signature(descriptor, CHECK_0);
3391 if(!valid) {
3392 ResourceMark rm(THREAD);
3393 Exceptions::fthrow(THREAD_AND_LOCATION,
3394 vmSymbols::java_lang_ClassFormatError(),
3395 "Descriptor from LoadableDescriptors attribute at index \"%d\" in class %s has illegal signature \"%s\"",
3396 descriptor_index, _class_name->as_C_string(), descriptor->as_C_string());
3397 return 0;
3398 }
3399 loadable_descriptors->at_put(index++, descriptor_index);
3400 }
3401 assert(index == size, "wrong size");
3402 }
3403
3404 // Restore buffer's current position.
3405 cfs->set_current(current_mark);
3406
3407 return length;
3408 }
3409
3410 // Record {
3411 // u2 attribute_name_index;
3412 // u4 attribute_length;
3413 // u2 components_count;
3414 // component_info components[components_count];
3415 // }
3416 // component_info {
3417 // u2 name_index;
3418 // u2 descriptor_index
3419 // u2 attributes_count;
3420 // attribute_info_attributes[attributes_count];
3421 // }
3422 u4 ClassFileParser::parse_classfile_record_attribute(const ClassFileStream* const cfs,
3423 const ConstantPool* cp,
3424 const u1* const record_attribute_start,
3425 TRAPS) {
3426 const u1* const current_mark = cfs->current();
3427 int components_count = 0;
3428 unsigned int calculate_attr_size = 0;
3429 if (record_attribute_start != nullptr) {
3674 }
3675 guarantee_property(current_start + attribute_byte_length == cfs->current(),
3676 "Bad length on BootstrapMethods in class file %s",
3677 CHECK);
3678 }
3679
3680 void ClassFileParser::parse_classfile_attributes(const ClassFileStream* const cfs,
3681 ConstantPool* cp,
3682 ClassFileParser::ClassAnnotationCollector* parsed_annotations,
3683 TRAPS) {
3684 assert(cfs != nullptr, "invariant");
3685 assert(cp != nullptr, "invariant");
3686 assert(parsed_annotations != nullptr, "invariant");
3687
3688 // Set inner classes attribute to default sentinel
3689 _inner_classes = Universe::the_empty_short_array();
3690 // Set nest members attribute to default sentinel
3691 _nest_members = Universe::the_empty_short_array();
3692 // Set _permitted_subclasses attribute to default sentinel
3693 _permitted_subclasses = Universe::the_empty_short_array();
3694 // Set _loadable_descriptors attribute to default sentinel
3695 _loadable_descriptors = Universe::the_empty_short_array();
3696 cfs->guarantee_more(2, CHECK); // attributes_count
3697 u2 attributes_count = cfs->get_u2_fast();
3698 bool parsed_sourcefile_attribute = false;
3699 bool parsed_innerclasses_attribute = false;
3700 bool parsed_nest_members_attribute = false;
3701 bool parsed_permitted_subclasses_attribute = false;
3702 bool parsed_loadable_descriptors_attribute = false;
3703 bool parsed_nest_host_attribute = false;
3704 bool parsed_record_attribute = false;
3705 bool parsed_enclosingmethod_attribute = false;
3706 bool parsed_bootstrap_methods_attribute = false;
3707 const u1* runtime_visible_annotations = nullptr;
3708 int runtime_visible_annotations_length = 0;
3709 const u1* runtime_invisible_annotations = nullptr;
3710 int runtime_invisible_annotations_length = 0;
3711 const u1* runtime_visible_type_annotations = nullptr;
3712 int runtime_visible_type_annotations_length = 0;
3713 const u1* runtime_invisible_type_annotations = nullptr;
3714 int runtime_invisible_type_annotations_length = 0;
3715 bool runtime_invisible_type_annotations_exists = false;
3716 bool runtime_invisible_annotations_exists = false;
3717 bool parsed_source_debug_ext_annotations_exist = false;
3718 const u1* inner_classes_attribute_start = nullptr;
3719 u4 inner_classes_attribute_length = 0;
3720 u2 enclosing_method_class_index = 0;
3721 u2 enclosing_method_method_index = 0;
3722 const u1* nest_members_attribute_start = nullptr;
3723 u4 nest_members_attribute_length = 0;
3724 const u1* record_attribute_start = nullptr;
3725 u4 record_attribute_length = 0;
3726 const u1* permitted_subclasses_attribute_start = nullptr;
3727 u4 permitted_subclasses_attribute_length = 0;
3728 const u1* loadable_descriptors_attribute_start = nullptr;
3729 u4 loadable_descriptors_attribute_length = 0;
3730
3731 // Iterate over attributes
3732 while (attributes_count--) {
3733 cfs->guarantee_more(6, CHECK); // attribute_name_index, attribute_length
3734 const u2 attribute_name_index = cfs->get_u2_fast();
3735 const u4 attribute_length = cfs->get_u4_fast();
3736 check_property(
3737 valid_symbol_at(attribute_name_index),
3738 "Attribute name has bad constant pool index %u in class file %s",
3739 attribute_name_index, CHECK);
3740 const Symbol* const tag = cp->symbol_at(attribute_name_index);
3741 if (tag == vmSymbols::tag_source_file()) {
3742 // Check for SourceFile tag
3743 if (_need_verify) {
3744 guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
3745 }
3746 if (parsed_sourcefile_attribute) {
3747 classfile_parse_error("Multiple SourceFile attributes in class file %s", THREAD);
3748 return;
3749 } else {
3936 return;
3937 }
3938 parsed_record_attribute = true;
3939 record_attribute_start = cfs->current();
3940 record_attribute_length = attribute_length;
3941 } else if (_major_version >= JAVA_17_VERSION) {
3942 if (tag == vmSymbols::tag_permitted_subclasses()) {
3943 if (parsed_permitted_subclasses_attribute) {
3944 classfile_parse_error("Multiple PermittedSubclasses attributes in class file %s", CHECK);
3945 return;
3946 }
3947 // Classes marked ACC_FINAL cannot have a PermittedSubclasses attribute.
3948 if (_access_flags.is_final()) {
3949 classfile_parse_error("PermittedSubclasses attribute in final class file %s", CHECK);
3950 return;
3951 }
3952 parsed_permitted_subclasses_attribute = true;
3953 permitted_subclasses_attribute_start = cfs->current();
3954 permitted_subclasses_attribute_length = attribute_length;
3955 }
3956 if (EnableValhalla && tag == vmSymbols::tag_loadable_descriptors()) {
3957 if (parsed_loadable_descriptors_attribute) {
3958 classfile_parse_error("Multiple LoadableDescriptors attributes in class file %s", CHECK);
3959 return;
3960 }
3961 parsed_loadable_descriptors_attribute = true;
3962 loadable_descriptors_attribute_start = cfs->current();
3963 loadable_descriptors_attribute_length = attribute_length;
3964 }
3965 }
3966 // Skip attribute_length for any attribute where major_verson >= JAVA_17_VERSION
3967 cfs->skip_u1(attribute_length, CHECK);
3968 } else {
3969 // Unknown attribute
3970 cfs->skip_u1(attribute_length, CHECK);
3971 }
3972 } else {
3973 // Unknown attribute
3974 cfs->skip_u1(attribute_length, CHECK);
3975 }
3976 } else {
3977 // Unknown attribute
3978 cfs->skip_u1(attribute_length, CHECK);
3979 }
3980 }
3981 _class_annotations = assemble_annotations(runtime_visible_annotations,
3982 runtime_visible_annotations_length,
3983 runtime_invisible_annotations,
3984 runtime_invisible_annotations_length,
4025 CHECK);
4026 if (_need_verify) {
4027 guarantee_property(record_attribute_length == calculated_attr_length,
4028 "Record attribute has wrong length in class file %s",
4029 CHECK);
4030 }
4031 }
4032
4033 if (parsed_permitted_subclasses_attribute) {
4034 const u2 num_subclasses = parse_classfile_permitted_subclasses_attribute(
4035 cfs,
4036 permitted_subclasses_attribute_start,
4037 CHECK);
4038 if (_need_verify) {
4039 guarantee_property(
4040 permitted_subclasses_attribute_length == sizeof(num_subclasses) + sizeof(u2) * num_subclasses,
4041 "Wrong PermittedSubclasses attribute length in class file %s", CHECK);
4042 }
4043 }
4044
4045 if (parsed_loadable_descriptors_attribute) {
4046 const u2 num_classes = parse_classfile_loadable_descriptors_attribute(
4047 cfs,
4048 loadable_descriptors_attribute_start,
4049 CHECK);
4050 if (_need_verify) {
4051 guarantee_property(
4052 loadable_descriptors_attribute_length == sizeof(num_classes) + sizeof(u2) * num_classes,
4053 "Wrong LoadableDescriptors attribute length in class file %s", CHECK);
4054 }
4055 }
4056
4057 if (_max_bootstrap_specifier_index >= 0) {
4058 guarantee_property(parsed_bootstrap_methods_attribute,
4059 "Missing BootstrapMethods attribute in class file %s", CHECK);
4060 }
4061 }
4062
4063 void ClassFileParser::apply_parsed_class_attributes(InstanceKlass* k) {
4064 assert(k != nullptr, "invariant");
4065
4066 if (_synthetic_flag)
4067 k->set_is_synthetic();
4068 if (_sourcefile_index != 0) {
4069 k->set_source_file_name_index(_sourcefile_index);
4070 }
4071 if (_generic_signature_index != 0) {
4072 k->set_generic_signature_index(_generic_signature_index);
4073 }
4074 if (_sde_buffer != nullptr) {
4075 k->set_source_debug_extension(_sde_buffer, _sde_length);
4076 }
4102 _class_annotations = nullptr;
4103 _class_type_annotations = nullptr;
4104 _fields_annotations = nullptr;
4105 _fields_type_annotations = nullptr;
4106 }
4107
4108 // Transfer ownership of metadata allocated to the InstanceKlass.
4109 void ClassFileParser::apply_parsed_class_metadata(
4110 InstanceKlass* this_klass,
4111 int java_fields_count) {
4112 assert(this_klass != nullptr, "invariant");
4113
4114 _cp->set_pool_holder(this_klass);
4115 this_klass->set_constants(_cp);
4116 this_klass->set_fieldinfo_stream(_fieldinfo_stream);
4117 this_klass->set_fields_status(_fields_status);
4118 this_klass->set_methods(_methods);
4119 this_klass->set_inner_classes(_inner_classes);
4120 this_klass->set_nest_members(_nest_members);
4121 this_klass->set_nest_host_index(_nest_host);
4122 this_klass->set_loadable_descriptors(_loadable_descriptors);
4123 this_klass->set_annotations(_combined_annotations);
4124 this_klass->set_permitted_subclasses(_permitted_subclasses);
4125 this_klass->set_record_components(_record_components);
4126 this_klass->set_inline_type_field_klasses_array(_inline_type_field_klasses);
4127 this_klass->set_null_marker_offsets_array(_null_marker_offsets);
4128 // Delay the setting of _local_interfaces and _transitive_interfaces until after
4129 // initialize_supers() in fill_instance_klass(). It is because the _local_interfaces could
4130 // be shared with _transitive_interfaces and _transitive_interfaces may be shared with
4131 // its _super. If an OOM occurs while loading the current klass, its _super field
4132 // may not have been set. When GC tries to free the klass, the _transitive_interfaces
4133 // may be deallocated mistakenly in InstanceKlass::deallocate_interfaces(). Subsequent
4134 // dereferences to the deallocated _transitive_interfaces will result in a crash.
4135
4136 // Clear out these fields so they don't get deallocated by the destructor
4137 clear_class_metadata();
4138 }
4139
4140 AnnotationArray* ClassFileParser::assemble_annotations(const u1* const runtime_visible_annotations,
4141 int runtime_visible_annotations_length,
4142 const u1* const runtime_invisible_annotations,
4143 int runtime_invisible_annotations_length,
4144 TRAPS) {
4145 AnnotationArray* annotations = nullptr;
4146 if (runtime_visible_annotations != nullptr ||
4147 runtime_invisible_annotations != nullptr) {
4156 }
4157 if (runtime_invisible_annotations != nullptr) {
4158 for (int i = 0; i < runtime_invisible_annotations_length; i++) {
4159 int append = runtime_visible_annotations_length+i;
4160 annotations->at_put(append, runtime_invisible_annotations[i]);
4161 }
4162 }
4163 }
4164 return annotations;
4165 }
4166
4167 const InstanceKlass* ClassFileParser::parse_super_class(ConstantPool* const cp,
4168 const int super_class_index,
4169 const bool need_verify,
4170 TRAPS) {
4171 assert(cp != nullptr, "invariant");
4172 const InstanceKlass* super_klass = nullptr;
4173
4174 if (super_class_index == 0) {
4175 check_property(_class_name == vmSymbols::java_lang_Object(),
4176 "Invalid superclass index 0 in class file %s",
4177 CHECK_NULL);
4178 } else {
4179 check_property(valid_klass_reference_at(super_class_index),
4180 "Invalid superclass index %u in class file %s",
4181 super_class_index,
4182 CHECK_NULL);
4183 // The class name should be legal because it is checked when parsing constant pool.
4184 // However, make sure it is not an array type.
4185 if (cp->tag_at(super_class_index).is_klass()) {
4186 super_klass = InstanceKlass::cast(cp->resolved_klass_at(super_class_index));
4187 }
4188 if (need_verify) {
4189 bool is_array = (cp->klass_name_at(super_class_index)->char_at(0) == JVM_SIGNATURE_ARRAY);
4190 guarantee_property(!is_array,
4191 "Bad superclass name in class file %s", CHECK_NULL);
4192 }
4193 }
4194 return super_klass;
4195 }
4196
4197 OopMapBlocksBuilder::OopMapBlocksBuilder(unsigned int max_blocks) {
4198 _max_nonstatic_oop_maps = max_blocks;
4199 _nonstatic_oop_map_count = 0;
4200 if (max_blocks == 0) {
4201 _nonstatic_oop_maps = nullptr;
4202 } else {
4203 _nonstatic_oop_maps =
4204 NEW_RESOURCE_ARRAY(OopMapBlock, _max_nonstatic_oop_maps);
4205 memset(_nonstatic_oop_maps, 0, sizeof(OopMapBlock) * max_blocks);
4206 }
4207 }
4208
4209 OopMapBlock* OopMapBlocksBuilder::last_oop_map() const {
4367 v = true;
4368 }
4369 }
4370 assert(v == ik->has_vanilla_constructor(), "inconsistent has_vanilla_constructor");
4371 #endif
4372 }
4373
4374 // If it cannot be fast-path allocated, set a bit in the layout helper.
4375 // See documentation of InstanceKlass::can_be_fastpath_allocated().
4376 assert(ik->size_helper() > 0, "layout_helper is initialized");
4377 if ((!RegisterFinalizersAtInit && ik->has_finalizer())
4378 || ik->is_abstract() || ik->is_interface()
4379 || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == nullptr)
4380 || ik->size_helper() >= FastAllocateSizeLimit) {
4381 // Forbid fast-path allocation.
4382 const jint lh = Klass::instance_layout_helper(ik->size_helper(), true);
4383 ik->set_layout_helper(lh);
4384 }
4385 }
4386
4387 bool ClassFileParser::supports_inline_types() const {
4388 // Inline types are only supported by class file version 67.65535 and later
4389 return _major_version > JAVA_23_VERSION ||
4390 (_major_version == JAVA_23_VERSION && _minor_version == JAVA_PREVIEW_MINOR_VERSION);
4391 }
4392
4393 // utility methods for appending an array with check for duplicates
4394
4395 static void append_interfaces(GrowableArray<InstanceKlass*>* result,
4396 const Array<InstanceKlass*>* const ifs) {
4397 // iterate over new interfaces
4398 for (int i = 0; i < ifs->length(); i++) {
4399 InstanceKlass* const e = ifs->at(i);
4400 assert(e->is_klass() && e->is_interface(), "just checking");
4401 // add new interface
4402 result->append_if_missing(e);
4403 }
4404 }
4405
4406 static Array<InstanceKlass*>* compute_transitive_interfaces(const InstanceKlass* super,
4407 Array<InstanceKlass*>* local_ifs,
4408 ClassLoaderData* loader_data,
4409 TRAPS) {
4410 assert(local_ifs != nullptr, "invariant");
4411 assert(loader_data != nullptr, "invariant");
4412
4416 // Add superclass transitive interfaces size
4417 if (super != nullptr) {
4418 super_size = super->transitive_interfaces()->length();
4419 max_transitive_size += super_size;
4420 }
4421 // Add local interfaces' super interfaces
4422 const int local_size = local_ifs->length();
4423 for (int i = 0; i < local_size; i++) {
4424 InstanceKlass* const l = local_ifs->at(i);
4425 max_transitive_size += l->transitive_interfaces()->length();
4426 }
4427 // Finally add local interfaces
4428 max_transitive_size += local_size;
4429 // Construct array
4430 if (max_transitive_size == 0) {
4431 // no interfaces, use canonicalized array
4432 return Universe::the_empty_instance_klass_array();
4433 } else if (max_transitive_size == super_size) {
4434 // no new local interfaces added, share superklass' transitive interface array
4435 return super->transitive_interfaces();
4436 // The three lines below are commented to work around bug JDK-8245487
4437 // } else if (max_transitive_size == local_size) {
4438 // // only local interfaces added, share local interface array
4439 // return local_ifs;
4440 } else {
4441 ResourceMark rm;
4442 GrowableArray<InstanceKlass*>* const result = new GrowableArray<InstanceKlass*>(max_transitive_size);
4443
4444 // Copy down from superclass
4445 if (super != nullptr) {
4446 append_interfaces(result, super->transitive_interfaces());
4447 }
4448
4449 // Copy down from local interfaces' superinterfaces
4450 for (int i = 0; i < local_size; i++) {
4451 InstanceKlass* const l = local_ifs->at(i);
4452 append_interfaces(result, l->transitive_interfaces());
4453 }
4454 // Finally add local interfaces
4455 append_interfaces(result, local_ifs);
4456
4457 // length will be less than the max_transitive_size if duplicates were removed
4458 const int length = result->length();
4459 assert(length <= max_transitive_size, "just checking");
4460
4461 Array<InstanceKlass*>* const new_result =
4462 MetadataFactory::new_array<InstanceKlass*>(loader_data, length, CHECK_NULL);
4463 for (int i = 0; i < length; i++) {
4464 InstanceKlass* const e = result->at(i);
4465 assert(e != nullptr, "just checking");
4466 new_result->at_put(i, e);
4467 }
4468 return new_result;
4469 }
4470 }
4471
4472 void ClassFileParser::check_super_class_access(const InstanceKlass* this_klass, TRAPS) {
4473 assert(this_klass != nullptr, "invariant");
4474 const Klass* const super = this_klass->super();
4475
4476 if (super != nullptr) {
4477 const InstanceKlass* super_ik = InstanceKlass::cast(super);
4478
4479 if (super->is_final()) {
4480 classfile_icce_error("class %s cannot inherit from final class %s", super_ik, THREAD);
4481 return;
4482 }
4483
4484 if (super_ik->is_sealed() && !super_ik->has_as_permitted_subclass(this_klass)) {
4485 classfile_icce_error("class %s cannot inherit from sealed class %s", super_ik, THREAD);
4486 return;
4487 }
4488
4489 // The JVMS says that super classes for value types must not have the ACC_IDENTITY
4490 // flag set. But, java.lang.Object must still be allowed to be a direct super class
4491 // for a value classes. So, it is treated as a special case for now.
4492 if (!this_klass->access_flags().is_identity_class() &&
4493 super_ik->name() != vmSymbols::java_lang_Object() &&
4494 super_ik->is_identity_class()) {
4495 classfile_icce_error("value class %s cannot inherit from class %s", super_ik, THREAD);
4496 return;
4497 }
4498
4499 // If the loader is not the boot loader then throw an exception if its
4500 // superclass is in package jdk.internal.reflect and its loader is not a
4501 // special reflection class loader
4502 if (!this_klass->class_loader_data()->is_the_null_class_loader_data()) {
4503 PackageEntry* super_package = super->package();
4504 if (super_package != nullptr &&
4505 super_package->name()->fast_compare(vmSymbols::jdk_internal_reflect()) == 0 &&
4506 !java_lang_ClassLoader::is_reflection_class_loader(this_klass->class_loader())) {
4507 ResourceMark rm(THREAD);
4508 Exceptions::fthrow(
4509 THREAD_AND_LOCATION,
4510 vmSymbols::java_lang_IllegalAccessError(),
4511 "class %s loaded by %s cannot access jdk/internal/reflect superclass %s",
4512 this_klass->external_name(),
4513 this_klass->class_loader_data()->loader_name_and_id(),
4514 super->external_name());
4515 return;
4516 }
4517 }
4518
4664
4665 for (int index = 0; index < num_methods; index++) {
4666 const Method* const m = methods->at(index);
4667 // if m is static and not the init method, throw a verify error
4668 if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) {
4669 ResourceMark rm(THREAD);
4670 Exceptions::fthrow(
4671 THREAD_AND_LOCATION,
4672 vmSymbols::java_lang_VerifyError(),
4673 "Illegal static method %s in interface %s",
4674 m->name()->as_C_string(),
4675 this_klass->external_name()
4676 );
4677 return;
4678 }
4679 }
4680 }
4681
4682 // utility methods for format checking
4683
4684 void ClassFileParser::verify_legal_class_modifiers(jint flags, const char* name, bool is_Object, TRAPS) const {
4685 const bool is_module = (flags & JVM_ACC_MODULE) != 0;
4686 const bool is_inner_class = name != nullptr;
4687 assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");
4688 if (is_module) {
4689 ResourceMark rm(THREAD);
4690 Exceptions::fthrow(
4691 THREAD_AND_LOCATION,
4692 vmSymbols::java_lang_NoClassDefFoundError(),
4693 "%s is not a class because access_flag ACC_MODULE is set",
4694 _class_name->as_C_string());
4695 return;
4696 }
4697
4698 if (!_need_verify) { return; }
4699
4700 const bool is_interface = (flags & JVM_ACC_INTERFACE) != 0;
4701 const bool is_abstract = (flags & JVM_ACC_ABSTRACT) != 0;
4702 const bool is_final = (flags & JVM_ACC_FINAL) != 0;
4703 const bool is_identity = (flags & JVM_ACC_IDENTITY) != 0;
4704 const bool is_enum = (flags & JVM_ACC_ENUM) != 0;
4705 const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4706 const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4707 const bool valid_value_class = is_identity || is_interface ||
4708 (supports_inline_types() && (!is_identity && (is_abstract || is_final)));
4709
4710 if ((is_abstract && is_final) ||
4711 (is_interface && !is_abstract) ||
4712 (is_interface && major_gte_1_5 && (is_identity || is_enum)) || // ACC_SUPER (now ACC_IDENTITY) was illegal for interfaces
4713 (!is_interface && major_gte_1_5 && is_annotation) ||
4714 (!valid_value_class)) {
4715 ResourceMark rm(THREAD);
4716 const char* class_note = "";
4717 if (!valid_value_class) {
4718 class_note = " (a value class must be final or else abstract)";
4719 }
4720 if (name == nullptr) { // Not an inner class
4721 Exceptions::fthrow(
4722 THREAD_AND_LOCATION,
4723 vmSymbols::java_lang_ClassFormatError(),
4724 "Illegal class modifiers in class %s%s: 0x%X",
4725 _class_name->as_C_string(), class_note, flags
4726 );
4727 return;
4728 } else {
4729 Exceptions::fthrow(
4730 THREAD_AND_LOCATION,
4731 vmSymbols::java_lang_ClassFormatError(),
4732 "Illegal class modifiers in declaration of inner class %s%s of class %s: 0x%X",
4733 name, class_note, _class_name->as_C_string(), flags
4734 );
4735 return;
4736 }
4737 }
4738 }
4739
4740 static bool has_illegal_visibility(jint flags) {
4741 const bool is_public = (flags & JVM_ACC_PUBLIC) != 0;
4742 const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4743 const bool is_private = (flags & JVM_ACC_PRIVATE) != 0;
4744
4745 return ((is_public && is_protected) ||
4746 (is_public && is_private) ||
4747 (is_protected && is_private));
4748 }
4749
4750 // A legal major_version.minor_version must be one of the following:
4751 //
4752 // Major_version >= 45 and major_version < 56, any minor_version.
4753 // Major_version >= 56 and major_version <= JVM_CLASSFILE_MAJOR_VERSION and minor_version = 0.
4754 // Major_version = JVM_CLASSFILE_MAJOR_VERSION and minor_version = 65535 and --enable-preview is present.
4755 //
4756 void ClassFileParser::verify_class_version(u2 major, u2 minor, Symbol* class_name, TRAPS){
4782 THREAD_AND_LOCATION,
4783 vmSymbols::java_lang_UnsupportedClassVersionError(),
4784 "%s (class file version %u.%u) was compiled with preview features that are unsupported. "
4785 "This version of the Java Runtime only recognizes preview features for class file version %u.%u",
4786 class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION, JAVA_PREVIEW_MINOR_VERSION);
4787 return;
4788 }
4789
4790 if (!Arguments::enable_preview()) {
4791 classfile_ucve_error("Preview features are not enabled for %s (class file version %u.%u). Try running with '--enable-preview'",
4792 class_name, major, minor, THREAD);
4793 return;
4794 }
4795
4796 } else { // minor != JAVA_PREVIEW_MINOR_VERSION
4797 classfile_ucve_error("%s (class file version %u.%u) was compiled with an invalid non-zero minor version",
4798 class_name, major, minor, THREAD);
4799 }
4800 }
4801
4802 void ClassFileParser:: verify_legal_field_modifiers(jint flags,
4803 AccessFlags class_access_flags,
4804 TRAPS) const {
4805 if (!_need_verify) { return; }
4806
4807 const bool is_public = (flags & JVM_ACC_PUBLIC) != 0;
4808 const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4809 const bool is_private = (flags & JVM_ACC_PRIVATE) != 0;
4810 const bool is_static = (flags & JVM_ACC_STATIC) != 0;
4811 const bool is_final = (flags & JVM_ACC_FINAL) != 0;
4812 const bool is_volatile = (flags & JVM_ACC_VOLATILE) != 0;
4813 const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
4814 const bool is_enum = (flags & JVM_ACC_ENUM) != 0;
4815 const bool is_strict = (flags & JVM_ACC_STRICT) != 0;
4816 const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4817
4818 const bool is_interface = class_access_flags.is_interface();
4819 const bool is_identity_class = class_access_flags.is_identity_class();
4820
4821 bool is_illegal = false;
4822 const char* error_msg = "";
4823
4824 // There is some overlap in the checks that apply, for example interface fields
4825 // must be static, static fields can't be strict, and therefore interfaces can't
4826 // have strict fields. So we don't have to check every possible invalid combination
4827 // individually as long as all are covered. Once we have found an illegal combination
4828 // we can stop checking.
4829
4830 if (supports_inline_types()) {
4831 if (is_strict && is_static) {
4832 is_illegal = true;
4833 error_msg = "field cannot be strict and static";
4834 }
4835 else if (is_strict && !is_final) {
4836 is_illegal = true;
4837 error_msg = "strict field must be final";
4838 }
4839 }
4840
4841 if (!is_illegal) {
4842 if (is_interface) {
4843 if (!is_public || !is_static || !is_final || is_private ||
4844 is_protected || is_volatile || is_transient ||
4845 (major_gte_1_5 && is_enum)) {
4846 is_illegal = true;
4847 error_msg = "interface fields must be public, static and final, and may be synthetic";
4848 }
4849 } else { // not interface
4850 if (has_illegal_visibility(flags)) {
4851 is_illegal = true;
4852 error_msg = "invalid visibility flags for class field";
4853 } else if (is_final && is_volatile) {
4854 is_illegal = true;
4855 error_msg = "fields cannot be final and volatile";
4856 } else if (supports_inline_types()) {
4857 if (!is_identity_class && !is_static && !is_strict) {
4858 is_illegal = true;
4859 error_msg = "value class fields must be either strict or static";
4860 }
4861 }
4862 }
4863 }
4864
4865 if (is_illegal) {
4866 ResourceMark rm(THREAD);
4867 Exceptions::fthrow(
4868 THREAD_AND_LOCATION,
4869 vmSymbols::java_lang_ClassFormatError(),
4870 "Illegal field modifiers (%s) in class %s: 0x%X",
4871 error_msg, _class_name->as_C_string(), flags);
4872 return;
4873 }
4874 }
4875
4876 void ClassFileParser::verify_legal_method_modifiers(jint flags,
4877 AccessFlags class_access_flags,
4878 const Symbol* name,
4879 TRAPS) const {
4880 if (!_need_verify) { return; }
4881
4882 const bool is_public = (flags & JVM_ACC_PUBLIC) != 0;
4883 const bool is_private = (flags & JVM_ACC_PRIVATE) != 0;
4884 const bool is_static = (flags & JVM_ACC_STATIC) != 0;
4885 const bool is_final = (flags & JVM_ACC_FINAL) != 0;
4886 const bool is_native = (flags & JVM_ACC_NATIVE) != 0;
4887 const bool is_abstract = (flags & JVM_ACC_ABSTRACT) != 0;
4888 const bool is_bridge = (flags & JVM_ACC_BRIDGE) != 0;
4889 const bool is_strict = (flags & JVM_ACC_STRICT) != 0;
4890 const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
4891 const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4892 const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4893 const bool major_gte_8 = _major_version >= JAVA_8_VERSION;
4894 const bool major_gte_17 = _major_version >= JAVA_17_VERSION;
4895 const bool is_initializer = (name == vmSymbols::object_initializer_name());
4896 // LW401 CR required: removal of value factories support
4897 const bool is_interface = class_access_flags.is_interface();
4898 const bool is_identity_class = class_access_flags.is_identity_class();
4899 const bool is_abstract_class = class_access_flags.is_abstract();
4900
4901 bool is_illegal = false;
4902
4903 const char* class_note = "";
4904 if (is_interface) {
4905 if (major_gte_8) {
4906 // Class file version is JAVA_8_VERSION or later Methods of
4907 // interfaces may set any of the flags except ACC_PROTECTED,
4908 // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must
4909 // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.
4910 if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
4911 (is_native || is_protected || is_final || is_synchronized) ||
4912 // If a specific method of a class or interface has its
4913 // ACC_ABSTRACT flag set, it must not have any of its
4914 // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,
4915 // ACC_STRICT, or ACC_SYNCHRONIZED flags set. No need to
4916 // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as
4917 // those flags are illegal irrespective of ACC_ABSTRACT being set or not.
4918 (is_abstract && (is_private || is_static || (!major_gte_17 && is_strict)))) {
4919 is_illegal = true;
4920 }
4921 } else if (major_gte_1_5) {
4922 // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)
4923 if (!is_public || is_private || is_protected || is_static || is_final ||
4924 is_synchronized || is_native || !is_abstract || is_strict) {
4925 is_illegal = true;
4926 }
4927 } else {
4928 // Class file version is pre-JAVA_1_5_VERSION
4929 if (!is_public || is_static || is_final || is_native || !is_abstract) {
4930 is_illegal = true;
4931 }
4932 }
4933 } else { // not interface
4934 if (has_illegal_visibility(flags)) {
4935 is_illegal = true;
4936 } else {
4937 if (is_initializer) {
4938 if (is_static || is_final || is_synchronized || is_native ||
4939 is_abstract || (major_gte_1_5 && is_bridge)) {
4940 is_illegal = true;
4941 }
4942 } else { // not initializer
4943 if (!is_identity_class && is_synchronized && !is_static) {
4944 is_illegal = true;
4945 class_note = " (not an identity class)";
4946 } else {
4947 if (is_abstract) {
4948 if ((is_final || is_native || is_private || is_static ||
4949 (major_gte_1_5 && (is_synchronized || (!major_gte_17 && is_strict))))) {
4950 is_illegal = true;
4951 }
4952 }
4953 }
4954 }
4955 }
4956 }
4957
4958 if (is_illegal) {
4959 ResourceMark rm(THREAD);
4960 Exceptions::fthrow(
4961 THREAD_AND_LOCATION,
4962 vmSymbols::java_lang_ClassFormatError(),
4963 "Method %s in class %s%s has illegal modifiers: 0x%X",
4964 name->as_C_string(), _class_name->as_C_string(),
4965 class_note, flags);
4966 return;
4967 }
4968 }
4969
4970 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer,
4971 int length,
4972 TRAPS) const {
4973 assert(_need_verify, "only called when _need_verify is true");
4974 if (!UTF8::is_legal_utf8(buffer, length, _major_version <= 47)) {
4975 classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", THREAD);
4976 }
4977 }
4978
4979 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
4980 // In class names, '/' separates unqualified names. This is verified in this function also.
4981 // Method names also may not contain the characters '<' or '>', unless <init>
4982 // or <clinit>. Note that method names may not be <init> or <clinit> in this
4983 // method. Because these names have been checked as special cases before
4984 // calling this method in verify_legal_method_name.
4985 //
5002 if (type == ClassFileParser::LegalClass) {
5003 if (p == name || p+1 >= name+length ||
5004 *(p+1) == JVM_SIGNATURE_SLASH) {
5005 return false;
5006 }
5007 } else {
5008 return false; // do not permit '/' unless it's class name
5009 }
5010 break;
5011 case JVM_SIGNATURE_SPECIAL:
5012 case JVM_SIGNATURE_ENDSPECIAL:
5013 // do not permit '<' or '>' in method names
5014 if (type == ClassFileParser::LegalMethod) {
5015 return false;
5016 }
5017 }
5018 }
5019 return true;
5020 }
5021
5022 bool ClassFileParser::is_class_in_loadable_descriptors_attribute(Symbol *klass) {
5023 if (_loadable_descriptors == nullptr) return false;
5024 for (int i = 0; i < _loadable_descriptors->length(); i++) {
5025 Symbol* class_name = _cp->symbol_at(_loadable_descriptors->at(i));
5026 if (class_name == klass) return true;
5027 }
5028 return false;
5029 }
5030
5031 // Take pointer to a UTF8 byte string (not NUL-terminated).
5032 // Skip over the longest part of the string that could
5033 // be taken as a fieldname. Allow non-trailing '/'s if slash_ok is true.
5034 // Return a pointer to just past the fieldname.
5035 // Return null if no fieldname at all was found, or in the case of slash_ok
5036 // being true, we saw consecutive slashes (meaning we were looking for a
5037 // qualified path but found something that was badly-formed).
5038 static const char* skip_over_field_name(const char* const name,
5039 bool slash_ok,
5040 unsigned int length) {
5041 const char* p;
5042 jboolean last_is_slash = false;
5043 jboolean not_first_ch = false;
5044
5045 for (p = name; p != name + length; not_first_ch = true) {
5046 const char* old_p = p;
5047 jchar ch = *p;
5048 if (ch < 128) {
5049 p++;
5050 // quick check for ascii
5112 // be taken as a field signature. Allow "void" if void_ok.
5113 // Return a pointer to just past the signature.
5114 // Return null if no legal signature is found.
5115 const char* ClassFileParser::skip_over_field_signature(const char* signature,
5116 bool void_ok,
5117 unsigned int length,
5118 TRAPS) const {
5119 unsigned int array_dim = 0;
5120 while (length > 0) {
5121 switch (signature[0]) {
5122 case JVM_SIGNATURE_VOID: if (!void_ok) { return nullptr; }
5123 case JVM_SIGNATURE_BOOLEAN:
5124 case JVM_SIGNATURE_BYTE:
5125 case JVM_SIGNATURE_CHAR:
5126 case JVM_SIGNATURE_SHORT:
5127 case JVM_SIGNATURE_INT:
5128 case JVM_SIGNATURE_FLOAT:
5129 case JVM_SIGNATURE_LONG:
5130 case JVM_SIGNATURE_DOUBLE:
5131 return signature + 1;
5132 case JVM_SIGNATURE_CLASS:
5133 {
5134 if (_major_version < JAVA_1_5_VERSION) {
5135 // Skip over the class name if one is there
5136 const char* const p = skip_over_field_name(signature + 1, true, --length);
5137
5138 // The next character better be a semicolon
5139 if (p && (p - signature) > 1 && p[0] == JVM_SIGNATURE_ENDCLASS) {
5140 return p + 1;
5141 }
5142 }
5143 else {
5144 // Skip leading 'L' or 'Q' and ignore first appearance of ';'
5145 signature++;
5146 const char* c = (const char*) memchr(signature, JVM_SIGNATURE_ENDCLASS, length - 1);
5147 // Format check signature
5148 if (c != nullptr) {
5149 int newlen = pointer_delta_as_int(c, (char*) signature);
5150 bool legal = verify_unqualified_name(signature, newlen, LegalClass);
5151 if (!legal) {
5152 classfile_parse_error("Class name is empty or contains illegal character "
5153 "in descriptor in class file %s",
5154 THREAD);
5155 return nullptr;
5156 }
5157 return signature + newlen + 1;
5158 }
5159 }
5160 return nullptr;
5161 }
5162 case JVM_SIGNATURE_ARRAY:
5163 array_dim++;
5164 if (array_dim > 255) {
5180
5181 // Checks if name is a legal class name.
5182 void ClassFileParser::verify_legal_class_name(const Symbol* name, TRAPS) const {
5183 if (!_need_verify || _relax_verify) { return; }
5184
5185 assert(name->refcount() > 0, "symbol must be kept alive");
5186 char* bytes = (char*)name->bytes();
5187 unsigned int length = name->utf8_length();
5188 bool legal = false;
5189
5190 if (length > 0) {
5191 const char* p;
5192 if (bytes[0] == JVM_SIGNATURE_ARRAY) {
5193 p = skip_over_field_signature(bytes, false, length, CHECK);
5194 legal = (p != nullptr) && ((p - bytes) == (int)length);
5195 } else if (_major_version < JAVA_1_5_VERSION) {
5196 if (bytes[0] != JVM_SIGNATURE_SPECIAL) {
5197 p = skip_over_field_name(bytes, true, length);
5198 legal = (p != nullptr) && ((p - bytes) == (int)length);
5199 }
5200 } else if ((_major_version >= CONSTANT_CLASS_DESCRIPTORS || _class_name->starts_with("jdk/internal/reflect/"))
5201 && bytes[length - 1] == ';' ) {
5202 // Support for L...; and Q...; descriptors
5203 legal = verify_unqualified_name(bytes + 1, length - 2, LegalClass);
5204 } else {
5205 // 4900761: relax the constraints based on JSR202 spec
5206 // Class names may be drawn from the entire Unicode character set.
5207 // Identifiers between '/' must be unqualified names.
5208 // The utf8 string has been verified when parsing cpool entries.
5209 legal = verify_unqualified_name(bytes, length, LegalClass);
5210 }
5211 }
5212 if (!legal) {
5213 ResourceMark rm(THREAD);
5214 assert(_class_name != nullptr, "invariant");
5215 Exceptions::fthrow(
5216 THREAD_AND_LOCATION,
5217 vmSymbols::java_lang_ClassFormatError(),
5218 "Illegal class name \"%.*s\" in class file %s", length, bytes,
5219 _class_name->as_C_string()
5220 );
5221 return;
5222 }
5223 }
5249 THREAD_AND_LOCATION,
5250 vmSymbols::java_lang_ClassFormatError(),
5251 "Illegal field name \"%.*s\" in class %s", length, bytes,
5252 _class_name->as_C_string()
5253 );
5254 return;
5255 }
5256 }
5257
5258 // Checks if name is a legal method name.
5259 void ClassFileParser::verify_legal_method_name(const Symbol* name, TRAPS) const {
5260 if (!_need_verify || _relax_verify) { return; }
5261
5262 assert(name != nullptr, "method name is null");
5263 char* bytes = (char*)name->bytes();
5264 unsigned int length = name->utf8_length();
5265 bool legal = false;
5266
5267 if (length > 0) {
5268 if (bytes[0] == JVM_SIGNATURE_SPECIAL) {
5269 if (name == vmSymbols::object_initializer_name() ||
5270 name == vmSymbols::class_initializer_name()) {
5271 legal = true;
5272 }
5273 } else if (_major_version < JAVA_1_5_VERSION) {
5274 const char* p;
5275 p = skip_over_field_name(bytes, false, length);
5276 legal = (p != nullptr) && ((p - bytes) == (int)length);
5277 } else {
5278 // 4881221: relax the constraints based on JSR202 spec
5279 legal = verify_unqualified_name(bytes, length, LegalMethod);
5280 }
5281 }
5282
5283 if (!legal) {
5284 ResourceMark rm(THREAD);
5285 assert(_class_name != nullptr, "invariant");
5286 Exceptions::fthrow(
5287 THREAD_AND_LOCATION,
5288 vmSymbols::java_lang_ClassFormatError(),
5289 "Illegal method name \"%.*s\" in class %s", length, bytes,
5290 _class_name->as_C_string()
5291 );
5292 return;
5293 }
5294 }
5295
5296 bool ClassFileParser::legal_field_signature(const Symbol* signature, TRAPS) const {
5297 const char* const bytes = (const char*)signature->bytes();
5298 const unsigned int length = signature->utf8_length();
5299 const char* const p = skip_over_field_signature(bytes, false, length, CHECK_false);
5300
5301 if (p == nullptr || (p - bytes) != (int)length) {
5302 return false;
5303 }
5304 return true;
5305 }
5306
5307 // Checks if signature is a legal field signature.
5308 void ClassFileParser::verify_legal_field_signature(const Symbol* name,
5309 const Symbol* signature,
5310 TRAPS) const {
5311 if (!_need_verify) { return; }
5312
5313 const char* const bytes = (const char*)signature->bytes();
5314 const unsigned int length = signature->utf8_length();
5315 const char* const p = skip_over_field_signature(bytes, false, length, CHECK);
5316
5317 if (p == nullptr || (p - bytes) != (int)length) {
5318 throwIllegalSignature("Field", name, signature, CHECK);
5319 }
5320 }
5321
5322 // Check that the signature is compatible with the method name. For example,
5323 // check that <init> has a void signature.
5324 void ClassFileParser::verify_legal_name_with_signature(const Symbol* name,
5325 const Symbol* signature,
5326 TRAPS) const {
5327 if (!_need_verify) {
5328 return;
5329 }
5330
5331 // Class initializers cannot have args for class format version >= 51.
5332 if (name == vmSymbols::class_initializer_name() &&
5333 signature != vmSymbols::void_method_signature() &&
5334 _major_version >= JAVA_7_VERSION) {
5335 throwIllegalSignature("Method", name, signature, THREAD);
5336 return;
5337 }
5338
5339 int sig_length = signature->utf8_length();
5340 if (name->utf8_length() > 0 &&
5341 name->char_at(0) == JVM_SIGNATURE_SPECIAL &&
5342 sig_length > 0 &&
5343 signature->char_at(sig_length - 1) != JVM_SIGNATURE_VOID) {
5344 throwIllegalSignature("Method", name, signature, THREAD);
5345 }
5346 }
5347
5348 // Checks if signature is a legal method signature.
5349 // Returns number of parameters
5350 int ClassFileParser::verify_legal_method_signature(const Symbol* name,
5351 const Symbol* signature,
5352 TRAPS) const {
5353 if (!_need_verify) {
5354 // make sure caller's args_size will be less than 0 even for non-static
5355 // method so it will be recomputed in compute_size_of_parameters().
5356 return -2;
5357 }
5358
5359 unsigned int args_size = 0;
5360 const char* p = (const char*)signature->bytes();
5361 unsigned int length = signature->utf8_length();
5362 const char* nextp;
5363
5500 }
5501 }
5502
5503 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook,
5504 const ClassInstanceInfo& cl_inst_info,
5505 TRAPS) {
5506 if (_klass != nullptr) {
5507 return _klass;
5508 }
5509
5510 InstanceKlass* const ik =
5511 InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
5512
5513 if (is_hidden()) {
5514 mangle_hidden_class_name(ik);
5515 }
5516
5517 fill_instance_klass(ik, changed_by_loadhook, cl_inst_info, CHECK_NULL);
5518
5519 assert(_klass == ik, "invariant");
5520 return ik;
5521 }
5522
5523 void ClassFileParser::fill_instance_klass(InstanceKlass* ik,
5524 bool changed_by_loadhook,
5525 const ClassInstanceInfo& cl_inst_info,
5526 TRAPS) {
5527 assert(ik != nullptr, "invariant");
5528
5529 // Set name and CLD before adding to CLD
5530 ik->set_class_loader_data(_loader_data);
5531 ik->set_name(_class_name);
5532
5533 // Add all classes to our internal class loader list here,
5534 // including classes in the bootstrap (null) class loader.
5535 const bool publicize = !is_internal();
5536
5537 _loader_data->add_class(ik, publicize);
5538
5539 set_klass_to_deallocate(ik);
5540
5541 assert(_field_info != nullptr, "invariant");
5542 assert(ik->static_field_size() == _field_info->_static_field_size, "sanity");
5543 assert(ik->nonstatic_oop_map_count() == _field_info->oop_map_blocks->_nonstatic_oop_map_count,
5544 "sanity");
5545
5546 assert(ik->is_instance_klass(), "sanity");
5547 assert(ik->size_helper() == _field_info->_instance_size, "sanity");
5548
5549 // Fill in information already parsed
5550 ik->set_should_verify_class(_need_verify);
5551
5552 // Not yet: supers are done below to support the new subtype-checking fields
5553 ik->set_nonstatic_field_size(_field_info->_nonstatic_field_size);
5554 ik->set_has_nonstatic_fields(_field_info->_has_nonstatic_fields);
5555 if (_field_info->_is_naturally_atomic && ik->is_inline_klass()) {
5556 ik->set_is_naturally_atomic();
5557 }
5558
5559 assert(_fac != nullptr, "invariant");
5560 ik->set_static_oop_field_count(_fac->count[STATIC_OOP] + _fac->count[STATIC_INLINE]);
5561
5562 // this transfers ownership of a lot of arrays from
5563 // the parser onto the InstanceKlass*
5564 apply_parsed_class_metadata(ik, _java_fields_count);
5565 if (ik->is_inline_klass()) {
5566 InlineKlass::cast(ik)->init_fixed_block();
5567 }
5568
5569 // can only set dynamic nest-host after static nest information is set
5570 if (cl_inst_info.dynamic_nest_host() != nullptr) {
5571 ik->set_nest_host(cl_inst_info.dynamic_nest_host());
5572 }
5573
5574 // note that is not safe to use the fields in the parser from this point on
5575 assert(nullptr == _cp, "invariant");
5576 assert(nullptr == _fieldinfo_stream, "invariant");
5577 assert(nullptr == _fields_status, "invariant");
5578 assert(nullptr == _methods, "invariant");
5579 assert(nullptr == _inner_classes, "invariant");
5580 assert(nullptr == _nest_members, "invariant");
5581 assert(nullptr == _loadable_descriptors, "invariant");
5582 assert(nullptr == _combined_annotations, "invariant");
5583 assert(nullptr == _record_components, "invariant");
5584 assert(nullptr == _permitted_subclasses, "invariant");
5585 assert(nullptr == _inline_type_field_klasses, "invariant");
5586
5587 if (_has_localvariable_table) {
5588 ik->set_has_localvariable_table(true);
5589 }
5590
5591 if (_has_final_method) {
5592 ik->set_has_final_method();
5593 }
5594
5595 ik->copy_method_ordering(_method_ordering, CHECK);
5596 // The InstanceKlass::_methods_jmethod_ids cache
5597 // is managed on the assumption that the initial cache
5598 // size is equal to the number of methods in the class. If
5599 // that changes, then InstanceKlass::idnum_can_increment()
5600 // has to be changed accordingly.
5601 ik->set_initial_method_idnum(checked_cast<u2>(ik->methods()->length()));
5602
5603 ik->set_this_class_index(_this_class_index);
5604
5605 if (_is_hidden) {
5606 // _this_class_index is a CONSTANT_Class entry that refers to this
5607 // hidden class itself. If this class needs to refer to its own methods
5608 // or fields, it would use a CONSTANT_MethodRef, etc, which would reference
5609 // _this_class_index. However, because this class is hidden (it's
5610 // not stored in SystemDictionary), _this_class_index cannot be resolved
5611 // with ConstantPool::klass_at_impl, which does a SystemDictionary lookup.
5612 // Therefore, we must eagerly resolve _this_class_index now.
5613 ik->constants()->klass_at_put(_this_class_index, ik);
5614 }
5615
5616 ik->set_minor_version(_minor_version);
5617 ik->set_major_version(_major_version);
5618 ik->set_has_nonstatic_concrete_methods(_has_nonstatic_concrete_methods);
5619 ik->set_declares_nonstatic_concrete_methods(_declares_nonstatic_concrete_methods);
5620
5621 if (_must_be_atomic) {
5622 ik->set_must_be_atomic();
5623 }
5624 if (_is_implicitly_constructible) {
5625 ik->set_is_implicitly_constructible();
5626 }
5627 if (_is_hidden) {
5628 ik->set_is_hidden();
5629 }
5630
5631 // Set PackageEntry for this_klass
5632 oop cl = ik->class_loader();
5633 Handle clh = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(cl));
5634 ClassLoaderData* cld = ClassLoaderData::class_loader_data_or_null(clh());
5635 ik->set_package(cld, nullptr, CHECK);
5636
5637 const Array<Method*>* const methods = ik->methods();
5638 assert(methods != nullptr, "invariant");
5639 const int methods_len = methods->length();
5640
5641 check_methods_for_intrinsics(ik, methods);
5642
5643 // Fill in field values obtained by parse_classfile_attributes
5644 if (_parsed_annotations->has_any_annotations()) {
5645 _parsed_annotations->apply_to(ik);
5646 }
5713
5714 assert(_all_mirandas != nullptr, "invariant");
5715
5716 // Generate any default methods - default methods are public interface methods
5717 // that have a default implementation. This is new with Java 8.
5718 if (_has_nonstatic_concrete_methods) {
5719 DefaultMethods::generate_default_methods(ik,
5720 _all_mirandas,
5721 CHECK);
5722 }
5723
5724 // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5725 if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5726 !module_entry->has_default_read_edges()) {
5727 if (!module_entry->set_has_default_read_edges()) {
5728 // We won a potential race
5729 JvmtiExport::add_default_read_edges(module_handle, THREAD);
5730 }
5731 }
5732
5733 bool all_fields_empty = true;
5734 for (AllFieldStream fs(ik); !fs.done(); fs.next()) {
5735 if (!fs.access_flags().is_static()) {
5736 if (fs.field_descriptor().is_null_free_inline_type()) {
5737 Klass* k = ik->inline_type_field_klasses_array()->at(fs.index());
5738 assert(k->is_inline_klass(), "must be");
5739 if (!InlineKlass::cast(k)->is_empty_inline_type()) { all_fields_empty = false; }
5740 } else {
5741 all_fields_empty = false;
5742 }
5743 } else if (is_inline_type() && (fs.name() == vmSymbols::default_value_name())) {
5744 InlineKlass::cast(ik)->set_default_value_offset(ik->field_offset(fs.index()));
5745 }
5746 }
5747
5748 if (_is_empty_inline_type || (is_inline_type() && all_fields_empty)) {
5749 ik->set_is_empty_inline_type();
5750 }
5751
5752 if (is_inline_type()) {
5753 InlineKlass* vk = InlineKlass::cast(ik);
5754 vk->set_alignment(_alignment);
5755 vk->set_first_field_offset(_first_field_offset);
5756 vk->set_payload_size_in_bytes(_payload_size_in_bytes);
5757 vk->set_internal_null_marker_offset(_internal_null_marker_offset);
5758 InlineKlass::cast(ik)->initialize_calling_convention(CHECK);
5759 }
5760
5761 ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5762
5763 if (!is_internal()) {
5764 ik->print_class_load_logging(_loader_data, module_entry, _stream);
5765
5766 if (ik->minor_version() == JAVA_PREVIEW_MINOR_VERSION &&
5767 ik->major_version() == JVM_CLASSFILE_MAJOR_VERSION &&
5768 log_is_enabled(Info, class, preview)) {
5769 ResourceMark rm;
5770 log_info(class, preview)("Loading class %s that depends on preview features (class file version %d.65535)",
5771 ik->external_name(), JVM_CLASSFILE_MAJOR_VERSION);
5772 }
5773
5774 if (log_is_enabled(Debug, class, resolve)) {
5775 ResourceMark rm;
5776 // print out the superclass.
5777 const char * from = ik->external_name();
5778 if (ik->java_super() != nullptr) {
5779 log_debug(class, resolve)("%s %s (super)",
5780 from,
5832 Symbol* name,
5833 ClassLoaderData* loader_data,
5834 const ClassLoadInfo* cl_info,
5835 Publicity pub_level,
5836 TRAPS) :
5837 _stream(stream),
5838 _class_name(nullptr),
5839 _loader_data(loader_data),
5840 _is_hidden(cl_info->is_hidden()),
5841 _can_access_vm_annotations(cl_info->can_access_vm_annotations()),
5842 _orig_cp_size(0),
5843 _super_klass(),
5844 _cp(nullptr),
5845 _fieldinfo_stream(nullptr),
5846 _fields_status(nullptr),
5847 _methods(nullptr),
5848 _inner_classes(nullptr),
5849 _nest_members(nullptr),
5850 _nest_host(0),
5851 _permitted_subclasses(nullptr),
5852 _loadable_descriptors(nullptr),
5853 _record_components(nullptr),
5854 _local_interfaces(nullptr),
5855 _local_interface_indexes(nullptr),
5856 _transitive_interfaces(nullptr),
5857 _combined_annotations(nullptr),
5858 _class_annotations(nullptr),
5859 _class_type_annotations(nullptr),
5860 _fields_annotations(nullptr),
5861 _fields_type_annotations(nullptr),
5862 _klass(nullptr),
5863 _klass_to_deallocate(nullptr),
5864 _parsed_annotations(nullptr),
5865 _fac(nullptr),
5866 _field_info(nullptr),
5867 _inline_type_field_klasses(nullptr),
5868 _null_marker_offsets(nullptr),
5869 _temp_field_info(nullptr),
5870 _method_ordering(nullptr),
5871 _all_mirandas(nullptr),
5872 _vtable_size(0),
5873 _itable_size(0),
5874 _num_miranda_methods(0),
5875 _protection_domain(cl_info->protection_domain()),
5876 _access_flags(),
5877 _pub_level(pub_level),
5878 _bad_constant_seen(0),
5879 _synthetic_flag(false),
5880 _sde_length(false),
5881 _sde_buffer(nullptr),
5882 _sourcefile_index(0),
5883 _generic_signature_index(0),
5884 _major_version(0),
5885 _minor_version(0),
5886 _this_class_index(0),
5887 _super_class_index(0),
5888 _itfs_len(0),
5889 _java_fields_count(0),
5890 _need_verify(false),
5891 _relax_verify(false),
5892 _has_nonstatic_concrete_methods(false),
5893 _declares_nonstatic_concrete_methods(false),
5894 _has_localvariable_table(false),
5895 _has_final_method(false),
5896 _has_contended_fields(false),
5897 _has_inline_type_fields(false),
5898 _has_nonstatic_fields(false),
5899 _is_empty_inline_type(false),
5900 _is_naturally_atomic(false),
5901 _must_be_atomic(true),
5902 _is_implicitly_constructible(false),
5903 _has_loosely_consistent_annotation(false),
5904 _has_implicitly_constructible_annotation(false),
5905 _has_finalizer(false),
5906 _has_empty_finalizer(false),
5907 _has_vanilla_constructor(false),
5908 _max_bootstrap_specifier_index(-1) {
5909
5910 _class_name = name != nullptr ? name : vmSymbols::unknown_class_name();
5911 _class_name->increment_refcount();
5912
5913 assert(_loader_data != nullptr, "invariant");
5914 assert(stream != nullptr, "invariant");
5915 assert(_stream != nullptr, "invariant");
5916 assert(_stream->buffer() == _stream->current(), "invariant");
5917 assert(_class_name != nullptr, "invariant");
5918 assert(0 == _access_flags.as_int(), "invariant");
5919
5920 // Figure out whether we can skip format checking (matching classic VM behavior)
5921 if (CDSConfig::is_dumping_static_archive()) {
5922 // verify == true means it's a 'remote' class (i.e., non-boot class)
5923 // Verification decision is based on BytecodeVerificationRemote flag
5924 // for those classes.
5935
5936 // Check if verification needs to be relaxed for this class file
5937 // Do not restrict it to jdk1.0 or jdk1.1 to maintain backward compatibility (4982376)
5938 _relax_verify = relax_format_check_for(_loader_data);
5939
5940 parse_stream(stream, CHECK);
5941
5942 post_process_parsed_stream(stream, _cp, CHECK);
5943 }
5944
5945 void ClassFileParser::clear_class_metadata() {
5946 // metadata created before the instance klass is created. Must be
5947 // deallocated if classfile parsing returns an error.
5948 _cp = nullptr;
5949 _fieldinfo_stream = nullptr;
5950 _fields_status = nullptr;
5951 _methods = nullptr;
5952 _inner_classes = nullptr;
5953 _nest_members = nullptr;
5954 _permitted_subclasses = nullptr;
5955 _loadable_descriptors = nullptr;
5956 _combined_annotations = nullptr;
5957 _class_annotations = _class_type_annotations = nullptr;
5958 _fields_annotations = _fields_type_annotations = nullptr;
5959 _record_components = nullptr;
5960 _inline_type_field_klasses = nullptr;
5961 _null_marker_offsets = nullptr;
5962 }
5963
5964 // Destructor to clean up
5965 ClassFileParser::~ClassFileParser() {
5966 _class_name->decrement_refcount();
5967
5968 if (_cp != nullptr) {
5969 MetadataFactory::free_metadata(_loader_data, _cp);
5970 }
5971
5972 if (_fieldinfo_stream != nullptr) {
5973 MetadataFactory::free_array<u1>(_loader_data, _fieldinfo_stream);
5974 }
5975
5976 if (_fields_status != nullptr) {
5977 MetadataFactory::free_array<FieldStatus>(_loader_data, _fields_status);
5978 }
5979
5980 if (_inline_type_field_klasses != nullptr) {
5981 MetadataFactory::free_array<InlineKlass*>(_loader_data, _inline_type_field_klasses);
5982 }
5983
5984 if (_null_marker_offsets != nullptr) {
5985 MetadataFactory::free_array<int>(_loader_data, _null_marker_offsets);
5986 }
5987
5988 if (_methods != nullptr) {
5989 // Free methods
5990 InstanceKlass::deallocate_methods(_loader_data, _methods);
5991 }
5992
5993 // beware of the Universe::empty_blah_array!!
5994 if (_inner_classes != nullptr && _inner_classes != Universe::the_empty_short_array()) {
5995 MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
5996 }
5997
5998 if (_nest_members != nullptr && _nest_members != Universe::the_empty_short_array()) {
5999 MetadataFactory::free_array<u2>(_loader_data, _nest_members);
6000 }
6001
6002 if (_record_components != nullptr) {
6003 InstanceKlass::deallocate_record_components(_loader_data, _record_components);
6004 }
6005
6006 if (_permitted_subclasses != nullptr && _permitted_subclasses != Universe::the_empty_short_array()) {
6007 MetadataFactory::free_array<u2>(_loader_data, _permitted_subclasses);
6008 }
6009
6010 if (_loadable_descriptors != nullptr && _loadable_descriptors != Universe::the_empty_short_array()) {
6011 MetadataFactory::free_array<u2>(_loader_data, _loadable_descriptors);
6012 }
6013
6014 // Free interfaces
6015 InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
6016 _local_interfaces, _transitive_interfaces);
6017
6018 if (_combined_annotations != nullptr) {
6019 // After all annotations arrays have been created, they are installed into the
6020 // Annotations object that will be assigned to the InstanceKlass being created.
6021
6022 // Deallocate the Annotations object and the installed annotations arrays.
6023 _combined_annotations->deallocate_contents(_loader_data);
6024
6025 // If the _combined_annotations pointer is non-null,
6026 // then the other annotations fields should have been cleared.
6027 assert(_class_annotations == nullptr, "Should have been cleared");
6028 assert(_class_type_annotations == nullptr, "Should have been cleared");
6029 assert(_fields_annotations == nullptr, "Should have been cleared");
6030 assert(_fields_type_annotations == nullptr, "Should have been cleared");
6031 } else {
6032 // If the annotations arrays were not installed into the Annotations object,
6033 // then they have to be deallocated explicitly.
6078 cp_size, CHECK);
6079
6080 _orig_cp_size = cp_size;
6081 if (is_hidden()) { // Add a slot for hidden class name.
6082 cp_size++;
6083 }
6084
6085 _cp = ConstantPool::allocate(_loader_data,
6086 cp_size,
6087 CHECK);
6088
6089 ConstantPool* const cp = _cp;
6090
6091 parse_constant_pool(stream, cp, _orig_cp_size, CHECK);
6092
6093 assert(cp_size == (u2)cp->length(), "invariant");
6094
6095 // ACCESS FLAGS
6096 stream->guarantee_more(8, CHECK); // flags, this_class, super_class, infs_len
6097
6098 jint recognized_modifiers = JVM_RECOGNIZED_CLASS_MODIFIERS;
6099 // JVM_ACC_MODULE is defined in JDK-9 and later.
6100 if (_major_version >= JAVA_9_VERSION) {
6101 recognized_modifiers |= JVM_ACC_MODULE;
6102 }
6103
6104 // Access flags
6105 jint flags = stream->get_u2_fast() & recognized_modifiers;
6106
6107 if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
6108 // Set abstract bit for old class files for backward compatibility
6109 flags |= JVM_ACC_ABSTRACT;
6110 }
6111
6112 // Fixing ACC_SUPER/ACC_IDENTITY for old class files
6113 if (!supports_inline_types()) {
6114 const bool is_module = (flags & JVM_ACC_MODULE) != 0;
6115 const bool is_interface = (flags & JVM_ACC_INTERFACE) != 0;
6116 if (!is_module && !is_interface) {
6117 flags |= JVM_ACC_IDENTITY;
6118 }
6119 }
6120
6121
6122 // This class and superclass
6123 _this_class_index = stream->get_u2_fast();
6124 check_property(
6125 valid_cp_range(_this_class_index, cp_size) &&
6126 cp->tag_at(_this_class_index).is_unresolved_klass(),
6127 "Invalid this class index %u in constant pool in class file %s",
6128 _this_class_index, CHECK);
6129
6130 Symbol* const class_name_in_cp = cp->klass_name_at(_this_class_index);
6131 assert(class_name_in_cp != nullptr, "class_name can't be null");
6132
6133 bool is_java_lang_Object = class_name_in_cp == vmSymbols::java_lang_Object();
6134
6135 verify_legal_class_modifiers(flags, nullptr, is_java_lang_Object, CHECK);
6136
6137 _access_flags.set_flags(flags);
6138
6139 short bad_constant = class_bad_constant_seen();
6140 if (bad_constant != 0) {
6141 // Do not throw CFE until after the access_flags are checked because if
6142 // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
6143 classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, THREAD);
6144 return;
6145 }
6146
6147 // Don't need to check whether this class name is legal or not.
6148 // It has been checked when constant pool is parsed.
6149 // However, make sure it is not an array type.
6150 if (_need_verify) {
6151 guarantee_property(class_name_in_cp->char_at(0) != JVM_SIGNATURE_ARRAY,
6152 "Bad class name in class file %s",
6153 CHECK);
6154 }
6155
6156 #ifdef ASSERT
6157 // Basic sanity checks
6158 if (_is_hidden) {
6159 assert(_class_name != vmSymbols::unknown_class_name(), "hidden classes should have a special name");
6160 }
6161 #endif
6162
6163 // Update the _class_name as needed depending on whether this is a named, un-named, or hidden class.
6164
6165 if (_is_hidden) {
6166 assert(_class_name != nullptr, "Unexpected null _class_name");
6206 }
6207 ls.cr();
6208 }
6209 }
6210
6211 // SUPERKLASS
6212 _super_class_index = stream->get_u2_fast();
6213 _super_klass = parse_super_class(cp,
6214 _super_class_index,
6215 _need_verify,
6216 CHECK);
6217
6218 // Interfaces
6219 _itfs_len = stream->get_u2_fast();
6220 parse_interfaces(stream,
6221 _itfs_len,
6222 cp,
6223 &_has_nonstatic_concrete_methods,
6224 CHECK);
6225
6226 // Fields (offsets are filled in later)
6227 _fac = new FieldAllocationCount();
6228 parse_fields(stream,
6229 _access_flags,
6230 _fac,
6231 cp,
6232 cp_size,
6233 &_java_fields_count,
6234 CHECK);
6235
6236 assert(_temp_field_info != nullptr, "invariant");
6237
6238 // Methods
6239 parse_methods(stream,
6240 is_interface(),
6241 !is_identity_class(),
6242 is_abstract_class(),
6243 &_has_localvariable_table,
6244 &_has_final_method,
6245 &_declares_nonstatic_concrete_methods,
6246 CHECK);
6247
6248 assert(_methods != nullptr, "invariant");
6249
6250 if (_declares_nonstatic_concrete_methods) {
6251 _has_nonstatic_concrete_methods = true;
6252 }
6253
6254 // Additional attributes/annotations
6255 _parsed_annotations = new ClassAnnotationCollector();
6256 parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK);
6257
6258 assert(_inner_classes != nullptr, "invariant");
6259
6260 // Finalize the Annotations metadata object,
6261 // now that all annotation arrays have been created.
6262 create_combined_annotations(CHECK);
6302 // Update this_class_index's slot in the constant pool with the new Utf8 entry.
6303 // We have to update the resolved_klass_index and the name_index together
6304 // so extract the existing resolved_klass_index first.
6305 CPKlassSlot cp_klass_slot = _cp->klass_slot_at(_this_class_index);
6306 int resolved_klass_index = cp_klass_slot.resolved_klass_index();
6307 _cp->unresolved_klass_at_put(_this_class_index, hidden_index, resolved_klass_index);
6308 assert(_cp->klass_slot_at(_this_class_index).name_index() == _orig_cp_size,
6309 "Bad name_index");
6310 }
6311
6312 void ClassFileParser::post_process_parsed_stream(const ClassFileStream* const stream,
6313 ConstantPool* cp,
6314 TRAPS) {
6315 assert(stream != nullptr, "invariant");
6316 assert(stream->at_eos(), "invariant");
6317 assert(cp != nullptr, "invariant");
6318 assert(_loader_data != nullptr, "invariant");
6319
6320 if (_class_name == vmSymbols::java_lang_Object()) {
6321 check_property(_local_interfaces == Universe::the_empty_instance_klass_array(),
6322 "java.lang.Object cannot implement an interface in class file %s",
6323 CHECK);
6324 }
6325 // We check super class after class file is parsed and format is checked
6326 if (_super_class_index > 0 && nullptr == _super_klass) {
6327 Symbol* const super_class_name = cp->klass_name_at(_super_class_index);
6328 if (is_interface()) {
6329 // Before attempting to resolve the superclass, check for class format
6330 // errors not checked yet.
6331 guarantee_property(super_class_name == vmSymbols::java_lang_Object(),
6332 "Interfaces must have java.lang.Object as superclass in class file %s",
6333 CHECK);
6334 }
6335 Handle loader(THREAD, _loader_data->class_loader());
6336 if (loader.is_null() && super_class_name == vmSymbols::java_lang_Object()) {
6337 _super_klass = vmClasses::Object_klass();
6338 } else {
6339 _super_klass = (const InstanceKlass*)
6340 SystemDictionary::resolve_with_circularity_detection_or_fail(_class_name,
6341 super_class_name,
6342 loader,
6343 _protection_domain,
6344 true,
6345 CHECK);
6346 }
6347 }
6348
6349 if (_super_klass != nullptr) {
6350 if (_super_klass->is_interface()) {
6351 classfile_icce_error("class %s has interface %s as super class", _super_klass, THREAD);
6352 return;
6353 }
6354
6355 if (_super_klass->is_final()) {
6356 classfile_icce_error("class %s cannot inherit from final class %s", _super_klass, THREAD);
6357 return;
6358 }
6359
6360 if (EnableValhalla) {
6361 check_identity_and_value_modifiers(this, _super_klass, CHECK);
6362 }
6363
6364 if (_super_klass->has_nonstatic_concrete_methods()) {
6365 _has_nonstatic_concrete_methods = true;
6366 }
6367 }
6368
6369 if (_parsed_annotations->has_annotation(AnnotationCollector::_jdk_internal_LooselyConsistentValue) && _access_flags.is_identity_class()) {
6370 THROW_MSG(vmSymbols::java_lang_ClassFormatError(),
6371 err_msg("class %s cannot have annotation jdk.internal.vm.annotation.LooselyConsistentValue, because it is not a value class",
6372 _class_name->as_klass_external_name()));
6373 }
6374 if (_parsed_annotations->has_annotation(AnnotationCollector::_jdk_internal_ImplicitlyConstructible) && _access_flags.is_identity_class()) {
6375 THROW_MSG(vmSymbols::java_lang_ClassFormatError(),
6376 err_msg("class %s cannot have annotation jdk.internal.vm.annotation.ImplicitlyConstructible, because it is not a value class",
6377 _class_name->as_klass_external_name()));
6378 }
6379
6380 // Determining is the class allows tearing or not (default is not)
6381 // Test might need extensions when field inheritance is added for value classes
6382 if (EnableValhalla && !_access_flags.is_identity_class()) {
6383 if (_parsed_annotations->has_annotation(ClassAnnotationCollector::_jdk_internal_LooselyConsistentValue)
6384 && (_super_klass == vmClasses::Object_klass() || !_super_klass->must_be_atomic())) {
6385 _must_be_atomic = false;
6386 }
6387 if (_parsed_annotations->has_annotation(ClassAnnotationCollector::_jdk_internal_ImplicitlyConstructible)
6388 && (_super_klass == vmClasses::Object_klass() || _super_klass->is_implicitly_constructible())) {
6389 _is_implicitly_constructible = true;
6390 }
6391 // Apply VM options override
6392 if (*ForceNonTearable != '\0') {
6393 // Allow a command line switch to force the same atomicity property:
6394 const char* class_name_str = _class_name->as_C_string();
6395 if (StringUtils::class_list_match(ForceNonTearable, class_name_str)) {
6396 _must_be_atomic = true;
6397 }
6398 }
6399 }
6400
6401 int itfs_len = _local_interface_indexes == nullptr ? 0 : _local_interface_indexes->length();
6402 _local_interfaces = MetadataFactory::new_array<InstanceKlass*>(_loader_data, itfs_len, nullptr, CHECK);
6403 if (_local_interface_indexes != nullptr) {
6404 for (int i = 0; i < _local_interface_indexes->length(); i++) {
6405 u2 interface_index = _local_interface_indexes->at(i);
6406 Klass* interf;
6407 if (cp->tag_at(interface_index).is_klass()) {
6408 interf = cp->resolved_klass_at(interface_index);
6409 } else {
6410 Symbol* const unresolved_klass = cp->klass_name_at(interface_index);
6411
6412 // Don't need to check legal name because it's checked when parsing constant pool.
6413 // But need to make sure it's not an array type.
6414 guarantee_property(unresolved_klass->char_at(0) != JVM_SIGNATURE_ARRAY,
6415 "Bad interface name in class file %s", CHECK);
6416
6417 // Call resolve_super so class circularity is checked
6418 interf = SystemDictionary::resolve_with_circularity_detection_or_fail(
6419 _class_name,
6420 unresolved_klass,
6421 Handle(THREAD, _loader_data->class_loader()),
6422 _protection_domain,
6423 false,
6424 CHECK);
6425 }
6426
6427 if (!interf->is_interface()) {
6428 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
6429 err_msg("class %s can not implement %s, because it is not an interface (%s)",
6430 _class_name->as_klass_external_name(),
6431 interf->external_name(),
6432 interf->class_in_module_of_loader()));
6433 }
6434
6435 if (EnableValhalla) {
6436 // Check modifiers and set carries_identity_modifier/carries_value_modifier flags
6437 check_identity_and_value_modifiers(this, InstanceKlass::cast(interf), CHECK);
6438 }
6439
6440 if (InstanceKlass::cast(interf)->has_nonstatic_concrete_methods()) {
6441 _has_nonstatic_concrete_methods = true;
6442 }
6443 _local_interfaces->at_put(i, InstanceKlass::cast(interf));
6444 }
6445 }
6446 assert(_local_interfaces != nullptr, "invariant");
6447
6448 // Compute the transitive list of all unique interfaces implemented by this class
6449 _transitive_interfaces =
6450 compute_transitive_interfaces(_super_klass,
6451 _local_interfaces,
6452 _loader_data,
6453 CHECK);
6454
6455 assert(_transitive_interfaces != nullptr, "invariant");
6456
6457 // sort methods
6458 _method_ordering = sort_methods(_methods);
6459
6460 _all_mirandas = new GrowableArray<Method*>(20);
6461
6462 Handle loader(THREAD, _loader_data->class_loader());
6463 klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
6464 &_num_miranda_methods,
6465 _all_mirandas,
6466 _super_klass,
6467 _methods,
6468 _access_flags,
6469 _major_version,
6470 loader,
6471 _class_name,
6472 _local_interfaces);
6473
6474 // Size of Java itable (in words)
6475 _itable_size = is_interface() ? 0 :
6476 klassItable::compute_itable_size(_transitive_interfaces);
6477
6478 assert(_fac != nullptr, "invariant");
6479 assert(_parsed_annotations != nullptr, "invariant");
6480
6481 if (EnableValhalla) {
6482 _inline_type_field_klasses = MetadataFactory::new_array<InlineKlass*>(_loader_data,
6483 java_fields_count(),
6484 nullptr,
6485 CHECK);
6486 for (GrowableArrayIterator<FieldInfo> it = _temp_field_info->begin(); it != _temp_field_info->end(); ++it) {
6487 FieldInfo fieldinfo = *it;
6488 if (fieldinfo.access_flags().is_static()) continue; // Only non-static fields are processed at load time
6489 Symbol* sig = fieldinfo.signature(cp);
6490 if (fieldinfo.field_flags().is_null_free_inline_type()) {
6491 // Pre-load classes of null-free fields that are candidate for flattening
6492 TempNewSymbol s = Signature::strip_envelope(sig);
6493 if (s == _class_name) {
6494 THROW_MSG(vmSymbols::java_lang_ClassCircularityError(), err_msg("Class %s cannot have a null-free non-static field of its own type", _class_name->as_C_string()));
6495 }
6496 log_info(class, preload)("Preloading class %s during loading of class %s. Cause: a null-free non-static field is declared with this type", s->as_C_string(), _class_name->as_C_string());
6497 Klass* klass = SystemDictionary::resolve_with_circularity_detection_or_fail(_class_name, s, Handle(THREAD, _loader_data->class_loader()), _protection_domain, false, THREAD);
6498 if (HAS_PENDING_EXCEPTION) {
6499 log_warning(class, preload)("Preloading of class %s during loading of class %s (cause: null-free non-static field) failed: %s",
6500 s->as_C_string(), _class_name->as_C_string(), PENDING_EXCEPTION->klass()->name()->as_C_string());
6501 return; // Exception is still pending
6502 }
6503 assert(klass != nullptr, "Sanity check");
6504 if (klass->access_flags().is_identity_class()) {
6505 assert(klass->is_instance_klass(), "Sanity check");
6506 ResourceMark rm(THREAD);
6507 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
6508 err_msg("Class %s expects class %s to be a value class, but it is an identity class",
6509 _class_name->as_C_string(),
6510 InstanceKlass::cast(klass)->external_name()));
6511 }
6512 if (klass->is_abstract()) {
6513 assert(klass->is_instance_klass(), "Sanity check");
6514 ResourceMark rm(THREAD);
6515 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
6516 err_msg("Class %s expects class %s to be concrete value type, but it is an abstract class",
6517 _class_name->as_C_string(),
6518 InstanceKlass::cast(klass)->external_name()));
6519 }
6520 InlineKlass* vk = InlineKlass::cast(klass);
6521 if (!vk->is_implicitly_constructible()) {
6522 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
6523 err_msg("class %s is not implicitly constructible and it is used in a null restricted non-static field (not supported)",
6524 klass->name()->as_C_string()));
6525 }
6526 _inline_type_field_klasses->at_put(fieldinfo.index(), vk);
6527 log_info(class, preload)("Preloading of class %s during loading of class %s (cause: null-free non-static field) succeeded", s->as_C_string(), _class_name->as_C_string());
6528 } else if (Signature::has_envelope(sig)) {
6529 // Preloading classes for nullable fields that are listed in the LoadableDescriptors attribute
6530 // Those classes would be required later for the flattening of nullable inline type fields
6531 TempNewSymbol name = Signature::strip_envelope(sig);
6532 if (name != _class_name && is_class_in_loadable_descriptors_attribute(sig)) {
6533 log_info(class, preload)("Preloading class %s during loading of class %s. Cause: field type in LoadableDescriptors attribute", name->as_C_string(), _class_name->as_C_string());
6534 oop loader = loader_data()->class_loader();
6535 Klass* klass = SystemDictionary::resolve_with_circularity_detection_or_fail(_class_name, name, Handle(THREAD, loader), _protection_domain, false, THREAD);
6536 if (klass != nullptr) {
6537 if (klass->is_inline_klass()) {
6538 _inline_type_field_klasses->at_put(fieldinfo.index(), InlineKlass::cast(klass));
6539 log_info(class, preload)("Preloading of class %s during loading of class %s (cause: field type in LoadableDescriptors attribute) succeeded", name->as_C_string(), _class_name->as_C_string());
6540 } else {
6541 // Non value class are allowed by the current spec, but it could be an indication of an issue so let's log a warning
6542 log_warning(class, preload)("Preloading class %s during loading of class %s (cause: field type in LoadableDescriptors attribute) but loaded class is not a value class", name->as_C_string(), _class_name->as_C_string());
6543 }
6544 } else {
6545 log_warning(class, preload)("Preloading of class %s during loading of class %s (cause: field type in LoadableDescriptors attribute) failed : %s",
6546 name->as_C_string(), _class_name->as_C_string(), PENDING_EXCEPTION->klass()->name()->as_C_string());
6547 }
6548 // Loads triggered by the LoadableDescriptors attribute are speculative, failures must not impact loading of current class
6549 if (HAS_PENDING_EXCEPTION) {
6550 CLEAR_PENDING_EXCEPTION;
6551 }
6552 }
6553 }
6554 }
6555 }
6556
6557 _field_info = new FieldLayoutInfo();
6558 FieldLayoutBuilder lb(class_name(), loader_data(), super_klass(), _cp, /*_fields*/ _temp_field_info,
6559 _parsed_annotations->is_contended(), is_inline_type(),
6560 access_flags().is_abstract() && !access_flags().is_identity_class() && !access_flags().is_interface(),
6561 _field_info, _inline_type_field_klasses);
6562 lb.build_layout();
6563 if (is_inline_type()) {
6564 _alignment = lb.get_alignment();
6565 _first_field_offset = lb.get_first_field_offset();
6566 _payload_size_in_bytes = lb.get_payload_size_in_byte();
6567 _internal_null_marker_offset = lb.get_internal_null_marker_offset();
6568 }
6569 _has_inline_type_fields = _field_info->_has_inline_fields;
6570
6571 int injected_fields_count = _temp_field_info->length() - _java_fields_count;
6572 _fieldinfo_stream =
6573 FieldInfoStream::create_FieldInfoStream(_temp_field_info, _java_fields_count,
6574 injected_fields_count, loader_data(), CHECK);
6575
6576 _fields_status =
6577 MetadataFactory::new_array<FieldStatus>(_loader_data, _temp_field_info->length(),
6578 FieldStatus(0), CHECK);
6579 if (_field_info->_has_null_marker_offsets) {
6580 int idx = 0;
6581 _null_marker_offsets = MetadataFactory::new_array<int>(_loader_data, _temp_field_info->length(), 0, CHECK);
6582 for (GrowableArrayIterator<FieldInfo> it = _temp_field_info->begin(); it != _temp_field_info->end(); ++it, ++idx) {
6583 FieldInfo fieldinfo = *it;
6584 if (fieldinfo.field_flags().has_null_marker()) {
6585 assert(fieldinfo.null_marker_offset() != 0, "Invalid value");
6586 _null_marker_offsets->at_put(idx, fieldinfo.null_marker_offset());
6587 }
6588 }
6589 }
6590 }
6591
6592 void ClassFileParser::set_klass(InstanceKlass* klass) {
6593
6594 #ifdef ASSERT
6595 if (klass != nullptr) {
6596 assert(nullptr == _klass, "leaking?");
6597 }
6598 #endif
6599
6600 _klass = klass;
6601 }
6602
6603 void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) {
6604
6605 #ifdef ASSERT
6606 if (klass != nullptr) {
6607 assert(nullptr == _klass_to_deallocate, "leaking?");
6608 }
6609 #endif
|