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