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