1 /*
2 * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "cds/cdsConfig.hpp"
26 #include "classfile/classFileParser.hpp"
27 #include "classfile/classFileStream.hpp"
28 #include "classfile/classLoader.hpp"
29 #include "classfile/classLoaderData.inline.hpp"
30 #include "classfile/classLoadInfo.hpp"
31 #include "classfile/defaultMethods.hpp"
32 #include "classfile/fieldLayoutBuilder.hpp"
33 #include "classfile/javaClasses.inline.hpp"
34 #include "classfile/moduleEntry.hpp"
35 #include "classfile/packageEntry.hpp"
36 #include "classfile/symbolTable.hpp"
37 #include "classfile/systemDictionary.hpp"
38 #include "classfile/verificationType.hpp"
39 #include "classfile/verifier.hpp"
40 #include "classfile/vmClasses.hpp"
41 #include "classfile/vmSymbols.hpp"
42 #include "jvm.h"
43 #include "logging/log.hpp"
44 #include "logging/logStream.hpp"
45 #include "memory/allocation.hpp"
46 #include "memory/metadataFactory.hpp"
47 #include "memory/oopFactory.hpp"
48 #include "memory/resourceArea.hpp"
49 #include "memory/universe.hpp"
50 #include "oops/annotations.hpp"
51 #include "oops/bsmAttribute.inline.hpp"
52 #include "oops/constantPool.inline.hpp"
53 #include "oops/fieldInfo.hpp"
54 #include "oops/fieldStreams.inline.hpp"
55 #include "oops/inlineKlass.inline.hpp"
56 #include "oops/instanceKlass.inline.hpp"
57 #include "oops/instanceMirrorKlass.hpp"
58 #include "oops/klass.inline.hpp"
59 #include "oops/klassVtable.hpp"
60 #include "oops/metadata.hpp"
61 #include "oops/method.inline.hpp"
62 #include "oops/oop.inline.hpp"
63 #include "oops/recordComponent.hpp"
64 #include "oops/symbol.hpp"
65 #include "prims/jvmtiExport.hpp"
66 #include "prims/jvmtiThreadState.hpp"
67 #include "runtime/arguments.hpp"
68 #include "runtime/fieldDescriptor.inline.hpp"
69 #include "runtime/handles.inline.hpp"
70 #include "runtime/javaCalls.hpp"
71 #include "runtime/os.hpp"
72 #include "runtime/perfData.hpp"
73 #include "runtime/reflection.hpp"
74 #include "runtime/safepointVerifiers.hpp"
75 #include "runtime/signature.hpp"
76 #include "runtime/timer.hpp"
77 #include "services/classLoadingService.hpp"
78 #include "services/threadService.hpp"
79 #include "utilities/align.hpp"
80 #include "utilities/bitMap.inline.hpp"
81 #include "utilities/checkedCast.hpp"
82 #include "utilities/copy.hpp"
83 #include "utilities/exceptions.hpp"
84 #include "utilities/formatBuffer.hpp"
85 #include "utilities/globalDefinitions.hpp"
86 #include "utilities/growableArray.hpp"
87 #include "utilities/hashTable.hpp"
88 #include "utilities/macros.hpp"
89 #include "utilities/ostream.hpp"
90 #include "utilities/stringUtils.hpp"
91 #include "utilities/utf8.hpp"
92 #if INCLUDE_CDS
93 #include "classfile/systemDictionaryShared.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:
108 // - to check for new additions to the class file format in JDK1.5
109 // - to check for bug fixes in the format checker in JDK1.5
110 #define JAVA_1_5_VERSION 49
111
112 // Used for backward compatibility reasons:
113 // - to check for javac bug fixes that happened after 1.5
114 // - also used as the max version when running in jdk6
115 #define JAVA_6_VERSION 50
116
117 // Used for backward compatibility reasons:
118 // - to disallow argument and require ACC_STATIC for <clinit> methods
119 #define JAVA_7_VERSION 51
120
121 // Extension method support.
122 #define JAVA_8_VERSION 52
123
124 #define JAVA_9_VERSION 53
125
126 #define JAVA_10_VERSION 54
127
128 #define JAVA_11_VERSION 55
129
130 #define JAVA_12_VERSION 56
131
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 #define JAVA_24_VERSION 68
155
156 #define JAVA_25_VERSION 69
157
158 #define JAVA_26_VERSION 70
159
160 #define JAVA_27_VERSION 71
161
162 void ClassFileParser::set_class_bad_constant_seen(short bad_constant) {
163 assert((bad_constant == JVM_CONSTANT_Module ||
164 bad_constant == JVM_CONSTANT_Package) && _major_version >= JAVA_9_VERSION,
165 "Unexpected bad constant pool entry");
166 if (_bad_constant_seen == 0) _bad_constant_seen = bad_constant;
167 }
168
169 void ClassFileParser::parse_constant_pool_entries(const ClassFileStream* const stream,
170 ConstantPool* cp,
171 const int length,
172 TRAPS) {
173 assert(stream != nullptr, "invariant");
174 assert(cp != nullptr, "invariant");
175
176 // Use a local copy of ClassFileStream. It helps the C++ compiler to optimize
177 // this function (_current can be allocated in a register, with scalar
178 // replacement of aggregates). The _current pointer is copied back to
179 // stream() when this function returns. DON'T call another method within
180 // this method that uses stream().
181 const ClassFileStream cfs1 = *stream;
182 const ClassFileStream* const cfs = &cfs1;
183
184 DEBUG_ONLY(const u1* const old_current = stream->current();)
185
186 // Used for batching symbol allocations.
187 const char* names[SymbolTable::symbol_alloc_batch_size];
188 int lengths[SymbolTable::symbol_alloc_batch_size];
189 int indices[SymbolTable::symbol_alloc_batch_size];
190 unsigned int hashValues[SymbolTable::symbol_alloc_batch_size];
191 int names_count = 0;
192
193 // parsing Index 0 is unused
194 for (int index = 1; index < length; index++) {
195 // Each of the following case guarantees one more byte in the stream
196 // for the following tag or the access_flags following constant pool,
197 // so we don't need bounds-check for reading tag.
198 const u1 tag = cfs->get_u1_fast();
199 switch (tag) {
200 case JVM_CONSTANT_Class: {
201 cfs->guarantee_more(3, CHECK); // name_index, tag/access_flags
202 const u2 name_index = cfs->get_u2_fast();
203 cp->klass_index_at_put(index, name_index);
204 break;
205 }
206 case JVM_CONSTANT_Fieldref: {
207 cfs->guarantee_more(5, CHECK); // class_index, name_and_type_index, tag/access_flags
208 const u2 class_index = cfs->get_u2_fast();
209 const u2 name_and_type_index = cfs->get_u2_fast();
210 cp->field_at_put(index, class_index, name_and_type_index);
211 break;
212 }
213 case JVM_CONSTANT_Methodref: {
214 cfs->guarantee_more(5, CHECK); // class_index, name_and_type_index, tag/access_flags
215 const u2 class_index = cfs->get_u2_fast();
216 const u2 name_and_type_index = cfs->get_u2_fast();
217 cp->method_at_put(index, class_index, name_and_type_index);
218 break;
219 }
220 case JVM_CONSTANT_InterfaceMethodref: {
221 cfs->guarantee_more(5, CHECK); // class_index, name_and_type_index, tag/access_flags
222 const u2 class_index = cfs->get_u2_fast();
223 const u2 name_and_type_index = cfs->get_u2_fast();
224 cp->interface_method_at_put(index, class_index, name_and_type_index);
225 break;
226 }
227 case JVM_CONSTANT_String : {
228 cfs->guarantee_more(3, CHECK); // string_index, tag/access_flags
229 const u2 string_index = cfs->get_u2_fast();
230 cp->string_index_at_put(index, string_index);
231 break;
232 }
233 case JVM_CONSTANT_MethodHandle :
234 case JVM_CONSTANT_MethodType: {
235 if (_major_version < Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {
236 classfile_parse_error(
237 "Class file version does not support constant tag %u in class file %s",
238 tag, THREAD);
239 return;
240 }
241 if (tag == JVM_CONSTANT_MethodHandle) {
242 cfs->guarantee_more(4, CHECK); // ref_kind, method_index, tag/access_flags
243 const u1 ref_kind = cfs->get_u1_fast();
244 const u2 method_index = cfs->get_u2_fast();
245 cp->method_handle_index_at_put(index, ref_kind, method_index);
246 }
247 else if (tag == JVM_CONSTANT_MethodType) {
248 cfs->guarantee_more(3, CHECK); // signature_index, tag/access_flags
249 const u2 signature_index = cfs->get_u2_fast();
250 cp->method_type_index_at_put(index, signature_index);
251 }
252 else {
253 ShouldNotReachHere();
254 }
255 break;
256 }
257 case JVM_CONSTANT_Dynamic : {
258 if (_major_version < Verifier::DYNAMICCONSTANT_MAJOR_VERSION) {
259 classfile_parse_error(
260 "Class file version does not support constant tag %u in class file %s",
261 tag, THREAD);
262 return;
263 }
264 cfs->guarantee_more(5, CHECK); // bsm_index, nt, tag/access_flags
265 const u2 bootstrap_specifier_index = cfs->get_u2_fast();
266 const u2 name_and_type_index = cfs->get_u2_fast();
267 if (_max_bootstrap_specifier_index < (int) bootstrap_specifier_index) {
268 _max_bootstrap_specifier_index = (int) bootstrap_specifier_index; // collect for later
269 }
270 cp->dynamic_constant_at_put(index, bootstrap_specifier_index, name_and_type_index);
271 break;
272 }
273 case JVM_CONSTANT_InvokeDynamic : {
274 if (_major_version < Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {
275 classfile_parse_error(
276 "Class file version does not support constant tag %u in class file %s",
277 tag, THREAD);
278 return;
279 }
280 cfs->guarantee_more(5, CHECK); // bsm_index, nt, tag/access_flags
281 const u2 bootstrap_specifier_index = cfs->get_u2_fast();
282 const u2 name_and_type_index = cfs->get_u2_fast();
283 if (_max_bootstrap_specifier_index < (int) bootstrap_specifier_index) {
284 _max_bootstrap_specifier_index = (int) bootstrap_specifier_index; // collect for later
285 }
286 cp->invoke_dynamic_at_put(index, bootstrap_specifier_index, name_and_type_index);
287 break;
288 }
289 case JVM_CONSTANT_Integer: {
290 cfs->guarantee_more(5, CHECK); // bytes, tag/access_flags
291 const u4 bytes = cfs->get_u4_fast();
292 cp->int_at_put(index, (jint)bytes);
293 break;
294 }
295 case JVM_CONSTANT_Float: {
296 cfs->guarantee_more(5, CHECK); // bytes, tag/access_flags
297 const u4 bytes = cfs->get_u4_fast();
298 cp->float_at_put(index, *(jfloat*)&bytes);
299 break;
300 }
301 case JVM_CONSTANT_Long: {
302 // A mangled type might cause you to overrun allocated memory
303 guarantee_property(index + 1 < length,
304 "Invalid constant pool entry %u in class file %s",
305 index,
306 CHECK);
307 cfs->guarantee_more(9, CHECK); // bytes, tag/access_flags
308 const u8 bytes = cfs->get_u8_fast();
309 cp->long_at_put(index, bytes);
310 index++; // Skip entry following eigth-byte constant, see JVM book p. 98
311 break;
312 }
313 case JVM_CONSTANT_Double: {
314 // A mangled type might cause you to overrun allocated memory
315 guarantee_property(index+1 < length,
316 "Invalid constant pool entry %u in class file %s",
317 index,
318 CHECK);
319 cfs->guarantee_more(9, CHECK); // bytes, tag/access_flags
320 const u8 bytes = cfs->get_u8_fast();
321 cp->double_at_put(index, *(jdouble*)&bytes);
322 index++; // Skip entry following eigth-byte constant, see JVM book p. 98
323 break;
324 }
325 case JVM_CONSTANT_NameAndType: {
326 cfs->guarantee_more(5, CHECK); // name_index, signature_index, tag/access_flags
327 const u2 name_index = cfs->get_u2_fast();
328 const u2 signature_index = cfs->get_u2_fast();
329 cp->name_and_type_at_put(index, name_index, signature_index);
330 break;
331 }
332 case JVM_CONSTANT_Utf8 : {
333 cfs->guarantee_more(2, CHECK); // utf8_length
334 u2 utf8_length = cfs->get_u2_fast();
335 const u1* utf8_buffer = cfs->current();
336 assert(utf8_buffer != nullptr, "null utf8 buffer");
337 // Got utf8 string, guarantee utf8_length+1 bytes, set stream position forward.
338 cfs->guarantee_more(utf8_length+1, CHECK); // utf8 string, tag/access_flags
339 cfs->skip_u1_fast(utf8_length);
340
341 // Before storing the symbol, make sure it's legal
342 if (_need_verify) {
343 verify_legal_utf8(utf8_buffer, utf8_length, CHECK);
344 }
345
346 unsigned int hash;
347 Symbol* const result = SymbolTable::lookup_only((const char*)utf8_buffer,
348 utf8_length,
349 hash);
350 if (result == nullptr) {
351 names[names_count] = (const char*)utf8_buffer;
352 lengths[names_count] = utf8_length;
353 indices[names_count] = index;
354 hashValues[names_count++] = hash;
355 if (names_count == SymbolTable::symbol_alloc_batch_size) {
356 SymbolTable::new_symbols(_loader_data,
357 constantPoolHandle(THREAD, cp),
358 names_count,
359 names,
360 lengths,
361 indices,
362 hashValues);
363 names_count = 0;
364 }
365 } else {
366 cp->symbol_at_put(index, result);
367 }
368 break;
369 }
370 case JVM_CONSTANT_Module:
371 case JVM_CONSTANT_Package: {
372 // Record that an error occurred in these two cases but keep parsing so
373 // that ACC_Module can be checked for in the access_flags. Need to
374 // throw NoClassDefFoundError in that case.
375 if (_major_version >= JAVA_9_VERSION) {
376 cfs->guarantee_more(3, CHECK);
377 cfs->get_u2_fast();
378 set_class_bad_constant_seen(tag);
379 break;
380 }
381 }
382 default: {
383 classfile_parse_error("Unknown constant tag %u in class file %s",
384 tag,
385 THREAD);
386 return;
387 }
388 } // end of switch(tag)
389 } // end of for
390
391 // Allocate the remaining symbols
392 if (names_count > 0) {
393 SymbolTable::new_symbols(_loader_data,
394 constantPoolHandle(THREAD, cp),
395 names_count,
396 names,
397 lengths,
398 indices,
399 hashValues);
400 }
401
402 // Copy _current pointer of local copy back to stream.
403 assert(stream->current() == old_current, "non-exclusive use of stream");
404 stream->set_current(cfs1.current());
405
406 }
407
408 static inline bool valid_cp_range(int index, int length) {
409 return (index > 0 && index < length);
410 }
411
412 static inline Symbol* check_symbol_at(const ConstantPool* cp, int index) {
413 assert(cp != nullptr, "invariant");
414 if (valid_cp_range(index, cp->length()) && cp->tag_at(index).is_utf8()) {
415 return cp->symbol_at(index);
416 }
417 return nullptr;
418 }
419
420 void ClassFileParser::parse_constant_pool(const ClassFileStream* const stream,
421 ConstantPool* const cp,
422 const int length,
423 TRAPS) {
424 assert(cp != nullptr, "invariant");
425 assert(stream != nullptr, "invariant");
426
427 // parsing constant pool entries
428 parse_constant_pool_entries(stream, cp, length, CHECK);
429 if (class_bad_constant_seen() != 0) {
430 // a bad CP entry has been detected previously so stop parsing and just return.
431 return;
432 }
433
434 int index = 1; // declared outside of loops for portability
435 int num_klasses = 0;
436
437 // first verification pass - validate cross references
438 // and fixup class and string constants
439 for (index = 1; index < length; index++) { // Index 0 is unused
440 const jbyte tag = cp->tag_at(index).value();
441 switch (tag) {
442 case JVM_CONSTANT_Class: {
443 ShouldNotReachHere(); // Only JVM_CONSTANT_ClassIndex should be present
444 break;
445 }
446 case JVM_CONSTANT_Fieldref:
447 // fall through
448 case JVM_CONSTANT_Methodref:
449 // fall through
450 case JVM_CONSTANT_InterfaceMethodref: {
451 if (!_need_verify) break;
452 const int klass_ref_index = cp->uncached_klass_ref_index_at(index);
453 const int name_and_type_ref_index = cp->uncached_name_and_type_ref_index_at(index);
454 guarantee_property(valid_klass_reference_at(klass_ref_index),
455 "Invalid constant pool index %u in class file %s",
456 klass_ref_index, CHECK);
457 guarantee_property(valid_cp_range(name_and_type_ref_index, length) &&
458 cp->tag_at(name_and_type_ref_index).is_name_and_type(),
459 "Invalid constant pool index %u in class file %s",
460 name_and_type_ref_index, CHECK);
461 break;
462 }
463 case JVM_CONSTANT_String: {
464 ShouldNotReachHere(); // Only JVM_CONSTANT_StringIndex should be present
465 break;
466 }
467 case JVM_CONSTANT_Integer:
468 break;
469 case JVM_CONSTANT_Float:
470 break;
471 case JVM_CONSTANT_Long:
472 case JVM_CONSTANT_Double: {
473 index++;
474 guarantee_property(
475 (index < length && cp->tag_at(index).is_invalid()),
476 "Improper constant pool long/double index %u in class file %s",
477 index, CHECK);
478 break;
479 }
480 case JVM_CONSTANT_NameAndType: {
481 if (!_need_verify) break;
482 const int name_ref_index = cp->name_ref_index_at(index);
483 const int signature_ref_index = cp->signature_ref_index_at(index);
484 guarantee_property(valid_symbol_at(name_ref_index),
485 "Invalid constant pool index %u in class file %s",
486 name_ref_index, CHECK);
487 guarantee_property(valid_symbol_at(signature_ref_index),
488 "Invalid constant pool index %u in class file %s",
489 signature_ref_index, CHECK);
490 break;
491 }
492 case JVM_CONSTANT_Utf8:
493 break;
494 case JVM_CONSTANT_UnresolvedClass: // fall-through
495 case JVM_CONSTANT_UnresolvedClassInError: {
496 ShouldNotReachHere(); // Only JVM_CONSTANT_ClassIndex should be present
497 break;
498 }
499 case JVM_CONSTANT_ClassIndex: {
500 const int class_index = cp->klass_index_at(index);
501 guarantee_property(valid_symbol_at(class_index),
502 "Invalid constant pool index %u in class file %s",
503 class_index, CHECK);
504
505 Symbol* const name = cp->symbol_at(class_index);
506 const unsigned int name_len = name->utf8_length();
507 cp->unresolved_klass_at_put(index, class_index, num_klasses++);
508 break;
509 }
510 case JVM_CONSTANT_StringIndex: {
511 const int string_index = cp->string_index_at(index);
512 guarantee_property(valid_symbol_at(string_index),
513 "Invalid constant pool index %u in class file %s",
514 string_index, CHECK);
515 Symbol* const sym = cp->symbol_at(string_index);
516 cp->unresolved_string_at_put(index, sym);
517 break;
518 }
519 case JVM_CONSTANT_MethodHandle: {
520 const int ref_index = cp->method_handle_index_at(index);
521 guarantee_property(valid_cp_range(ref_index, length),
522 "Invalid constant pool index %u in class file %s",
523 ref_index, CHECK);
524 const constantTag tag = cp->tag_at(ref_index);
525 const int ref_kind = cp->method_handle_ref_kind_at(index);
526
527 switch (ref_kind) {
528 case JVM_REF_getField:
529 case JVM_REF_getStatic:
530 case JVM_REF_putField:
531 case JVM_REF_putStatic: {
532 guarantee_property(
533 tag.is_field(),
534 "Invalid constant pool index %u in class file %s (not a field)",
535 ref_index, CHECK);
536 break;
537 }
538 case JVM_REF_invokeVirtual:
539 case JVM_REF_newInvokeSpecial: {
540 guarantee_property(
541 tag.is_method(),
542 "Invalid constant pool index %u in class file %s (not a method)",
543 ref_index, CHECK);
544 break;
545 }
546 case JVM_REF_invokeStatic:
547 case JVM_REF_invokeSpecial: {
548 guarantee_property(
549 tag.is_method() ||
550 ((_major_version >= JAVA_8_VERSION) && tag.is_interface_method()),
551 "Invalid constant pool index %u in class file %s (not a method)",
552 ref_index, CHECK);
553 break;
554 }
555 case JVM_REF_invokeInterface: {
556 guarantee_property(
557 tag.is_interface_method(),
558 "Invalid constant pool index %u in class file %s (not an interface method)",
559 ref_index, CHECK);
560 break;
561 }
562 default: {
563 classfile_parse_error(
564 "Bad method handle kind at constant pool index %u in class file %s",
565 index, THREAD);
566 return;
567 }
568 } // switch(refkind)
569 // Keep the ref_index unchanged. It will be indirected at link-time.
570 break;
571 } // case MethodHandle
572 case JVM_CONSTANT_MethodType: {
573 const int ref_index = cp->method_type_index_at(index);
574 guarantee_property(valid_symbol_at(ref_index),
575 "Invalid constant pool index %u in class file %s",
576 ref_index, CHECK);
577 break;
578 }
579 case JVM_CONSTANT_Dynamic: {
580 const int name_and_type_ref_index =
581 cp->bootstrap_name_and_type_ref_index_at(index);
582
583 guarantee_property(valid_cp_range(name_and_type_ref_index, length) &&
584 cp->tag_at(name_and_type_ref_index).is_name_and_type(),
585 "Invalid constant pool index %u in class file %s",
586 name_and_type_ref_index, CHECK);
587 // bootstrap specifier index must be checked later,
588 // when BootstrapMethods attr is available
589
590 // Mark the constant pool as having a CONSTANT_Dynamic_info structure
591 cp->set_has_dynamic_constant();
592 break;
593 }
594 case JVM_CONSTANT_InvokeDynamic: {
595 const int name_and_type_ref_index =
596 cp->bootstrap_name_and_type_ref_index_at(index);
597
598 guarantee_property(valid_cp_range(name_and_type_ref_index, length) &&
599 cp->tag_at(name_and_type_ref_index).is_name_and_type(),
600 "Invalid constant pool index %u in class file %s",
601 name_and_type_ref_index, CHECK);
602 // bootstrap specifier index must be checked later,
603 // when BootstrapMethods attr is available
604 break;
605 }
606 default: {
607 fatal("bad constant pool tag value %u", cp->tag_at(index).value());
608 ShouldNotReachHere();
609 break;
610 }
611 } // switch(tag)
612 } // end of for
613
614 cp->allocate_resolved_klasses(_loader_data, num_klasses, CHECK);
615
616 if (!_need_verify) {
617 return;
618 }
619
620 // second verification pass - checks the strings are of the right format.
621 // but not yet to the other entries
622 for (index = 1; index < length; index++) {
623 const jbyte tag = cp->tag_at(index).value();
624 switch (tag) {
625 case JVM_CONSTANT_UnresolvedClass: {
626 const Symbol* const class_name = cp->klass_name_at(index);
627 // check the name
628 verify_legal_class_name(class_name, CHECK);
629 break;
630 }
631 case JVM_CONSTANT_NameAndType: {
632 if (_need_verify) {
633 const int sig_index = cp->signature_ref_index_at(index);
634 const int name_index = cp->name_ref_index_at(index);
635 const Symbol* const name = cp->symbol_at(name_index);
636 const Symbol* const sig = cp->symbol_at(sig_index);
637 guarantee_property(sig->utf8_length() != 0,
638 "Illegal zero length constant pool entry at %d in class %s",
639 sig_index, CHECK);
640 guarantee_property(name->utf8_length() != 0,
641 "Illegal zero length constant pool entry at %d in class %s",
642 name_index, CHECK);
643
644 if (Signature::is_method(sig)) {
645 // Format check method name and signature
646 verify_legal_method_name(name, CHECK);
647 verify_legal_method_signature(name, sig, CHECK);
648 } else {
649 // Format check field name and signature
650 verify_legal_field_name(name, CHECK);
651 verify_legal_field_signature(name, sig, CHECK);
652 }
653 }
654 break;
655 }
656 case JVM_CONSTANT_Dynamic: {
657 const int name_and_type_ref_index =
658 cp->uncached_name_and_type_ref_index_at(index);
659 // already verified to be utf8
660 const int name_ref_index =
661 cp->name_ref_index_at(name_and_type_ref_index);
662 // already verified to be utf8
663 const int signature_ref_index =
664 cp->signature_ref_index_at(name_and_type_ref_index);
665 const Symbol* const name = cp->symbol_at(name_ref_index);
666 const Symbol* const signature = cp->symbol_at(signature_ref_index);
667 if (_need_verify) {
668 // CONSTANT_Dynamic's name and signature are verified above, when iterating NameAndType_info.
669 // Need only to be sure signature is the right type.
670 if (Signature::is_method(signature)) {
671 throwIllegalSignature("CONSTANT_Dynamic", name, signature, CHECK);
672 }
673 }
674 break;
675 }
676 case JVM_CONSTANT_InvokeDynamic:
677 case JVM_CONSTANT_Fieldref:
678 case JVM_CONSTANT_Methodref:
679 case JVM_CONSTANT_InterfaceMethodref: {
680 const int name_and_type_ref_index =
681 cp->uncached_name_and_type_ref_index_at(index);
682 // already verified to be utf8
683 const int name_ref_index =
684 cp->name_ref_index_at(name_and_type_ref_index);
685 // already verified to be utf8
686 const int signature_ref_index =
687 cp->signature_ref_index_at(name_and_type_ref_index);
688 const Symbol* const name = cp->symbol_at(name_ref_index);
689 const Symbol* const signature = cp->symbol_at(signature_ref_index);
690 if (tag == JVM_CONSTANT_Fieldref) {
691 if (_need_verify) {
692 // Field name and signature are verified above, when iterating NameAndType_info.
693 // Need only to be sure signature is non-zero length and the right type.
694 if (Signature::is_method(signature)) {
695 throwIllegalSignature("Field", name, signature, CHECK);
696 }
697 }
698 } else {
699 if (_need_verify) {
700 // Method name and signature are individually verified above, when iterating
701 // NameAndType_info. Need to check here that signature is non-zero length and
702 // the right type.
703 if (!Signature::is_method(signature)) {
704 throwIllegalSignature("Method", name, signature, CHECK);
705 }
706 }
707 // If a class method name begins with '<', it must be "<init>" and have void signature.
708 const unsigned int name_len = name->utf8_length();
709 if (tag == JVM_CONSTANT_Methodref && name_len != 0 &&
710 name->char_at(0) == JVM_SIGNATURE_SPECIAL) {
711 if (name != vmSymbols::object_initializer_name()) {
712 classfile_parse_error(
713 "Bad method name at constant pool index %u in class file %s",
714 name_ref_index, THREAD);
715 return;
716 } else if (!Signature::is_void_method(signature)) { // must have void signature.
717 throwIllegalSignature("Method", name, signature, CHECK);
718 }
719 }
720 }
721 break;
722 }
723 case JVM_CONSTANT_MethodHandle: {
724 const int ref_index = cp->method_handle_index_at(index);
725 const int ref_kind = cp->method_handle_ref_kind_at(index);
726 switch (ref_kind) {
727 case JVM_REF_invokeVirtual:
728 case JVM_REF_invokeStatic:
729 case JVM_REF_invokeSpecial:
730 case JVM_REF_newInvokeSpecial: {
731 const int name_and_type_ref_index =
732 cp->uncached_name_and_type_ref_index_at(ref_index);
733 const int name_ref_index =
734 cp->name_ref_index_at(name_and_type_ref_index);
735 const Symbol* const name = cp->symbol_at(name_ref_index);
736
737 if (name != vmSymbols::object_initializer_name()) { // !<init>
738 if (ref_kind == JVM_REF_newInvokeSpecial) {
739 classfile_parse_error(
740 "Bad constructor name at constant pool index %u in class file %s",
741 name_ref_index, THREAD);
742 return;
743 }
744 } else { // <init>
745 // The allowed invocation mode of <init> depends on its signature.
746 // This test corresponds to verify_invoke_instructions in the verifier.
747 const int signature_ref_index =
748 cp->signature_ref_index_at(name_and_type_ref_index);
749 const Symbol* const signature = cp->symbol_at(signature_ref_index);
750 if (signature->is_void_method_signature()
751 && ref_kind == JVM_REF_newInvokeSpecial) {
752 // OK, could be a constructor call
753 } else {
754 classfile_parse_error(
755 "Bad method name at constant pool index %u in class file %s",
756 name_ref_index, THREAD);
757 return;
758 }
759 }
760 break;
761 }
762 // Other ref_kinds are already fully checked in previous pass.
763 } // switch(ref_kind)
764 break;
765 }
766 case JVM_CONSTANT_MethodType: {
767 const Symbol* const no_name = vmSymbols::type_name(); // place holder
768 const Symbol* const signature = cp->method_type_signature_at(index);
769 verify_legal_method_signature(no_name, signature, CHECK);
770 break;
771 }
772 case JVM_CONSTANT_Utf8: {
773 assert(cp->symbol_at(index)->refcount() != 0, "count corrupted");
774 }
775 } // switch(tag)
776 } // end of for
777 }
778
779 class NameSigHash: public ResourceObj {
780 public:
781 const Symbol* _name; // name
782 const Symbol* _sig; // signature
783
784 static const int HASH_ROW_SIZE = 256;
785
786 NameSigHash(Symbol* name, Symbol* sig) :
787 _name(name),
788 _sig(sig) {}
789
790 static unsigned int hash(NameSigHash const& namesig) {
791 return namesig._name->identity_hash() ^ namesig._sig->identity_hash();
792 }
793
794 static bool equals(NameSigHash const& e0, NameSigHash const& e1) {
795 return (e0._name == e1._name) &&
796 (e0._sig == e1._sig);
797 }
798 };
799
800 using NameSigHashtable = HashTable<NameSigHash, int,
801 NameSigHash::HASH_ROW_SIZE,
802 AnyObj::RESOURCE_AREA, mtInternal,
803 &NameSigHash::hash, &NameSigHash::equals>;
804
805 static void check_identity_and_value_modifiers(ClassFileParser* current, const InstanceKlass* super_type, TRAPS) {
806 assert(super_type != nullptr,"Method doesn't support null super type");
807 if (super_type->access_flags().is_identity_class() && !current->access_flags().is_identity_class()
808 && super_type->name() != vmSymbols::java_lang_Object()) {
809 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
810 err_msg("Value type %s has an identity type as supertype",
811 current->class_name()->as_klass_external_name()));
812 }
813 }
814
815 void ClassFileParser::parse_interfaces(const ClassFileStream* stream,
816 int itfs_len,
817 ConstantPool* cp,
818 bool* const has_nonstatic_concrete_methods,
819 // FIXME: lots of these functions
820 // declare their parameters as const,
821 // which adds only noise to the code.
822 // Remove the spurious const modifiers.
823 // Many are of the form "const int x"
824 // or "T* const x".
825 TRAPS) {
826 assert(stream != nullptr, "invariant");
827 assert(cp != nullptr, "invariant");
828 assert(has_nonstatic_concrete_methods != nullptr, "invariant");
829
830 if (itfs_len == 0) {
831 _local_interfaces = Universe::the_empty_instance_klass_array();
832
833 } else {
834 assert(itfs_len > 0, "only called for len>0");
835 _local_interface_indexes = new GrowableArray<u2>(itfs_len);
836 int index = 0;
837 for (index = 0; index < itfs_len; index++) {
838 const u2 interface_index = stream->get_u2(CHECK);
839 guarantee_property(
840 valid_klass_reference_at(interface_index),
841 "Interface name has bad constant pool index %u in class file %s",
842 interface_index, CHECK);
843 _local_interface_indexes->at_put_grow(index, interface_index);
844 }
845
846 if (!_need_verify || itfs_len <= 1) {
847 return;
848 }
849
850 // Check if there's any duplicates in interfaces
851 ResourceMark rm(THREAD);
852 // Set containing interface names
853 HashTable<Symbol*, int>* interface_names = new HashTable<Symbol*, int>();
854 for (index = 0; index < itfs_len; index++) {
855 Symbol* interface_name = cp->klass_name_at(_local_interface_indexes->at(index));
856 // If no duplicates, add (name, nullptr) in hashtable interface_names.
857 if (!interface_names->put(interface_name, 0)) {
858 classfile_parse_error("Duplicate interface name \"%s\" in class file %s",
859 interface_name->as_C_string(), THREAD);
860 return;
861 }
862 }
863 }
864 }
865
866 void ClassFileParser::verify_constantvalue(const ConstantPool* const cp,
867 int constantvalue_index,
868 int signature_index,
869 TRAPS) const {
870 // Make sure the constant pool entry is of a type appropriate to this field
871 guarantee_property(
872 (constantvalue_index > 0 &&
873 constantvalue_index < cp->length()),
874 "Bad initial value index %u in ConstantValue attribute in class file %s",
875 constantvalue_index, CHECK);
876
877 const constantTag value_type = cp->tag_at(constantvalue_index);
878 switch(cp->basic_type_for_signature_at(signature_index)) {
879 case T_LONG: {
880 guarantee_property(value_type.is_long(),
881 "Inconsistent constant value type in class file %s",
882 CHECK);
883 break;
884 }
885 case T_FLOAT: {
886 guarantee_property(value_type.is_float(),
887 "Inconsistent constant value type in class file %s",
888 CHECK);
889 break;
890 }
891 case T_DOUBLE: {
892 guarantee_property(value_type.is_double(),
893 "Inconsistent constant value type in class file %s",
894 CHECK);
895 break;
896 }
897 case T_BYTE:
898 case T_CHAR:
899 case T_SHORT:
900 case T_BOOLEAN:
901 case T_INT: {
902 guarantee_property(value_type.is_int(),
903 "Inconsistent constant value type in class file %s",
904 CHECK);
905 break;
906 }
907 case T_OBJECT: {
908 guarantee_property((cp->symbol_at(signature_index)->equals("Ljava/lang/String;")
909 && value_type.is_string()),
910 "Bad string initial value in class file %s",
911 CHECK);
912 break;
913 }
914 default: {
915 classfile_parse_error("Unable to set initial value %u in class file %s",
916 constantvalue_index,
917 THREAD);
918 }
919 }
920 }
921
922 class AnnotationCollector : public ResourceObj{
923 public:
924 enum Location { _in_field, _in_method, _in_class };
925 enum ID {
926 _unknown = 0,
927 _method_CallerSensitive,
928 _method_ForceInline,
929 _method_DontInline,
930 _method_ChangesCurrentThread,
931 _method_JvmtiHideEvents,
932 _method_JvmtiMountTransition,
933 _method_InjectedProfile,
934 _method_LambdaForm_Compiled,
935 _method_Hidden,
936 _method_Scoped,
937 _method_IntrinsicCandidate,
938 _jdk_internal_vm_annotation_Contended,
939 _field_Stable,
940 _jdk_internal_vm_annotation_ReservedStackAccess,
941 _jdk_internal_ValueBased,
942 _jdk_internal_LooselyConsistentValue,
943 _jdk_internal_NullRestricted,
944 _java_lang_Deprecated,
945 _java_lang_Deprecated_for_removal,
946 _jdk_internal_vm_annotation_AOTSafeClassInitializer,
947 _method_AOTRuntimeSetup,
948 _jdk_internal_vm_annotation_TrustFinalFields,
949 _annotation_LIMIT
950 };
951 const Location _location;
952 int _annotations_present;
953 u2 _contended_group;
954
955 AnnotationCollector(Location location)
956 : _location(location), _annotations_present(0), _contended_group(0)
957 {
958 assert((int)_annotation_LIMIT <= (int)sizeof(_annotations_present) * BitsPerByte, "");
959 }
960 // If this annotation name has an ID, report it (or _none).
961 ID annotation_index(const ClassLoaderData* loader_data, const Symbol* name, bool can_access_vm_annotations);
962 // Set the annotation name:
963 void set_annotation(ID id) {
964 assert((int)id >= 0 && (int)id < (int)_annotation_LIMIT, "oob");
965 _annotations_present |= (int)nth_bit((int)id);
966 }
967
968 void remove_annotation(ID id) {
969 assert((int)id >= 0 && (int)id < (int)_annotation_LIMIT, "oob");
970 _annotations_present &= (int)~nth_bit((int)id);
971 }
972
973 // Report if the annotation is present.
974 bool has_any_annotations() const { return _annotations_present != 0; }
975 bool has_annotation(ID id) const { return (nth_bit((int)id) & _annotations_present) != 0; }
976
977 void set_contended_group(u2 group) { _contended_group = group; }
978 u2 contended_group() const { return _contended_group; }
979
980 bool is_contended() const { return has_annotation(_jdk_internal_vm_annotation_Contended); }
981
982 void set_stable(bool stable) { set_annotation(_field_Stable); }
983 bool is_stable() const { return has_annotation(_field_Stable); }
984
985 bool has_aot_runtime_setup() const { return has_annotation(_method_AOTRuntimeSetup); }
986 };
987
988 // This class also doubles as a holder for metadata cleanup.
989 class ClassFileParser::FieldAnnotationCollector : public AnnotationCollector {
990 private:
991 ClassLoaderData* _loader_data;
992 AnnotationArray* _field_annotations;
993 AnnotationArray* _field_type_annotations;
994 public:
995 FieldAnnotationCollector(ClassLoaderData* loader_data) :
996 AnnotationCollector(_in_field),
997 _loader_data(loader_data),
998 _field_annotations(nullptr),
999 _field_type_annotations(nullptr) {}
1000 ~FieldAnnotationCollector();
1001 void apply_to(FieldInfo* f);
1002 AnnotationArray* field_annotations() { return _field_annotations; }
1003 AnnotationArray* field_type_annotations() { return _field_type_annotations; }
1004
1005 void set_field_annotations(AnnotationArray* a) { _field_annotations = a; }
1006 void set_field_type_annotations(AnnotationArray* a) { _field_type_annotations = a; }
1007 };
1008
1009 class MethodAnnotationCollector : public AnnotationCollector{
1010 public:
1011 MethodAnnotationCollector() : AnnotationCollector(_in_method) { }
1012 void apply_to(const methodHandle& m);
1013 };
1014
1015 class ClassFileParser::ClassAnnotationCollector : public AnnotationCollector{
1016 public:
1017 ClassAnnotationCollector() : AnnotationCollector(_in_class) { }
1018 void apply_to(InstanceKlass* ik);
1019 };
1020
1021
1022 static int skip_annotation_value(const u1* buffer, int limit, int index, int recursion_depth); // fwd decl
1023 static const int max_recursion_depth = 5;
1024
1025 // Safely increment index by val if does not pass limit
1026 #define SAFE_ADD(index, limit, val) \
1027 if (index >= limit - val) return limit; \
1028 index += val;
1029
1030 // Skip an annotation. Return >=limit if there is any problem.
1031 static int skip_annotation(const u1* buffer, int limit, int index, int recursion_depth = 0) {
1032 assert(buffer != nullptr, "invariant");
1033 if (recursion_depth > max_recursion_depth) {
1034 return limit;
1035 }
1036 // annotation := atype:u2 do(nmem:u2) {member:u2 value}
1037 // value := switch (tag:u1) { ... }
1038 SAFE_ADD(index, limit, 4); // skip atype and read nmem
1039 int nmem = Bytes::get_Java_u2((address)buffer + index - 2);
1040 while (--nmem >= 0 && index < limit) {
1041 SAFE_ADD(index, limit, 2); // skip member
1042 index = skip_annotation_value(buffer, limit, index, recursion_depth + 1);
1043 }
1044 return index;
1045 }
1046
1047 // Skip an annotation value. Return >=limit if there is any problem.
1048 static int skip_annotation_value(const u1* buffer, int limit, int index, int recursion_depth) {
1049 assert(buffer != nullptr, "invariant");
1050
1051 if (recursion_depth > max_recursion_depth) {
1052 return limit;
1053 }
1054 // value := switch (tag:u1) {
1055 // case B, C, I, S, Z, D, F, J, c: con:u2;
1056 // case e: e_class:u2 e_name:u2;
1057 // case s: s_con:u2;
1058 // case [: do(nval:u2) {value};
1059 // case @: annotation;
1060 // case s: s_con:u2;
1061 // }
1062 SAFE_ADD(index, limit, 1); // read tag
1063 const u1 tag = buffer[index - 1];
1064 switch (tag) {
1065 case 'B':
1066 case 'C':
1067 case 'I':
1068 case 'S':
1069 case 'Z':
1070 case 'D':
1071 case 'F':
1072 case 'J':
1073 case 'c':
1074 case 's':
1075 SAFE_ADD(index, limit, 2); // skip con or s_con
1076 break;
1077 case 'e':
1078 SAFE_ADD(index, limit, 4); // skip e_class, e_name
1079 break;
1080 case '[':
1081 {
1082 SAFE_ADD(index, limit, 2); // read nval
1083 int nval = Bytes::get_Java_u2((address)buffer + index - 2);
1084 while (--nval >= 0 && index < limit) {
1085 index = skip_annotation_value(buffer, limit, index, recursion_depth + 1);
1086 }
1087 }
1088 break;
1089 case '@':
1090 index = skip_annotation(buffer, limit, index, recursion_depth + 1);
1091 break;
1092 default:
1093 return limit; // bad tag byte
1094 }
1095 return index;
1096 }
1097
1098 // Sift through annotations, looking for those significant to the VM:
1099 static void parse_annotations(const ConstantPool* const cp,
1100 const u1* buffer, int limit,
1101 AnnotationCollector* coll,
1102 ClassLoaderData* loader_data,
1103 const bool can_access_vm_annotations) {
1104
1105 assert(cp != nullptr, "invariant");
1106 assert(buffer != nullptr, "invariant");
1107 assert(coll != nullptr, "invariant");
1108 assert(loader_data != nullptr, "invariant");
1109
1110 // annotations := do(nann:u2) {annotation}
1111 int index = 2; // read nann
1112 if (index >= limit) return;
1113 int nann = Bytes::get_Java_u2((address)buffer + index - 2);
1114 enum { // initial annotation layout
1115 atype_off = 0, // utf8 such as 'Ljava/lang/annotation/Retention;'
1116 count_off = 2, // u2 such as 1 (one value)
1117 member_off = 4, // utf8 such as 'value'
1118 tag_off = 6, // u1 such as 'c' (type) or 'e' (enum)
1119 e_tag_val = 'e',
1120 e_type_off = 7, // utf8 such as 'Ljava/lang/annotation/RetentionPolicy;'
1121 e_con_off = 9, // utf8 payload, such as 'SOURCE', 'CLASS', 'RUNTIME'
1122 e_size = 11, // end of 'e' annotation
1123 c_tag_val = 'c', // payload is type
1124 c_con_off = 7, // utf8 payload, such as 'I'
1125 c_size = 9, // end of 'c' annotation
1126 s_tag_val = 's', // payload is String
1127 s_con_off = 7, // utf8 payload, such as 'Ljava/lang/String;'
1128 s_size = 9,
1129 b_tag_val = 'Z', // payload is boolean
1130 min_size = 6 // smallest possible size (zero members)
1131 };
1132 // Cannot add min_size to index in case of overflow MAX_INT
1133 while ((--nann) >= 0 && (index - 2 <= limit - min_size)) {
1134 int index0 = index;
1135 index = skip_annotation(buffer, limit, index);
1136 const u1* const abase = buffer + index0;
1137 const int atype = Bytes::get_Java_u2((address)abase + atype_off);
1138 const int count = Bytes::get_Java_u2((address)abase + count_off);
1139 const Symbol* const aname = check_symbol_at(cp, atype);
1140 if (aname == nullptr) break; // invalid annotation name
1141 const Symbol* member = nullptr;
1142 if (count >= 1) {
1143 const int member_index = Bytes::get_Java_u2((address)abase + member_off);
1144 member = check_symbol_at(cp, member_index);
1145 if (member == nullptr) break; // invalid member name
1146 }
1147
1148 // Here is where parsing particular annotations will take place.
1149 AnnotationCollector::ID id = coll->annotation_index(loader_data, aname, can_access_vm_annotations);
1150 if (AnnotationCollector::_unknown == id) continue;
1151 coll->set_annotation(id);
1152 if (AnnotationCollector::_java_lang_Deprecated == id) {
1153 // @Deprecated can specify forRemoval=true, which we need
1154 // to record for JFR to use. If the annotation is not well-formed
1155 // then we may not be able to determine that.
1156 const u1* offset = abase + member_off;
1157 // There are only 2 members in @Deprecated.
1158 int n_members = MIN2(count, 2);
1159 for (int i = 0; i < n_members; ++i) {
1160 int member_index = Bytes::get_Java_u2((address)offset);
1161 offset += 2;
1162 member = check_symbol_at(cp, member_index);
1163 if (member == vmSymbols::since() &&
1164 (*((address)offset) == s_tag_val)) {
1165 // Found `since` first so skip over it
1166 offset += 3;
1167 }
1168 else if (member == vmSymbols::for_removal() &&
1169 (*((address)offset) == b_tag_val)) {
1170 const u2 boolean_value_index = Bytes::get_Java_u2((address)offset + 1);
1171 // No guarantee the entry is valid so check it refers to an int in the CP.
1172 if (cp->is_within_bounds(boolean_value_index) &&
1173 cp->tag_at(boolean_value_index).is_int() &&
1174 cp->int_at(boolean_value_index) == 1) {
1175 // forRemoval == true
1176 coll->set_annotation(AnnotationCollector::_java_lang_Deprecated_for_removal);
1177 }
1178 break; // no need to check further
1179 }
1180 else {
1181 // This @Deprecated annotation is malformed so we don't try to
1182 // determine whether forRemoval is set.
1183 break;
1184 }
1185 }
1186 continue; // proceed to next annotation
1187 }
1188
1189 if (AnnotationCollector::_jdk_internal_vm_annotation_Contended == id) {
1190 // @Contended can optionally specify the contention group.
1191 //
1192 // Contended group defines the equivalence class over the fields:
1193 // the fields within the same contended group are not treated distinct.
1194 // The only exception is default group, which does not incur the
1195 // equivalence. Naturally, contention group for classes is meaningless.
1196 //
1197 // While the contention group is specified as String, annotation
1198 // values are already interned, and we might as well use the constant
1199 // pool index as the group tag.
1200 //
1201 u2 group_index = 0; // default contended group
1202 if (count == 1
1203 && s_size == (index - index0) // match size
1204 && s_tag_val == *(abase + tag_off)
1205 && member == vmSymbols::value_name()) {
1206 group_index = Bytes::get_Java_u2((address)abase + s_con_off);
1207 // No guarantee the group_index is valid so check it refers to a
1208 // symbol in the CP.
1209 if (cp->is_within_bounds(group_index) &&
1210 cp->tag_at(group_index).is_utf8()) {
1211 // Seems valid, so check for empty string and reset
1212 if (cp->symbol_at(group_index)->utf8_length() == 0) {
1213 group_index = 0; // default contended group
1214 }
1215 } else {
1216 // Not valid so use the default
1217 group_index = 0;
1218 }
1219 }
1220 coll->set_contended_group(group_index);
1221 continue; // proceed to next annotation
1222 }
1223 }
1224 }
1225
1226
1227 // Parse attributes for a field.
1228 void ClassFileParser::parse_field_attributes(const ClassFileStream* const cfs,
1229 u2 attributes_count,
1230 bool is_static, u2 signature_index,
1231 u2* const constantvalue_index_addr,
1232 bool* const is_synthetic_addr,
1233 u2* const generic_signature_index_addr,
1234 ClassFileParser::FieldAnnotationCollector* parsed_annotations,
1235 TRAPS) {
1236 assert(cfs != nullptr, "invariant");
1237 assert(constantvalue_index_addr != nullptr, "invariant");
1238 assert(is_synthetic_addr != nullptr, "invariant");
1239 assert(generic_signature_index_addr != nullptr, "invariant");
1240 assert(parsed_annotations != nullptr, "invariant");
1241 assert(attributes_count > 0, "attributes_count should be greater than 0");
1242
1243 u2 constantvalue_index = 0;
1244 u2 generic_signature_index = 0;
1245 bool is_synthetic = false;
1246 const u1* runtime_visible_annotations = nullptr;
1247 int runtime_visible_annotations_length = 0;
1248 const u1* runtime_visible_type_annotations = nullptr;
1249 int runtime_visible_type_annotations_length = 0;
1250 bool runtime_invisible_annotations_exists = false;
1251 bool runtime_invisible_type_annotations_exists = false;
1252 const ConstantPool* const cp = _cp;
1253
1254 while (attributes_count--) {
1255 cfs->guarantee_more(6, CHECK); // attribute_name_index, attribute_length
1256 const u2 attribute_name_index = cfs->get_u2_fast();
1257 const u4 attribute_length = cfs->get_u4_fast();
1258 guarantee_property(valid_symbol_at(attribute_name_index),
1259 "Invalid field attribute index %u in class file %s",
1260 attribute_name_index,
1261 CHECK);
1262
1263 const Symbol* const attribute_name = cp->symbol_at(attribute_name_index);
1264 if (is_static && attribute_name == vmSymbols::tag_constant_value()) {
1265 // ignore if non-static
1266 if (constantvalue_index != 0) {
1267 classfile_parse_error("Duplicate ConstantValue attribute in class file %s", THREAD);
1268 return;
1269 }
1270 guarantee_property(
1271 attribute_length == 2,
1272 "Invalid ConstantValue field attribute length %u in class file %s",
1273 attribute_length, CHECK);
1274
1275 constantvalue_index = cfs->get_u2(CHECK);
1276 if (_need_verify) {
1277 verify_constantvalue(cp, constantvalue_index, signature_index, CHECK);
1278 }
1279 } else if (attribute_name == vmSymbols::tag_synthetic()) {
1280 if (attribute_length != 0) {
1281 classfile_parse_error(
1282 "Invalid Synthetic field attribute length %u in class file %s",
1283 attribute_length, THREAD);
1284 return;
1285 }
1286 is_synthetic = true;
1287 } else if (attribute_name == vmSymbols::tag_deprecated()) { // 4276120
1288 if (attribute_length != 0) {
1289 classfile_parse_error(
1290 "Invalid Deprecated field attribute length %u in class file %s",
1291 attribute_length, THREAD);
1292 return;
1293 }
1294 } else if (_major_version >= JAVA_1_5_VERSION) {
1295 if (attribute_name == vmSymbols::tag_signature()) {
1296 if (generic_signature_index != 0) {
1297 classfile_parse_error(
1298 "Multiple Signature attributes for field in class file %s", THREAD);
1299 return;
1300 }
1301 if (attribute_length != 2) {
1302 classfile_parse_error(
1303 "Wrong size %u for field's Signature attribute in class file %s",
1304 attribute_length, THREAD);
1305 return;
1306 }
1307 generic_signature_index = parse_generic_signature_attribute(cfs, CHECK);
1308 } else if (attribute_name == vmSymbols::tag_runtime_visible_annotations()) {
1309 if (runtime_visible_annotations != nullptr) {
1310 classfile_parse_error(
1311 "Multiple RuntimeVisibleAnnotations attributes for field in class file %s", THREAD);
1312 return;
1313 }
1314 runtime_visible_annotations_length = attribute_length;
1315 runtime_visible_annotations = cfs->current();
1316 assert(runtime_visible_annotations != nullptr, "null visible annotations");
1317 cfs->guarantee_more(runtime_visible_annotations_length, CHECK);
1318 parse_annotations(cp,
1319 runtime_visible_annotations,
1320 runtime_visible_annotations_length,
1321 parsed_annotations,
1322 _loader_data,
1323 _can_access_vm_annotations);
1324 cfs->skip_u1_fast(runtime_visible_annotations_length);
1325 } else if (attribute_name == vmSymbols::tag_runtime_invisible_annotations()) {
1326 if (runtime_invisible_annotations_exists) {
1327 classfile_parse_error(
1328 "Multiple RuntimeInvisibleAnnotations attributes for field in class file %s", THREAD);
1329 return;
1330 }
1331 runtime_invisible_annotations_exists = true;
1332 cfs->skip_u1(attribute_length, CHECK);
1333 } else if (attribute_name == vmSymbols::tag_runtime_visible_type_annotations()) {
1334 if (runtime_visible_type_annotations != nullptr) {
1335 classfile_parse_error(
1336 "Multiple RuntimeVisibleTypeAnnotations attributes for field in class file %s", THREAD);
1337 return;
1338 }
1339 runtime_visible_type_annotations_length = attribute_length;
1340 runtime_visible_type_annotations = cfs->current();
1341 assert(runtime_visible_type_annotations != nullptr, "null visible type annotations");
1342 cfs->skip_u1(runtime_visible_type_annotations_length, CHECK);
1343 } else if (attribute_name == vmSymbols::tag_runtime_invisible_type_annotations()) {
1344 if (runtime_invisible_type_annotations_exists) {
1345 classfile_parse_error(
1346 "Multiple RuntimeInvisibleTypeAnnotations attributes for field in class file %s", THREAD);
1347 return;
1348 } else {
1349 runtime_invisible_type_annotations_exists = true;
1350 }
1351 cfs->skip_u1(attribute_length, CHECK);
1352 } else {
1353 cfs->skip_u1(attribute_length, CHECK); // Skip unknown attributes
1354 }
1355 } else {
1356 cfs->skip_u1(attribute_length, CHECK); // Skip unknown attributes
1357 }
1358 }
1359
1360 *constantvalue_index_addr = constantvalue_index;
1361 *is_synthetic_addr = is_synthetic;
1362 *generic_signature_index_addr = generic_signature_index;
1363 AnnotationArray* a = allocate_annotations(runtime_visible_annotations,
1364 runtime_visible_annotations_length,
1365 CHECK);
1366 parsed_annotations->set_field_annotations(a);
1367 a = allocate_annotations(runtime_visible_type_annotations,
1368 runtime_visible_type_annotations_length,
1369 CHECK);
1370 parsed_annotations->set_field_type_annotations(a);
1371 return;
1372 }
1373
1374
1375 // Side-effects: populates the _fields, _fields_annotations,
1376 // _fields_type_annotations fields
1377 void ClassFileParser::parse_fields(const ClassFileStream* const cfs,
1378 AccessFlags class_access_flags,
1379 ConstantPool* cp,
1380 const int cp_size,
1381 u2* const java_fields_count_ptr,
1382 TRAPS) {
1383
1384 assert(cfs != nullptr, "invariant");
1385 assert(cp != nullptr, "invariant");
1386 assert(java_fields_count_ptr != nullptr, "invariant");
1387
1388 assert(nullptr == _fields_annotations, "invariant");
1389 assert(nullptr == _fields_type_annotations, "invariant");
1390
1391 // "inline type" means concrete value class
1392 bool is_inline_type = !class_access_flags.is_identity_class() && !class_access_flags.is_abstract();
1393 // "value class" can be either abstract or concrete value class
1394 bool is_value_class = !class_access_flags.is_identity_class() && !class_access_flags.is_interface();
1395 cfs->guarantee_more(2, CHECK); // length
1396 const u2 length = cfs->get_u2_fast();
1397 *java_fields_count_ptr = length;
1398
1399 int num_injected = 0;
1400 const InjectedField* const injected = JavaClasses::get_injected(_class_name,
1401 &num_injected);
1402
1403 // Two more slots are required for inline classes:
1404 // - The static field ".null_reset" which carries the nullable flat layout
1405 // representation of null, added below
1406 // - The nonstatic field ".empty" the JVM injects when detecting an empty
1407 // inline class, added in FieldLayoutBuilder::compute_inline_class_layout
1408 // One more slot is required for both abstract value class and inline classes:
1409 // - The static field ".acmp_maps" for acmp and identity hash, tracks
1410 // nonstatic fields both inherited or declared, added below
1411 const int total_fields = length + num_injected + (is_inline_type ? 2 : 0)
1412 + (is_value_class ? 1 : 0);
1413
1414 // Allocate a temporary resource array to collect field data.
1415 // After parsing all fields, data are stored in a UNSIGNED5 compressed stream.
1416 _temp_field_info = new GrowableArray<FieldInfo>(total_fields);
1417
1418 ResourceMark rm(THREAD);
1419 for (int n = 0; n < length; n++) {
1420 // access_flags, name_index, descriptor_index, attributes_count
1421 cfs->guarantee_more(8, CHECK);
1422
1423 jint recognized_modifiers = JVM_RECOGNIZED_FIELD_MODIFIERS;
1424 if (!supports_inline_types()) {
1425 recognized_modifiers &= ~JVM_ACC_STRICT_INIT;
1426 }
1427
1428 const jint flags = cfs->get_u2_fast() & recognized_modifiers;
1429 verify_legal_field_modifiers(flags, class_access_flags, CHECK);
1430 AccessFlags access_flags;
1431 access_flags.set_flags(flags);
1432 FieldInfo::FieldFlags fieldFlags(0);
1433
1434 const u2 name_index = cfs->get_u2_fast();
1435 guarantee_property(valid_symbol_at(name_index),
1436 "Invalid constant pool index %u for field name in class file %s",
1437 name_index, CHECK);
1438 const Symbol* const name = cp->symbol_at(name_index);
1439 verify_legal_field_name(name, CHECK);
1440
1441 const u2 signature_index = cfs->get_u2_fast();
1442 guarantee_property(valid_symbol_at(signature_index),
1443 "Invalid constant pool index %u for field signature in class file %s",
1444 signature_index, CHECK);
1445 const Symbol* const sig = cp->symbol_at(signature_index);
1446 verify_legal_field_signature(name, sig, CHECK);
1447
1448 u2 constantvalue_index = 0;
1449 bool is_synthetic = false;
1450 u2 generic_signature_index = 0;
1451 const bool is_static = access_flags.is_static();
1452 FieldAnnotationCollector parsed_annotations(_loader_data);
1453
1454 bool is_null_restricted = false;
1455
1456 const u2 attributes_count = cfs->get_u2_fast();
1457 if (attributes_count > 0) {
1458 parse_field_attributes(cfs,
1459 attributes_count,
1460 is_static,
1461 signature_index,
1462 &constantvalue_index,
1463 &is_synthetic,
1464 &generic_signature_index,
1465 &parsed_annotations,
1466 CHECK);
1467
1468 if (parsed_annotations.field_annotations() != nullptr) {
1469 if (_fields_annotations == nullptr) {
1470 _fields_annotations = MetadataFactory::new_array<AnnotationArray*>(
1471 _loader_data, length, nullptr,
1472 CHECK);
1473 }
1474 _fields_annotations->at_put(n, parsed_annotations.field_annotations());
1475 parsed_annotations.set_field_annotations(nullptr);
1476 if (parsed_annotations.has_annotation(AnnotationCollector::_jdk_internal_NullRestricted)) {
1477 if (!Signature::has_envelope(sig)) {
1478 Exceptions::fthrow(
1479 THREAD_AND_LOCATION,
1480 vmSymbols::java_lang_ClassFormatError(),
1481 "Illegal use of @jdk.internal.vm.annotation.NullRestricted annotation on field %s.%s with signature %s (primitive types can never be null)",
1482 class_name()->as_C_string(), name->as_C_string(), sig->as_C_string());
1483 return;
1484 }
1485 if (!supports_inline_types()) {
1486 Exceptions::fthrow(
1487 THREAD_AND_LOCATION,
1488 vmSymbols::java_lang_ClassFormatError(),
1489 "Illegal use of @jdk.internal.vm.annotation.NullRestricted annotation on field %s.%s in non-preview class file",
1490 class_name()->as_C_string(), name->as_C_string());
1491 return;
1492 }
1493
1494 if ((flags & JVM_ACC_STRICT_INIT) == 0) {
1495 // Inject STRICT_INIT and validate in context
1496 const jint patched_flags = flags | JVM_ACC_STRICT_INIT;
1497 verify_legal_field_modifiers(patched_flags, class_access_flags, CHECK);
1498 access_flags.set_flags(patched_flags);
1499 }
1500 is_null_restricted = true;
1501 }
1502 parsed_annotations.set_field_annotations(nullptr);
1503 }
1504 if (parsed_annotations.field_type_annotations() != nullptr) {
1505 if (_fields_type_annotations == nullptr) {
1506 _fields_type_annotations =
1507 MetadataFactory::new_array<AnnotationArray*>(_loader_data,
1508 length,
1509 nullptr,
1510 CHECK);
1511 }
1512 _fields_type_annotations->at_put(n, parsed_annotations.field_type_annotations());
1513 parsed_annotations.set_field_type_annotations(nullptr);
1514 }
1515
1516 if (is_synthetic) {
1517 access_flags.set_is_synthetic();
1518 }
1519 if (generic_signature_index != 0) {
1520 fieldFlags.update_generic(true);
1521 }
1522 }
1523
1524 if (is_null_restricted) {
1525 fieldFlags.update_null_free_inline_type(true);
1526 }
1527
1528 const BasicType type = cp->basic_type_for_signature_at(signature_index);
1529
1530 // Update number of static oop fields.
1531 if (is_static && is_reference_type(type)) {
1532 _static_oop_count++;
1533 }
1534
1535 FieldInfo fi(access_flags, name_index, signature_index, constantvalue_index, fieldFlags);
1536 fi.set_index(n);
1537 if (fieldFlags.is_generic()) {
1538 fi.set_generic_signature_index(generic_signature_index);
1539 }
1540 parsed_annotations.apply_to(&fi);
1541 if (fi.field_flags().is_contended()) {
1542 _has_contended_fields = true;
1543 }
1544 if (access_flags.is_strict() && access_flags.is_static()) {
1545 _has_strict_static_fields = true;
1546 }
1547 _temp_field_info->append(fi);
1548 }
1549 assert(_temp_field_info->length() == length, "Must be");
1550
1551 if (num_injected != 0) {
1552 for (int n = 0; n < num_injected; n++) {
1553 // Check for duplicates
1554 if (injected[n].may_be_java) {
1555 const Symbol* const name = injected[n].name();
1556 const Symbol* const signature = injected[n].signature();
1557 bool duplicate = false;
1558 for (int i = 0; i < length; i++) {
1559 const FieldInfo* const f = _temp_field_info->adr_at(i);
1560 if (name == cp->symbol_at(f->name_index()) &&
1561 signature == cp->symbol_at(f->signature_index())) {
1562 // Symbol is desclared in Java so skip this one
1563 duplicate = true;
1564 break;
1565 }
1566 }
1567 if (duplicate) {
1568 // These will be removed from the field array at the end
1569 continue;
1570 }
1571 }
1572
1573 // Injected field
1574 FieldInfo::FieldFlags fflags(0);
1575 fflags.update_injected(true);
1576 AccessFlags aflags;
1577 FieldInfo fi(aflags, (u2)(injected[n].name_index), (u2)(injected[n].signature_index), 0, fflags);
1578 int idx = _temp_field_info->append(fi);
1579 _temp_field_info->adr_at(idx)->set_index(idx);
1580 }
1581 }
1582
1583 if (is_inline_type) {
1584 // Inject static ".null_reset" field. This is an all-zero value with its null-channel set to zero.
1585 // IT should never be seen by user code, it is used when writing "null" to a nullable flat field
1586 // The all-zero value ensure that any embedded oop will be set to null, to avoid keeping dead objects
1587 // alive.
1588 FieldInfo::FieldFlags fflags2(0);
1589 fflags2.update_injected(true);
1590 AccessFlags aflags2(JVM_ACC_STATIC);
1591 FieldInfo fi2(aflags2,
1592 (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(null_reset_value_name)),
1593 (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(object_signature)),
1594 0,
1595 fflags2);
1596 int idx2 = _temp_field_info->append(fi2);
1597 _temp_field_info->adr_at(idx2)->set_index(idx2);
1598 _static_oop_count++;
1599 }
1600 if (!access_flags().is_identity_class() && !access_flags().is_interface()
1601 && _class_name != vmSymbols::java_lang_Object()) {
1602 // Acmp map ".acmp_maps" required for abstract and concrete value classes
1603 FieldInfo::FieldFlags fflags2(0);
1604 fflags2.update_injected(true);
1605 fflags2.update_stable(true);
1606 AccessFlags aflags2(JVM_ACC_STATIC | JVM_ACC_FINAL);
1607 FieldInfo fi3(aflags2,
1608 (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(acmp_maps_name)),
1609 (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(int_array_signature)),
1610 0,
1611 fflags2);
1612 int idx2 = _temp_field_info->append(fi3);
1613 _temp_field_info->adr_at(idx2)->set_index(idx2);
1614 _static_oop_count++;
1615 }
1616
1617 if (_need_verify && length > 1) {
1618 // Check duplicated fields
1619 ResourceMark rm(THREAD);
1620 // Set containing name-signature pairs
1621 NameSigHashtable* names_and_sigs = new NameSigHashtable();
1622 for (int i = 0; i < _temp_field_info->length(); i++) {
1623 NameSigHash name_and_sig(_temp_field_info->adr_at(i)->name(_cp),
1624 _temp_field_info->adr_at(i)->signature(_cp));
1625 // If no duplicates, add name/signature in hashtable names_and_sigs.
1626 if(!names_and_sigs->put(name_and_sig, 0)) {
1627 classfile_parse_error("Duplicate field name \"%s\" with signature \"%s\" in class file %s",
1628 name_and_sig._name->as_C_string(), name_and_sig._sig->as_klass_external_name(), THREAD);
1629 return;
1630 }
1631 }
1632 }
1633 }
1634
1635
1636 const ClassFileParser::unsafe_u2* ClassFileParser::parse_exception_table(const ClassFileStream* const cfs,
1637 u4 code_length,
1638 u4 exception_table_length,
1639 TRAPS) {
1640 assert(cfs != nullptr, "invariant");
1641
1642 const unsafe_u2* const exception_table_start = cfs->current();
1643 assert(exception_table_start != nullptr, "null exception table");
1644
1645 cfs->guarantee_more(8 * exception_table_length, CHECK_NULL); // start_pc,
1646 // end_pc,
1647 // handler_pc,
1648 // catch_type_index
1649
1650 // Will check legal target after parsing code array in verifier.
1651 if (_need_verify) {
1652 for (unsigned int i = 0; i < exception_table_length; i++) {
1653 const u2 start_pc = cfs->get_u2_fast();
1654 const u2 end_pc = cfs->get_u2_fast();
1655 const u2 handler_pc = cfs->get_u2_fast();
1656 const u2 catch_type_index = cfs->get_u2_fast();
1657 guarantee_property((start_pc < end_pc) && (end_pc <= code_length),
1658 "Illegal exception table range in class file %s",
1659 CHECK_NULL);
1660 guarantee_property(handler_pc < code_length,
1661 "Illegal exception table handler in class file %s",
1662 CHECK_NULL);
1663 if (catch_type_index != 0) {
1664 guarantee_property(valid_klass_reference_at(catch_type_index),
1665 "Catch type in exception table has bad constant type in class file %s", CHECK_NULL);
1666 }
1667 }
1668 } else {
1669 cfs->skip_u2_fast(exception_table_length * 4);
1670 }
1671 return exception_table_start;
1672 }
1673
1674 void ClassFileParser::parse_linenumber_table(u4 code_attribute_length,
1675 u4 code_length,
1676 CompressedLineNumberWriteStream**const write_stream,
1677 TRAPS) {
1678
1679 const ClassFileStream* const cfs = _stream;
1680 unsigned int num_entries = cfs->get_u2(CHECK);
1681
1682 // Each entry is a u2 start_pc, and a u2 line_number
1683 const unsigned int length_in_bytes = num_entries * (sizeof(u2) * 2);
1684
1685 // Verify line number attribute and table length
1686 guarantee_property(
1687 code_attribute_length == sizeof(u2) + length_in_bytes,
1688 "LineNumberTable attribute has wrong length in class file %s", CHECK);
1689
1690 cfs->guarantee_more(length_in_bytes, CHECK);
1691
1692 if ((*write_stream) == nullptr) {
1693 if (length_in_bytes > fixed_buffer_size) {
1694 (*write_stream) = new CompressedLineNumberWriteStream(length_in_bytes);
1695 } else {
1696 (*write_stream) = new CompressedLineNumberWriteStream(
1697 _linenumbertable_buffer, fixed_buffer_size);
1698 }
1699 }
1700
1701 while (num_entries-- > 0) {
1702 const u2 bci = cfs->get_u2_fast(); // start_pc
1703 const u2 line = cfs->get_u2_fast(); // line_number
1704 guarantee_property(bci < code_length,
1705 "Invalid pc in LineNumberTable in class file %s", CHECK);
1706 (*write_stream)->write_pair(bci, line);
1707 }
1708 }
1709
1710
1711 class LVT_Hash : public AllStatic {
1712 public:
1713
1714 static bool equals(LocalVariableTableElement const& e0, LocalVariableTableElement const& e1) {
1715 /*
1716 * 3-tuple start_bci/length/slot has to be unique key,
1717 * so the following comparison seems to be redundant:
1718 * && elem->name_cp_index == entry->_elem->name_cp_index
1719 */
1720 return (e0.start_bci == e1.start_bci &&
1721 e0.length == e1.length &&
1722 e0.name_cp_index == e1.name_cp_index &&
1723 e0.slot == e1.slot);
1724 }
1725
1726 static unsigned int hash(LocalVariableTableElement const& e0) {
1727 unsigned int raw_hash = e0.start_bci;
1728
1729 raw_hash = e0.length + raw_hash * 37;
1730 raw_hash = e0.name_cp_index + raw_hash * 37;
1731 raw_hash = e0.slot + raw_hash * 37;
1732
1733 return raw_hash;
1734 }
1735 };
1736
1737
1738 // Class file LocalVariableTable elements.
1739 class Classfile_LVT_Element {
1740 public:
1741 u2 start_bci;
1742 u2 length;
1743 u2 name_cp_index;
1744 u2 descriptor_cp_index;
1745 u2 slot;
1746 };
1747
1748 static void copy_lvt_element(const Classfile_LVT_Element* const src,
1749 LocalVariableTableElement* const lvt) {
1750 lvt->start_bci = Bytes::get_Java_u2((u1*) &src->start_bci);
1751 lvt->length = Bytes::get_Java_u2((u1*) &src->length);
1752 lvt->name_cp_index = Bytes::get_Java_u2((u1*) &src->name_cp_index);
1753 lvt->descriptor_cp_index = Bytes::get_Java_u2((u1*) &src->descriptor_cp_index);
1754 lvt->signature_cp_index = 0;
1755 lvt->slot = Bytes::get_Java_u2((u1*) &src->slot);
1756 }
1757
1758 // Function is used to parse both attributes:
1759 // LocalVariableTable (LVT) and LocalVariableTypeTable (LVTT)
1760 const ClassFileParser::unsafe_u2* ClassFileParser::parse_localvariable_table(const ClassFileStream* cfs,
1761 u4 code_length,
1762 u2 max_locals,
1763 u4 code_attribute_length,
1764 u2* const localvariable_table_length,
1765 bool isLVTT,
1766 TRAPS) {
1767 const char* const tbl_name = (isLVTT) ? "LocalVariableTypeTable" : "LocalVariableTable";
1768 *localvariable_table_length = cfs->get_u2(CHECK_NULL);
1769 const unsigned int size = checked_cast<unsigned>(
1770 (*localvariable_table_length) * sizeof(Classfile_LVT_Element) / sizeof(u2));
1771
1772 const ConstantPool* const cp = _cp;
1773
1774 // Verify local variable table attribute has right length
1775 if (_need_verify) {
1776 guarantee_property(code_attribute_length == (sizeof(*localvariable_table_length) + size * sizeof(u2)),
1777 "%s has wrong length in class file %s", tbl_name, CHECK_NULL);
1778 }
1779
1780 const unsafe_u2* const localvariable_table_start = cfs->current();
1781 assert(localvariable_table_start != nullptr, "null local variable table");
1782 if (!_need_verify) {
1783 cfs->skip_u2_fast(size);
1784 } else {
1785 cfs->guarantee_more(size * 2, CHECK_NULL);
1786 for(int i = 0; i < (*localvariable_table_length); i++) {
1787 const u2 start_pc = cfs->get_u2_fast();
1788 const u2 length = cfs->get_u2_fast();
1789 const u2 name_index = cfs->get_u2_fast();
1790 const u2 descriptor_index = cfs->get_u2_fast();
1791 const u2 index = cfs->get_u2_fast();
1792 // Assign to a u4 to avoid overflow
1793 const u4 end_pc = (u4)start_pc + (u4)length;
1794
1795 if (start_pc >= code_length) {
1796 classfile_parse_error(
1797 "Invalid start_pc %u in %s in class file %s",
1798 start_pc, tbl_name, THREAD);
1799 return nullptr;
1800 }
1801 if (end_pc > code_length) {
1802 classfile_parse_error(
1803 "Invalid length %u in %s in class file %s",
1804 length, tbl_name, THREAD);
1805 return nullptr;
1806 }
1807 const int cp_size = cp->length();
1808 guarantee_property(valid_symbol_at(name_index),
1809 "Name index %u in %s has bad constant type in class file %s",
1810 name_index, tbl_name, CHECK_NULL);
1811 guarantee_property(valid_symbol_at(descriptor_index),
1812 "Signature index %u in %s has bad constant type in class file %s",
1813 descriptor_index, tbl_name, CHECK_NULL);
1814
1815 const Symbol* const name = cp->symbol_at(name_index);
1816 const Symbol* const sig = cp->symbol_at(descriptor_index);
1817 verify_legal_field_name(name, CHECK_NULL);
1818 u2 extra_slot = 0;
1819 if (!isLVTT) {
1820 verify_legal_field_signature(name, sig, CHECK_NULL);
1821
1822 // 4894874: check special cases for double and long local variables
1823 if (sig == vmSymbols::type_signature(T_DOUBLE) ||
1824 sig == vmSymbols::type_signature(T_LONG)) {
1825 extra_slot = 1;
1826 }
1827 }
1828 guarantee_property((index + extra_slot) < max_locals,
1829 "Invalid index %u in %s in class file %s",
1830 index, tbl_name, CHECK_NULL);
1831 }
1832 }
1833 return localvariable_table_start;
1834 }
1835
1836 static const u1* parse_stackmap_table(const ClassFileStream* const cfs,
1837 u4 code_attribute_length,
1838 TRAPS) {
1839 assert(cfs != nullptr, "invariant");
1840
1841 if (0 == code_attribute_length) {
1842 return nullptr;
1843 }
1844
1845 const u1* const stackmap_table_start = cfs->current();
1846 assert(stackmap_table_start != nullptr, "null stackmap table");
1847
1848 // check code_attribute_length
1849 cfs->skip_u1(code_attribute_length, CHECK_NULL);
1850
1851 return stackmap_table_start;
1852 }
1853
1854 const ClassFileParser::unsafe_u2* ClassFileParser::parse_checked_exceptions(const ClassFileStream* const cfs,
1855 u2* const checked_exceptions_length,
1856 u4 method_attribute_length,
1857 TRAPS) {
1858 assert(cfs != nullptr, "invariant");
1859 assert(checked_exceptions_length != nullptr, "invariant");
1860
1861 cfs->guarantee_more(2, CHECK_NULL); // checked_exceptions_length
1862 *checked_exceptions_length = cfs->get_u2_fast();
1863 const unsigned int size =
1864 (*checked_exceptions_length) * sizeof(CheckedExceptionElement) / sizeof(u2);
1865 const unsafe_u2* const checked_exceptions_start = cfs->current();
1866 assert(checked_exceptions_start != nullptr, "null checked exceptions");
1867 if (!_need_verify) {
1868 cfs->skip_u2_fast(size);
1869 } else {
1870 // Verify each value in the checked exception table
1871 u2 checked_exception;
1872 const u2 len = *checked_exceptions_length;
1873 cfs->guarantee_more(2 * len, CHECK_NULL);
1874 for (int i = 0; i < len; i++) {
1875 checked_exception = cfs->get_u2_fast();
1876 guarantee_property(
1877 valid_klass_reference_at(checked_exception),
1878 "Exception name has bad type at constant pool %u in class file %s",
1879 checked_exception, CHECK_NULL);
1880 }
1881 }
1882 // check exceptions attribute length
1883 if (_need_verify) {
1884 guarantee_property(method_attribute_length == (sizeof(*checked_exceptions_length) +
1885 sizeof(u2) * size),
1886 "Exceptions attribute has wrong length in class file %s", CHECK_NULL);
1887 }
1888 return checked_exceptions_start;
1889 }
1890
1891 void ClassFileParser::throwIllegalSignature(const char* type,
1892 const Symbol* name,
1893 const Symbol* sig,
1894 TRAPS) const {
1895 assert(name != nullptr, "invariant");
1896 assert(sig != nullptr, "invariant");
1897
1898 ResourceMark rm(THREAD);
1899 // Names are all known to be < 64k so we know this formatted message is not excessively large.
1900 Exceptions::fthrow(THREAD_AND_LOCATION,
1901 vmSymbols::java_lang_ClassFormatError(),
1902 "%s \"%s\" in class %s has illegal signature \"%s\"", type,
1903 name->as_C_string(), _class_name->as_C_string(), sig->as_C_string());
1904 }
1905
1906 AnnotationCollector::ID
1907 AnnotationCollector::annotation_index(const ClassLoaderData* loader_data,
1908 const Symbol* name,
1909 const bool can_access_vm_annotations) {
1910 const vmSymbolID sid = vmSymbols::find_sid(name);
1911 // Privileged code can use all annotations. Other code silently drops some.
1912 const bool privileged = loader_data->is_boot_class_loader_data() ||
1913 loader_data->is_platform_class_loader_data() ||
1914 can_access_vm_annotations;
1915 switch (sid) {
1916 case VM_SYMBOL_ENUM_NAME(reflect_CallerSensitive_signature): {
1917 if (_location != _in_method) break; // only allow for methods
1918 if (!privileged) break; // only allow in privileged code
1919 return _method_CallerSensitive;
1920 }
1921 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ForceInline_signature): {
1922 if (_location != _in_method) break; // only allow for methods
1923 if (!privileged) break; // only allow in privileged code
1924 return _method_ForceInline;
1925 }
1926 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_DontInline_signature): {
1927 if (_location != _in_method) break; // only allow for methods
1928 if (!privileged) break; // only allow in privileged code
1929 return _method_DontInline;
1930 }
1931 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ChangesCurrentThread_signature): {
1932 if (_location != _in_method) break; // only allow for methods
1933 if (!privileged) break; // only allow in privileged code
1934 return _method_ChangesCurrentThread;
1935 }
1936 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_JvmtiHideEvents_signature): {
1937 if (_location != _in_method) break; // only allow for methods
1938 if (!privileged) break; // only allow in privileged code
1939 return _method_JvmtiHideEvents;
1940 }
1941 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_JvmtiMountTransition_signature): {
1942 if (_location != _in_method) break; // only allow for methods
1943 if (!privileged) break; // only allow in privileged code
1944 return _method_JvmtiMountTransition;
1945 }
1946 case VM_SYMBOL_ENUM_NAME(java_lang_invoke_InjectedProfile_signature): {
1947 if (_location != _in_method) break; // only allow for methods
1948 if (!privileged) break; // only allow in privileged code
1949 return _method_InjectedProfile;
1950 }
1951 case VM_SYMBOL_ENUM_NAME(java_lang_invoke_LambdaForm_Compiled_signature): {
1952 if (_location != _in_method) break; // only allow for methods
1953 if (!privileged) break; // only allow in privileged code
1954 return _method_LambdaForm_Compiled;
1955 }
1956 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Hidden_signature): {
1957 if (_location != _in_method) break; // only allow for methods
1958 if (!privileged) break; // only allow in privileged code
1959 return _method_Hidden;
1960 }
1961 case VM_SYMBOL_ENUM_NAME(jdk_internal_misc_Scoped_signature): {
1962 if (_location != _in_method) break; // only allow for methods
1963 if (!privileged) break; // only allow in privileged code
1964 return _method_Scoped;
1965 }
1966 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_IntrinsicCandidate_signature): {
1967 if (_location != _in_method) break; // only allow for methods
1968 if (!privileged) break; // only allow in privileged code
1969 return _method_IntrinsicCandidate;
1970 }
1971 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Stable_signature): {
1972 if (_location != _in_field) break; // only allow for fields
1973 if (!privileged) break; // only allow in privileged code
1974 return _field_Stable;
1975 }
1976 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_TrustFinalFields_signature): {
1977 if (_location != _in_class) break; // only allow for classes
1978 if (!privileged) break; // only allow in privileged code
1979 return _jdk_internal_vm_annotation_TrustFinalFields;
1980 }
1981 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Contended_signature): {
1982 if (_location != _in_field && _location != _in_class) {
1983 break; // only allow for fields and classes
1984 }
1985 if (!EnableContended || (RestrictContended && !privileged)) {
1986 break; // honor privileges
1987 }
1988 return _jdk_internal_vm_annotation_Contended;
1989 }
1990 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ReservedStackAccess_signature): {
1991 if (_location != _in_method) break; // only allow for methods
1992 if (RestrictReservedStack && !privileged) break; // honor privileges
1993 return _jdk_internal_vm_annotation_ReservedStackAccess;
1994 }
1995 case VM_SYMBOL_ENUM_NAME(jdk_internal_ValueBased_signature): {
1996 if (_location != _in_class) break; // only allow for classes
1997 if (!privileged) break; // only allow in privileged code
1998 return _jdk_internal_ValueBased;
1999 }
2000 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_LooselyConsistentValue_signature): {
2001 if (_location != _in_class) break; // only allow for classes
2002 return _jdk_internal_LooselyConsistentValue;
2003 }
2004 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_NullRestricted_signature): {
2005 if (_location != _in_field) break; // only allow for fields
2006 return _jdk_internal_NullRestricted;
2007 }
2008 case VM_SYMBOL_ENUM_NAME(java_lang_Deprecated): {
2009 return _java_lang_Deprecated;
2010 }
2011 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_AOTSafeClassInitializer_signature): {
2012 if (_location != _in_class) break; // only allow for classes
2013 if (!privileged) break; // only allow in privileged code
2014 return _jdk_internal_vm_annotation_AOTSafeClassInitializer;
2015 }
2016 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_AOTRuntimeSetup_signature): {
2017 if (_location != _in_method) break; // only allow for methods
2018 if (!privileged) break; // only allow in privileged code
2019 return _method_AOTRuntimeSetup;
2020 }
2021 default: {
2022 break;
2023 }
2024 }
2025 return AnnotationCollector::_unknown;
2026 }
2027
2028 void ClassFileParser::FieldAnnotationCollector::apply_to(FieldInfo* f) {
2029 if (is_contended())
2030 // Setting the contended group also sets the contended bit in field flags
2031 f->set_contended_group(contended_group());
2032 if (is_stable())
2033 (f->field_flags_addr())->update_stable(true);
2034 }
2035
2036 ClassFileParser::FieldAnnotationCollector::~FieldAnnotationCollector() {
2037 // If there's an error deallocate metadata for field annotations
2038 MetadataFactory::free_array<u1>(_loader_data, _field_annotations);
2039 MetadataFactory::free_array<u1>(_loader_data, _field_type_annotations);
2040 }
2041
2042 void MethodAnnotationCollector::apply_to(const methodHandle& m) {
2043 if (has_annotation(_method_CallerSensitive))
2044 m->set_caller_sensitive();
2045 if (has_annotation(_method_ForceInline))
2046 m->set_force_inline();
2047 if (has_annotation(_method_DontInline))
2048 m->set_dont_inline();
2049 if (has_annotation(_method_ChangesCurrentThread))
2050 m->set_changes_current_thread();
2051 if (has_annotation(_method_JvmtiHideEvents))
2052 m->set_jvmti_hide_events();
2053 if (has_annotation(_method_JvmtiMountTransition))
2054 m->set_jvmti_mount_transition();
2055 if (has_annotation(_method_InjectedProfile))
2056 m->set_has_injected_profile();
2057 if (has_annotation(_method_LambdaForm_Compiled) && m->intrinsic_id() == vmIntrinsics::_none)
2058 m->set_intrinsic_id(vmIntrinsics::_compiledLambdaForm);
2059 if (has_annotation(_method_Hidden))
2060 m->set_is_hidden();
2061 if (has_annotation(_method_Scoped))
2062 m->set_scoped();
2063 if (has_annotation(_method_IntrinsicCandidate) && !m->is_synthetic())
2064 m->set_intrinsic_candidate();
2065 if (has_annotation(_jdk_internal_vm_annotation_ReservedStackAccess))
2066 m->set_has_reserved_stack_access();
2067 if (has_annotation(_java_lang_Deprecated))
2068 m->set_deprecated();
2069 if (has_annotation(_java_lang_Deprecated_for_removal))
2070 m->set_deprecated_for_removal();
2071 }
2072
2073 void ClassFileParser::ClassAnnotationCollector::apply_to(InstanceKlass* ik) {
2074 assert(ik != nullptr, "invariant");
2075 if (has_annotation(_jdk_internal_vm_annotation_Contended)) {
2076 ik->set_is_contended(is_contended());
2077 }
2078 if (has_annotation(_jdk_internal_ValueBased)) {
2079 ik->set_has_value_based_class_annotation();
2080 if (DiagnoseSyncOnValueBasedClasses) {
2081 ik->set_is_value_based();
2082 }
2083 }
2084 if (has_annotation(_java_lang_Deprecated)) {
2085 Array<Method*>* methods = ik->methods();
2086 int length = ik->methods()->length();
2087 for (int i = 0; i < length; i++) {
2088 Method* m = methods->at(i);
2089 m->set_deprecated();
2090 }
2091 }
2092 if (has_annotation(_java_lang_Deprecated_for_removal)) {
2093 Array<Method*>* methods = ik->methods();
2094 int length = ik->methods()->length();
2095 for (int i = 0; i < length; i++) {
2096 Method* m = methods->at(i);
2097 m->set_deprecated_for_removal();
2098 }
2099 }
2100 if (has_annotation(_jdk_internal_vm_annotation_AOTSafeClassInitializer)) {
2101 ik->set_has_aot_safe_initializer();
2102 }
2103 if (has_annotation(_jdk_internal_vm_annotation_TrustFinalFields)) {
2104 ik->set_trust_final_fields(true);
2105 }
2106 }
2107
2108 #define MAX_ARGS_SIZE 255
2109 #define MAX_CODE_SIZE 65535
2110 #define INITIAL_MAX_LVT_NUMBER 256
2111
2112 /* Copy class file LVT's/LVTT's into the HotSpot internal LVT.
2113 *
2114 * Rules for LVT's and LVTT's are:
2115 * - There can be any number of LVT's and LVTT's.
2116 * - If there are n LVT's, it is the same as if there was just
2117 * one LVT containing all the entries from the n LVT's.
2118 * - There may be no more than one LVT entry per local variable.
2119 * Two LVT entries are 'equal' if these fields are the same:
2120 * start_pc, length, name, slot
2121 * - There may be no more than one LVTT entry per each LVT entry.
2122 * Each LVTT entry has to match some LVT entry.
2123 * - HotSpot internal LVT keeps natural ordering of class file LVT entries.
2124 */
2125 void ClassFileParser::copy_localvariable_table(const ConstMethod* cm,
2126 int lvt_cnt,
2127 u2* const localvariable_table_length,
2128 const unsafe_u2** const localvariable_table_start,
2129 int lvtt_cnt,
2130 u2* const localvariable_type_table_length,
2131 const unsafe_u2** const localvariable_type_table_start,
2132 TRAPS) {
2133
2134 ResourceMark rm(THREAD);
2135
2136 typedef HashTable<LocalVariableTableElement, LocalVariableTableElement*,
2137 256, AnyObj::RESOURCE_AREA, mtInternal,
2138 &LVT_Hash::hash, &LVT_Hash::equals> LVT_HashTable;
2139
2140 LVT_HashTable* const table = new LVT_HashTable();
2141
2142 // To fill LocalVariableTable in
2143 const Classfile_LVT_Element* cf_lvt;
2144 LocalVariableTableElement* lvt = cm->localvariable_table_start();
2145
2146 for (int tbl_no = 0; tbl_no < lvt_cnt; tbl_no++) {
2147 cf_lvt = (Classfile_LVT_Element *) localvariable_table_start[tbl_no];
2148 for (int idx = 0; idx < localvariable_table_length[tbl_no]; idx++, lvt++) {
2149 copy_lvt_element(&cf_lvt[idx], lvt);
2150 // If no duplicates, add LVT elem in hashtable.
2151 if (table->put(*lvt, lvt) == false
2152 && _need_verify
2153 && _major_version >= JAVA_1_5_VERSION) {
2154 classfile_parse_error("Duplicated LocalVariableTable attribute "
2155 "entry for '%s' in class file %s",
2156 _cp->symbol_at(lvt->name_cp_index)->as_utf8(),
2157 THREAD);
2158 return;
2159 }
2160 }
2161 }
2162
2163 // To merge LocalVariableTable and LocalVariableTypeTable
2164 const Classfile_LVT_Element* cf_lvtt;
2165 LocalVariableTableElement lvtt_elem;
2166
2167 for (int tbl_no = 0; tbl_no < lvtt_cnt; tbl_no++) {
2168 cf_lvtt = (Classfile_LVT_Element *) localvariable_type_table_start[tbl_no];
2169 for (int idx = 0; idx < localvariable_type_table_length[tbl_no]; idx++) {
2170 copy_lvt_element(&cf_lvtt[idx], &lvtt_elem);
2171 LocalVariableTableElement** entry = table->get(lvtt_elem);
2172 if (entry == nullptr) {
2173 if (_need_verify) {
2174 classfile_parse_error("LVTT entry for '%s' in class file %s "
2175 "does not match any LVT entry",
2176 _cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(),
2177 THREAD);
2178 return;
2179 }
2180 } else if ((*entry)->signature_cp_index != 0 && _need_verify) {
2181 classfile_parse_error("Duplicated LocalVariableTypeTable attribute "
2182 "entry for '%s' in class file %s",
2183 _cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(),
2184 THREAD);
2185 return;
2186 } else {
2187 // to add generic signatures into LocalVariableTable
2188 (*entry)->signature_cp_index = lvtt_elem.descriptor_cp_index;
2189 }
2190 }
2191 }
2192 }
2193
2194
2195 void ClassFileParser::copy_method_annotations(ConstMethod* cm,
2196 const u1* runtime_visible_annotations,
2197 int runtime_visible_annotations_length,
2198 const u1* runtime_visible_parameter_annotations,
2199 int runtime_visible_parameter_annotations_length,
2200 const u1* runtime_visible_type_annotations,
2201 int runtime_visible_type_annotations_length,
2202 const u1* annotation_default,
2203 int annotation_default_length,
2204 TRAPS) {
2205
2206 AnnotationArray* a;
2207
2208 if (runtime_visible_annotations_length > 0) {
2209 a = allocate_annotations(runtime_visible_annotations,
2210 runtime_visible_annotations_length,
2211 CHECK);
2212 cm->set_method_annotations(a);
2213 }
2214
2215 if (runtime_visible_parameter_annotations_length > 0) {
2216 a = allocate_annotations(runtime_visible_parameter_annotations,
2217 runtime_visible_parameter_annotations_length,
2218 CHECK);
2219 cm->set_parameter_annotations(a);
2220 }
2221
2222 if (annotation_default_length > 0) {
2223 a = allocate_annotations(annotation_default,
2224 annotation_default_length,
2225 CHECK);
2226 cm->set_default_annotations(a);
2227 }
2228
2229 if (runtime_visible_type_annotations_length > 0) {
2230 a = allocate_annotations(runtime_visible_type_annotations,
2231 runtime_visible_type_annotations_length,
2232 CHECK);
2233 cm->set_type_annotations(a);
2234 }
2235 }
2236
2237
2238 // Note: the parse_method below is big and clunky because all parsing of the code and exceptions
2239 // attribute is inlined. This is cumbersome to avoid since we inline most of the parts in the
2240 // Method* to save footprint, so we only know the size of the resulting Method* when the
2241 // entire method attribute is parsed.
2242 //
2243 // The has_localvariable_table parameter is used to pass up the value to InstanceKlass.
2244
2245 Method* ClassFileParser::parse_method(const ClassFileStream* const cfs,
2246 bool is_interface,
2247 bool is_value_class,
2248 bool is_abstract_class,
2249 const ConstantPool* cp,
2250 bool* const has_localvariable_table,
2251 TRAPS) {
2252 assert(cfs != nullptr, "invariant");
2253 assert(cp != nullptr, "invariant");
2254 assert(has_localvariable_table != nullptr, "invariant");
2255
2256 ResourceMark rm(THREAD);
2257 // Parse fixed parts:
2258 // access_flags, name_index, descriptor_index, attributes_count
2259 cfs->guarantee_more(8, CHECK_NULL);
2260
2261 u2 flags = cfs->get_u2_fast();
2262 const u2 name_index = cfs->get_u2_fast();
2263 const int cp_size = cp->length();
2264 guarantee_property(
2265 valid_symbol_at(name_index),
2266 "Illegal constant pool index %u for method name in class file %s",
2267 name_index, CHECK_NULL);
2268 const Symbol* const name = cp->symbol_at(name_index);
2269 verify_legal_method_name(name, CHECK_NULL);
2270
2271 const u2 signature_index = cfs->get_u2_fast();
2272 guarantee_property(
2273 valid_symbol_at(signature_index),
2274 "Illegal constant pool index %u for method signature in class file %s",
2275 signature_index, CHECK_NULL);
2276 const Symbol* const signature = cp->symbol_at(signature_index);
2277
2278 if (name == vmSymbols::class_initializer_name()) {
2279 // We ignore the other access flags for a valid class initializer.
2280 // (JVM Spec 2nd ed., chapter 4.6)
2281 if (_major_version < 51) { // backward compatibility
2282 flags = JVM_ACC_STATIC;
2283 } else if ((flags & JVM_ACC_STATIC) == JVM_ACC_STATIC) {
2284 flags &= JVM_ACC_STATIC | (_major_version <= JAVA_16_VERSION ? JVM_ACC_STRICT : 0);
2285 } else {
2286 classfile_parse_error("Method <clinit> is not static in class file %s", THREAD);
2287 return nullptr;
2288 }
2289 } else {
2290 verify_legal_method_modifiers(flags, access_flags() , name, CHECK_NULL);
2291 }
2292
2293 if (name == vmSymbols::object_initializer_name() && is_interface) {
2294 classfile_parse_error("Interface cannot have a method named <init>, class file %s", THREAD);
2295 return nullptr;
2296 }
2297
2298 if (Arguments::is_valhalla_enabled()) {
2299 if (((flags & JVM_ACC_SYNCHRONIZED) == JVM_ACC_SYNCHRONIZED)
2300 && ((flags & JVM_ACC_STATIC) == 0 )
2301 && !_access_flags.is_identity_class()) {
2302 classfile_parse_error("Invalid synchronized method in non-identity class %s", THREAD);
2303 return nullptr;
2304 }
2305 }
2306
2307 int args_size = -1; // only used when _need_verify is true
2308 if (_need_verify) {
2309 verify_legal_name_with_signature(name, signature, CHECK_NULL);
2310 args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) +
2311 verify_legal_method_signature(name, signature, CHECK_NULL);
2312 if (args_size > MAX_ARGS_SIZE) {
2313 classfile_parse_error("Too many arguments in method signature in class file %s", THREAD);
2314 return nullptr;
2315 }
2316 }
2317
2318 AccessFlags access_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS);
2319
2320 // Default values for code and exceptions attribute elements
2321 u2 max_stack = 0;
2322 u2 max_locals = 0;
2323 u4 code_length = 0;
2324 const u1* code_start = nullptr;
2325 u2 exception_table_length = 0;
2326 const unsafe_u2* exception_table_start = nullptr; // (potentially unaligned) pointer to array of u2 elements
2327 Array<int>* exception_handlers = Universe::the_empty_int_array();
2328 u2 checked_exceptions_length = 0;
2329 const unsafe_u2* checked_exceptions_start = nullptr; // (potentially unaligned) pointer to array of u2 elements
2330 CompressedLineNumberWriteStream* linenumber_table = nullptr;
2331 int linenumber_table_length = 0;
2332 int total_lvt_length = 0;
2333 u2 lvt_cnt = 0;
2334 u2 lvtt_cnt = 0;
2335 bool lvt_allocated = false;
2336 u2 max_lvt_cnt = INITIAL_MAX_LVT_NUMBER;
2337 u2 max_lvtt_cnt = INITIAL_MAX_LVT_NUMBER;
2338 u2* localvariable_table_length = nullptr;
2339 const unsafe_u2** localvariable_table_start = nullptr; // (potentially unaligned) pointer to array of LVT attributes
2340 u2* localvariable_type_table_length = nullptr;
2341 const unsafe_u2** localvariable_type_table_start = nullptr; // (potentially unaligned) pointer to LVTT attributes
2342 int method_parameters_length = -1;
2343 const u1* method_parameters_data = nullptr;
2344 bool method_parameters_seen = false;
2345 bool parsed_code_attribute = false;
2346 bool parsed_checked_exceptions_attribute = false;
2347 bool parsed_stackmap_attribute = false;
2348 // stackmap attribute - JDK1.5
2349 const u1* stackmap_data = nullptr;
2350 int stackmap_data_length = 0;
2351 u2 generic_signature_index = 0;
2352 MethodAnnotationCollector parsed_annotations;
2353 const u1* runtime_visible_annotations = nullptr;
2354 int runtime_visible_annotations_length = 0;
2355 const u1* runtime_visible_parameter_annotations = nullptr;
2356 int runtime_visible_parameter_annotations_length = 0;
2357 const u1* runtime_visible_type_annotations = nullptr;
2358 int runtime_visible_type_annotations_length = 0;
2359 bool runtime_invisible_annotations_exists = false;
2360 bool runtime_invisible_type_annotations_exists = false;
2361 bool runtime_invisible_parameter_annotations_exists = false;
2362 const u1* annotation_default = nullptr;
2363 int annotation_default_length = 0;
2364
2365 // Parse code and exceptions attribute
2366 u2 method_attributes_count = cfs->get_u2_fast();
2367 while (method_attributes_count--) {
2368 cfs->guarantee_more(6, CHECK_NULL); // method_attribute_name_index, method_attribute_length
2369 const u2 method_attribute_name_index = cfs->get_u2_fast();
2370 const u4 method_attribute_length = cfs->get_u4_fast();
2371 guarantee_property(
2372 valid_symbol_at(method_attribute_name_index),
2373 "Invalid method attribute name index %u in class file %s",
2374 method_attribute_name_index, CHECK_NULL);
2375
2376 const Symbol* const method_attribute_name = cp->symbol_at(method_attribute_name_index);
2377 if (method_attribute_name == vmSymbols::tag_code()) {
2378 // Parse Code attribute
2379 if (_need_verify) {
2380 guarantee_property(
2381 !access_flags.is_native() && !access_flags.is_abstract(),
2382 "Code attribute in native or abstract methods in class file %s",
2383 CHECK_NULL);
2384 }
2385 if (parsed_code_attribute) {
2386 classfile_parse_error("Multiple Code attributes in class file %s",
2387 THREAD);
2388 return nullptr;
2389 }
2390 parsed_code_attribute = true;
2391
2392 // Stack size, locals size, and code size
2393 cfs->guarantee_more(8, CHECK_NULL);
2394 max_stack = cfs->get_u2_fast();
2395 max_locals = cfs->get_u2_fast();
2396 code_length = cfs->get_u4_fast();
2397 if (_need_verify) {
2398 guarantee_property(args_size <= max_locals,
2399 "Arguments can't fit into locals in class file %s",
2400 CHECK_NULL);
2401 guarantee_property(code_length > 0 && code_length <= MAX_CODE_SIZE,
2402 "Invalid method Code length %u in class file %s",
2403 code_length, CHECK_NULL);
2404 }
2405 // Code pointer
2406 code_start = cfs->current();
2407 assert(code_start != nullptr, "null code start");
2408 cfs->guarantee_more(code_length, CHECK_NULL);
2409 cfs->skip_u1_fast(code_length);
2410
2411 // Exception handler table
2412 cfs->guarantee_more(2, CHECK_NULL); // exception_table_length
2413 exception_table_length = cfs->get_u2_fast();
2414 if (exception_table_length > 0) {
2415 exception_table_start = parse_exception_table(cfs,
2416 code_length,
2417 exception_table_length,
2418 CHECK_NULL);
2419 }
2420
2421 // Parse additional attributes in code attribute
2422 cfs->guarantee_more(2, CHECK_NULL); // code_attributes_count
2423 u2 code_attributes_count = cfs->get_u2_fast();
2424
2425 unsigned int calculated_attribute_length = 0;
2426
2427 calculated_attribute_length =
2428 sizeof(max_stack) + sizeof(max_locals) + sizeof(code_length);
2429 calculated_attribute_length += checked_cast<unsigned int>(
2430 code_length +
2431 sizeof(exception_table_length) +
2432 sizeof(code_attributes_count) +
2433 exception_table_length *
2434 ( sizeof(u2) + // start_pc
2435 sizeof(u2) + // end_pc
2436 sizeof(u2) + // handler_pc
2437 sizeof(u2) )); // catch_type_index
2438
2439 while (code_attributes_count--) {
2440 cfs->guarantee_more(6, CHECK_NULL); // code_attribute_name_index, code_attribute_length
2441 const u2 code_attribute_name_index = cfs->get_u2_fast();
2442 const u4 code_attribute_length = cfs->get_u4_fast();
2443 calculated_attribute_length += code_attribute_length +
2444 (unsigned)sizeof(code_attribute_name_index) +
2445 (unsigned)sizeof(code_attribute_length);
2446 guarantee_property(valid_symbol_at(code_attribute_name_index),
2447 "Invalid code attribute name index %u in class file %s",
2448 code_attribute_name_index,
2449 CHECK_NULL);
2450 if (LoadLineNumberTables &&
2451 cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_line_number_table()) {
2452 // Parse and compress line number table
2453 parse_linenumber_table(code_attribute_length,
2454 code_length,
2455 &linenumber_table,
2456 CHECK_NULL);
2457
2458 } else if (LoadLocalVariableTables &&
2459 cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_table()) {
2460 // Parse local variable table
2461 if (!lvt_allocated) {
2462 localvariable_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2463 THREAD, u2, INITIAL_MAX_LVT_NUMBER);
2464 localvariable_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2465 THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER);
2466 localvariable_type_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2467 THREAD, u2, INITIAL_MAX_LVT_NUMBER);
2468 localvariable_type_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2469 THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER);
2470 lvt_allocated = true;
2471 }
2472 if (lvt_cnt == max_lvt_cnt) {
2473 max_lvt_cnt <<= 1;
2474 localvariable_table_length = REALLOC_RESOURCE_ARRAY(u2, localvariable_table_length, lvt_cnt, max_lvt_cnt);
2475 localvariable_table_start = REALLOC_RESOURCE_ARRAY(const unsafe_u2*, localvariable_table_start, lvt_cnt, max_lvt_cnt);
2476 }
2477 localvariable_table_start[lvt_cnt] =
2478 parse_localvariable_table(cfs,
2479 code_length,
2480 max_locals,
2481 code_attribute_length,
2482 &localvariable_table_length[lvt_cnt],
2483 false, // is not LVTT
2484 CHECK_NULL);
2485 total_lvt_length += localvariable_table_length[lvt_cnt];
2486 lvt_cnt++;
2487 } else if (LoadLocalVariableTypeTables &&
2488 _major_version >= JAVA_1_5_VERSION &&
2489 cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_type_table()) {
2490 if (!lvt_allocated) {
2491 localvariable_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2492 THREAD, u2, INITIAL_MAX_LVT_NUMBER);
2493 localvariable_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2494 THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER);
2495 localvariable_type_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2496 THREAD, u2, INITIAL_MAX_LVT_NUMBER);
2497 localvariable_type_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2498 THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER);
2499 lvt_allocated = true;
2500 }
2501 // Parse local variable type table
2502 if (lvtt_cnt == max_lvtt_cnt) {
2503 max_lvtt_cnt <<= 1;
2504 localvariable_type_table_length = REALLOC_RESOURCE_ARRAY(u2, localvariable_type_table_length, lvtt_cnt, max_lvtt_cnt);
2505 localvariable_type_table_start = REALLOC_RESOURCE_ARRAY(const unsafe_u2*, localvariable_type_table_start, lvtt_cnt, max_lvtt_cnt);
2506 }
2507 localvariable_type_table_start[lvtt_cnt] =
2508 parse_localvariable_table(cfs,
2509 code_length,
2510 max_locals,
2511 code_attribute_length,
2512 &localvariable_type_table_length[lvtt_cnt],
2513 true, // is LVTT
2514 CHECK_NULL);
2515 lvtt_cnt++;
2516 } else if (_major_version >= Verifier::STACKMAP_ATTRIBUTE_MAJOR_VERSION &&
2517 cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_stack_map_table()) {
2518 // Stack map is only needed by the new verifier in JDK1.5.
2519 if (parsed_stackmap_attribute) {
2520 classfile_parse_error("Multiple StackMapTable attributes in class file %s", THREAD);
2521 return nullptr;
2522 }
2523 stackmap_data = parse_stackmap_table(cfs, code_attribute_length, CHECK_NULL);
2524 stackmap_data_length = code_attribute_length;
2525 parsed_stackmap_attribute = true;
2526 } else {
2527 // Skip unknown attributes
2528 cfs->skip_u1(code_attribute_length, CHECK_NULL);
2529 }
2530 }
2531 // check method attribute length
2532 if (_need_verify) {
2533 guarantee_property(method_attribute_length == calculated_attribute_length,
2534 "Code segment has wrong length in class file %s",
2535 CHECK_NULL);
2536 }
2537 } else if (method_attribute_name == vmSymbols::tag_exceptions()) {
2538 // Parse Exceptions attribute
2539 if (parsed_checked_exceptions_attribute) {
2540 classfile_parse_error("Multiple Exceptions attributes in class file %s",
2541 THREAD);
2542 return nullptr;
2543 }
2544 parsed_checked_exceptions_attribute = true;
2545 checked_exceptions_start =
2546 parse_checked_exceptions(cfs,
2547 &checked_exceptions_length,
2548 method_attribute_length,
2549 CHECK_NULL);
2550 } else if (method_attribute_name == vmSymbols::tag_method_parameters()) {
2551 // reject multiple method parameters
2552 if (method_parameters_seen) {
2553 classfile_parse_error("Multiple MethodParameters attributes in class file %s",
2554 THREAD);
2555 return nullptr;
2556 }
2557 method_parameters_seen = true;
2558 method_parameters_length = cfs->get_u1_fast();
2559 const u4 real_length = (method_parameters_length * 4u) + 1u;
2560 if (method_attribute_length != real_length) {
2561 classfile_parse_error(
2562 "Invalid MethodParameters method attribute length %u in class file",
2563 method_attribute_length, THREAD);
2564 return nullptr;
2565 }
2566 method_parameters_data = cfs->current();
2567 cfs->skip_u2_fast(method_parameters_length);
2568 cfs->skip_u2_fast(method_parameters_length);
2569 // ignore this attribute if it cannot be reflected
2570 if (!vmClasses::reflect_Parameter_klass_is_loaded())
2571 method_parameters_length = -1;
2572 } else if (method_attribute_name == vmSymbols::tag_synthetic()) {
2573 if (method_attribute_length != 0) {
2574 classfile_parse_error(
2575 "Invalid Synthetic method attribute length %u in class file %s",
2576 method_attribute_length, THREAD);
2577 return nullptr;
2578 }
2579 // Should we check that there hasn't already been a synthetic attribute?
2580 access_flags.set_is_synthetic();
2581 } else if (method_attribute_name == vmSymbols::tag_deprecated()) { // 4276120
2582 if (method_attribute_length != 0) {
2583 classfile_parse_error(
2584 "Invalid Deprecated method attribute length %u in class file %s",
2585 method_attribute_length, THREAD);
2586 return nullptr;
2587 }
2588 } else if (_major_version >= JAVA_1_5_VERSION) {
2589 if (method_attribute_name == vmSymbols::tag_signature()) {
2590 if (generic_signature_index != 0) {
2591 classfile_parse_error(
2592 "Multiple Signature attributes for method in class file %s",
2593 THREAD);
2594 return nullptr;
2595 }
2596 if (method_attribute_length != 2) {
2597 classfile_parse_error(
2598 "Invalid Signature attribute length %u in class file %s",
2599 method_attribute_length, THREAD);
2600 return nullptr;
2601 }
2602 generic_signature_index = parse_generic_signature_attribute(cfs, CHECK_NULL);
2603 } else if (method_attribute_name == vmSymbols::tag_runtime_visible_annotations()) {
2604 if (runtime_visible_annotations != nullptr) {
2605 classfile_parse_error(
2606 "Multiple RuntimeVisibleAnnotations attributes for method in class file %s",
2607 THREAD);
2608 return nullptr;
2609 }
2610 runtime_visible_annotations_length = method_attribute_length;
2611 runtime_visible_annotations = cfs->current();
2612 assert(runtime_visible_annotations != nullptr, "null visible annotations");
2613 cfs->guarantee_more(runtime_visible_annotations_length, CHECK_NULL);
2614 parse_annotations(cp,
2615 runtime_visible_annotations,
2616 runtime_visible_annotations_length,
2617 &parsed_annotations,
2618 _loader_data,
2619 _can_access_vm_annotations);
2620 cfs->skip_u1_fast(runtime_visible_annotations_length);
2621 } else if (method_attribute_name == vmSymbols::tag_runtime_invisible_annotations()) {
2622 if (runtime_invisible_annotations_exists) {
2623 classfile_parse_error(
2624 "Multiple RuntimeInvisibleAnnotations attributes for method in class file %s",
2625 THREAD);
2626 return nullptr;
2627 }
2628 runtime_invisible_annotations_exists = true;
2629 cfs->skip_u1(method_attribute_length, CHECK_NULL);
2630 } else if (method_attribute_name == vmSymbols::tag_runtime_visible_parameter_annotations()) {
2631 if (runtime_visible_parameter_annotations != nullptr) {
2632 classfile_parse_error(
2633 "Multiple RuntimeVisibleParameterAnnotations attributes for method in class file %s",
2634 THREAD);
2635 return nullptr;
2636 }
2637 runtime_visible_parameter_annotations_length = method_attribute_length;
2638 runtime_visible_parameter_annotations = cfs->current();
2639 assert(runtime_visible_parameter_annotations != nullptr, "null visible parameter annotations");
2640 cfs->skip_u1(runtime_visible_parameter_annotations_length, CHECK_NULL);
2641 } else if (method_attribute_name == vmSymbols::tag_runtime_invisible_parameter_annotations()) {
2642 if (runtime_invisible_parameter_annotations_exists) {
2643 classfile_parse_error(
2644 "Multiple RuntimeInvisibleParameterAnnotations attributes for method in class file %s",
2645 THREAD);
2646 return nullptr;
2647 }
2648 runtime_invisible_parameter_annotations_exists = true;
2649 cfs->skip_u1(method_attribute_length, CHECK_NULL);
2650 } else if (method_attribute_name == vmSymbols::tag_annotation_default()) {
2651 if (annotation_default != nullptr) {
2652 classfile_parse_error(
2653 "Multiple AnnotationDefault attributes for method in class file %s",
2654 THREAD);
2655 return nullptr;
2656 }
2657 annotation_default_length = method_attribute_length;
2658 annotation_default = cfs->current();
2659 assert(annotation_default != nullptr, "null annotation default");
2660 cfs->skip_u1(annotation_default_length, CHECK_NULL);
2661 } else if (method_attribute_name == vmSymbols::tag_runtime_visible_type_annotations()) {
2662 if (runtime_visible_type_annotations != nullptr) {
2663 classfile_parse_error(
2664 "Multiple RuntimeVisibleTypeAnnotations attributes for method in class file %s",
2665 THREAD);
2666 return nullptr;
2667 }
2668 runtime_visible_type_annotations_length = method_attribute_length;
2669 runtime_visible_type_annotations = cfs->current();
2670 assert(runtime_visible_type_annotations != nullptr, "null visible type annotations");
2671 // No need for the VM to parse Type annotations
2672 cfs->skip_u1(runtime_visible_type_annotations_length, CHECK_NULL);
2673 } else if (method_attribute_name == vmSymbols::tag_runtime_invisible_type_annotations()) {
2674 if (runtime_invisible_type_annotations_exists) {
2675 classfile_parse_error(
2676 "Multiple RuntimeInvisibleTypeAnnotations attributes for method in class file %s",
2677 THREAD);
2678 return nullptr;
2679 }
2680 runtime_invisible_type_annotations_exists = true;
2681 cfs->skip_u1(method_attribute_length, CHECK_NULL);
2682 } else {
2683 // Skip unknown attributes
2684 cfs->skip_u1(method_attribute_length, CHECK_NULL);
2685 }
2686 } else {
2687 // Skip unknown attributes
2688 cfs->skip_u1(method_attribute_length, CHECK_NULL);
2689 }
2690 }
2691
2692 if (linenumber_table != nullptr) {
2693 linenumber_table->write_terminator();
2694 linenumber_table_length = linenumber_table->position();
2695 }
2696
2697 // Make sure there's at least one Code attribute in non-native/non-abstract method
2698 if (_need_verify) {
2699 guarantee_property(access_flags.is_native() ||
2700 access_flags.is_abstract() ||
2701 parsed_code_attribute,
2702 "Absent Code attribute in method that is not native or abstract in class file %s",
2703 CHECK_NULL);
2704 }
2705
2706 // All sizing information for a Method* is finally available, now create it
2707 InlineTableSizes sizes(
2708 total_lvt_length,
2709 linenumber_table_length,
2710 exception_table_length,
2711 checked_exceptions_length,
2712 method_parameters_length,
2713 generic_signature_index,
2714 runtime_visible_annotations_length,
2715 runtime_visible_parameter_annotations_length,
2716 runtime_visible_type_annotations_length,
2717 annotation_default_length,
2718 0);
2719
2720 Method* const m = Method::allocate(_loader_data,
2721 code_length,
2722 access_flags,
2723 &sizes,
2724 ConstMethod::NORMAL,
2725 _cp->symbol_at(name_index),
2726 CHECK_NULL);
2727
2728 ClassLoadingService::add_class_method_size(m->size()*wordSize);
2729
2730 // Fill in information from fixed part (access_flags already set)
2731 m->set_constants(_cp);
2732 m->set_name_index(name_index);
2733 m->set_signature_index(signature_index);
2734 m->constMethod()->compute_from_signature(cp->symbol_at(signature_index), access_flags.is_static());
2735 assert(args_size < 0 || args_size == m->size_of_parameters(), "");
2736
2737 // Fill in code attribute information
2738 m->set_max_stack(max_stack);
2739 m->set_max_locals(max_locals);
2740 if (stackmap_data != nullptr) {
2741 m->constMethod()->copy_stackmap_data(_loader_data,
2742 (u1*)stackmap_data,
2743 stackmap_data_length,
2744 CHECK_NULL);
2745 }
2746
2747 // Copy byte codes
2748 m->set_code((u1*)code_start);
2749
2750 // Copy line number table
2751 if (linenumber_table != nullptr) {
2752 memcpy(m->compressed_linenumber_table(),
2753 linenumber_table->buffer(),
2754 linenumber_table_length);
2755 }
2756
2757 // Copy exception table
2758 if (exception_table_length > 0) {
2759 Copy::conjoint_swap_if_needed<Endian::JAVA>(exception_table_start,
2760 m->exception_table_start(),
2761 exception_table_length * sizeof(ExceptionTableElement),
2762 sizeof(u2));
2763 }
2764
2765 // Copy method parameters
2766 if (method_parameters_length > 0) {
2767 MethodParametersElement* elem = m->constMethod()->method_parameters_start();
2768 for (int i = 0; i < method_parameters_length; i++) {
2769 elem[i].name_cp_index = Bytes::get_Java_u2((address)method_parameters_data);
2770 method_parameters_data += 2;
2771 elem[i].flags = Bytes::get_Java_u2((address)method_parameters_data);
2772 method_parameters_data += 2;
2773 }
2774 }
2775
2776 // Copy checked exceptions
2777 if (checked_exceptions_length > 0) {
2778 Copy::conjoint_swap_if_needed<Endian::JAVA>(checked_exceptions_start,
2779 m->checked_exceptions_start(),
2780 checked_exceptions_length * sizeof(CheckedExceptionElement),
2781 sizeof(u2));
2782 }
2783
2784 // Copy class file LVT's/LVTT's into the HotSpot internal LVT.
2785 if (total_lvt_length > 0) {
2786 *has_localvariable_table = true;
2787 copy_localvariable_table(m->constMethod(),
2788 lvt_cnt,
2789 localvariable_table_length,
2790 localvariable_table_start,
2791 lvtt_cnt,
2792 localvariable_type_table_length,
2793 localvariable_type_table_start,
2794 CHECK_NULL);
2795 }
2796
2797 if (parsed_annotations.has_any_annotations())
2798 parsed_annotations.apply_to(methodHandle(THREAD, m));
2799
2800 if (is_hidden()) { // Mark methods in hidden classes as 'hidden'.
2801 m->set_is_hidden();
2802 }
2803 if (parsed_annotations.has_aot_runtime_setup()) {
2804 if (name != vmSymbols::runtimeSetup() || signature != vmSymbols::void_method_signature() ||
2805 !access_flags.is_private() || !access_flags.is_static()) {
2806 classfile_parse_error("@AOTRuntimeSetup method must be declared private static void runtimeSetup() for class %s", CHECK_NULL);
2807 }
2808 _has_aot_runtime_setup_method = true;
2809 }
2810
2811 // Copy annotations
2812 copy_method_annotations(m->constMethod(),
2813 runtime_visible_annotations,
2814 runtime_visible_annotations_length,
2815 runtime_visible_parameter_annotations,
2816 runtime_visible_parameter_annotations_length,
2817 runtime_visible_type_annotations,
2818 runtime_visible_type_annotations_length,
2819 annotation_default,
2820 annotation_default_length,
2821 CHECK_NULL);
2822
2823 if (InstanceKlass::is_finalization_enabled() &&
2824 name == vmSymbols::finalize_method_name() &&
2825 signature == vmSymbols::void_method_signature()) {
2826 if (m->is_empty_method()) {
2827 _has_empty_finalizer = true;
2828 } else {
2829 _has_finalizer = true;
2830 }
2831 }
2832
2833 NOT_PRODUCT(m->verify());
2834 return m;
2835 }
2836
2837
2838 // Side-effects: populates the _methods field in the parser
2839 void ClassFileParser::parse_methods(const ClassFileStream* const cfs,
2840 bool is_interface,
2841 bool is_value_class,
2842 bool is_abstract_type,
2843 bool* const has_localvariable_table,
2844 bool* has_final_method,
2845 bool* declares_nonstatic_concrete_methods,
2846 TRAPS) {
2847 assert(cfs != nullptr, "invariant");
2848 assert(has_localvariable_table != nullptr, "invariant");
2849 assert(has_final_method != nullptr, "invariant");
2850 assert(declares_nonstatic_concrete_methods != nullptr, "invariant");
2851
2852 assert(nullptr == _methods, "invariant");
2853
2854 cfs->guarantee_more(2, CHECK); // length
2855 const u2 length = cfs->get_u2_fast();
2856 if (length == 0) {
2857 _methods = Universe::the_empty_method_array();
2858 } else {
2859 _methods = MetadataFactory::new_array<Method*>(_loader_data,
2860 length,
2861 nullptr,
2862 CHECK);
2863
2864 for (int index = 0; index < length; index++) {
2865 Method* method = parse_method(cfs,
2866 is_interface,
2867 is_value_class,
2868 is_abstract_type,
2869 _cp,
2870 has_localvariable_table,
2871 CHECK);
2872
2873 if (method->is_final()) {
2874 *has_final_method = true;
2875 }
2876 // declares_nonstatic_concrete_methods: declares concrete instance methods, any access flags
2877 // used for interface initialization, and default method inheritance analysis
2878 if (is_interface && !(*declares_nonstatic_concrete_methods)
2879 && !method->is_abstract() && !method->is_static()) {
2880 *declares_nonstatic_concrete_methods = true;
2881 }
2882 _methods->at_put(index, method);
2883 }
2884
2885 if (_need_verify && length > 1) {
2886 // Check duplicated methods
2887 ResourceMark rm(THREAD);
2888 // Set containing name-signature pairs
2889 NameSigHashtable* names_and_sigs = new NameSigHashtable();
2890 for (int i = 0; i < length; i++) {
2891 const Method* const m = _methods->at(i);
2892 NameSigHash name_and_sig(m->name(), m->signature());
2893 // If no duplicates, add name/signature in hashtable names_and_sigs.
2894 if(!names_and_sigs->put(name_and_sig, 0)) {
2895 classfile_parse_error("Duplicate method name \"%s\" with signature \"%s\" in class file %s",
2896 name_and_sig._name->as_C_string(), name_and_sig._sig->as_klass_external_name(), THREAD);
2897 return;
2898 }
2899 }
2900 }
2901 }
2902 }
2903
2904 static const intArray* sort_methods(Array<Method*>* methods) {
2905 const int length = methods->length();
2906 // If JVMTI original method ordering or sharing is enabled we have to
2907 // remember the original class file ordering.
2908 // We temporarily use the vtable_index field in the Method* to store the
2909 // class file index, so we can read in after calling qsort.
2910 // Put the method ordering in the shared archive.
2911 if (JvmtiExport::can_maintain_original_method_order() || CDSConfig::is_dumping_archive()) {
2912 for (int index = 0; index < length; index++) {
2913 Method* const m = methods->at(index);
2914 assert(!m->valid_vtable_index(), "vtable index should not be set");
2915 m->set_vtable_index(index);
2916 }
2917 }
2918 // Sort method array by ascending method name (for faster lookups & vtable construction)
2919 // Note that the ordering is not alphabetical, see Symbol::fast_compare
2920 Method::sort_methods(methods);
2921
2922 intArray* method_ordering = nullptr;
2923 // If JVMTI original method ordering or sharing is enabled construct int
2924 // array remembering the original ordering
2925 if (JvmtiExport::can_maintain_original_method_order() || CDSConfig::is_dumping_archive()) {
2926 method_ordering = new intArray(length, length, -1);
2927 for (int index = 0; index < length; index++) {
2928 Method* const m = methods->at(index);
2929 const int old_index = m->vtable_index();
2930 assert(old_index >= 0 && old_index < length, "invalid method index");
2931 method_ordering->at_put(index, old_index);
2932 m->set_vtable_index(Method::invalid_vtable_index);
2933 }
2934 }
2935 return method_ordering;
2936 }
2937
2938 // Parse generic_signature attribute for methods and fields
2939 u2 ClassFileParser::parse_generic_signature_attribute(const ClassFileStream* const cfs,
2940 TRAPS) {
2941 assert(cfs != nullptr, "invariant");
2942
2943 cfs->guarantee_more(2, CHECK_0); // generic_signature_index
2944 const u2 generic_signature_index = cfs->get_u2_fast();
2945 guarantee_property(
2946 valid_symbol_at(generic_signature_index),
2947 "Invalid Signature attribute at constant pool index %u in class file %s",
2948 generic_signature_index, CHECK_0);
2949 return generic_signature_index;
2950 }
2951
2952 void ClassFileParser::parse_classfile_sourcefile_attribute(const ClassFileStream* const cfs,
2953 TRAPS) {
2954
2955 assert(cfs != nullptr, "invariant");
2956
2957 cfs->guarantee_more(2, CHECK); // sourcefile_index
2958 const u2 sourcefile_index = cfs->get_u2_fast();
2959 guarantee_property(
2960 valid_symbol_at(sourcefile_index),
2961 "Invalid SourceFile attribute at constant pool index %u in class file %s",
2962 sourcefile_index, CHECK);
2963 set_class_sourcefile_index(sourcefile_index);
2964 }
2965
2966 void ClassFileParser::parse_classfile_source_debug_extension_attribute(const ClassFileStream* const cfs,
2967 int length,
2968 TRAPS) {
2969 assert(cfs != nullptr, "invariant");
2970
2971 const u1* const sde_buffer = cfs->current();
2972 assert(sde_buffer != nullptr, "null sde buffer");
2973
2974 // Don't bother storing it if there is no way to retrieve it
2975 if (JvmtiExport::can_get_source_debug_extension()) {
2976 assert((length+1) > length, "Overflow checking");
2977 u1* const sde = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, u1, length+1);
2978 for (int i = 0; i < length; i++) {
2979 sde[i] = sde_buffer[i];
2980 }
2981 sde[length] = '\0';
2982 set_class_sde_buffer((const char*)sde, length);
2983 }
2984 // Got utf8 string, set stream position forward
2985 cfs->skip_u1(length, CHECK);
2986 }
2987
2988
2989 // Inner classes can be static, private or protected (classic VM does this)
2990 #define RECOGNIZED_INNER_CLASS_MODIFIERS ( JVM_RECOGNIZED_CLASS_MODIFIERS | \
2991 JVM_ACC_PRIVATE | \
2992 JVM_ACC_PROTECTED | \
2993 JVM_ACC_STATIC \
2994 )
2995
2996 // Find index of the InnerClasses entry for the specified inner_class_info_index.
2997 // Return -1 if none is found.
2998 static int inner_classes_find_index(const Array<u2>* inner_classes, int inner, const ConstantPool* cp, int length) {
2999 Symbol* cp_klass_name = cp->klass_name_at(inner);
3000 for (int idx = 0; idx < length; idx += InstanceKlass::inner_class_next_offset) {
3001 int idx_inner = inner_classes->at(idx + InstanceKlass::inner_class_inner_class_info_offset);
3002 if (cp->klass_name_at(idx_inner) == cp_klass_name) {
3003 return idx;
3004 }
3005 }
3006 return -1;
3007 }
3008
3009 // Return the outer_class_info_index for the InnerClasses entry containing the
3010 // specified inner_class_info_index. Return -1 if no InnerClasses entry is found.
3011 static int inner_classes_jump_to_outer(const Array<u2>* inner_classes, int inner, const ConstantPool* cp, int length) {
3012 if (inner == 0) return -1;
3013 int idx = inner_classes_find_index(inner_classes, inner, cp, length);
3014 if (idx == -1) return -1;
3015 int result = inner_classes->at(idx + InstanceKlass::inner_class_outer_class_info_offset);
3016 return result;
3017 }
3018
3019 // Return true if circularity is found, false if no circularity is found.
3020 // Use Floyd's cycle finding algorithm.
3021 static bool inner_classes_check_loop_through_outer(const Array<u2>* inner_classes, int idx, const ConstantPool* cp, int length) {
3022 int slow = inner_classes->at(idx + InstanceKlass::inner_class_inner_class_info_offset);
3023 int fast = inner_classes->at(idx + InstanceKlass::inner_class_outer_class_info_offset);
3024
3025 while (fast != -1 && fast != 0) {
3026 if (slow != 0 && (cp->klass_name_at(slow) == cp->klass_name_at(fast))) {
3027 return true; // found a circularity
3028 }
3029 fast = inner_classes_jump_to_outer(inner_classes, fast, cp, length);
3030 if (fast == -1) return false;
3031 fast = inner_classes_jump_to_outer(inner_classes, fast, cp, length);
3032 if (fast == -1) return false;
3033 slow = inner_classes_jump_to_outer(inner_classes, slow, cp, length);
3034 assert(slow != -1, "sanity check");
3035 }
3036 return false;
3037 }
3038
3039 // Loop through each InnerClasses entry checking for circularities and duplications
3040 // with other entries. If duplicate entries are found then throw CFE. Otherwise,
3041 // return true if a circularity or entries with duplicate inner_class_info_indexes
3042 // are found.
3043 bool ClassFileParser::check_inner_classes_circularity(const ConstantPool* cp, int length, TRAPS) {
3044 // Loop through each InnerClasses entry.
3045 for (int idx = 0; idx < length; idx += InstanceKlass::inner_class_next_offset) {
3046 // Return true if there are circular entries.
3047 if (inner_classes_check_loop_through_outer(_inner_classes, idx, cp, length)) {
3048 return true;
3049 }
3050 // Check if there are duplicate entries or entries with the same inner_class_info_index.
3051 for (int y = idx + InstanceKlass::inner_class_next_offset; y < length;
3052 y += InstanceKlass::inner_class_next_offset) {
3053
3054 // 4347400: make sure there's no duplicate entry in the classes array
3055 if (_major_version >= JAVA_1_5_VERSION) {
3056 guarantee_property((_inner_classes->at(idx) != _inner_classes->at(y) ||
3057 _inner_classes->at(idx+1) != _inner_classes->at(y+1) ||
3058 _inner_classes->at(idx+2) != _inner_classes->at(y+2) ||
3059 _inner_classes->at(idx+3) != _inner_classes->at(y+3)),
3060 "Duplicate entry in InnerClasses attribute in class file %s",
3061 CHECK_(true));
3062 }
3063 // Return true if there are two entries with the same inner_class_info_index.
3064 if (_inner_classes->at(y) == _inner_classes->at(idx)) {
3065 return true;
3066 }
3067 }
3068 }
3069 return false;
3070 }
3071
3072 // Return number of classes in the inner classes attribute table
3073 u2 ClassFileParser::parse_classfile_inner_classes_attribute(const ClassFileStream* const cfs,
3074 const ConstantPool* cp,
3075 const u1* const inner_classes_attribute_start,
3076 bool parsed_enclosingmethod_attribute,
3077 u2 enclosing_method_class_index,
3078 u2 enclosing_method_method_index,
3079 TRAPS) {
3080 const u1* const current_mark = cfs->current();
3081 u2 length = 0;
3082 if (inner_classes_attribute_start != nullptr) {
3083 cfs->set_current(inner_classes_attribute_start);
3084 cfs->guarantee_more(2, CHECK_0); // length
3085 length = cfs->get_u2_fast();
3086 }
3087
3088 // 4-tuples of shorts of inner classes data and 2 shorts of enclosing
3089 // method data:
3090 // [inner_class_info_index,
3091 // outer_class_info_index,
3092 // inner_name_index,
3093 // inner_class_access_flags,
3094 // ...
3095 // enclosing_method_class_index,
3096 // enclosing_method_method_index]
3097 const int size = length * 4 + (parsed_enclosingmethod_attribute ? 2 : 0);
3098 Array<u2>* inner_classes = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
3099 _inner_classes = inner_classes;
3100
3101 int index = 0;
3102 cfs->guarantee_more(8 * length, CHECK_0); // 4-tuples of u2
3103 for (int n = 0; n < length; n++) {
3104 // Inner class index
3105 const u2 inner_class_info_index = cfs->get_u2_fast();
3106 guarantee_property(
3107 valid_klass_reference_at(inner_class_info_index),
3108 "inner_class_info_index %u has bad constant type in class file %s",
3109 inner_class_info_index, CHECK_0);
3110 // Outer class index
3111 const u2 outer_class_info_index = cfs->get_u2_fast();
3112 guarantee_property(
3113 outer_class_info_index == 0 ||
3114 valid_klass_reference_at(outer_class_info_index),
3115 "outer_class_info_index %u has bad constant type in class file %s",
3116 outer_class_info_index, CHECK_0);
3117
3118 if (outer_class_info_index != 0) {
3119 const Symbol* const outer_class_name = cp->klass_name_at(outer_class_info_index);
3120 char* bytes = (char*)outer_class_name->bytes();
3121 guarantee_property(bytes[0] != JVM_SIGNATURE_ARRAY,
3122 "Outer class is an array class in class file %s", CHECK_0);
3123 }
3124 // Inner class name
3125 const u2 inner_name_index = cfs->get_u2_fast();
3126 guarantee_property(
3127 inner_name_index == 0 || valid_symbol_at(inner_name_index),
3128 "inner_name_index %u has bad constant type in class file %s",
3129 inner_name_index, CHECK_0);
3130 if (_need_verify) {
3131 guarantee_property(inner_class_info_index != outer_class_info_index,
3132 "Class is both outer and inner class in class file %s", CHECK_0);
3133 }
3134
3135 // Access flags
3136 u2 flags;
3137 // JVM_ACC_MODULE is defined in JDK-9 and later.
3138 if (_major_version >= JAVA_9_VERSION) {
3139 flags = cfs->get_u2_fast() & (RECOGNIZED_INNER_CLASS_MODIFIERS | JVM_ACC_MODULE);
3140 } else {
3141 flags = cfs->get_u2_fast() & RECOGNIZED_INNER_CLASS_MODIFIERS;
3142 }
3143
3144 if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
3145 // Set abstract bit for old class files for backward compatibility
3146 flags |= JVM_ACC_ABSTRACT;
3147 }
3148
3149 if (!supports_inline_types()) {
3150 const bool is_module = (flags & JVM_ACC_MODULE) != 0;
3151 const bool is_interface = (flags & JVM_ACC_INTERFACE) != 0;
3152 if (!is_module && !is_interface) {
3153 flags |= JVM_ACC_IDENTITY;
3154 }
3155 }
3156
3157 Symbol* inner_name_symbol = inner_name_index == 0 ? nullptr : cp->symbol_at(inner_name_index);
3158 verify_legal_class_modifiers(flags, inner_name_symbol, inner_name_index == 0, CHECK_0);
3159 AccessFlags inner_access_flags(flags);
3160
3161 inner_classes->at_put(index++, inner_class_info_index);
3162 inner_classes->at_put(index++, outer_class_info_index);
3163 inner_classes->at_put(index++, inner_name_index);
3164 inner_classes->at_put(index++, inner_access_flags.as_unsigned_short());
3165 }
3166
3167 // Check for circular and duplicate entries.
3168 bool has_circularity = false;
3169 if (_need_verify) {
3170 has_circularity = check_inner_classes_circularity(cp, length * 4, CHECK_0);
3171 if (has_circularity) {
3172 // If circularity check failed then ignore InnerClasses attribute.
3173 MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
3174 index = 0;
3175 if (parsed_enclosingmethod_attribute) {
3176 inner_classes = MetadataFactory::new_array<u2>(_loader_data, 2, CHECK_0);
3177 _inner_classes = inner_classes;
3178 } else {
3179 _inner_classes = Universe::the_empty_short_array();
3180 }
3181 }
3182 }
3183 // Set EnclosingMethod class and method indexes.
3184 if (parsed_enclosingmethod_attribute) {
3185 inner_classes->at_put(index++, enclosing_method_class_index);
3186 inner_classes->at_put(index++, enclosing_method_method_index);
3187 }
3188 assert(index == size || has_circularity, "wrong size");
3189
3190 // Restore buffer's current position.
3191 cfs->set_current(current_mark);
3192
3193 return length;
3194 }
3195
3196 u2 ClassFileParser::parse_classfile_nest_members_attribute(const ClassFileStream* const cfs,
3197 const u1* const nest_members_attribute_start,
3198 TRAPS) {
3199 const u1* const current_mark = cfs->current();
3200 u2 length = 0;
3201 if (nest_members_attribute_start != nullptr) {
3202 cfs->set_current(nest_members_attribute_start);
3203 cfs->guarantee_more(2, CHECK_0); // length
3204 length = cfs->get_u2_fast();
3205 }
3206 const int size = length;
3207 Array<u2>* const nest_members = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
3208 _nest_members = nest_members;
3209
3210 int index = 0;
3211 cfs->guarantee_more(2 * length, CHECK_0);
3212 for (int n = 0; n < length; n++) {
3213 const u2 class_info_index = cfs->get_u2_fast();
3214 guarantee_property(
3215 valid_klass_reference_at(class_info_index),
3216 "Nest member class_info_index %u has bad constant type in class file %s",
3217 class_info_index, CHECK_0);
3218 nest_members->at_put(index++, class_info_index);
3219 }
3220 assert(index == size, "wrong size");
3221
3222 // Restore buffer's current position.
3223 cfs->set_current(current_mark);
3224
3225 return length;
3226 }
3227
3228 u2 ClassFileParser::parse_classfile_permitted_subclasses_attribute(const ClassFileStream* const cfs,
3229 const u1* const permitted_subclasses_attribute_start,
3230 TRAPS) {
3231 const u1* const current_mark = cfs->current();
3232 u2 length = 0;
3233 if (permitted_subclasses_attribute_start != nullptr) {
3234 cfs->set_current(permitted_subclasses_attribute_start);
3235 cfs->guarantee_more(2, CHECK_0); // length
3236 length = cfs->get_u2_fast();
3237 }
3238 const int size = length;
3239 Array<u2>* const permitted_subclasses = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
3240 _permitted_subclasses = permitted_subclasses;
3241
3242 if (length > 0) {
3243 int index = 0;
3244 cfs->guarantee_more(2 * length, CHECK_0);
3245 for (int n = 0; n < length; n++) {
3246 const u2 class_info_index = cfs->get_u2_fast();
3247 guarantee_property(
3248 valid_klass_reference_at(class_info_index),
3249 "Permitted subclass class_info_index %u has bad constant type in class file %s",
3250 class_info_index, CHECK_0);
3251 permitted_subclasses->at_put(index++, class_info_index);
3252 }
3253 assert(index == size, "wrong size");
3254 }
3255
3256 // Restore buffer's current position.
3257 cfs->set_current(current_mark);
3258
3259 return length;
3260 }
3261
3262 u2 ClassFileParser::parse_classfile_loadable_descriptors_attribute(const ClassFileStream* const cfs,
3263 const u1* const loadable_descriptors_attribute_start,
3264 TRAPS) {
3265 const u1* const current_mark = cfs->current();
3266 u2 length = 0;
3267 if (loadable_descriptors_attribute_start != nullptr) {
3268 cfs->set_current(loadable_descriptors_attribute_start);
3269 cfs->guarantee_more(2, CHECK_0); // length
3270 length = cfs->get_u2_fast();
3271 }
3272 const int size = length;
3273 Array<u2>* const loadable_descriptors = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
3274 _loadable_descriptors = loadable_descriptors;
3275 if (length > 0) {
3276 int index = 0;
3277 cfs->guarantee_more(2 * length, CHECK_0);
3278 for (int n = 0; n < length; n++) {
3279 const u2 descriptor_index = cfs->get_u2_fast();
3280 guarantee_property(
3281 valid_symbol_at(descriptor_index),
3282 "LoadableDescriptors descriptor_index %u has bad constant type in class file %s",
3283 descriptor_index, CHECK_0);
3284 Symbol* descriptor = _cp->symbol_at(descriptor_index);
3285 bool valid = legal_field_signature(descriptor, CHECK_0);
3286 if(!valid) {
3287 ResourceMark rm(THREAD);
3288 Exceptions::fthrow(THREAD_AND_LOCATION,
3289 vmSymbols::java_lang_ClassFormatError(),
3290 "Descriptor from LoadableDescriptors attribute at index \"%d\" in class %s has illegal signature \"%s\"",
3291 descriptor_index, _class_name->as_C_string(), descriptor->as_C_string());
3292 return 0;
3293 }
3294 loadable_descriptors->at_put(index++, descriptor_index);
3295 }
3296 assert(index == size, "wrong size");
3297 }
3298
3299 // Restore buffer's current position.
3300 cfs->set_current(current_mark);
3301
3302 return length;
3303 }
3304
3305 // Record {
3306 // u2 attribute_name_index;
3307 // u4 attribute_length;
3308 // u2 components_count;
3309 // component_info components[components_count];
3310 // }
3311 // component_info {
3312 // u2 name_index;
3313 // u2 descriptor_index
3314 // u2 attributes_count;
3315 // attribute_info_attributes[attributes_count];
3316 // }
3317 u4 ClassFileParser::parse_classfile_record_attribute(const ClassFileStream* const cfs,
3318 const ConstantPool* cp,
3319 const u1* const record_attribute_start,
3320 TRAPS) {
3321 const u1* const current_mark = cfs->current();
3322 int components_count = 0;
3323 unsigned int calculate_attr_size = 0;
3324 if (record_attribute_start != nullptr) {
3325 cfs->set_current(record_attribute_start);
3326 cfs->guarantee_more(2, CHECK_0); // num of components
3327 components_count = (int)cfs->get_u2_fast();
3328 calculate_attr_size = 2;
3329 }
3330
3331 Array<RecordComponent*>* const record_components =
3332 MetadataFactory::new_array<RecordComponent*>(_loader_data, components_count, nullptr, CHECK_0);
3333 _record_components = record_components;
3334
3335 for (int x = 0; x < components_count; x++) {
3336 cfs->guarantee_more(6, CHECK_0); // name_index, descriptor_index, attributes_count
3337
3338 const u2 name_index = cfs->get_u2_fast();
3339 guarantee_property(valid_symbol_at(name_index),
3340 "Invalid constant pool index %u for name in Record attribute in class file %s",
3341 name_index, CHECK_0);
3342 const Symbol* const name = cp->symbol_at(name_index);
3343 verify_legal_field_name(name, CHECK_0);
3344
3345 const u2 descriptor_index = cfs->get_u2_fast();
3346 guarantee_property(valid_symbol_at(descriptor_index),
3347 "Invalid constant pool index %u for descriptor in Record attribute in class file %s",
3348 descriptor_index, CHECK_0);
3349 const Symbol* const descr = cp->symbol_at(descriptor_index);
3350 verify_legal_field_signature(name, descr, CHECK_0);
3351
3352 const u2 attributes_count = cfs->get_u2_fast();
3353 calculate_attr_size += 6;
3354 u2 generic_sig_index = 0;
3355 const u1* runtime_visible_annotations = nullptr;
3356 int runtime_visible_annotations_length = 0;
3357 bool runtime_invisible_annotations_exists = false;
3358 const u1* runtime_visible_type_annotations = nullptr;
3359 int runtime_visible_type_annotations_length = 0;
3360 bool runtime_invisible_type_annotations_exists = false;
3361
3362 // Expected attributes for record components are Signature, Runtime(In)VisibleAnnotations,
3363 // and Runtime(In)VisibleTypeAnnotations. Other attributes are ignored.
3364 for (int y = 0; y < attributes_count; y++) {
3365 cfs->guarantee_more(6, CHECK_0); // attribute_name_index, attribute_length
3366 const u2 attribute_name_index = cfs->get_u2_fast();
3367 const u4 attribute_length = cfs->get_u4_fast();
3368 calculate_attr_size += 6;
3369 guarantee_property(
3370 valid_symbol_at(attribute_name_index),
3371 "Invalid Record attribute name index %u in class file %s",
3372 attribute_name_index, CHECK_0);
3373
3374 const Symbol* const attribute_name = cp->symbol_at(attribute_name_index);
3375 if (attribute_name == vmSymbols::tag_signature()) {
3376 if (generic_sig_index != 0) {
3377 classfile_parse_error(
3378 "Multiple Signature attributes for Record component in class file %s",
3379 THREAD);
3380 return 0;
3381 }
3382 if (attribute_length != 2) {
3383 classfile_parse_error(
3384 "Invalid Signature attribute length %u in Record component in class file %s",
3385 attribute_length, THREAD);
3386 return 0;
3387 }
3388 generic_sig_index = parse_generic_signature_attribute(cfs, CHECK_0);
3389
3390 } else if (attribute_name == vmSymbols::tag_runtime_visible_annotations()) {
3391 if (runtime_visible_annotations != nullptr) {
3392 classfile_parse_error(
3393 "Multiple RuntimeVisibleAnnotations attributes for Record component in class file %s", THREAD);
3394 return 0;
3395 }
3396 runtime_visible_annotations_length = attribute_length;
3397 runtime_visible_annotations = cfs->current();
3398
3399 assert(runtime_visible_annotations != nullptr, "null record component visible annotation");
3400 cfs->guarantee_more(runtime_visible_annotations_length, CHECK_0);
3401 cfs->skip_u1_fast(runtime_visible_annotations_length);
3402
3403 } else if (attribute_name == vmSymbols::tag_runtime_invisible_annotations()) {
3404 if (runtime_invisible_annotations_exists) {
3405 classfile_parse_error(
3406 "Multiple RuntimeInvisibleAnnotations attributes for Record component in class file %s", THREAD);
3407 return 0;
3408 }
3409 runtime_invisible_annotations_exists = true;
3410 cfs->skip_u1(attribute_length, CHECK_0);
3411
3412 } else if (attribute_name == vmSymbols::tag_runtime_visible_type_annotations()) {
3413 if (runtime_visible_type_annotations != nullptr) {
3414 classfile_parse_error(
3415 "Multiple RuntimeVisibleTypeAnnotations attributes for Record component in class file %s", THREAD);
3416 return 0;
3417 }
3418 runtime_visible_type_annotations_length = attribute_length;
3419 runtime_visible_type_annotations = cfs->current();
3420
3421 assert(runtime_visible_type_annotations != nullptr, "null record component visible type annotation");
3422 cfs->guarantee_more(runtime_visible_type_annotations_length, CHECK_0);
3423 cfs->skip_u1_fast(runtime_visible_type_annotations_length);
3424
3425 } else if (attribute_name == vmSymbols::tag_runtime_invisible_type_annotations()) {
3426 if (runtime_invisible_type_annotations_exists) {
3427 classfile_parse_error(
3428 "Multiple RuntimeInvisibleTypeAnnotations attributes for Record component in class file %s", THREAD);
3429 return 0;
3430 }
3431 runtime_invisible_type_annotations_exists = true;
3432 cfs->skip_u1(attribute_length, CHECK_0);
3433
3434 } else {
3435 // Skip unknown attributes
3436 cfs->skip_u1(attribute_length, CHECK_0);
3437 }
3438 calculate_attr_size += attribute_length;
3439 } // End of attributes For loop
3440
3441 AnnotationArray* annotations = allocate_annotations(runtime_visible_annotations,
3442 runtime_visible_annotations_length,
3443 CHECK_0);
3444 AnnotationArray* type_annotations = allocate_annotations(runtime_visible_type_annotations,
3445 runtime_visible_type_annotations_length,
3446 CHECK_0);
3447
3448 RecordComponent* record_component =
3449 RecordComponent::allocate(_loader_data, name_index, descriptor_index, generic_sig_index,
3450 annotations, type_annotations, CHECK_0);
3451 record_components->at_put(x, record_component);
3452 } // End of component processing loop
3453
3454 // Restore buffer's current position.
3455 cfs->set_current(current_mark);
3456 return calculate_attr_size;
3457 }
3458
3459 void ClassFileParser::parse_classfile_synthetic_attribute() {
3460 set_class_synthetic_flag(true);
3461 }
3462
3463 void ClassFileParser::parse_classfile_signature_attribute(const ClassFileStream* const cfs, TRAPS) {
3464 assert(cfs != nullptr, "invariant");
3465
3466 const u2 signature_index = cfs->get_u2(CHECK);
3467 guarantee_property(
3468 valid_symbol_at(signature_index),
3469 "Invalid constant pool index %u in Signature attribute in class file %s",
3470 signature_index, CHECK);
3471 set_class_generic_signature_index(signature_index);
3472 }
3473
3474 void ClassFileParser::parse_classfile_bootstrap_methods_attribute(const ClassFileStream* const cfs,
3475 ConstantPool* cp,
3476 u4 attribute_byte_length,
3477 TRAPS) {
3478 assert(cfs != nullptr, "invariant");
3479 assert(cp != nullptr, "invariant");
3480 const int cp_size = cp->length();
3481
3482 const u1* const current_before_parsing = cfs->current();
3483
3484 guarantee_property(attribute_byte_length >= sizeof(u2),
3485 "Invalid BootstrapMethods attribute length %u in class file %s",
3486 attribute_byte_length,
3487 CHECK);
3488
3489 cfs->guarantee_more(attribute_byte_length, CHECK);
3490
3491 const int num_bootstrap_methods = cfs->get_u2_fast();
3492
3493 guarantee_property(_max_bootstrap_specifier_index < num_bootstrap_methods,
3494 "Short length on BootstrapMethods in class file %s",
3495 CHECK);
3496
3497 const u4 bootstrap_methods_u2_len = (attribute_byte_length - sizeof(u2)) / sizeof(u2);
3498
3499 // Eagerly assign the arrays so that they will be deallocated with the constant
3500 // pool if there is an error.
3501 BSMAttributeEntries::InsertionIterator iter =
3502 cp->bsm_entries().start_extension(num_bootstrap_methods,
3503 bootstrap_methods_u2_len,
3504 _loader_data,
3505 CHECK);
3506
3507 for (int i = 0; i < num_bootstrap_methods; i++) {
3508 cfs->guarantee_more(sizeof(u2) * 2, CHECK); // bsm, argc
3509 u2 bootstrap_method_ref = cfs->get_u2_fast();
3510 u2 num_bootstrap_arguments = cfs->get_u2_fast();
3511 guarantee_property(
3512 valid_cp_range(bootstrap_method_ref, cp_size) &&
3513 cp->tag_at(bootstrap_method_ref).is_method_handle(),
3514 "bootstrap_method_index %u has bad constant type in class file %s",
3515 bootstrap_method_ref,
3516 CHECK);
3517 cfs->guarantee_more(sizeof(u2) * num_bootstrap_arguments, CHECK); // argv[argc]
3518
3519 BSMAttributeEntry* entry = iter.reserve_new_entry(bootstrap_method_ref, num_bootstrap_arguments);
3520 guarantee_property(entry != nullptr,
3521 "Invalid BootstrapMethods num_bootstrap_methods."
3522 " The total amount of space reserved for the BootstrapMethod attribute was not sufficient", CHECK);
3523
3524 for (int argi = 0; argi < num_bootstrap_arguments; argi++) {
3525 const u2 argument_index = cfs->get_u2_fast();
3526 guarantee_property(
3527 valid_cp_range(argument_index, cp_size) &&
3528 cp->tag_at(argument_index).is_loadable_constant(),
3529 "argument_index %u has bad constant type in class file %s",
3530 argument_index,
3531 CHECK);
3532 entry->set_argument(argi, argument_index);
3533 }
3534 }
3535 cp->bsm_entries().end_extension(iter, _loader_data, CHECK);
3536 guarantee_property(current_before_parsing + attribute_byte_length == cfs->current(),
3537 "Bad length on BootstrapMethods in class file %s",
3538 CHECK);
3539 }
3540
3541 void ClassFileParser::parse_classfile_attributes(const ClassFileStream* const cfs,
3542 ConstantPool* cp,
3543 ClassFileParser::ClassAnnotationCollector* parsed_annotations,
3544 TRAPS) {
3545 assert(cfs != nullptr, "invariant");
3546 assert(cp != nullptr, "invariant");
3547 assert(parsed_annotations != nullptr, "invariant");
3548
3549 // Set inner classes attribute to default sentinel
3550 _inner_classes = Universe::the_empty_short_array();
3551 // Set nest members attribute to default sentinel
3552 _nest_members = Universe::the_empty_short_array();
3553 // Set _permitted_subclasses attribute to default sentinel
3554 _permitted_subclasses = Universe::the_empty_short_array();
3555 // Set _loadable_descriptors attribute to default sentinel
3556 _loadable_descriptors = Universe::the_empty_short_array();
3557 cfs->guarantee_more(2, CHECK); // attributes_count
3558 u2 attributes_count = cfs->get_u2_fast();
3559 bool parsed_sourcefile_attribute = false;
3560 bool parsed_innerclasses_attribute = false;
3561 bool parsed_nest_members_attribute = false;
3562 bool parsed_permitted_subclasses_attribute = false;
3563 bool parsed_loadable_descriptors_attribute = false;
3564 bool parsed_nest_host_attribute = false;
3565 bool parsed_record_attribute = false;
3566 bool parsed_enclosingmethod_attribute = false;
3567 bool parsed_bootstrap_methods_attribute = false;
3568 const u1* runtime_visible_annotations = nullptr;
3569 int runtime_visible_annotations_length = 0;
3570 const u1* runtime_visible_type_annotations = nullptr;
3571 int runtime_visible_type_annotations_length = 0;
3572 bool runtime_invisible_type_annotations_exists = false;
3573 bool runtime_invisible_annotations_exists = false;
3574 bool parsed_source_debug_ext_annotations_exist = false;
3575 const u1* inner_classes_attribute_start = nullptr;
3576 u4 inner_classes_attribute_length = 0;
3577 u2 enclosing_method_class_index = 0;
3578 u2 enclosing_method_method_index = 0;
3579 const u1* nest_members_attribute_start = nullptr;
3580 u4 nest_members_attribute_length = 0;
3581 const u1* record_attribute_start = nullptr;
3582 u4 record_attribute_length = 0;
3583 const u1* permitted_subclasses_attribute_start = nullptr;
3584 u4 permitted_subclasses_attribute_length = 0;
3585 const u1* loadable_descriptors_attribute_start = nullptr;
3586 u4 loadable_descriptors_attribute_length = 0;
3587
3588 // Iterate over attributes
3589 while (attributes_count--) {
3590 cfs->guarantee_more(6, CHECK); // attribute_name_index, attribute_length
3591 const u2 attribute_name_index = cfs->get_u2_fast();
3592 const u4 attribute_length = cfs->get_u4_fast();
3593 guarantee_property(
3594 valid_symbol_at(attribute_name_index),
3595 "Attribute name has bad constant pool index %u in class file %s",
3596 attribute_name_index, CHECK);
3597 const Symbol* const tag = cp->symbol_at(attribute_name_index);
3598 if (tag == vmSymbols::tag_source_file()) {
3599 // Check for SourceFile tag
3600 if (_need_verify) {
3601 guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
3602 }
3603 if (parsed_sourcefile_attribute) {
3604 classfile_parse_error("Multiple SourceFile attributes in class file %s", THREAD);
3605 return;
3606 } else {
3607 parsed_sourcefile_attribute = true;
3608 }
3609 parse_classfile_sourcefile_attribute(cfs, CHECK);
3610 } else if (tag == vmSymbols::tag_source_debug_extension()) {
3611 // Check for SourceDebugExtension tag
3612 if (parsed_source_debug_ext_annotations_exist) {
3613 classfile_parse_error(
3614 "Multiple SourceDebugExtension attributes in class file %s", THREAD);
3615 return;
3616 }
3617 parsed_source_debug_ext_annotations_exist = true;
3618 parse_classfile_source_debug_extension_attribute(cfs, (int)attribute_length, CHECK);
3619 } else if (tag == vmSymbols::tag_inner_classes()) {
3620 // Check for InnerClasses tag
3621 if (parsed_innerclasses_attribute) {
3622 classfile_parse_error("Multiple InnerClasses attributes in class file %s", THREAD);
3623 return;
3624 } else {
3625 parsed_innerclasses_attribute = true;
3626 }
3627 inner_classes_attribute_start = cfs->current();
3628 inner_classes_attribute_length = attribute_length;
3629 cfs->skip_u1(inner_classes_attribute_length, CHECK);
3630 } else if (tag == vmSymbols::tag_synthetic()) {
3631 // Check for Synthetic tag
3632 // Shouldn't we check that the synthetic flags wasn't already set? - not required in spec
3633 if (attribute_length != 0) {
3634 classfile_parse_error(
3635 "Invalid Synthetic classfile attribute length %u in class file %s",
3636 attribute_length, THREAD);
3637 return;
3638 }
3639 parse_classfile_synthetic_attribute();
3640 } else if (tag == vmSymbols::tag_deprecated()) {
3641 // Check for Deprecated tag - 4276120
3642 if (attribute_length != 0) {
3643 classfile_parse_error(
3644 "Invalid Deprecated classfile attribute length %u in class file %s",
3645 attribute_length, THREAD);
3646 return;
3647 }
3648 } else if (_major_version >= JAVA_1_5_VERSION) {
3649 if (tag == vmSymbols::tag_signature()) {
3650 if (_generic_signature_index != 0) {
3651 classfile_parse_error(
3652 "Multiple Signature attributes in class file %s", THREAD);
3653 return;
3654 }
3655 if (attribute_length != 2) {
3656 classfile_parse_error(
3657 "Wrong Signature attribute length %u in class file %s",
3658 attribute_length, THREAD);
3659 return;
3660 }
3661 parse_classfile_signature_attribute(cfs, CHECK);
3662 } else if (tag == vmSymbols::tag_runtime_visible_annotations()) {
3663 if (runtime_visible_annotations != nullptr) {
3664 classfile_parse_error(
3665 "Multiple RuntimeVisibleAnnotations attributes in class file %s", THREAD);
3666 return;
3667 }
3668 runtime_visible_annotations_length = attribute_length;
3669 runtime_visible_annotations = cfs->current();
3670 assert(runtime_visible_annotations != nullptr, "null visible annotations");
3671 cfs->guarantee_more(runtime_visible_annotations_length, CHECK);
3672 parse_annotations(cp,
3673 runtime_visible_annotations,
3674 runtime_visible_annotations_length,
3675 parsed_annotations,
3676 _loader_data,
3677 _can_access_vm_annotations);
3678 cfs->skip_u1_fast(runtime_visible_annotations_length);
3679 } else if (tag == vmSymbols::tag_runtime_invisible_annotations()) {
3680 if (runtime_invisible_annotations_exists) {
3681 classfile_parse_error(
3682 "Multiple RuntimeInvisibleAnnotations attributes in class file %s", THREAD);
3683 return;
3684 }
3685 runtime_invisible_annotations_exists = true;
3686 cfs->skip_u1(attribute_length, CHECK);
3687 } else if (tag == vmSymbols::tag_enclosing_method()) {
3688 if (parsed_enclosingmethod_attribute) {
3689 classfile_parse_error("Multiple EnclosingMethod attributes in class file %s", THREAD);
3690 return;
3691 } else {
3692 parsed_enclosingmethod_attribute = true;
3693 }
3694 guarantee_property(attribute_length == 4,
3695 "Wrong EnclosingMethod attribute length %u in class file %s",
3696 attribute_length, CHECK);
3697 cfs->guarantee_more(4, CHECK); // class_index, method_index
3698 enclosing_method_class_index = cfs->get_u2_fast();
3699 enclosing_method_method_index = cfs->get_u2_fast();
3700 if (enclosing_method_class_index == 0) {
3701 classfile_parse_error("Invalid class index in EnclosingMethod attribute in class file %s", THREAD);
3702 return;
3703 }
3704 // Validate the constant pool indices and types
3705 guarantee_property(valid_klass_reference_at(enclosing_method_class_index),
3706 "Invalid or out-of-bounds class index in EnclosingMethod attribute in class file %s", CHECK);
3707 if (enclosing_method_method_index != 0 &&
3708 (!cp->is_within_bounds(enclosing_method_method_index) ||
3709 !cp->tag_at(enclosing_method_method_index).is_name_and_type())) {
3710 classfile_parse_error("Invalid or out-of-bounds method index in EnclosingMethod attribute in class file %s", THREAD);
3711 return;
3712 }
3713 } else if (tag == vmSymbols::tag_bootstrap_methods() &&
3714 _major_version >= Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {
3715 if (parsed_bootstrap_methods_attribute) {
3716 classfile_parse_error("Multiple BootstrapMethods attributes in class file %s", THREAD);
3717 return;
3718 }
3719 parsed_bootstrap_methods_attribute = true;
3720 parse_classfile_bootstrap_methods_attribute(cfs, cp, attribute_length, CHECK);
3721 } else if (tag == vmSymbols::tag_runtime_visible_type_annotations()) {
3722 if (runtime_visible_type_annotations != nullptr) {
3723 classfile_parse_error(
3724 "Multiple RuntimeVisibleTypeAnnotations attributes in class file %s", THREAD);
3725 return;
3726 }
3727 runtime_visible_type_annotations_length = attribute_length;
3728 runtime_visible_type_annotations = cfs->current();
3729 assert(runtime_visible_type_annotations != nullptr, "null visible type annotations");
3730 // No need for the VM to parse Type annotations
3731 cfs->skip_u1(runtime_visible_type_annotations_length, CHECK);
3732 } else if (tag == vmSymbols::tag_runtime_invisible_type_annotations()) {
3733 if (runtime_invisible_type_annotations_exists) {
3734 classfile_parse_error(
3735 "Multiple RuntimeInvisibleTypeAnnotations attributes in class file %s", THREAD);
3736 return;
3737 }
3738 runtime_invisible_type_annotations_exists = true;
3739 cfs->skip_u1(attribute_length, CHECK);
3740 } else if (_major_version >= JAVA_11_VERSION) {
3741 if (tag == vmSymbols::tag_nest_members()) {
3742 // Check for NestMembers tag
3743 if (parsed_nest_members_attribute) {
3744 classfile_parse_error("Multiple NestMembers attributes in class file %s", THREAD);
3745 return;
3746 } else {
3747 parsed_nest_members_attribute = true;
3748 }
3749 if (parsed_nest_host_attribute) {
3750 classfile_parse_error("Conflicting NestHost and NestMembers attributes in class file %s", THREAD);
3751 return;
3752 }
3753 nest_members_attribute_start = cfs->current();
3754 nest_members_attribute_length = attribute_length;
3755 cfs->skip_u1(nest_members_attribute_length, CHECK);
3756 } else if (tag == vmSymbols::tag_nest_host()) {
3757 if (parsed_nest_host_attribute) {
3758 classfile_parse_error("Multiple NestHost attributes in class file %s", THREAD);
3759 return;
3760 } else {
3761 parsed_nest_host_attribute = true;
3762 }
3763 if (parsed_nest_members_attribute) {
3764 classfile_parse_error("Conflicting NestMembers and NestHost attributes in class file %s", THREAD);
3765 return;
3766 }
3767 if (_need_verify) {
3768 guarantee_property(attribute_length == 2, "Wrong NestHost attribute length in class file %s", CHECK);
3769 }
3770 cfs->guarantee_more(2, CHECK);
3771 u2 class_info_index = cfs->get_u2_fast();
3772 guarantee_property(
3773 valid_klass_reference_at(class_info_index),
3774 "Nest-host class_info_index %u has bad constant type in class file %s",
3775 class_info_index, CHECK);
3776 _nest_host = class_info_index;
3777
3778 } else if (_major_version >= JAVA_16_VERSION) {
3779 if (tag == vmSymbols::tag_record()) {
3780 if (parsed_record_attribute) {
3781 classfile_parse_error("Multiple Record attributes in class file %s", THREAD);
3782 return;
3783 }
3784 parsed_record_attribute = true;
3785 record_attribute_start = cfs->current();
3786 record_attribute_length = attribute_length;
3787 } else if (_major_version >= JAVA_17_VERSION) {
3788 if (tag == vmSymbols::tag_permitted_subclasses()) {
3789 if (parsed_permitted_subclasses_attribute) {
3790 classfile_parse_error("Multiple PermittedSubclasses attributes in class file %s", CHECK);
3791 return;
3792 }
3793 // Classes marked ACC_FINAL cannot have a PermittedSubclasses attribute.
3794 if (_access_flags.is_final()) {
3795 classfile_parse_error("PermittedSubclasses attribute in final class file %s", CHECK);
3796 return;
3797 }
3798 parsed_permitted_subclasses_attribute = true;
3799 permitted_subclasses_attribute_start = cfs->current();
3800 permitted_subclasses_attribute_length = attribute_length;
3801 }
3802 if (Arguments::is_valhalla_enabled() && tag == vmSymbols::tag_loadable_descriptors()) {
3803 if (parsed_loadable_descriptors_attribute) {
3804 classfile_parse_error("Multiple LoadableDescriptors attributes in class file %s", CHECK);
3805 return;
3806 }
3807 parsed_loadable_descriptors_attribute = true;
3808 loadable_descriptors_attribute_start = cfs->current();
3809 loadable_descriptors_attribute_length = attribute_length;
3810 }
3811 }
3812 // Skip attribute_length for any attribute where major_verson >= JAVA_17_VERSION
3813 cfs->skip_u1(attribute_length, CHECK);
3814 } else {
3815 // Unknown attribute
3816 cfs->skip_u1(attribute_length, CHECK);
3817 }
3818 } else {
3819 // Unknown attribute
3820 cfs->skip_u1(attribute_length, CHECK);
3821 }
3822 } else {
3823 // Unknown attribute
3824 cfs->skip_u1(attribute_length, CHECK);
3825 }
3826 }
3827 _class_annotations = allocate_annotations(runtime_visible_annotations,
3828 runtime_visible_annotations_length,
3829 CHECK);
3830 _class_type_annotations = allocate_annotations(runtime_visible_type_annotations,
3831 runtime_visible_type_annotations_length,
3832 CHECK);
3833
3834 if (parsed_innerclasses_attribute || parsed_enclosingmethod_attribute) {
3835 const u2 num_of_classes = parse_classfile_inner_classes_attribute(
3836 cfs,
3837 cp,
3838 inner_classes_attribute_start,
3839 parsed_innerclasses_attribute,
3840 enclosing_method_class_index,
3841 enclosing_method_method_index,
3842 CHECK);
3843 if (parsed_innerclasses_attribute && _need_verify && _major_version >= JAVA_1_5_VERSION) {
3844 guarantee_property(
3845 inner_classes_attribute_length == sizeof(num_of_classes) + 4 * sizeof(u2) * num_of_classes,
3846 "Wrong InnerClasses attribute length in class file %s", CHECK);
3847 }
3848 }
3849
3850 if (parsed_nest_members_attribute) {
3851 const u2 num_of_classes = parse_classfile_nest_members_attribute(
3852 cfs,
3853 nest_members_attribute_start,
3854 CHECK);
3855 if (_need_verify) {
3856 guarantee_property(
3857 nest_members_attribute_length == sizeof(num_of_classes) + sizeof(u2) * num_of_classes,
3858 "Wrong NestMembers attribute length in class file %s", CHECK);
3859 }
3860 }
3861
3862 if (parsed_record_attribute) {
3863 const unsigned int calculated_attr_length = parse_classfile_record_attribute(
3864 cfs,
3865 cp,
3866 record_attribute_start,
3867 CHECK);
3868 if (_need_verify) {
3869 guarantee_property(record_attribute_length == calculated_attr_length,
3870 "Record attribute has wrong length in class file %s",
3871 CHECK);
3872 }
3873 }
3874
3875 if (parsed_permitted_subclasses_attribute) {
3876 const u2 num_subclasses = parse_classfile_permitted_subclasses_attribute(
3877 cfs,
3878 permitted_subclasses_attribute_start,
3879 CHECK);
3880 if (_need_verify) {
3881 guarantee_property(
3882 permitted_subclasses_attribute_length == sizeof(num_subclasses) + sizeof(u2) * num_subclasses,
3883 "Wrong PermittedSubclasses attribute length in class file %s", CHECK);
3884 }
3885 }
3886
3887 if (parsed_loadable_descriptors_attribute) {
3888 const u2 num_classes = parse_classfile_loadable_descriptors_attribute(
3889 cfs,
3890 loadable_descriptors_attribute_start,
3891 CHECK);
3892 if (_need_verify) {
3893 guarantee_property(
3894 loadable_descriptors_attribute_length == sizeof(num_classes) + sizeof(u2) * num_classes,
3895 "Wrong LoadableDescriptors attribute length in class file %s", CHECK);
3896 }
3897 }
3898
3899 if (_max_bootstrap_specifier_index >= 0) {
3900 guarantee_property(parsed_bootstrap_methods_attribute,
3901 "Missing BootstrapMethods attribute in class file %s", CHECK);
3902 }
3903 }
3904
3905 void ClassFileParser::apply_parsed_class_attributes(InstanceKlass* k) {
3906 assert(k != nullptr, "invariant");
3907
3908 if (_synthetic_flag)
3909 k->set_is_synthetic();
3910 if (_sourcefile_index != 0) {
3911 k->set_source_file_name_index(_sourcefile_index);
3912 }
3913 if (_generic_signature_index != 0) {
3914 k->set_generic_signature_index(_generic_signature_index);
3915 }
3916 if (_sde_buffer != nullptr) {
3917 k->set_source_debug_extension(_sde_buffer, _sde_length);
3918 }
3919 }
3920
3921 // Create the Annotations object that will
3922 // hold the annotations array for the Klass.
3923 void ClassFileParser::create_combined_annotations(TRAPS) {
3924 if (_class_annotations == nullptr &&
3925 _class_type_annotations == nullptr &&
3926 _fields_annotations == nullptr &&
3927 _fields_type_annotations == nullptr) {
3928 // Don't create the Annotations object unnecessarily.
3929 return;
3930 }
3931
3932 Annotations* const annotations = Annotations::allocate(_loader_data, CHECK);
3933 annotations->set_class_annotations(_class_annotations);
3934 annotations->set_class_type_annotations(_class_type_annotations);
3935 annotations->set_fields_annotations(_fields_annotations);
3936 annotations->set_fields_type_annotations(_fields_type_annotations);
3937
3938 // This is the Annotations object that will be
3939 // assigned to InstanceKlass being constructed.
3940 _combined_annotations = annotations;
3941
3942 // The annotations arrays below has been transferred the
3943 // _combined_annotations so these fields can now be cleared.
3944 _class_annotations = nullptr;
3945 _class_type_annotations = nullptr;
3946 _fields_annotations = nullptr;
3947 _fields_type_annotations = nullptr;
3948 }
3949
3950 // Transfer ownership of metadata allocated to the InstanceKlass.
3951 void ClassFileParser::apply_parsed_class_metadata(
3952 InstanceKlass* this_klass,
3953 int java_fields_count) {
3954 assert(this_klass != nullptr, "invariant");
3955
3956 _cp->set_pool_holder(this_klass);
3957 this_klass->set_constants(_cp);
3958 this_klass->set_fieldinfo_stream(_fieldinfo_stream);
3959 this_klass->set_fieldinfo_search_table(_fieldinfo_search_table);
3960 this_klass->set_fields_status(_fields_status);
3961 this_klass->set_methods(_methods);
3962 this_klass->set_inner_classes(_inner_classes);
3963 this_klass->set_nest_members(_nest_members);
3964 this_klass->set_nest_host_index(_nest_host);
3965 this_klass->set_loadable_descriptors(_loadable_descriptors);
3966 this_klass->set_annotations(_combined_annotations);
3967 this_klass->set_permitted_subclasses(_permitted_subclasses);
3968 this_klass->set_record_components(_record_components);
3969 this_klass->set_inline_layout_info_array(_inline_layout_info_array);
3970
3971 DEBUG_ONLY(FieldInfoStream::validate_search_table(_cp, _fieldinfo_stream, _fieldinfo_search_table));
3972
3973 // Delay the setting of _local_interfaces and _transitive_interfaces until after
3974 // initialize_supers() in fill_instance_klass(). It is because the _local_interfaces could
3975 // be shared with _transitive_interfaces and _transitive_interfaces may be shared with
3976 // its _super. If an OOM occurs while loading the current klass, its _super field
3977 // may not have been set. When GC tries to free the klass, the _transitive_interfaces
3978 // may be deallocated mistakenly in InstanceKlass::deallocate_interfaces(). Subsequent
3979 // dereferences to the deallocated _transitive_interfaces will result in a crash.
3980
3981 // Clear out these fields so they don't get deallocated by the destructor
3982 clear_class_metadata();
3983 }
3984
3985 AnnotationArray* ClassFileParser::allocate_annotations(const u1* const anno,
3986 int anno_length,
3987 TRAPS) {
3988 AnnotationArray* annotations = nullptr;
3989 if (anno != nullptr) {
3990 annotations = MetadataFactory::new_array<u1>(_loader_data,
3991 anno_length,
3992 CHECK_(annotations));
3993 for (int i = 0; i < anno_length; i++) {
3994 annotations->at_put(i, anno[i]);
3995 }
3996 }
3997 return annotations;
3998 }
3999
4000 void ClassFileParser::check_super_class(ConstantPool* const cp,
4001 const int super_class_index,
4002 const bool need_verify,
4003 TRAPS) {
4004 assert(cp != nullptr, "invariant");
4005
4006 if (super_class_index == 0) {
4007 guarantee_property(_class_name == vmSymbols::java_lang_Object(),
4008 "Invalid superclass index 0 in class file %s",
4009 CHECK);
4010 } else {
4011 guarantee_property(valid_klass_reference_at(super_class_index),
4012 "Invalid superclass index %u in class file %s",
4013 super_class_index,
4014 CHECK);
4015
4016 // The class name should be legal because it is checked when parsing constant pool.
4017 // However, make sure it is not an array type.
4018 if (need_verify) {
4019 guarantee_property(cp->klass_name_at(super_class_index)->char_at(0) != JVM_SIGNATURE_ARRAY,
4020 "Bad superclass name in class file %s", CHECK);
4021 }
4022 }
4023 }
4024
4025 OopMapBlocksBuilder::OopMapBlocksBuilder(unsigned int max_blocks) {
4026 _max_nonstatic_oop_maps = max_blocks;
4027 _nonstatic_oop_map_count = 0;
4028 if (max_blocks == 0) {
4029 _nonstatic_oop_maps = nullptr;
4030 } else {
4031 _nonstatic_oop_maps =
4032 NEW_RESOURCE_ARRAY(OopMapBlock, _max_nonstatic_oop_maps);
4033 memset(_nonstatic_oop_maps, 0, sizeof(OopMapBlock) * max_blocks);
4034 }
4035 }
4036
4037 OopMapBlock* OopMapBlocksBuilder::last_oop_map() const {
4038 assert(_nonstatic_oop_map_count > 0, "Has no oop maps");
4039 return _nonstatic_oop_maps + (_nonstatic_oop_map_count - 1);
4040 }
4041
4042 // addition of super oop maps
4043 void OopMapBlocksBuilder::initialize_inherited_blocks(OopMapBlock* blocks, unsigned int nof_blocks) {
4044 assert(nof_blocks && _nonstatic_oop_map_count == 0 &&
4045 nof_blocks <= _max_nonstatic_oop_maps, "invariant");
4046
4047 memcpy(_nonstatic_oop_maps, blocks, sizeof(OopMapBlock) * nof_blocks);
4048 _nonstatic_oop_map_count += nof_blocks;
4049 }
4050
4051 // collection of oops
4052 void OopMapBlocksBuilder::add(int offset, int count) {
4053 if (_nonstatic_oop_map_count == 0) {
4054 _nonstatic_oop_map_count++;
4055 }
4056 OopMapBlock* nonstatic_oop_map = last_oop_map();
4057 if (nonstatic_oop_map->count() == 0) { // Unused map, set it up
4058 nonstatic_oop_map->set_offset(offset);
4059 nonstatic_oop_map->set_count(count);
4060 } else if (nonstatic_oop_map->is_contiguous(offset)) { // contiguous, add
4061 nonstatic_oop_map->increment_count(count);
4062 } else { // Need a new one...
4063 _nonstatic_oop_map_count++;
4064 assert(_nonstatic_oop_map_count <= _max_nonstatic_oop_maps, "range check");
4065 nonstatic_oop_map = last_oop_map();
4066 nonstatic_oop_map->set_offset(offset);
4067 nonstatic_oop_map->set_count(count);
4068 }
4069 }
4070
4071 // general purpose copy, e.g. into allocated instanceKlass
4072 void OopMapBlocksBuilder::copy(OopMapBlock* dst) {
4073 if (_nonstatic_oop_map_count != 0) {
4074 memcpy(dst, _nonstatic_oop_maps, sizeof(OopMapBlock) * _nonstatic_oop_map_count);
4075 }
4076 }
4077
4078 // Sort and compact adjacent blocks
4079 void OopMapBlocksBuilder::compact() {
4080 if (_nonstatic_oop_map_count <= 1) {
4081 return;
4082 }
4083 /*
4084 * Since field layout sneaks in oops before values, we will be able to condense
4085 * blocks. There is potential to compact between super, own refs and values
4086 * containing refs.
4087 *
4088 * Currently compaction is slightly limited due to values being 8 byte aligned.
4089 * This may well change: FixMe if it doesn't, the code below is fairly general purpose
4090 * and maybe it doesn't need to be.
4091 */
4092 qsort(_nonstatic_oop_maps, _nonstatic_oop_map_count, sizeof(OopMapBlock),
4093 (_sort_Fn)OopMapBlock::compare_offset);
4094 if (_nonstatic_oop_map_count < 2) {
4095 return;
4096 }
4097
4098 // Make a temp copy, and iterate through and copy back into the original
4099 ResourceMark rm;
4100 OopMapBlock* oop_maps_copy =
4101 NEW_RESOURCE_ARRAY(OopMapBlock, _nonstatic_oop_map_count);
4102 OopMapBlock* oop_maps_copy_end = oop_maps_copy + _nonstatic_oop_map_count;
4103 copy(oop_maps_copy);
4104 OopMapBlock* nonstatic_oop_map = _nonstatic_oop_maps;
4105 unsigned int new_count = 1;
4106 oop_maps_copy++;
4107 while(oop_maps_copy < oop_maps_copy_end) {
4108 assert(nonstatic_oop_map->offset() < oop_maps_copy->offset(), "invariant");
4109 if (nonstatic_oop_map->is_contiguous(oop_maps_copy->offset())) {
4110 nonstatic_oop_map->increment_count(oop_maps_copy->count());
4111 } else {
4112 nonstatic_oop_map++;
4113 new_count++;
4114 nonstatic_oop_map->set_offset(oop_maps_copy->offset());
4115 nonstatic_oop_map->set_count(oop_maps_copy->count());
4116 }
4117 oop_maps_copy++;
4118 }
4119 assert(new_count <= _nonstatic_oop_map_count, "end up with more maps after compact() ?");
4120 _nonstatic_oop_map_count = new_count;
4121 }
4122
4123 void OopMapBlocksBuilder::print_on(outputStream* st) const {
4124 st->print_cr(" OopMapBlocks: %3d /%3d", _nonstatic_oop_map_count, _max_nonstatic_oop_maps);
4125 if (_nonstatic_oop_map_count > 0) {
4126 OopMapBlock* map = _nonstatic_oop_maps;
4127 OopMapBlock* last_map = last_oop_map();
4128 assert(map <= last_map, "Last less than first");
4129 while (map <= last_map) {
4130 st->print_cr(" Offset: %3d -%3d Count: %3d", map->offset(),
4131 map->offset() + map->offset_span() - heapOopSize, map->count());
4132 map++;
4133 }
4134 }
4135 }
4136
4137 void OopMapBlocksBuilder::print_value_on(outputStream* st) const {
4138 print_on(st);
4139 }
4140
4141 void ClassFileParser::set_precomputed_flags(InstanceKlass* ik) {
4142 assert(ik != nullptr, "invariant");
4143
4144 const InstanceKlass* const super = ik->super();
4145
4146 // Check if this klass has an empty finalize method (i.e. one with return bytecode only),
4147 // in which case we don't have to register objects as finalizable
4148 if (!_has_empty_finalizer) {
4149 if (_has_finalizer ||
4150 (super != nullptr && super->has_finalizer())) {
4151 ik->set_has_finalizer();
4152 }
4153 }
4154
4155 #ifdef ASSERT
4156 bool f = false;
4157 const Method* const m = ik->lookup_method(vmSymbols::finalize_method_name(),
4158 vmSymbols::void_method_signature());
4159 if (InstanceKlass::is_finalization_enabled() &&
4160 (m != nullptr) && !m->is_empty_method()) {
4161 f = true;
4162 }
4163
4164 // Spec doesn't prevent agent from redefinition of empty finalizer.
4165 // Despite the fact that it's generally bad idea and redefined finalizer
4166 // will not work as expected we shouldn't abort vm in this case
4167 if (!ik->has_redefined_this_or_super()) {
4168 assert(ik->has_finalizer() == f, "inconsistent has_finalizer");
4169 }
4170 #endif
4171
4172 // Check if this klass supports the java.lang.Cloneable interface
4173 if (vmClasses::Cloneable_klass_is_loaded()) {
4174 if (ik->is_subtype_of(vmClasses::Cloneable_klass())) {
4175 ik->set_is_cloneable();
4176 }
4177 }
4178
4179 // If it cannot be fast-path allocated, set a bit in the layout helper.
4180 // See documentation of InstanceKlass::can_be_fastpath_allocated().
4181 assert(ik->size_helper() > 0, "layout_helper is initialized");
4182 if (ik->is_abstract() || ik->is_interface()
4183 || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == nullptr)
4184 || ik->size_helper() >= FastAllocateSizeLimit) {
4185 // Forbid fast-path allocation.
4186 const jint lh = Klass::instance_layout_helper(ik->size_helper(), true);
4187 ik->set_layout_helper(lh);
4188 }
4189
4190 // Propagate the AOT runtimeSetup method discovery
4191 if (_has_aot_runtime_setup_method) {
4192 ik->set_is_runtime_setup_required();
4193 if (log_is_enabled(Info, aot, init)) {
4194 ResourceMark rm;
4195 log_info(aot, init)("Found @AOTRuntimeSetup class %s", ik->external_name());
4196 }
4197 }
4198 }
4199
4200 bool ClassFileParser::supports_inline_types() const {
4201 // Inline types are only supported by class file version 71.65535 and later
4202 return _major_version > JAVA_27_VERSION ||
4203 (_major_version == JAVA_27_VERSION && _minor_version == JAVA_PREVIEW_MINOR_VERSION);
4204 }
4205
4206 // utility methods for appending an array with check for duplicates
4207
4208 static void append_interfaces(GrowableArray<InstanceKlass*>* result,
4209 const Array<InstanceKlass*>* const ifs) {
4210 // iterate over new interfaces
4211 for (int i = 0; i < ifs->length(); i++) {
4212 InstanceKlass* const e = ifs->at(i);
4213 assert(e->is_klass() && e->is_interface(), "just checking");
4214 // add new interface
4215 result->append_if_missing(e);
4216 }
4217 }
4218
4219 static Array<InstanceKlass*>* compute_transitive_interfaces(const InstanceKlass* super,
4220 Array<InstanceKlass*>* local_ifs,
4221 ClassLoaderData* loader_data,
4222 TRAPS) {
4223 assert(local_ifs != nullptr, "invariant");
4224 assert(loader_data != nullptr, "invariant");
4225
4226 // Compute maximum size for transitive interfaces
4227 int max_transitive_size = 0;
4228 int super_size = 0;
4229 // Add superclass transitive interfaces size
4230 if (super != nullptr) {
4231 super_size = super->transitive_interfaces()->length();
4232 max_transitive_size += super_size;
4233 }
4234 // Add local interfaces' super interfaces
4235 const int local_size = local_ifs->length();
4236 for (int i = 0; i < local_size; i++) {
4237 InstanceKlass* const l = local_ifs->at(i);
4238 max_transitive_size += l->transitive_interfaces()->length();
4239 }
4240 // Finally add local interfaces
4241 max_transitive_size += local_size;
4242 // Construct array
4243 if (max_transitive_size == 0) {
4244 // no interfaces, use canonicalized array
4245 return Universe::the_empty_instance_klass_array();
4246 } else if (max_transitive_size == super_size) {
4247 // no new local interfaces added, share superklass' transitive interface array
4248 return super->transitive_interfaces();
4249 // The three lines below are commented to work around bug JDK-8245487
4250 // } else if (max_transitive_size == local_size) {
4251 // // only local interfaces added, share local interface array
4252 // return local_ifs;
4253 } else {
4254 ResourceMark rm;
4255 GrowableArray<InstanceKlass*>* const result = new GrowableArray<InstanceKlass*>(max_transitive_size);
4256
4257 // Copy down from superclass
4258 if (super != nullptr) {
4259 append_interfaces(result, super->transitive_interfaces());
4260 }
4261
4262 // Copy down from local interfaces' superinterfaces
4263 for (int i = 0; i < local_size; i++) {
4264 InstanceKlass* const l = local_ifs->at(i);
4265 append_interfaces(result, l->transitive_interfaces());
4266 }
4267 // Finally add local interfaces
4268 append_interfaces(result, local_ifs);
4269
4270 // length will be less than the max_transitive_size if duplicates were removed
4271 const int length = result->length();
4272 assert(length <= max_transitive_size, "just checking");
4273
4274 Array<InstanceKlass*>* const new_result =
4275 MetadataFactory::new_array<InstanceKlass*>(loader_data, length, CHECK_NULL);
4276 for (int i = 0; i < length; i++) {
4277 InstanceKlass* const e = result->at(i);
4278 assert(e != nullptr, "just checking");
4279 new_result->at_put(i, e);
4280 }
4281 return new_result;
4282 }
4283 }
4284
4285 void ClassFileParser::check_super_class_access(const InstanceKlass* this_klass, TRAPS) {
4286 assert(this_klass != nullptr, "invariant");
4287 const InstanceKlass* const super = this_klass->super();
4288
4289 if (super != nullptr) {
4290 if (super->is_final()) {
4291 classfile_icce_error("class %s cannot inherit from final class %s", super, THREAD);
4292 return;
4293 }
4294
4295 if (super->is_sealed()) {
4296 stringStream ss;
4297 ResourceMark rm(THREAD);
4298 if (!super->has_as_permitted_subclass(this_klass, ss)) {
4299 classfile_icce_error(ss.as_string(), THREAD);
4300 return;
4301 }
4302 }
4303
4304 // The JVMS says that super classes for value types must not have the ACC_IDENTITY
4305 // flag set. But, java.lang.Object must still be allowed to be a direct super class
4306 // for a value classes. So, it is treated as a special case for now.
4307 if (!this_klass->access_flags().is_identity_class() &&
4308 super->name() != vmSymbols::java_lang_Object() &&
4309 super->is_identity_class()) {
4310 classfile_icce_error("value class %s cannot inherit from class %s", super, THREAD);
4311 return;
4312 }
4313
4314 Reflection::VerifyClassAccessResults vca_result =
4315 Reflection::verify_class_access(this_klass, super, false);
4316 if (vca_result != Reflection::ACCESS_OK) {
4317 ResourceMark rm(THREAD);
4318 char* msg = Reflection::verify_class_access_msg(this_klass,
4319 super,
4320 vca_result);
4321
4322 // Names are all known to be < 64k so we know this formatted message is not excessively large.
4323 if (msg == nullptr) {
4324 bool same_module = (this_klass->module() == super->module());
4325 Exceptions::fthrow(
4326 THREAD_AND_LOCATION,
4327 vmSymbols::java_lang_IllegalAccessError(),
4328 "class %s cannot access its %ssuperclass %s (%s%s%s)",
4329 this_klass->external_name(),
4330 super->is_abstract() ? "abstract " : "",
4331 super->external_name(),
4332 (same_module) ? this_klass->joint_in_module_of_loader(super) : this_klass->class_in_module_of_loader(),
4333 (same_module) ? "" : "; ",
4334 (same_module) ? "" : super->class_in_module_of_loader());
4335 } else {
4336 // Add additional message content.
4337 Exceptions::fthrow(
4338 THREAD_AND_LOCATION,
4339 vmSymbols::java_lang_IllegalAccessError(),
4340 "superclass access check failed: %s",
4341 msg);
4342 }
4343 }
4344 }
4345 }
4346
4347
4348 void ClassFileParser::check_super_interface_access(const InstanceKlass* this_klass, TRAPS) {
4349 assert(this_klass != nullptr, "invariant");
4350 const Array<InstanceKlass*>* const local_interfaces = this_klass->local_interfaces();
4351 const int lng = local_interfaces->length();
4352 for (int i = lng - 1; i >= 0; i--) {
4353 InstanceKlass* const k = local_interfaces->at(i);
4354 assert (k != nullptr && k->is_interface(), "invalid interface");
4355
4356 if (k->is_sealed()) {
4357 stringStream ss;
4358 ResourceMark rm(THREAD);
4359 if (!k->has_as_permitted_subclass(this_klass, ss)) {
4360 classfile_icce_error(ss.as_string(), THREAD);
4361 return;
4362 }
4363 }
4364
4365 Reflection::VerifyClassAccessResults vca_result =
4366 Reflection::verify_class_access(this_klass, k, false);
4367 if (vca_result != Reflection::ACCESS_OK) {
4368 ResourceMark rm(THREAD);
4369 char* msg = Reflection::verify_class_access_msg(this_klass,
4370 k,
4371 vca_result);
4372
4373 // Names are all known to be < 64k so we know this formatted message is not excessively large.
4374 if (msg == nullptr) {
4375 bool same_module = (this_klass->module() == k->module());
4376 Exceptions::fthrow(
4377 THREAD_AND_LOCATION,
4378 vmSymbols::java_lang_IllegalAccessError(),
4379 "class %s cannot access its superinterface %s (%s%s%s)",
4380 this_klass->external_name(),
4381 k->external_name(),
4382 (same_module) ? this_klass->joint_in_module_of_loader(k) : this_klass->class_in_module_of_loader(),
4383 (same_module) ? "" : "; ",
4384 (same_module) ? "" : k->class_in_module_of_loader());
4385 return;
4386 } else {
4387 // Add additional message content.
4388 Exceptions::fthrow(
4389 THREAD_AND_LOCATION,
4390 vmSymbols::java_lang_IllegalAccessError(),
4391 "superinterface check failed: %s",
4392 msg);
4393 return;
4394 }
4395 }
4396 }
4397 }
4398
4399
4400 static void check_final_method_override(const InstanceKlass* this_klass, TRAPS) {
4401 assert(this_klass != nullptr, "invariant");
4402 const Array<Method*>* const methods = this_klass->methods();
4403 const int num_methods = methods->length();
4404
4405 // go thru each method and check if it overrides a final method
4406 for (int index = 0; index < num_methods; index++) {
4407 const Method* const m = methods->at(index);
4408
4409 // skip private, static, and <init> methods
4410 if ((!m->is_private() && !m->is_static()) &&
4411 (m->name() != vmSymbols::object_initializer_name())) {
4412
4413 const Symbol* const name = m->name();
4414 const Symbol* const signature = m->signature();
4415 const InstanceKlass* k = this_klass->super();
4416 const Method* super_m = nullptr;
4417 while (k != nullptr) {
4418 // skip supers that don't have final methods.
4419 if (k->has_final_method()) {
4420 // lookup a matching method in the super class hierarchy
4421 super_m = k->lookup_method(name, signature);
4422 if (super_m == nullptr) {
4423 break; // didn't find any match; get out
4424 }
4425
4426 if (super_m->is_final() && !super_m->is_static() &&
4427 !super_m->access_flags().is_private()) {
4428 // matching method in super is final, and not static or private
4429 bool can_access = Reflection::verify_member_access(this_klass,
4430 super_m->method_holder(),
4431 super_m->method_holder(),
4432 super_m->access_flags(),
4433 false, false, CHECK);
4434 if (can_access) {
4435 // this class can access super final method and therefore override
4436 ResourceMark rm(THREAD);
4437 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
4438 err_msg("class %s overrides final method %s.%s%s",
4439 this_klass->external_name(),
4440 super_m->method_holder()->external_name(),
4441 name->as_C_string(),
4442 signature->as_C_string()));
4443 }
4444 }
4445
4446 // continue to look from super_m's holder's super.
4447 k = super_m->method_holder()->super();
4448 continue;
4449 }
4450
4451 k = k->super();
4452 }
4453 }
4454 }
4455 }
4456
4457
4458 // assumes that this_klass is an interface
4459 static void check_illegal_static_method(const InstanceKlass* this_klass, TRAPS) {
4460 assert(this_klass != nullptr, "invariant");
4461 assert(this_klass->is_interface(), "not an interface");
4462 const Array<Method*>* methods = this_klass->methods();
4463 const int num_methods = methods->length();
4464
4465 for (int index = 0; index < num_methods; index++) {
4466 const Method* const m = methods->at(index);
4467 // if m is static and not the init method, throw a verify error
4468 if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) {
4469 ResourceMark rm(THREAD);
4470
4471 // Names are all known to be < 64k so we know this formatted message is not excessively large.
4472 Exceptions::fthrow(
4473 THREAD_AND_LOCATION,
4474 vmSymbols::java_lang_VerifyError(),
4475 "Illegal static method %s in interface %s",
4476 m->name()->as_C_string(),
4477 this_klass->external_name()
4478 );
4479 return;
4480 }
4481 }
4482 }
4483
4484 // utility methods for format checking
4485
4486 // Verify the class modifiers for the current class, or an inner class if inner_name is non-null.
4487 void ClassFileParser::verify_legal_class_modifiers(jint flags, Symbol* inner_name, bool is_anonymous_inner_class, TRAPS) const {
4488 const bool is_module = (flags & JVM_ACC_MODULE) != 0;
4489 assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");
4490 if (is_module) {
4491 ResourceMark rm(THREAD);
4492 // Names are all known to be < 64k so we know this formatted message is not excessively large.
4493 Exceptions::fthrow(
4494 THREAD_AND_LOCATION,
4495 vmSymbols::java_lang_NoClassDefFoundError(),
4496 "%s is not a class because access_flag ACC_MODULE is set",
4497 _class_name->as_C_string());
4498 return;
4499 }
4500
4501 if (!_need_verify) { return; }
4502
4503 const bool is_interface = (flags & JVM_ACC_INTERFACE) != 0;
4504 const bool is_abstract = (flags & JVM_ACC_ABSTRACT) != 0;
4505 const bool is_final = (flags & JVM_ACC_FINAL) != 0;
4506 const bool is_identity = (flags & JVM_ACC_IDENTITY) != 0;
4507 const bool is_enum = (flags & JVM_ACC_ENUM) != 0;
4508 const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4509 const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4510 const bool valid_value_class = is_identity || is_interface || (supports_inline_types() && (is_abstract || is_final));
4511
4512 if ((is_abstract && is_final) ||
4513 (is_interface && !is_abstract) ||
4514 (is_interface && major_gte_1_5 && (is_identity || is_enum)) || // ACC_SUPER (now ACC_IDENTITY) was illegal for interfaces
4515 (!is_interface && major_gte_1_5 && is_annotation) ||
4516 (!valid_value_class)) {
4517 ResourceMark rm(THREAD);
4518 // Names are all known to be < 64k so we know this formatted message is not excessively large.
4519 if (inner_name == nullptr && !is_anonymous_inner_class) {
4520 Exceptions::fthrow(
4521 THREAD_AND_LOCATION,
4522 vmSymbols::java_lang_ClassFormatError(),
4523 "Illegal class modifiers in class %s: 0x%X",
4524 _class_name->as_C_string(), flags
4525 );
4526 } else {
4527 if (is_anonymous_inner_class) {
4528 Exceptions::fthrow(
4529 THREAD_AND_LOCATION,
4530 vmSymbols::java_lang_ClassFormatError(),
4531 "Illegal class modifiers in anonymous inner class of class %s: 0x%X",
4532 _class_name->as_C_string(), flags
4533 );
4534 } else {
4535 Exceptions::fthrow(
4536 THREAD_AND_LOCATION,
4537 vmSymbols::java_lang_ClassFormatError(),
4538 "Illegal class modifiers in inner class %s of class %s: 0x%X",
4539 inner_name->as_C_string(), _class_name->as_C_string(), flags
4540 );
4541 }
4542 }
4543 return;
4544 }
4545 }
4546
4547 static bool has_illegal_visibility(jint flags) {
4548 const bool is_public = (flags & JVM_ACC_PUBLIC) != 0;
4549 const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4550 const bool is_private = (flags & JVM_ACC_PRIVATE) != 0;
4551
4552 return ((is_public && is_protected) ||
4553 (is_public && is_private) ||
4554 (is_protected && is_private));
4555 }
4556
4557 // A legal major_version.minor_version must be one of the following:
4558 //
4559 // Major_version >= 45 and major_version < 56, any minor_version.
4560 // Major_version >= 56 and major_version <= JVM_CLASSFILE_MAJOR_VERSION and minor_version = 0.
4561 // Major_version = JVM_CLASSFILE_MAJOR_VERSION and minor_version = 65535 and --enable-preview is present.
4562 //
4563 void ClassFileParser::verify_class_version(u2 major, u2 minor, Symbol* class_name, TRAPS){
4564 ResourceMark rm(THREAD);
4565 const u2 max_version = JVM_CLASSFILE_MAJOR_VERSION;
4566 if (major < JAVA_MIN_SUPPORTED_VERSION) {
4567 classfile_ucve_error("%s (class file version %u.%u) was compiled with an invalid major version",
4568 class_name, major, minor, THREAD);
4569 return;
4570 }
4571
4572 if (major > max_version) {
4573 // Names are all known to be < 64k so we know this formatted message is not excessively large.
4574 Exceptions::fthrow(
4575 THREAD_AND_LOCATION,
4576 vmSymbols::java_lang_UnsupportedClassVersionError(),
4577 "%s has been compiled by a more recent version of the Java Runtime (class file version %u.%u), "
4578 "this version of the Java Runtime only recognizes class file versions up to %u.0",
4579 class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION);
4580 return;
4581 }
4582
4583 if (major < JAVA_12_VERSION || minor == 0) {
4584 return;
4585 }
4586
4587 if (minor == JAVA_PREVIEW_MINOR_VERSION) {
4588 if (major != max_version) {
4589 // Names are all known to be < 64k so we know this formatted message is not excessively large.
4590 Exceptions::fthrow(
4591 THREAD_AND_LOCATION,
4592 vmSymbols::java_lang_UnsupportedClassVersionError(),
4593 "%s (class file version %u.%u) was compiled with preview features that are unsupported. "
4594 "This version of the Java Runtime only recognizes preview features for class file version %u.%u",
4595 class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION, JAVA_PREVIEW_MINOR_VERSION);
4596 return;
4597 }
4598
4599 if (!Arguments::enable_preview()) {
4600 classfile_ucve_error("Preview features are not enabled for %s (class file version %u.%u). Try running with '--enable-preview'",
4601 class_name, major, minor, THREAD);
4602 return;
4603 }
4604
4605 } else { // minor != JAVA_PREVIEW_MINOR_VERSION
4606 classfile_ucve_error("%s (class file version %u.%u) was compiled with an invalid non-zero minor version",
4607 class_name, major, minor, THREAD);
4608 }
4609 }
4610
4611 void ClassFileParser:: verify_legal_field_modifiers(jint flags,
4612 AccessFlags class_access_flags,
4613 TRAPS) const {
4614 if (!_need_verify) { return; }
4615
4616 const bool is_public = (flags & JVM_ACC_PUBLIC) != 0;
4617 const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4618 const bool is_private = (flags & JVM_ACC_PRIVATE) != 0;
4619 const bool is_static = (flags & JVM_ACC_STATIC) != 0;
4620 const bool is_final = (flags & JVM_ACC_FINAL) != 0;
4621 const bool is_volatile = (flags & JVM_ACC_VOLATILE) != 0;
4622 const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
4623 const bool is_enum = (flags & JVM_ACC_ENUM) != 0;
4624 const bool is_strict = (flags & JVM_ACC_STRICT_INIT) != 0;
4625 const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4626
4627 const bool is_interface = class_access_flags.is_interface();
4628 const bool is_identity_class = class_access_flags.is_identity_class();
4629
4630 bool is_illegal = false;
4631 const char* error_msg = "";
4632
4633 // There is some overlap in the checks that apply, for example interface fields
4634 // must be static, static fields can't be strict, and therefore interfaces can't
4635 // have strict fields. So we don't have to check every possible invalid combination
4636 // individually as long as all are covered. Once we have found an illegal combination
4637 // we can stop checking.
4638
4639 if (!is_illegal) {
4640 if (is_interface) {
4641 if (!is_public || !is_static || !is_final || is_private ||
4642 is_protected || is_volatile || is_transient ||
4643 (major_gte_1_5 && is_enum)) {
4644 is_illegal = true;
4645 error_msg = "interface fields must be public, static and final, and may be synthetic";
4646 }
4647 } else { // not interface
4648 if (has_illegal_visibility(flags)) {
4649 is_illegal = true;
4650 error_msg = "invalid visibility flags for class field";
4651 } else if (is_final && is_volatile) {
4652 is_illegal = true;
4653 error_msg = "fields cannot be final and volatile";
4654 } else if (supports_inline_types()) {
4655 if (!is_identity_class && !is_static && (!is_strict || !is_final)) {
4656 is_illegal = true;
4657 error_msg = "value class fields must be either non-static final and strict, or static";
4658 }
4659 }
4660 }
4661 }
4662
4663 if (is_illegal) {
4664 ResourceMark rm(THREAD);
4665 // Names are all known to be < 64k so we know this formatted message is not excessively large.
4666 Exceptions::fthrow(
4667 THREAD_AND_LOCATION,
4668 vmSymbols::java_lang_ClassFormatError(),
4669 "Illegal field modifiers (%s) in class %s: 0x%X",
4670 error_msg, _class_name->as_C_string(), flags);
4671 return;
4672 }
4673 }
4674
4675 void ClassFileParser::verify_legal_method_modifiers(jint flags,
4676 AccessFlags class_access_flags,
4677 const Symbol* name,
4678 TRAPS) const {
4679 if (!_need_verify) { return; }
4680
4681 const bool is_public = (flags & JVM_ACC_PUBLIC) != 0;
4682 const bool is_private = (flags & JVM_ACC_PRIVATE) != 0;
4683 const bool is_static = (flags & JVM_ACC_STATIC) != 0;
4684 const bool is_final = (flags & JVM_ACC_FINAL) != 0;
4685 const bool is_native = (flags & JVM_ACC_NATIVE) != 0;
4686 const bool is_abstract = (flags & JVM_ACC_ABSTRACT) != 0;
4687 const bool is_bridge = (flags & JVM_ACC_BRIDGE) != 0;
4688 const bool is_strict = (flags & JVM_ACC_STRICT) != 0;
4689 const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
4690 const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4691 const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4692 const bool major_gte_8 = _major_version >= JAVA_8_VERSION;
4693 const bool major_gte_17 = _major_version >= JAVA_17_VERSION;
4694 const bool is_initializer = (name == vmSymbols::object_initializer_name());
4695 // LW401 CR required: removal of value factories support
4696 const bool is_interface = class_access_flags.is_interface();
4697 const bool is_identity_class = class_access_flags.is_identity_class();
4698 const bool is_abstract_class = class_access_flags.is_abstract();
4699
4700 bool is_illegal = false;
4701
4702 const char* class_note = "";
4703 if (is_interface) {
4704 if (major_gte_8) {
4705 // Class file version is JAVA_8_VERSION or later Methods of
4706 // interfaces may set any of the flags except ACC_PROTECTED,
4707 // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must
4708 // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.
4709 if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
4710 (is_native || is_protected || is_final || is_synchronized) ||
4711 // If a specific method of a class or interface has its
4712 // ACC_ABSTRACT flag set, it must not have any of its
4713 // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,
4714 // ACC_STRICT, or ACC_SYNCHRONIZED flags set. No need to
4715 // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as
4716 // those flags are illegal irrespective of ACC_ABSTRACT being set or not.
4717 (is_abstract && (is_private || is_static || (!major_gte_17 && is_strict)))) {
4718 is_illegal = true;
4719 }
4720 } else if (major_gte_1_5) {
4721 // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)
4722 if (!is_public || is_private || is_protected || is_static || is_final ||
4723 is_synchronized || is_native || !is_abstract || is_strict) {
4724 is_illegal = true;
4725 }
4726 } else {
4727 // Class file version is pre-JAVA_1_5_VERSION
4728 if (!is_public || is_static || is_final || is_native || !is_abstract) {
4729 is_illegal = true;
4730 }
4731 }
4732 } else { // not interface
4733 if (has_illegal_visibility(flags)) {
4734 is_illegal = true;
4735 } else {
4736 if (is_initializer) {
4737 if (is_static || is_final || is_synchronized || is_native ||
4738 is_abstract || (major_gte_1_5 && is_bridge)) {
4739 is_illegal = true;
4740 }
4741 } else { // not initializer
4742 if (!is_identity_class && is_synchronized && !is_static) {
4743 is_illegal = true;
4744 class_note = " (not an identity class)";
4745 } else {
4746 if (is_abstract) {
4747 if ((is_final || is_native || is_private || is_static ||
4748 (major_gte_1_5 && (is_synchronized || (!major_gte_17 && is_strict))))) {
4749 is_illegal = true;
4750 }
4751 }
4752 }
4753 }
4754 }
4755 }
4756
4757 if (is_illegal) {
4758 ResourceMark rm(THREAD);
4759 // Names are all known to be < 64k so we know this formatted message is not excessively large.
4760 Exceptions::fthrow(
4761 THREAD_AND_LOCATION,
4762 vmSymbols::java_lang_ClassFormatError(),
4763 "Method %s in class %s%s has illegal modifiers: 0x%X",
4764 name->as_C_string(), _class_name->as_C_string(),
4765 class_note, flags);
4766 return;
4767 }
4768 }
4769
4770 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer,
4771 int length,
4772 TRAPS) const {
4773 assert(_need_verify, "only called when _need_verify is true");
4774 // Note: 0 <= length < 64K, as it comes from a u2 entry in the CP.
4775 if (!UTF8::is_legal_utf8(buffer, static_cast<size_t>(length), _major_version <= 47)) {
4776 classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", THREAD);
4777 }
4778 }
4779
4780 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
4781 // In class names, '/' separates unqualified names. This is verified in this function also.
4782 // Method names also may not contain the characters '<' or '>', unless <init>
4783 // or <clinit>. Note that method names may not be <init> or <clinit> in this
4784 // method. Because these names have been checked as special cases before
4785 // calling this method in verify_legal_method_name.
4786 //
4787 // This method is also called from the modular system APIs in modules.cpp
4788 // to verify the validity of module and package names.
4789 bool ClassFileParser::verify_unqualified_name(const char* name,
4790 unsigned int length,
4791 int type) {
4792 if (length == 0) return false; // Must have at least one char.
4793 for (const char* p = name; p != name + length; p++) {
4794 switch(*p) {
4795 case JVM_SIGNATURE_DOT:
4796 case JVM_SIGNATURE_ENDCLASS:
4797 case JVM_SIGNATURE_ARRAY:
4798 // do not permit '.', ';', or '['
4799 return false;
4800 case JVM_SIGNATURE_SLASH:
4801 // check for '//' or leading or trailing '/' which are not legal
4802 // unqualified name must not be empty
4803 if (type == ClassFileParser::LegalClass) {
4804 if (p == name || p+1 >= name+length ||
4805 *(p+1) == JVM_SIGNATURE_SLASH) {
4806 return false;
4807 }
4808 } else {
4809 return false; // do not permit '/' unless it's class name
4810 }
4811 break;
4812 case JVM_SIGNATURE_SPECIAL:
4813 case JVM_SIGNATURE_ENDSPECIAL:
4814 // do not permit '<' or '>' in method names
4815 if (type == ClassFileParser::LegalMethod) {
4816 return false;
4817 }
4818 }
4819 }
4820 return true;
4821 }
4822
4823 bool ClassFileParser::is_class_in_loadable_descriptors_attribute(Symbol *klass) {
4824 if (_loadable_descriptors == nullptr) return false;
4825 for (int i = 0; i < _loadable_descriptors->length(); i++) {
4826 Symbol* class_name = _cp->symbol_at(_loadable_descriptors->at(i));
4827 if (class_name == klass) return true;
4828 }
4829 return false;
4830 }
4831
4832 // Take pointer to a UTF8 byte string (not NUL-terminated).
4833 // Skip over the longest part of the string that could
4834 // be taken as a fieldname. Allow non-trailing '/'s if slash_ok is true.
4835 // Return a pointer to just past the fieldname.
4836 // Return null if no fieldname at all was found, or in the case of slash_ok
4837 // being true, we saw consecutive slashes (meaning we were looking for a
4838 // qualified path but found something that was badly-formed).
4839 static const char* skip_over_field_name(const char* const name,
4840 bool slash_ok,
4841 unsigned int length) {
4842 const char* p;
4843 jboolean last_is_slash = false;
4844 jboolean not_first_ch = false;
4845
4846 for (p = name; p != name + length; not_first_ch = true) {
4847 const char* old_p = p;
4848 jchar ch = *p;
4849 if (ch < 128) {
4850 p++;
4851 // quick check for ascii
4852 if ((ch >= 'a' && ch <= 'z') ||
4853 (ch >= 'A' && ch <= 'Z') ||
4854 (ch == '_' || ch == '$') ||
4855 (not_first_ch && ch >= '0' && ch <= '9')) {
4856 last_is_slash = false;
4857 continue;
4858 }
4859 if (slash_ok && ch == JVM_SIGNATURE_SLASH) {
4860 if (last_is_slash) {
4861 return nullptr; // Don't permit consecutive slashes
4862 }
4863 last_is_slash = true;
4864 continue;
4865 }
4866 }
4867 else {
4868 jint unicode_ch;
4869 char* tmp_p = UTF8::next_character(p, &unicode_ch);
4870 p = tmp_p;
4871 last_is_slash = false;
4872 // Check if ch is Java identifier start or is Java identifier part
4873 // 4672820: call java.lang.Character methods directly without generating separate tables.
4874 EXCEPTION_MARK;
4875 // return value
4876 JavaValue result(T_BOOLEAN);
4877 // Set up the arguments to isJavaIdentifierStart or isJavaIdentifierPart
4878 JavaCallArguments args;
4879 args.push_int(unicode_ch);
4880
4881 if (not_first_ch) {
4882 // public static boolean isJavaIdentifierPart(char ch);
4883 JavaCalls::call_static(&result,
4884 vmClasses::Character_klass(),
4885 vmSymbols::isJavaIdentifierPart_name(),
4886 vmSymbols::int_bool_signature(),
4887 &args,
4888 THREAD);
4889 } else {
4890 // public static boolean isJavaIdentifierStart(char ch);
4891 JavaCalls::call_static(&result,
4892 vmClasses::Character_klass(),
4893 vmSymbols::isJavaIdentifierStart_name(),
4894 vmSymbols::int_bool_signature(),
4895 &args,
4896 THREAD);
4897 }
4898 if (HAS_PENDING_EXCEPTION) {
4899 CLEAR_PENDING_EXCEPTION;
4900 return nullptr;
4901 }
4902 if(result.get_jboolean()) {
4903 continue;
4904 }
4905 }
4906 return (not_first_ch) ? old_p : nullptr;
4907 }
4908 return (not_first_ch && !last_is_slash) ? p : nullptr;
4909 }
4910
4911 // Take pointer to a UTF8 byte string (not NUL-terminated).
4912 // Skip over the longest part of the string that could
4913 // be taken as a field signature. Allow "void" if void_ok.
4914 // Return a pointer to just past the signature.
4915 // Return null if no legal signature is found.
4916 const char* ClassFileParser::skip_over_field_signature(const char* signature,
4917 bool void_ok,
4918 unsigned int length,
4919 TRAPS) const {
4920 unsigned int array_dim = 0;
4921 while (length > 0) {
4922 switch (signature[0]) {
4923 case JVM_SIGNATURE_VOID: if (!void_ok) { return nullptr; }
4924 case JVM_SIGNATURE_BOOLEAN:
4925 case JVM_SIGNATURE_BYTE:
4926 case JVM_SIGNATURE_CHAR:
4927 case JVM_SIGNATURE_SHORT:
4928 case JVM_SIGNATURE_INT:
4929 case JVM_SIGNATURE_FLOAT:
4930 case JVM_SIGNATURE_LONG:
4931 case JVM_SIGNATURE_DOUBLE:
4932 return signature + 1;
4933 case JVM_SIGNATURE_CLASS:
4934 {
4935 if (_major_version < JAVA_1_5_VERSION) {
4936 signature++;
4937 length--;
4938 // Skip over the class name if one is there
4939 const char* const p = skip_over_field_name(signature, true, length);
4940 assert(p == nullptr || p > signature, "must parse one character at least");
4941 // The next character better be a semicolon
4942 if (p != nullptr && // Parse of field name succeeded.
4943 p - signature < static_cast<int>(length) && // There is at least one character left to parse.
4944 p[0] == JVM_SIGNATURE_ENDCLASS) {
4945 return p + 1;
4946 }
4947 }
4948 else {
4949 // Skip leading 'L' or 'Q' and ignore first appearance of ';'
4950 signature++;
4951 const char* c = (const char*) memchr(signature, JVM_SIGNATURE_ENDCLASS, length - 1);
4952 // Format check signature
4953 if (c != nullptr) {
4954 int newlen = pointer_delta_as_int(c, (char*) signature);
4955 bool legal = verify_unqualified_name(signature, newlen, LegalClass);
4956 if (!legal) {
4957 classfile_parse_error("Class name is empty or contains illegal character "
4958 "in descriptor in class file %s",
4959 THREAD);
4960 return nullptr;
4961 }
4962 return signature + newlen + 1;
4963 }
4964 }
4965 return nullptr;
4966 }
4967 case JVM_SIGNATURE_ARRAY:
4968 array_dim++;
4969 if (array_dim > 255) {
4970 // 4277370: array descriptor is valid only if it represents 255 or fewer dimensions.
4971 classfile_parse_error("Array type descriptor has more than 255 dimensions in class file %s", THREAD);
4972 return nullptr;
4973 }
4974 // The rest of what's there better be a legal signature
4975 signature++;
4976 length--;
4977 void_ok = false;
4978 break;
4979 default:
4980 return nullptr;
4981 }
4982 }
4983 return nullptr;
4984 }
4985
4986 // Checks if name is a legal class name.
4987 void ClassFileParser::verify_legal_class_name(const Symbol* name, TRAPS) const {
4988 if (!_need_verify) { return; }
4989
4990 assert(name->refcount() > 0, "symbol must be kept alive");
4991 char* bytes = (char*)name->bytes();
4992 unsigned int length = name->utf8_length();
4993 bool legal = false;
4994
4995 if (length > 0) {
4996 const char* p;
4997 if (bytes[0] == JVM_SIGNATURE_ARRAY) {
4998 p = skip_over_field_signature(bytes, false, length, CHECK);
4999 legal = (p != nullptr) && ((p - bytes) == (int)length);
5000 } else if (_major_version < JAVA_1_5_VERSION) {
5001 if (bytes[0] != JVM_SIGNATURE_SPECIAL) {
5002 p = skip_over_field_name(bytes, true, length);
5003 legal = (p != nullptr) && ((p - bytes) == (int)length);
5004 }
5005 } else {
5006 // 4900761: relax the constraints based on JSR202 spec
5007 // Class names may be drawn from the entire Unicode character set.
5008 // Identifiers between '/' must be unqualified names.
5009 // The utf8 string has been verified when parsing cpool entries.
5010 legal = verify_unqualified_name(bytes, length, LegalClass);
5011 }
5012 }
5013 if (!legal) {
5014 ResourceMark rm(THREAD);
5015 assert(_class_name != nullptr, "invariant");
5016 // Names are all known to be < 64k so we know this formatted message is not excessively large.
5017 Exceptions::fthrow(
5018 THREAD_AND_LOCATION,
5019 vmSymbols::java_lang_ClassFormatError(),
5020 "Illegal class name \"%.*s\" in class file %s", length, bytes,
5021 _class_name->as_C_string()
5022 );
5023 return;
5024 }
5025 }
5026
5027 // Checks if name is a legal field name.
5028 void ClassFileParser::verify_legal_field_name(const Symbol* name, TRAPS) const {
5029 if (!_need_verify) { return; }
5030
5031 char* bytes = (char*)name->bytes();
5032 unsigned int length = name->utf8_length();
5033 bool legal = false;
5034
5035 if (length > 0) {
5036 if (_major_version < JAVA_1_5_VERSION) {
5037 if (bytes[0] != JVM_SIGNATURE_SPECIAL) {
5038 const char* p = skip_over_field_name(bytes, false, length);
5039 legal = (p != nullptr) && ((p - bytes) == (int)length);
5040 }
5041 } else {
5042 // 4881221: relax the constraints based on JSR202 spec
5043 legal = verify_unqualified_name(bytes, length, LegalField);
5044 }
5045 }
5046
5047 if (!legal) {
5048 ResourceMark rm(THREAD);
5049 assert(_class_name != nullptr, "invariant");
5050 // Names are all known to be < 64k so we know this formatted message is not excessively large.
5051 Exceptions::fthrow(
5052 THREAD_AND_LOCATION,
5053 vmSymbols::java_lang_ClassFormatError(),
5054 "Illegal field name \"%.*s\" in class %s", length, bytes,
5055 _class_name->as_C_string()
5056 );
5057 return;
5058 }
5059 }
5060
5061 // Checks if name is a legal method name.
5062 void ClassFileParser::verify_legal_method_name(const Symbol* name, TRAPS) const {
5063 if (!_need_verify) { return; }
5064
5065 assert(name != nullptr, "method name is null");
5066 char* bytes = (char*)name->bytes();
5067 unsigned int length = name->utf8_length();
5068 bool legal = false;
5069
5070 if (length > 0) {
5071 if (bytes[0] == JVM_SIGNATURE_SPECIAL) {
5072 if (name == vmSymbols::object_initializer_name() ||
5073 name == vmSymbols::class_initializer_name()) {
5074 legal = true;
5075 }
5076 } else if (_major_version < JAVA_1_5_VERSION) {
5077 const char* p;
5078 p = skip_over_field_name(bytes, false, length);
5079 legal = (p != nullptr) && ((p - bytes) == (int)length);
5080 } else {
5081 // 4881221: relax the constraints based on JSR202 spec
5082 legal = verify_unqualified_name(bytes, length, LegalMethod);
5083 }
5084 }
5085
5086 if (!legal) {
5087 ResourceMark rm(THREAD);
5088 assert(_class_name != nullptr, "invariant");
5089 // Names are all known to be < 64k so we know this formatted message is not excessively large.
5090 Exceptions::fthrow(
5091 THREAD_AND_LOCATION,
5092 vmSymbols::java_lang_ClassFormatError(),
5093 "Illegal method name \"%.*s\" in class %s", length, bytes,
5094 _class_name->as_C_string()
5095 );
5096 return;
5097 }
5098 }
5099
5100 bool ClassFileParser::legal_field_signature(const Symbol* signature, TRAPS) const {
5101 const char* const bytes = (const char*)signature->bytes();
5102 const unsigned int length = signature->utf8_length();
5103 const char* const p = skip_over_field_signature(bytes, false, length, CHECK_false);
5104
5105 if (p == nullptr || (p - bytes) != (int)length) {
5106 return false;
5107 }
5108 return true;
5109 }
5110
5111 // Checks if signature is a legal field signature.
5112 void ClassFileParser::verify_legal_field_signature(const Symbol* name,
5113 const Symbol* signature,
5114 TRAPS) const {
5115 if (!_need_verify) { return; }
5116
5117 const char* const bytes = (const char*)signature->bytes();
5118 const unsigned int length = signature->utf8_length();
5119 const char* const p = skip_over_field_signature(bytes, false, length, CHECK);
5120
5121 if (p == nullptr || (p - bytes) != (int)length) {
5122 throwIllegalSignature("Field", name, signature, CHECK);
5123 }
5124 }
5125
5126 // Check that the signature is compatible with the method name. For example,
5127 // check that <init> has a void signature.
5128 void ClassFileParser::verify_legal_name_with_signature(const Symbol* name,
5129 const Symbol* signature,
5130 TRAPS) const {
5131 if (!_need_verify) {
5132 return;
5133 }
5134
5135 // Class initializers cannot have args for class format version >= 51.
5136 if (name == vmSymbols::class_initializer_name() &&
5137 signature != vmSymbols::void_method_signature() &&
5138 _major_version >= JAVA_7_VERSION) {
5139 throwIllegalSignature("Method", name, signature, THREAD);
5140 return;
5141 }
5142
5143 int sig_length = signature->utf8_length();
5144 if (name->utf8_length() > 0 &&
5145 name->char_at(0) == JVM_SIGNATURE_SPECIAL &&
5146 sig_length > 0 &&
5147 signature->char_at(sig_length - 1) != JVM_SIGNATURE_VOID) {
5148 throwIllegalSignature("Method", name, signature, THREAD);
5149 }
5150 }
5151
5152 // Checks if signature is a legal method signature.
5153 // Returns number of parameters
5154 int ClassFileParser::verify_legal_method_signature(const Symbol* name,
5155 const Symbol* signature,
5156 TRAPS) const {
5157 if (!_need_verify) {
5158 // make sure caller's args_size will be less than 0 even for non-static
5159 // method so it will be recomputed in compute_size_of_parameters().
5160 return -2;
5161 }
5162
5163 unsigned int args_size = 0;
5164 const char* p = (const char*)signature->bytes();
5165 unsigned int length = signature->utf8_length();
5166 const char* nextp;
5167
5168 // The first character must be a '('
5169 if ((length > 0) && (*p++ == JVM_SIGNATURE_FUNC)) {
5170 length--;
5171 // Skip over legal field signatures
5172 nextp = skip_over_field_signature(p, false, length, CHECK_0);
5173 while ((length > 0) && (nextp != nullptr)) {
5174 args_size++;
5175 if (p[0] == 'J' || p[0] == 'D') {
5176 args_size++;
5177 }
5178 length -= pointer_delta_as_int(nextp, p);
5179 p = nextp;
5180 nextp = skip_over_field_signature(p, false, length, CHECK_0);
5181 }
5182 // The first non-signature thing better be a ')'
5183 if ((length > 0) && (*p++ == JVM_SIGNATURE_ENDFUNC)) {
5184 length--;
5185 // Now we better just have a return value
5186 nextp = skip_over_field_signature(p, true, length, CHECK_0);
5187 if (nextp && ((int)length == (nextp - p))) {
5188 return args_size;
5189 }
5190 }
5191 }
5192 // Report error
5193 throwIllegalSignature("Method", name, signature, THREAD);
5194 return 0;
5195 }
5196
5197 int ClassFileParser::static_field_size() const {
5198 assert(_layout_info != nullptr, "invariant");
5199 return _layout_info->_static_field_size;
5200 }
5201
5202 int ClassFileParser::total_oop_map_count() const {
5203 assert(_layout_info != nullptr, "invariant");
5204 return _layout_info->oop_map_blocks->_nonstatic_oop_map_count;
5205 }
5206
5207 jint ClassFileParser::layout_size() const {
5208 assert(_layout_info != nullptr, "invariant");
5209 return _layout_info->_instance_size;
5210 }
5211
5212 static void check_methods_for_intrinsics(const InstanceKlass* ik,
5213 const Array<Method*>* methods) {
5214 assert(ik != nullptr, "invariant");
5215 assert(methods != nullptr, "invariant");
5216
5217 // Set up Method*::intrinsic_id as soon as we know the names of methods.
5218 // (We used to do this lazily, but now we query it in Rewriter,
5219 // which is eagerly done for every method, so we might as well do it now,
5220 // when everything is fresh in memory.)
5221 const vmSymbolID klass_id = Method::klass_id_for_intrinsics(ik);
5222
5223 if (klass_id != vmSymbolID::NO_SID) {
5224 for (int j = 0; j < methods->length(); ++j) {
5225 Method* method = methods->at(j);
5226 method->init_intrinsic_id(klass_id);
5227
5228 if (CheckIntrinsics) {
5229 // Check if an intrinsic is defined for method 'method',
5230 // but the method is not annotated with @IntrinsicCandidate.
5231 if (method->intrinsic_id() != vmIntrinsics::_none &&
5232 !method->intrinsic_candidate()) {
5233 tty->print("Compiler intrinsic is defined for method [%s], "
5234 "but the method is not annotated with @IntrinsicCandidate.%s",
5235 method->name_and_sig_as_C_string(),
5236 NOT_DEBUG(" Method will not be inlined.") DEBUG_ONLY(" Exiting.")
5237 );
5238 tty->cr();
5239 DEBUG_ONLY(vm_exit(1));
5240 }
5241 // Check is the method 'method' is annotated with @IntrinsicCandidate,
5242 // but there is no intrinsic available for it.
5243 if (method->intrinsic_candidate() &&
5244 method->intrinsic_id() == vmIntrinsics::_none) {
5245 tty->print("Method [%s] is annotated with @IntrinsicCandidate, "
5246 "but no compiler intrinsic is defined for the method.%s",
5247 method->name_and_sig_as_C_string(),
5248 NOT_DEBUG("") DEBUG_ONLY(" Exiting.")
5249 );
5250 tty->cr();
5251 DEBUG_ONLY(vm_exit(1));
5252 }
5253 }
5254 } // end for
5255
5256 #ifdef ASSERT
5257 if (CheckIntrinsics) {
5258 // Check for orphan methods in the current class. A method m
5259 // of a class C is orphan if an intrinsic is defined for method m,
5260 // but class C does not declare m.
5261 // The check is potentially expensive, therefore it is available
5262 // only in debug builds.
5263
5264 for (auto id : EnumRange<vmIntrinsicID>{}) {
5265 if (vmIntrinsics::_compiledLambdaForm == id) {
5266 // The _compiledLamdbdaForm intrinsic is a special marker for bytecode
5267 // generated for the JVM from a LambdaForm and therefore no method
5268 // is defined for it.
5269 continue;
5270 }
5271 if (vmIntrinsics::_blackhole == id) {
5272 // The _blackhole intrinsic is a special marker. No explicit method
5273 // is defined for it.
5274 continue;
5275 }
5276
5277 if (vmIntrinsics::class_for(id) == klass_id) {
5278 // Check if the current class contains a method with the same
5279 // name, flags, signature.
5280 bool match = false;
5281 for (int j = 0; j < methods->length(); ++j) {
5282 const Method* method = methods->at(j);
5283 if (method->intrinsic_id() == id) {
5284 match = true;
5285 break;
5286 }
5287 }
5288
5289 if (!match) {
5290 char buf[1000];
5291 tty->print("Compiler intrinsic is defined for method [%s], "
5292 "but the method is not available in class [%s].%s",
5293 vmIntrinsics::short_name_as_C_string(id, buf, sizeof(buf)),
5294 ik->name()->as_C_string(),
5295 NOT_DEBUG("") DEBUG_ONLY(" Exiting.")
5296 );
5297 tty->cr();
5298 DEBUG_ONLY(vm_exit(1));
5299 }
5300 }
5301 } // end for
5302 } // CheckIntrinsics
5303 #endif // ASSERT
5304 }
5305 }
5306
5307 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook,
5308 const ClassInstanceInfo& cl_inst_info,
5309 TRAPS) {
5310 if (_klass != nullptr) {
5311 return _klass;
5312 }
5313
5314 InstanceKlass* const ik =
5315 InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
5316
5317 if (is_hidden()) {
5318 mangle_hidden_class_name(ik);
5319 }
5320
5321 fill_instance_klass(ik, changed_by_loadhook, cl_inst_info, CHECK_NULL);
5322
5323 assert(_klass == ik, "invariant");
5324 return ik;
5325 }
5326
5327 void ClassFileParser::fill_instance_klass(InstanceKlass* ik,
5328 bool changed_by_loadhook,
5329 const ClassInstanceInfo& cl_inst_info,
5330 TRAPS) {
5331 assert(ik != nullptr, "invariant");
5332
5333 // Set name and CLD before adding to CLD
5334 ik->set_class_loader_data(_loader_data);
5335 ik->set_class_loader_type();
5336 ik->set_name(_class_name);
5337
5338 // Add all classes to our internal class loader list here,
5339 // including classes in the bootstrap (null) class loader.
5340 const bool publicize = !is_internal();
5341
5342 _loader_data->add_class(ik, publicize);
5343
5344 set_klass_to_deallocate(ik);
5345
5346 assert(_layout_info != nullptr, "invariant");
5347 assert(ik->static_field_size() == _layout_info->_static_field_size, "sanity");
5348 assert(ik->nonstatic_oop_map_count() == _layout_info->oop_map_blocks->_nonstatic_oop_map_count,
5349 "sanity");
5350
5351 assert(ik->is_instance_klass(), "sanity");
5352 assert(ik->size_helper() == _layout_info->_instance_size, "sanity");
5353
5354 // Fill in information already parsed
5355 ik->set_should_verify_class(_need_verify);
5356
5357 // Not yet: supers are done below to support the new subtype-checking fields
5358 ik->set_nonstatic_field_size(_layout_info->_nonstatic_field_size);
5359 ik->set_has_nonstatic_fields(_layout_info->_has_nonstatic_fields);
5360 ik->set_has_strict_static_fields(_has_strict_static_fields);
5361
5362 if (_layout_info->_is_naturally_atomic) {
5363 ik->set_is_naturally_atomic();
5364 }
5365
5366 if (_layout_info->_must_be_atomic) {
5367 ik->set_must_be_atomic();
5368 }
5369
5370 ik->set_static_oop_field_count(_static_oop_count);
5371
5372 // this transfers ownership of a lot of arrays from
5373 // the parser onto the InstanceKlass*
5374 apply_parsed_class_metadata(ik, _java_fields_count);
5375
5376 // can only set dynamic nest-host after static nest information is set
5377 if (cl_inst_info.dynamic_nest_host() != nullptr) {
5378 ik->set_nest_host(cl_inst_info.dynamic_nest_host());
5379 }
5380
5381 // note that is not safe to use the fields in the parser from this point on
5382 assert(nullptr == _cp, "invariant");
5383 assert(nullptr == _fieldinfo_stream, "invariant");
5384 assert(nullptr == _fieldinfo_search_table, "invariant");
5385 assert(nullptr == _fields_status, "invariant");
5386 assert(nullptr == _methods, "invariant");
5387 assert(nullptr == _inner_classes, "invariant");
5388 assert(nullptr == _nest_members, "invariant");
5389 assert(nullptr == _loadable_descriptors, "invariant");
5390 assert(nullptr == _combined_annotations, "invariant");
5391 assert(nullptr == _record_components, "invariant");
5392 assert(nullptr == _permitted_subclasses, "invariant");
5393 assert(nullptr == _inline_layout_info_array, "invariant");
5394
5395 if (_has_localvariable_table) {
5396 ik->set_has_localvariable_table(true);
5397 }
5398
5399 if (_has_final_method) {
5400 ik->set_has_final_method();
5401 }
5402
5403 ik->copy_method_ordering(_method_ordering, CHECK);
5404 // The InstanceKlass::_methods_jmethod_ids cache
5405 // is managed on the assumption that the initial cache
5406 // size is equal to the number of methods in the class. If
5407 // that changes, then InstanceKlass::idnum_can_increment()
5408 // has to be changed accordingly.
5409 ik->set_initial_method_idnum(checked_cast<u2>(ik->methods()->length()));
5410
5411 ik->set_this_class_index(_this_class_index);
5412
5413 if (_is_hidden) {
5414 // _this_class_index is a CONSTANT_Class entry that refers to this
5415 // hidden class itself. If this class needs to refer to its own methods
5416 // or fields, it would use a CONSTANT_MethodRef, etc, which would reference
5417 // _this_class_index. However, because this class is hidden (it's
5418 // not stored in SystemDictionary), _this_class_index cannot be resolved
5419 // with ConstantPool::klass_at_impl, which does a SystemDictionary lookup.
5420 // Therefore, we must eagerly resolve _this_class_index now.
5421 ik->constants()->klass_at_put(_this_class_index, ik);
5422 }
5423
5424 ik->set_minor_version(_minor_version);
5425 ik->set_major_version(_major_version);
5426 ik->set_has_nonstatic_concrete_methods(_has_nonstatic_concrete_methods);
5427 ik->set_declares_nonstatic_concrete_methods(_declares_nonstatic_concrete_methods);
5428
5429 assert(!_is_hidden || ik->is_hidden(), "must be set already");
5430
5431 // Set PackageEntry for this_klass
5432 oop cl = ik->class_loader();
5433 Handle clh = Handle(THREAD, cl);
5434 ClassLoaderData* cld = ClassLoaderData::class_loader_data_or_null(clh());
5435 ik->set_package(cld, nullptr, CHECK);
5436
5437 const Array<Method*>* const methods = ik->methods();
5438 assert(methods != nullptr, "invariant");
5439 const int methods_len = methods->length();
5440
5441 check_methods_for_intrinsics(ik, methods);
5442
5443 // Fill in field values obtained by parse_classfile_attributes
5444 if (_parsed_annotations->has_any_annotations())
5445 _parsed_annotations->apply_to(ik);
5446
5447 apply_parsed_class_attributes(ik);
5448
5449 // Miranda methods
5450 if ((_num_miranda_methods > 0) ||
5451 // if this class introduced new miranda methods or
5452 (_super_klass != nullptr && _super_klass->has_miranda_methods())
5453 // super class exists and this class inherited miranda methods
5454 ) {
5455 ik->set_has_miranda_methods(); // then set a flag
5456 }
5457
5458 // Fill in information needed to compute superclasses.
5459 ik->initialize_supers(const_cast<InstanceKlass*>(_super_klass), _transitive_interfaces, CHECK);
5460 ik->set_transitive_interfaces(_transitive_interfaces);
5461 ik->set_local_interfaces(_local_interfaces);
5462 _transitive_interfaces = nullptr;
5463 _local_interfaces = nullptr;
5464
5465 // Initialize itable offset tables
5466 klassItable::setup_itable_offset_table(ik);
5467
5468 // Compute transitive closure of interfaces this class implements
5469 // Do final class setup
5470 OopMapBlocksBuilder* oop_map_blocks = _layout_info->oop_map_blocks;
5471 if (oop_map_blocks->_nonstatic_oop_map_count > 0) {
5472 oop_map_blocks->copy(ik->start_of_nonstatic_oop_maps());
5473 }
5474
5475 if (_has_contended_fields || _parsed_annotations->is_contended() ||
5476 ( _super_klass != nullptr && _super_klass->has_contended_annotations())) {
5477 ik->set_has_contended_annotations(true);
5478 }
5479
5480 // Fill in has_finalizer and layout_helper
5481 set_precomputed_flags(ik);
5482
5483 // check if this class can access its super class
5484 check_super_class_access(ik, CHECK);
5485
5486 // check if this class can access its superinterfaces
5487 check_super_interface_access(ik, CHECK);
5488
5489 // check if this class overrides any final method
5490 check_final_method_override(ik, CHECK);
5491
5492 // reject static interface methods prior to Java 8
5493 if (ik->is_interface() && _major_version < JAVA_8_VERSION) {
5494 check_illegal_static_method(ik, CHECK);
5495 }
5496
5497 // Obtain this_klass' module entry
5498 ModuleEntry* module_entry = ik->module();
5499 assert(module_entry != nullptr, "module_entry should always be set");
5500
5501 // Obtain java.lang.Module
5502 Handle module_handle(THREAD, module_entry->module_oop());
5503
5504 // Allocate mirror and initialize static fields
5505 java_lang_Class::create_mirror(ik,
5506 Handle(THREAD, _loader_data->class_loader()),
5507 module_handle,
5508 _protection_domain,
5509 cl_inst_info.class_data(),
5510 CHECK);
5511
5512 assert(_all_mirandas != nullptr, "invariant");
5513
5514 // Generate any default methods - default methods are public interface methods
5515 // that have a default implementation. This is new with Java 8.
5516 if (_has_nonstatic_concrete_methods) {
5517 DefaultMethods::generate_default_methods(ik,
5518 _all_mirandas,
5519 CHECK);
5520 }
5521
5522 // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5523 if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5524 !module_entry->has_default_read_edges()) {
5525 if (!module_entry->set_has_default_read_edges()) {
5526 // We won a potential race
5527 JvmtiExport::add_default_read_edges(module_handle, THREAD);
5528 }
5529 }
5530
5531 if (is_inline_type()) {
5532 InlineKlass* vk = InlineKlass::cast(ik);
5533 vk->set_payload_alignment(_layout_info->_payload_alignment);
5534 vk->set_payload_offset(_layout_info->_payload_offset);
5535 vk->set_payload_size_in_bytes(_layout_info->_payload_size_in_bytes);
5536 vk->set_null_free_non_atomic_size_in_bytes(_layout_info->_null_free_non_atomic_size_in_bytes);
5537 vk->set_null_free_non_atomic_alignment(_layout_info->_null_free_non_atomic_alignment);
5538 vk->set_null_free_atomic_size_in_bytes(_layout_info->_null_free_atomic_layout_size_in_bytes);
5539 vk->set_nullable_atomic_size_in_bytes(_layout_info->_nullable_atomic_layout_size_in_bytes);
5540 vk->set_nullable_non_atomic_size_in_bytes(_layout_info->_nullable_non_atomic_layout_size_in_bytes);
5541 vk->set_null_marker_offset(_layout_info->_null_marker_offset);
5542 vk->set_null_reset_value_offset(_layout_info->_null_reset_value_offset);
5543 if (_layout_info->_is_empty_inline_klass) vk->set_is_empty_inline_type();
5544 vk->initialize_calling_convention(CHECK);
5545 }
5546
5547 if (Arguments::is_valhalla_enabled() && !access_flags().is_identity_class() && !access_flags().is_interface()
5548 && _class_name != vmSymbols::java_lang_Object()) {
5549 // Both abstract and concrete value classes need a field map for acmp
5550 ik->set_acmp_maps_offset(_layout_info->_acmp_maps_offset);
5551 // Current format of acmp maps:
5552 // All maps are stored contiguously in a single int array because it might
5553 // be too early to instantiate an Object array (to be investigated)
5554 // Format is:
5555 // [number_of_nonoop_entries][offset0][size[0][offset1][size1]...[oop_offset0][oop_offset1]...
5556 // ^ ^
5557 // | |
5558 // --------------------- Pair of integer describing a segment of
5559 // contiguous non-oop fields
5560 // First element is the number of segment of contiguous non-oop fields
5561 // Then, each segment of contiguous non-oop fields is described by two consecutive elements:
5562 // the offset then the size.
5563 // After the last segment of contiguous non-oop fields, oop fields are described, one element
5564 // per oop field, containing the offset of the field.
5565 int nonoop_acmp_map_size = _layout_info->_nonoop_acmp_map->length() * 2;
5566 int oop_acmp_map_size = _layout_info->_oop_acmp_map->length();
5567 int acmp_map_size = nonoop_acmp_map_size + oop_acmp_map_size + 1;
5568
5569 typeArrayOop map = oopFactory::new_intArray(acmp_map_size, CHECK);
5570 typeArrayHandle map_h(THREAD, map);
5571 Array<int>* acmp_maps_array = MetadataFactory::new_array<int>(loader_data(), acmp_map_size, CHECK);
5572
5573 map_h->int_at_put(0, _layout_info->_nonoop_acmp_map->length());
5574 acmp_maps_array->at_put(0, _layout_info->_nonoop_acmp_map->length());
5575 for (int i = 0; i < _layout_info->_nonoop_acmp_map->length(); i++) {
5576 map_h->int_at_put(i * 2 + 1, _layout_info->_nonoop_acmp_map->at(i).first);
5577 map_h->int_at_put(i * 2 + 2, _layout_info->_nonoop_acmp_map->at(i).second);
5578
5579 // Also store acmp maps as metadata for regeneration when using dynamic archive or AOT training data.
5580 acmp_maps_array->at_put(i * 2 + 1, _layout_info->_nonoop_acmp_map->at(i).first);
5581 acmp_maps_array->at_put(i * 2 + 2, _layout_info->_nonoop_acmp_map->at(i).second);
5582 }
5583 int oop_map_start = nonoop_acmp_map_size + 1;
5584 for (int i = 0; i < _layout_info->_oop_acmp_map->length(); i++) {
5585 map_h->int_at_put(oop_map_start + i, _layout_info->_oop_acmp_map->at(i));
5586 acmp_maps_array->at_put(oop_map_start + i, _layout_info->_oop_acmp_map->at(i));
5587 }
5588 assert(acmp_maps_array->length() == map_h->length(), "sanity");
5589 ik->java_mirror()->obj_field_put(ik->acmp_maps_offset(), map_h());
5590 ik->set_acmp_maps_array(acmp_maps_array);
5591 }
5592
5593 ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5594
5595 if (!is_internal()) {
5596 ik->print_class_load_logging(_loader_data, module_entry, _stream);
5597
5598 if (ik->minor_version() == JAVA_PREVIEW_MINOR_VERSION &&
5599 ik->major_version() == JVM_CLASSFILE_MAJOR_VERSION &&
5600 log_is_enabled(Info, class, preview)) {
5601 ResourceMark rm;
5602 log_info(class, preview)("Loading class %s that depends on preview features (class file version %d.65535)",
5603 ik->external_name(), JVM_CLASSFILE_MAJOR_VERSION);
5604 }
5605
5606 if (log_is_enabled(Debug, class, resolve)) {
5607 ResourceMark rm;
5608 // print out the superclass.
5609 const char * from = ik->external_name();
5610 if (ik->super() != nullptr) {
5611 log_debug(class, resolve)("%s %s (super)",
5612 from,
5613 ik->super()->external_name());
5614 }
5615 // print out each of the interface classes referred to by this class.
5616 const Array<InstanceKlass*>* const local_interfaces = ik->local_interfaces();
5617 if (local_interfaces != nullptr) {
5618 const int length = local_interfaces->length();
5619 for (int i = 0; i < length; i++) {
5620 const InstanceKlass* const k = local_interfaces->at(i);
5621 const char * to = k->external_name();
5622 log_debug(class, resolve)("%s %s (interface)", from, to);
5623 }
5624 }
5625 }
5626 }
5627
5628 // If we reach here, all is well.
5629 // Now remove the InstanceKlass* from the _klass_to_deallocate field
5630 // in order for it to not be destroyed in the ClassFileParser destructor.
5631 set_klass_to_deallocate(nullptr);
5632
5633 // it's official
5634 set_klass(ik);
5635
5636 DEBUG_ONLY(ik->verify();)
5637 }
5638
5639 void ClassFileParser::update_class_name(Symbol* new_class_name) {
5640 // Decrement the refcount in the old name, since we're clobbering it.
5641 _class_name->decrement_refcount();
5642
5643 _class_name = new_class_name;
5644 // Increment the refcount of the new name.
5645 // Now the ClassFileParser owns this name and will decrement in
5646 // the destructor.
5647 _class_name->increment_refcount();
5648 }
5649
5650 ClassFileParser::ClassFileParser(ClassFileStream* stream,
5651 Symbol* name,
5652 ClassLoaderData* loader_data,
5653 const ClassLoadInfo* cl_info,
5654 Publicity pub_level,
5655 TRAPS) :
5656 _stream(stream),
5657 _class_name(nullptr),
5658 _loader_data(loader_data),
5659 _is_hidden(cl_info->is_hidden()),
5660 _can_access_vm_annotations(cl_info->can_access_vm_annotations()),
5661 _orig_cp_size(0),
5662 _static_oop_count(0),
5663 _super_klass(),
5664 _cp(nullptr),
5665 _fieldinfo_stream(nullptr),
5666 _fieldinfo_search_table(nullptr),
5667 _fields_status(nullptr),
5668 _methods(nullptr),
5669 _inner_classes(nullptr),
5670 _nest_members(nullptr),
5671 _nest_host(0),
5672 _permitted_subclasses(nullptr),
5673 _loadable_descriptors(nullptr),
5674 _record_components(nullptr),
5675 _local_interfaces(nullptr),
5676 _local_interface_indexes(nullptr),
5677 _transitive_interfaces(nullptr),
5678 _combined_annotations(nullptr),
5679 _class_annotations(nullptr),
5680 _class_type_annotations(nullptr),
5681 _fields_annotations(nullptr),
5682 _fields_type_annotations(nullptr),
5683 _klass(nullptr),
5684 _klass_to_deallocate(nullptr),
5685 _parsed_annotations(nullptr),
5686 _layout_info(nullptr),
5687 _inline_layout_info_array(nullptr),
5688 _temp_field_info(nullptr),
5689 _method_ordering(nullptr),
5690 _all_mirandas(nullptr),
5691 _vtable_size(0),
5692 _itable_size(0),
5693 _num_miranda_methods(0),
5694 _protection_domain(cl_info->protection_domain()),
5695 _access_flags(),
5696 _pub_level(pub_level),
5697 _bad_constant_seen(0),
5698 _synthetic_flag(false),
5699 _sde_length(false),
5700 _sde_buffer(nullptr),
5701 _sourcefile_index(0),
5702 _generic_signature_index(0),
5703 _major_version(0),
5704 _minor_version(0),
5705 _this_class_index(0),
5706 _super_class_index(0),
5707 _itfs_len(0),
5708 _java_fields_count(0),
5709 _need_verify(false),
5710 _has_nonstatic_concrete_methods(false),
5711 _declares_nonstatic_concrete_methods(false),
5712 _has_localvariable_table(false),
5713 _has_final_method(false),
5714 _has_contended_fields(false),
5715 _has_aot_runtime_setup_method(false),
5716 _has_strict_static_fields(false),
5717 _is_naturally_atomic(false),
5718 _must_be_atomic(true),
5719 _has_loosely_consistent_annotation(false),
5720 _has_finalizer(false),
5721 _has_empty_finalizer(false),
5722 _max_bootstrap_specifier_index(-1) {
5723
5724 _class_name = name != nullptr ? name : vmSymbols::unknown_class_name();
5725 _class_name->increment_refcount();
5726
5727 assert(_loader_data != nullptr, "invariant");
5728 assert(stream != nullptr, "invariant");
5729 assert(_stream != nullptr, "invariant");
5730 assert(_stream->buffer() == _stream->current(), "invariant");
5731 assert(_class_name != nullptr, "invariant");
5732 assert(0 == _access_flags.as_unsigned_short(), "invariant");
5733
5734 // Figure out whether we can skip format checking (matching classic VM behavior)
5735 // Always verify CFLH bytes from the user agents.
5736 _need_verify = stream->from_class_file_load_hook() ? true : Verifier::should_verify_for(_loader_data->class_loader());
5737
5738 // synch back verification state to stream to check for truncation.
5739 stream->set_need_verify(_need_verify);
5740
5741 parse_stream(stream, CHECK);
5742
5743 post_process_parsed_stream(stream, _cp, CHECK);
5744 }
5745
5746 void ClassFileParser::clear_class_metadata() {
5747 // metadata created before the instance klass is created. Must be
5748 // deallocated if classfile parsing returns an error.
5749 _cp = nullptr;
5750 _fieldinfo_stream = nullptr;
5751 _fieldinfo_search_table = nullptr;
5752 _fields_status = nullptr;
5753 _methods = nullptr;
5754 _inner_classes = nullptr;
5755 _nest_members = nullptr;
5756 _permitted_subclasses = nullptr;
5757 _loadable_descriptors = nullptr;
5758 _combined_annotations = nullptr;
5759 _class_annotations = _class_type_annotations = nullptr;
5760 _fields_annotations = _fields_type_annotations = nullptr;
5761 _record_components = nullptr;
5762 _inline_layout_info_array = nullptr;
5763 }
5764
5765 // Destructor to clean up
5766 ClassFileParser::~ClassFileParser() {
5767 _class_name->decrement_refcount();
5768
5769 if (_cp != nullptr) {
5770 MetadataFactory::free_metadata(_loader_data, _cp);
5771 }
5772
5773 if (_fieldinfo_stream != nullptr) {
5774 MetadataFactory::free_array<u1>(_loader_data, _fieldinfo_stream);
5775 }
5776 MetadataFactory::free_array<u1>(_loader_data, _fieldinfo_search_table);
5777
5778 if (_fields_status != nullptr) {
5779 MetadataFactory::free_array<FieldStatus>(_loader_data, _fields_status);
5780 }
5781
5782 if (_inline_layout_info_array != nullptr) {
5783 MetadataFactory::free_array<InlineLayoutInfo>(_loader_data, _inline_layout_info_array);
5784 }
5785
5786 if (_methods != nullptr) {
5787 // Free methods
5788 InstanceKlass::deallocate_methods(_loader_data, _methods);
5789 }
5790
5791 // beware of the Universe::empty_blah_array!!
5792 if (_inner_classes != nullptr && _inner_classes != Universe::the_empty_short_array()) {
5793 MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
5794 }
5795
5796 if (_nest_members != nullptr && _nest_members != Universe::the_empty_short_array()) {
5797 MetadataFactory::free_array<u2>(_loader_data, _nest_members);
5798 }
5799
5800 if (_record_components != nullptr) {
5801 InstanceKlass::deallocate_record_components(_loader_data, _record_components);
5802 }
5803
5804 if (_permitted_subclasses != nullptr && _permitted_subclasses != Universe::the_empty_short_array()) {
5805 MetadataFactory::free_array<u2>(_loader_data, _permitted_subclasses);
5806 }
5807
5808 if (_loadable_descriptors != nullptr && _loadable_descriptors != Universe::the_empty_short_array()) {
5809 MetadataFactory::free_array<u2>(_loader_data, _loadable_descriptors);
5810 }
5811
5812 // Free interfaces
5813 InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
5814 _local_interfaces, _transitive_interfaces);
5815
5816 if (_combined_annotations != nullptr) {
5817 // After all annotations arrays have been created, they are installed into the
5818 // Annotations object that will be assigned to the InstanceKlass being created.
5819
5820 // Deallocate the Annotations object and the installed annotations arrays.
5821 _combined_annotations->deallocate_contents(_loader_data);
5822
5823 // If the _combined_annotations pointer is non-null,
5824 // then the other annotations fields should have been cleared.
5825 assert(_class_annotations == nullptr, "Should have been cleared");
5826 assert(_class_type_annotations == nullptr, "Should have been cleared");
5827 assert(_fields_annotations == nullptr, "Should have been cleared");
5828 assert(_fields_type_annotations == nullptr, "Should have been cleared");
5829 } else {
5830 // If the annotations arrays were not installed into the Annotations object,
5831 // then they have to be deallocated explicitly.
5832 MetadataFactory::free_array<u1>(_loader_data, _class_annotations);
5833 MetadataFactory::free_array<u1>(_loader_data, _class_type_annotations);
5834 Annotations::free_contents(_loader_data, _fields_annotations);
5835 Annotations::free_contents(_loader_data, _fields_type_annotations);
5836 }
5837
5838 clear_class_metadata();
5839 _transitive_interfaces = nullptr;
5840 _local_interfaces = nullptr;
5841
5842 // deallocate the klass if already created. Don't directly deallocate, but add
5843 // to the deallocate list so that the klass is removed from the CLD::_klasses list
5844 // at a safepoint.
5845 if (_klass_to_deallocate != nullptr) {
5846 _loader_data->add_to_deallocate_list(_klass_to_deallocate);
5847 }
5848 }
5849
5850 void ClassFileParser::parse_stream(const ClassFileStream* const stream,
5851 TRAPS) {
5852
5853 assert(stream != nullptr, "invariant");
5854 assert(_class_name != nullptr, "invariant");
5855
5856 // BEGIN STREAM PARSING
5857 stream->guarantee_more(8, CHECK); // magic, major, minor
5858 // Magic value
5859 const u4 magic = stream->get_u4_fast();
5860 guarantee_property(magic == JAVA_CLASSFILE_MAGIC,
5861 "Incompatible magic value %u in class file %s",
5862 magic, CHECK);
5863
5864 // Version numbers
5865 _minor_version = stream->get_u2_fast();
5866 _major_version = stream->get_u2_fast();
5867
5868 // Check version numbers - we check this even with verifier off
5869 verify_class_version(_major_version, _minor_version, _class_name, CHECK);
5870
5871 stream->guarantee_more(3, CHECK); // length, first cp tag
5872 u2 cp_size = stream->get_u2_fast();
5873
5874 guarantee_property(
5875 cp_size >= 1, "Illegal constant pool size %u in class file %s",
5876 cp_size, CHECK);
5877
5878 _orig_cp_size = cp_size;
5879 if (is_hidden()) { // Add a slot for hidden class name.
5880 guarantee_property((u4)cp_size < 0xffff, "Overflow in constant pool size for hidden class %s", CHECK);
5881 cp_size++;
5882 }
5883
5884 _cp = ConstantPool::allocate(_loader_data,
5885 cp_size,
5886 CHECK);
5887
5888 ConstantPool* const cp = _cp;
5889
5890 parse_constant_pool(stream, cp, _orig_cp_size, CHECK);
5891
5892 assert(cp_size == (u2)cp->length(), "invariant");
5893
5894 // ACCESS FLAGS
5895 stream->guarantee_more(8, CHECK); // flags, this_class, super_class, infs_len
5896
5897 // Access flags
5898 u2 flags;
5899 // JVM_ACC_MODULE is defined in JDK-9 and later.
5900 if (_major_version >= JAVA_9_VERSION) {
5901 flags = stream->get_u2_fast() & (JVM_RECOGNIZED_CLASS_MODIFIERS | JVM_ACC_MODULE);
5902 } else {
5903 flags = stream->get_u2_fast() & JVM_RECOGNIZED_CLASS_MODIFIERS;
5904 }
5905
5906 if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
5907 // Set abstract bit for old class files for backward compatibility
5908 flags |= JVM_ACC_ABSTRACT;
5909 }
5910
5911 // Fixing ACC_SUPER/ACC_IDENTITY for old class files
5912 if (!supports_inline_types()) {
5913 const bool is_module = (flags & JVM_ACC_MODULE) != 0;
5914 const bool is_interface = (flags & JVM_ACC_INTERFACE) != 0;
5915 if (!is_module && !is_interface) {
5916 flags |= JVM_ACC_IDENTITY;
5917 }
5918 }
5919
5920 verify_legal_class_modifiers(flags, nullptr, false, CHECK);
5921
5922 short bad_constant = class_bad_constant_seen();
5923 if (bad_constant != 0) {
5924 // Do not throw CFE until after the access_flags are checked because if
5925 // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
5926 classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, THREAD);
5927 return;
5928 }
5929
5930 _access_flags.set_flags(flags);
5931
5932 // This class and superclass
5933 _this_class_index = stream->get_u2_fast();
5934 guarantee_property(
5935 valid_cp_range(_this_class_index, cp_size) &&
5936 cp->tag_at(_this_class_index).is_unresolved_klass(),
5937 "Invalid this class index %u in constant pool in class file %s",
5938 _this_class_index, CHECK);
5939
5940 Symbol* const class_name_in_cp = cp->klass_name_at(_this_class_index);
5941 assert(class_name_in_cp != nullptr, "class_name can't be null");
5942
5943 // Don't need to check whether this class name is legal or not.
5944 // It has been checked when constant pool is parsed.
5945 // However, make sure it is not an array type.
5946 if (_need_verify) {
5947 guarantee_property(class_name_in_cp->char_at(0) != JVM_SIGNATURE_ARRAY,
5948 "Bad class name in class file %s",
5949 CHECK);
5950 }
5951
5952 #ifdef ASSERT
5953 // Basic sanity checks
5954 if (_is_hidden) {
5955 assert(_class_name != vmSymbols::unknown_class_name(), "hidden classes should have a special name");
5956 }
5957 #endif
5958
5959 // Update the _class_name as needed depending on whether this is a named, un-named, or hidden class.
5960
5961 if (_is_hidden) {
5962 assert(_class_name != nullptr, "Unexpected null _class_name");
5963 #ifdef ASSERT
5964 if (_need_verify) {
5965 verify_legal_class_name(_class_name, CHECK);
5966 }
5967 #endif
5968
5969 } else {
5970 // Check if name in class file matches given name
5971 if (_class_name != class_name_in_cp) {
5972 if (_class_name != vmSymbols::unknown_class_name()) {
5973 ResourceMark rm(THREAD);
5974 // Names are all known to be < 64k so we know this formatted message is not excessively large.
5975 Exceptions::fthrow(THREAD_AND_LOCATION,
5976 vmSymbols::java_lang_NoClassDefFoundError(),
5977 "%s (wrong name: %s)",
5978 _class_name->as_C_string(),
5979 class_name_in_cp->as_C_string()
5980 );
5981 return;
5982 } else {
5983 // The class name was not known by the caller so we set it from
5984 // the value in the CP.
5985 update_class_name(class_name_in_cp);
5986 }
5987 // else nothing to do: the expected class name matches what is in the CP
5988 }
5989 }
5990
5991 // Verification prevents us from creating names with dots in them, this
5992 // asserts that that's the case.
5993 assert(is_internal_format(_class_name), "external class name format used internally");
5994
5995 if (!is_internal()) {
5996 LogTarget(Debug, class, preorder) lt;
5997 if (lt.is_enabled()){
5998 ResourceMark rm(THREAD);
5999 LogStream ls(lt);
6000 ls.print("%s", _class_name->as_klass_external_name());
6001 if (stream->source() != nullptr) {
6002 ls.print(" source: %s", stream->source());
6003 }
6004 ls.cr();
6005 }
6006 }
6007
6008 // SUPERKLASS
6009 _super_class_index = stream->get_u2_fast();
6010 check_super_class(cp,
6011 _super_class_index,
6012 _need_verify,
6013 CHECK);
6014
6015 // Interfaces
6016 _itfs_len = stream->get_u2_fast();
6017 parse_interfaces(stream,
6018 _itfs_len,
6019 cp,
6020 &_has_nonstatic_concrete_methods,
6021 CHECK);
6022
6023 // Fields (offsets are filled in later)
6024 parse_fields(stream,
6025 _access_flags,
6026 cp,
6027 cp_size,
6028 &_java_fields_count,
6029 CHECK);
6030
6031 assert(_temp_field_info != nullptr, "invariant");
6032
6033 // Methods
6034 parse_methods(stream,
6035 is_interface(),
6036 !is_identity_class(),
6037 is_abstract_class(),
6038 &_has_localvariable_table,
6039 &_has_final_method,
6040 &_declares_nonstatic_concrete_methods,
6041 CHECK);
6042
6043 assert(_methods != nullptr, "invariant");
6044
6045 if (_declares_nonstatic_concrete_methods) {
6046 _has_nonstatic_concrete_methods = true;
6047 }
6048
6049 // Additional attributes/annotations
6050 _parsed_annotations = new ClassAnnotationCollector();
6051 parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK);
6052
6053 assert(_inner_classes != nullptr, "invariant");
6054
6055 // Finalize the Annotations metadata object,
6056 // now that all annotation arrays have been created.
6057 create_combined_annotations(CHECK);
6058
6059 // Make sure this is the end of class file stream
6060 guarantee_property(stream->at_eos(),
6061 "Extra bytes at the end of class file %s",
6062 CHECK);
6063
6064 // all bytes in stream read and parsed
6065 }
6066
6067 void ClassFileParser::mangle_hidden_class_name(InstanceKlass* const ik) {
6068 ResourceMark rm;
6069 // Construct hidden name from _class_name, "+", and &ik. Note that we can't
6070 // use a '/' because that confuses finding the class's package. Also, can't
6071 // use an illegal char such as ';' because that causes serialization issues
6072 // and issues with hidden classes that create their own hidden classes.
6073 char addr_buf[20];
6074 if (CDSConfig::is_dumping_static_archive()) {
6075 // We want stable names for the archived hidden classes (only for static
6076 // archive for now). Spaces under default_SharedBaseAddress() will be
6077 // occupied by the archive at run time, so we know that no dynamically
6078 // loaded InstanceKlass will be placed under there.
6079 static volatile size_t counter = 0;
6080 AtomicAccess::cmpxchg(&counter, (size_t)0, Arguments::default_SharedBaseAddress()); // initialize it
6081 size_t new_id = AtomicAccess::add(&counter, (size_t)1);
6082 jio_snprintf(addr_buf, 20, "0x%zx", new_id);
6083 } else {
6084 jio_snprintf(addr_buf, 20, INTPTR_FORMAT, p2i(ik));
6085 }
6086 size_t new_name_len = _class_name->utf8_length() + 2 + strlen(addr_buf);
6087 char* new_name = NEW_RESOURCE_ARRAY(char, new_name_len);
6088 jio_snprintf(new_name, new_name_len, "%s+%s",
6089 _class_name->as_C_string(), addr_buf);
6090 update_class_name(SymbolTable::new_symbol(new_name));
6091
6092 // Add a Utf8 entry containing the hidden name.
6093 assert(_class_name != nullptr, "Unexpected null _class_name");
6094 int hidden_index = _orig_cp_size; // this is an extra slot we added
6095 _cp->symbol_at_put(hidden_index, _class_name);
6096
6097 // Update this_class_index's slot in the constant pool with the new Utf8 entry.
6098 // We have to update the resolved_klass_index and the name_index together
6099 // so extract the existing resolved_klass_index first.
6100 CPKlassSlot cp_klass_slot = _cp->klass_slot_at(_this_class_index);
6101 int resolved_klass_index = cp_klass_slot.resolved_klass_index();
6102 _cp->unresolved_klass_at_put(_this_class_index, hidden_index, resolved_klass_index);
6103 assert(_cp->klass_slot_at(_this_class_index).name_index() == _orig_cp_size,
6104 "Bad name_index");
6105 }
6106
6107 void ClassFileParser::post_process_parsed_stream(const ClassFileStream* const stream,
6108 ConstantPool* cp,
6109 TRAPS) {
6110 assert(stream != nullptr, "invariant");
6111 assert(stream->at_eos(), "invariant");
6112 assert(cp != nullptr, "invariant");
6113 assert(_loader_data != nullptr, "invariant");
6114
6115 if (_class_name == vmSymbols::java_lang_Object()) {
6116 precond(_super_class_index == 0);
6117 precond(_super_klass == nullptr);
6118 guarantee_property(_local_interfaces == Universe::the_empty_instance_klass_array(),
6119 "java.lang.Object cannot implement an interface in class file %s",
6120 CHECK);
6121 } else {
6122 // Set _super_klass after class file is parsed and format is checked
6123 assert(_super_class_index > 0, "any class other than Object must have a super class");
6124 Symbol* const super_class_name = cp->klass_name_at(_super_class_index);
6125 if (is_interface()) {
6126 // Before attempting to resolve the superclass, check for class format
6127 // errors not checked yet.
6128 guarantee_property(super_class_name == vmSymbols::java_lang_Object(),
6129 "Interfaces must have java.lang.Object as superclass in class file %s",
6130 CHECK);
6131 }
6132 Handle loader(THREAD, _loader_data->class_loader());
6133 if (loader.is_null() && super_class_name == vmSymbols::java_lang_Object()) {
6134 // fast path to avoid lookup
6135 _super_klass = vmClasses::Object_klass();
6136 } else {
6137 _super_klass = (const InstanceKlass*)
6138 SystemDictionary::resolve_super_or_fail(_class_name,
6139 super_class_name,
6140 loader,
6141 true,
6142 CHECK);
6143 }
6144 }
6145
6146 if (_super_klass != nullptr) {
6147 if (_super_klass->is_interface()) {
6148 classfile_icce_error("class %s has interface %s as super class", _super_klass, THREAD);
6149 return;
6150 }
6151
6152 if (_super_klass->is_final()) {
6153 classfile_icce_error("class %s cannot inherit from final class %s", _super_klass, THREAD);
6154 return;
6155 }
6156
6157 if (Arguments::is_valhalla_enabled()) {
6158 check_identity_and_value_modifiers(this, _super_klass, CHECK);
6159 }
6160
6161 if (_super_klass->has_nonstatic_concrete_methods()) {
6162 _has_nonstatic_concrete_methods = true;
6163 }
6164 }
6165
6166 if (_parsed_annotations->has_annotation(AnnotationCollector::_jdk_internal_LooselyConsistentValue) && _access_flags.is_identity_class()) {
6167 THROW_MSG(vmSymbols::java_lang_ClassFormatError(),
6168 err_msg("class %s cannot have annotation jdk.internal.vm.annotation.LooselyConsistentValue, because it is not a value class",
6169 _class_name->as_klass_external_name()));
6170 }
6171
6172 // Determining if the class allows tearing or not (default is not)
6173 if (Arguments::is_valhalla_enabled() && !_access_flags.is_identity_class()) {
6174 if (_parsed_annotations->has_annotation(ClassAnnotationCollector::_jdk_internal_LooselyConsistentValue)
6175 && (_super_klass == vmClasses::Object_klass() || !_super_klass->must_be_atomic())) {
6176 // Conditions above are not sufficient to determine atomicity requirements,
6177 // the presence of fields with atomic requirements could force the current class to have atomicy requirements too
6178 // Marking as not needing atomicity for now, can be updated when computing the fields layout
6179 // The InstanceKlass must be filled with the value from the FieldLayoutInfo returned by
6180 // the FieldLayoutBuilder, not with this _must_be_atomic field.
6181 _must_be_atomic = false;
6182 }
6183 // Apply VM options override
6184 if (*ForceNonTearable != '\0') {
6185 // Allow a command line switch to force the same atomicity property:
6186 const char* class_name_str = _class_name->as_C_string();
6187 if (StringUtils::class_list_match(ForceNonTearable, class_name_str)) {
6188 _must_be_atomic = true;
6189 }
6190 }
6191 }
6192
6193 int itfs_len = _local_interface_indexes == nullptr ? 0 : _local_interface_indexes->length();
6194 _local_interfaces = MetadataFactory::new_array<InstanceKlass*>(_loader_data, itfs_len, nullptr, CHECK);
6195 if (_local_interface_indexes != nullptr) {
6196 for (int i = 0; i < _local_interface_indexes->length(); i++) {
6197 u2 interface_index = _local_interface_indexes->at(i);
6198 Klass* interf;
6199 if (cp->tag_at(interface_index).is_klass()) {
6200 interf = cp->resolved_klass_at(interface_index);
6201 } else {
6202 Symbol* const unresolved_klass = cp->klass_name_at(interface_index);
6203
6204 // Don't need to check legal name because it's checked when parsing constant pool.
6205 // But need to make sure it's not an array type.
6206 guarantee_property(unresolved_klass->char_at(0) != JVM_SIGNATURE_ARRAY,
6207 "Bad interface name in class file %s", CHECK);
6208
6209 // Call resolve on the interface class name with class circularity checking
6210 interf = SystemDictionary::resolve_super_or_fail(
6211 _class_name,
6212 unresolved_klass,
6213 Handle(THREAD, _loader_data->class_loader()),
6214 false,
6215 CHECK);
6216 }
6217
6218 if (!interf->is_interface()) {
6219 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
6220 err_msg("class %s can not implement %s, because it is not an interface (%s)",
6221 _class_name->as_klass_external_name(),
6222 interf->external_name(),
6223 interf->class_in_module_of_loader()));
6224 }
6225
6226 if (Arguments::is_valhalla_enabled()) {
6227 // Check modifiers and set carries_identity_modifier/carries_value_modifier flags
6228 check_identity_and_value_modifiers(this, InstanceKlass::cast(interf), CHECK);
6229 }
6230
6231 if (InstanceKlass::cast(interf)->has_nonstatic_concrete_methods()) {
6232 _has_nonstatic_concrete_methods = true;
6233 }
6234 _local_interfaces->at_put(i, InstanceKlass::cast(interf));
6235 }
6236 }
6237 assert(_local_interfaces != nullptr, "invariant");
6238
6239 // Compute the transitive list of all unique interfaces implemented by this class
6240 _transitive_interfaces =
6241 compute_transitive_interfaces(_super_klass,
6242 _local_interfaces,
6243 _loader_data,
6244 CHECK);
6245
6246 assert(_transitive_interfaces != nullptr, "invariant");
6247
6248 // sort methods
6249 _method_ordering = sort_methods(_methods);
6250
6251 _all_mirandas = new GrowableArray<Method*>(20);
6252
6253 Handle loader(THREAD, _loader_data->class_loader());
6254 klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
6255 &_num_miranda_methods,
6256 _all_mirandas,
6257 _super_klass,
6258 _methods,
6259 _access_flags,
6260 _major_version,
6261 loader,
6262 _class_name,
6263 _local_interfaces);
6264
6265 // Size of Java itable (in words)
6266 _itable_size = is_interface() ? 0 :
6267 klassItable::compute_itable_size(_transitive_interfaces);
6268
6269 assert(_parsed_annotations != nullptr, "invariant");
6270
6271 if (Arguments::is_valhalla_enabled()) {
6272 for (GrowableArrayIterator<FieldInfo> it = _temp_field_info->begin(); it != _temp_field_info->end(); ++it) {
6273 FieldInfo fieldinfo = *it;
6274 if (fieldinfo.access_flags().is_static()) continue; // Only non-static fields are processed at load time
6275 Symbol* sig = fieldinfo.signature(cp);
6276 if (fieldinfo.field_flags().is_null_free_inline_type()) {
6277 // Pre-load classes of null-free fields that are candidate for flattening
6278 TempNewSymbol s = Signature::strip_envelope(sig);
6279 if (s == _class_name) {
6280 THROW_MSG(vmSymbols::java_lang_ClassCircularityError(),
6281 err_msg("Class %s cannot have a null-free non-static field of its own type", _class_name->as_C_string()));
6282 }
6283 log_info(class, preload)("Preloading of class %s during loading of class %s. "
6284 "Cause: a null-free non-static field is declared with this type",
6285 s->as_C_string(), _class_name->as_C_string());
6286 InstanceKlass* klass = SystemDictionary::resolve_with_circularity_detection(_class_name, s,
6287 Handle(THREAD,
6288 _loader_data->class_loader()),
6289 false, THREAD);
6290 if (HAS_PENDING_EXCEPTION) {
6291 log_info(class, preload)("Preloading of class %s during loading of class %s "
6292 "(cause: null-free non-static field) failed: %s",
6293 s->as_C_string(), _class_name->as_C_string(),
6294 PENDING_EXCEPTION->klass()->name()->as_C_string());
6295 return; // Exception is still pending
6296 }
6297 assert(klass != nullptr, "Sanity check");
6298 InstanceKlass::check_can_be_annotated_with_NullRestricted(klass, _class_name, CHECK);
6299 set_inline_layout_info_klass(fieldinfo.index(), InlineKlass::cast(klass), CHECK);
6300 log_info(class, preload)("Preloading of class %s during loading of class %s "
6301 "(cause: null-free non-static field) succeeded",
6302 s->as_C_string(), _class_name->as_C_string());
6303 } else if (Signature::has_envelope(sig) && PreloadClasses) {
6304 // Preloading classes for nullable fields that are listed in the LoadableDescriptors attribute
6305 // Those classes would be required later for the flattening of nullable inline type fields
6306 TempNewSymbol name = Signature::strip_envelope(sig);
6307 if (name != _class_name && is_class_in_loadable_descriptors_attribute(sig)) {
6308 log_info(class, preload)("Preloading of class %s during loading of class %s. "
6309 "Cause: field type in LoadableDescriptors attribute",
6310 name->as_C_string(), _class_name->as_C_string());
6311 oop loader = loader_data()->class_loader();
6312 InstanceKlass* klass = SystemDictionary::resolve_super_or_fail(_class_name, name,
6313 Handle(THREAD, loader),
6314 false, THREAD);
6315
6316 assert((klass == nullptr) == HAS_PENDING_EXCEPTION, "Must be the same");
6317
6318 if (klass != nullptr) {
6319 if (klass->is_inline_klass()) {
6320 set_inline_layout_info_klass(fieldinfo.index(), InlineKlass::cast(klass), CHECK);
6321 log_info(class, preload)("Preloading of class %s during loading of class %s "
6322 "(cause: field type in LoadableDescriptors attribute) succeeded",
6323 name->as_C_string(), _class_name->as_C_string());
6324 } else {
6325 // Non value class are allowed by the current spec, but it could be an indication of an issue so let's log this
6326 log_info(class, preload)("Preloading of class %s during loading of class %s "
6327 "(cause: field type in LoadableDescriptors attribute) but loaded class is not a value class",
6328 name->as_C_string(), _class_name->as_C_string());
6329 }
6330 } else {
6331 log_info(class, preload)("Preloading of class %s during loading of class %s "
6332 "(cause: field type in LoadableDescriptors attribute) failed : %s",
6333 name->as_C_string(), _class_name->as_C_string(),
6334 PENDING_EXCEPTION->klass()->name()->as_C_string());
6335
6336 // Loads triggered by the LoadableDescriptors attribute are speculative, failures must not
6337 // impact loading of current class.
6338 CLEAR_PENDING_EXCEPTION;
6339 }
6340 } else {
6341 // Just poking the system dictionary to see if the class has already be loaded. Looking for migrated classes
6342 // used when --enable-preview when jdk isn't compiled with --enable-preview so doesn't include LoadableDescriptors.
6343 // This is temporary.
6344 oop loader = loader_data()->class_loader();
6345 InstanceKlass* klass = SystemDictionary::find_instance_klass(THREAD, name, Handle(THREAD, loader));
6346 if (klass != nullptr && klass->is_inline_klass()) {
6347 set_inline_layout_info_klass(fieldinfo.index(), InlineKlass::cast(klass), CHECK);
6348 log_info(class, preload)("Preloading of class %s during loading of class %s "
6349 "(cause: field type not in LoadableDescriptors attribute) succeeded",
6350 name->as_C_string(), _class_name->as_C_string());
6351 }
6352 }
6353 }
6354 }
6355 }
6356
6357 _layout_info = new FieldLayoutInfo();
6358 FieldLayoutBuilder lb(class_name(), loader_data(), super_klass(), _cp, /*_fields*/ _temp_field_info,
6359 _parsed_annotations->is_contended(), is_inline_type(),
6360 access_flags().is_abstract() && !access_flags().is_identity_class() && !access_flags().is_interface(),
6361 _must_be_atomic, _layout_info, _inline_layout_info_array);
6362 lb.build_layout();
6363
6364 // If it turned out that we didn't inline any of the fields, we deallocate
6365 // the array of InlineLayoutInfo since it isn't needed, and so it isn't
6366 // transferred to the allocated InstanceKlass.
6367 if (_inline_layout_info_array != nullptr && !_layout_info->_has_inlined_fields) {
6368 MetadataFactory::free_array<InlineLayoutInfo>(_loader_data, _inline_layout_info_array);
6369 _inline_layout_info_array = nullptr;
6370 }
6371
6372 int injected_fields_count = _temp_field_info->length() - _java_fields_count;
6373 _fieldinfo_stream =
6374 FieldInfoStream::create_FieldInfoStream(_temp_field_info, _java_fields_count,
6375 injected_fields_count, loader_data(), CHECK);
6376 _fieldinfo_search_table = FieldInfoStream::create_search_table(_cp, _fieldinfo_stream, _loader_data, CHECK);
6377 _fields_status =
6378 MetadataFactory::new_array<FieldStatus>(_loader_data, _temp_field_info->length(),
6379 FieldStatus(0), CHECK);
6380
6381 // Strict static fields track initialization status from the beginning of time.
6382 // After this class runs <clinit>, they will be verified as being "not unset".
6383 // See Step 8 of InstanceKlass::initialize_impl.
6384 if (_has_strict_static_fields) {
6385 bool found_one = false;
6386 for (int i = 0; i < _temp_field_info->length(); i++) {
6387 FieldInfo& fi = *_temp_field_info->adr_at(i);
6388 if (fi.access_flags().is_strict() && fi.access_flags().is_static()) {
6389 found_one = true;
6390 if (fi.initializer_index() != 0) {
6391 // skip strict static fields with ConstantValue attributes
6392 } else {
6393 _fields_status->adr_at(fi.index())->update_strict_static_unset(true);
6394 _fields_status->adr_at(fi.index())->update_strict_static_unread(true);
6395 }
6396 }
6397 }
6398 assert(found_one == _has_strict_static_fields,
6399 "correct prediction = %d", (int)_has_strict_static_fields);
6400 }
6401 }
6402
6403 void ClassFileParser::set_klass(InstanceKlass* klass) {
6404
6405 #ifdef ASSERT
6406 if (klass != nullptr) {
6407 assert(nullptr == _klass, "leaking?");
6408 }
6409 #endif
6410
6411 _klass = klass;
6412 }
6413
6414 void ClassFileParser::set_inline_layout_info_klass(int field_index, InlineKlass* ik, TRAPS) {
6415 assert(field_index >= 0 && field_index < java_fields_count(), "IOOB: 0 <= %d < %d", field_index, (int)java_fields_count());
6416
6417 // The array of InlineLayoutInfo is allocated on demand. This way the array is
6418 // never allocated for an InstanceKlass which has no need for this information.
6419 if (_inline_layout_info_array == nullptr) {
6420 _inline_layout_info_array = MetadataFactory::new_array<InlineLayoutInfo>(_loader_data,
6421 java_fields_count(),
6422 CHECK);
6423 }
6424
6425 // Set the Klass for the field's index
6426 _inline_layout_info_array->adr_at(field_index)->set_klass(ik);
6427 }
6428
6429 void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) {
6430
6431 #ifdef ASSERT
6432 if (klass != nullptr) {
6433 assert(nullptr == _klass_to_deallocate, "leaking?");
6434 }
6435 #endif
6436
6437 _klass_to_deallocate = klass;
6438 }
6439
6440 // Caller responsible for ResourceMark
6441 // clone stream with rewound position
6442 const ClassFileStream* ClassFileParser::clone_stream() const {
6443 assert(_stream != nullptr, "invariant");
6444
6445 return _stream->clone();
6446 }
6447
6448 ReferenceType ClassFileParser::super_reference_type() const {
6449 return _super_klass == nullptr ? REF_NONE : _super_klass->reference_type();
6450 }
6451
6452 bool ClassFileParser::is_instance_ref_klass() const {
6453 // Only the subclasses of j.l.r.Reference are InstanceRefKlass.
6454 // j.l.r.Reference itself is InstanceKlass because InstanceRefKlass denotes a
6455 // klass requiring special treatment in ref-processing. The abstract
6456 // j.l.r.Reference cannot be instantiated so doesn't partake in
6457 // ref-processing.
6458 return is_java_lang_ref_Reference_subclass();
6459 }
6460
6461 bool ClassFileParser::is_java_lang_ref_Reference_subclass() const {
6462 if (_super_klass == nullptr) {
6463 return false;
6464 }
6465
6466 if (_super_klass->name() == vmSymbols::java_lang_ref_Reference()) {
6467 // Direct subclass of j.l.r.Reference: Soft|Weak|Final|Phantom
6468 return true;
6469 }
6470
6471 return _super_klass->reference_type() != REF_NONE;
6472 }
6473
6474 // ----------------------------------------------------------------------------
6475 // debugging
6476
6477 #ifdef ASSERT
6478
6479 // return true if class_name contains no '.' (internal format is '/')
6480 bool ClassFileParser::is_internal_format(Symbol* class_name) {
6481 if (class_name != nullptr) {
6482 ResourceMark rm;
6483 char* name = class_name->as_C_string();
6484 return strchr(name, JVM_SIGNATURE_DOT) == nullptr;
6485 } else {
6486 return true;
6487 }
6488 }
6489
6490 #endif