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_static && is_reference_type(type)) {
1470 _static_oop_count++;
1471 }
1472
1473 FieldInfo fi(access_flags, name_index, signature_index, constantvalue_index, fieldFlags);
1474 fi.set_index(n);
1475 if (fieldFlags.is_generic()) {
1476 fi.set_generic_signature_index(generic_signature_index);
1477 }
1478 parsed_annotations.apply_to(&fi);
1479 if (fi.field_flags().is_contended()) {
1480 _has_contended_fields = true;
1481 }
1482 _temp_field_info->append(fi);
1483 }
1484 assert(_temp_field_info->length() == length, "Must be");
1485
1486 int index = length;
1487 if (num_injected != 0) {
1488 for (int n = 0; n < num_injected; n++) {
1489 // Check for duplicates
1490 if (injected[n].may_be_java) {
1491 const Symbol* const name = injected[n].name();
1492 const Symbol* const signature = injected[n].signature();
1493 bool duplicate = false;
1494 for (int i = 0; i < length; i++) {
1495 const FieldInfo* const f = _temp_field_info->adr_at(i);
1496 if (name == cp->symbol_at(f->name_index()) &&
1497 signature == cp->symbol_at(f->signature_index())) {
1498 // Symbol is desclared in Java so skip this one
1499 duplicate = true;
1500 break;
1501 }
1502 }
1503 if (duplicate) {
1504 // These will be removed from the field array at the end
1505 continue;
1506 }
1507 }
1508
1509 // Injected field
1510 FieldInfo::FieldFlags fflags(0);
1511 fflags.update_injected(true);
1512 AccessFlags aflags;
1513 FieldInfo fi(aflags, (u2)(injected[n].name_index), (u2)(injected[n].signature_index), 0, fflags);
1514 fi.set_index(index);
1515 _temp_field_info->append(fi);
1516 index++;
1517 }
1518 }
1519
1520 assert(_temp_field_info->length() == index, "Must be");
1521
1522 if (_need_verify && length > 1) {
1523 // Check duplicated fields
1524 ResourceMark rm(THREAD);
1525 // Set containing name-signature pairs
1526 NameSigHashtable* names_and_sigs = new NameSigHashtable();
1527 for (int i = 0; i < _temp_field_info->length(); i++) {
1528 NameSigHash name_and_sig(_temp_field_info->adr_at(i)->name(_cp),
1529 _temp_field_info->adr_at(i)->signature(_cp));
1530 // If no duplicates, add name/signature in hashtable names_and_sigs.
1531 if(!names_and_sigs->put(name_and_sig, 0)) {
1532 classfile_parse_error("Duplicate field name \"%s\" with signature \"%s\" in class file %s",
1533 name_and_sig._name->as_C_string(), name_and_sig._sig->as_klass_external_name(), THREAD);
1534 return;
1535 }
1536 }
1537 }
1538 }
1539
1540
1541 const ClassFileParser::unsafe_u2* ClassFileParser::parse_exception_table(const ClassFileStream* const cfs,
1542 u4 code_length,
1543 u4 exception_table_length,
1544 TRAPS) {
1545 assert(cfs != nullptr, "invariant");
1546
1547 const unsafe_u2* const exception_table_start = cfs->current();
1548 assert(exception_table_start != nullptr, "null exception table");
1549
1550 cfs->guarantee_more(8 * exception_table_length, CHECK_NULL); // start_pc,
1551 // end_pc,
1552 // handler_pc,
1553 // catch_type_index
1554
1555 // Will check legal target after parsing code array in verifier.
1556 if (_need_verify) {
1557 for (unsigned int i = 0; i < exception_table_length; i++) {
1558 const u2 start_pc = cfs->get_u2_fast();
1559 const u2 end_pc = cfs->get_u2_fast();
1560 const u2 handler_pc = cfs->get_u2_fast();
1561 const u2 catch_type_index = cfs->get_u2_fast();
1562 guarantee_property((start_pc < end_pc) && (end_pc <= code_length),
1563 "Illegal exception table range in class file %s",
1564 CHECK_NULL);
1565 guarantee_property(handler_pc < code_length,
1566 "Illegal exception table handler in class file %s",
1567 CHECK_NULL);
1568 if (catch_type_index != 0) {
1569 guarantee_property(valid_klass_reference_at(catch_type_index),
1570 "Catch type in exception table has bad constant type in class file %s", CHECK_NULL);
1571 }
1572 }
1573 } else {
1574 cfs->skip_u2_fast(exception_table_length * 4);
1575 }
1576 return exception_table_start;
1577 }
1578
1579 void ClassFileParser::parse_linenumber_table(u4 code_attribute_length,
1580 u4 code_length,
1581 CompressedLineNumberWriteStream**const write_stream,
1582 TRAPS) {
1583
1584 const ClassFileStream* const cfs = _stream;
1585 unsigned int num_entries = cfs->get_u2(CHECK);
1586
1587 // Each entry is a u2 start_pc, and a u2 line_number
1588 const unsigned int length_in_bytes = num_entries * (sizeof(u2) * 2);
1589
1590 // Verify line number attribute and table length
1591 guarantee_property(
1592 code_attribute_length == sizeof(u2) + length_in_bytes,
1593 "LineNumberTable attribute has wrong length in class file %s", CHECK);
1594
1595 cfs->guarantee_more(length_in_bytes, CHECK);
1596
1597 if ((*write_stream) == nullptr) {
1598 if (length_in_bytes > fixed_buffer_size) {
1599 (*write_stream) = new CompressedLineNumberWriteStream(length_in_bytes);
1600 } else {
1601 (*write_stream) = new CompressedLineNumberWriteStream(
1602 _linenumbertable_buffer, fixed_buffer_size);
1603 }
1604 }
1605
1606 while (num_entries-- > 0) {
1607 const u2 bci = cfs->get_u2_fast(); // start_pc
1608 const u2 line = cfs->get_u2_fast(); // line_number
1609 guarantee_property(bci < code_length,
1610 "Invalid pc in LineNumberTable in class file %s", CHECK);
1611 (*write_stream)->write_pair(bci, line);
1612 }
1613 }
1614
1615
1616 class LVT_Hash : public AllStatic {
1617 public:
1618
1619 static bool equals(LocalVariableTableElement const& e0, LocalVariableTableElement const& e1) {
1620 /*
1621 * 3-tuple start_bci/length/slot has to be unique key,
1622 * so the following comparison seems to be redundant:
1623 * && elem->name_cp_index == entry->_elem->name_cp_index
1624 */
1625 return (e0.start_bci == e1.start_bci &&
1626 e0.length == e1.length &&
1627 e0.name_cp_index == e1.name_cp_index &&
1628 e0.slot == e1.slot);
1629 }
1630
1631 static unsigned int hash(LocalVariableTableElement const& e0) {
1632 unsigned int raw_hash = e0.start_bci;
1633
1634 raw_hash = e0.length + raw_hash * 37;
1635 raw_hash = e0.name_cp_index + raw_hash * 37;
1636 raw_hash = e0.slot + raw_hash * 37;
1637
1638 return raw_hash;
1639 }
1640 };
1641
1642
1643 // Class file LocalVariableTable elements.
1644 class Classfile_LVT_Element {
1645 public:
1646 u2 start_bci;
1647 u2 length;
1648 u2 name_cp_index;
1649 u2 descriptor_cp_index;
1650 u2 slot;
1651 };
1652
1653 static void copy_lvt_element(const Classfile_LVT_Element* const src,
1654 LocalVariableTableElement* const lvt) {
1655 lvt->start_bci = Bytes::get_Java_u2((u1*) &src->start_bci);
1656 lvt->length = Bytes::get_Java_u2((u1*) &src->length);
1657 lvt->name_cp_index = Bytes::get_Java_u2((u1*) &src->name_cp_index);
1658 lvt->descriptor_cp_index = Bytes::get_Java_u2((u1*) &src->descriptor_cp_index);
1659 lvt->signature_cp_index = 0;
1660 lvt->slot = Bytes::get_Java_u2((u1*) &src->slot);
1661 }
1662
1663 // Function is used to parse both attributes:
1664 // LocalVariableTable (LVT) and LocalVariableTypeTable (LVTT)
1665 const ClassFileParser::unsafe_u2* ClassFileParser::parse_localvariable_table(const ClassFileStream* cfs,
1666 u4 code_length,
1667 u2 max_locals,
1668 u4 code_attribute_length,
1669 u2* const localvariable_table_length,
1670 bool isLVTT,
1671 TRAPS) {
1672 const char* const tbl_name = (isLVTT) ? "LocalVariableTypeTable" : "LocalVariableTable";
1673 *localvariable_table_length = cfs->get_u2(CHECK_NULL);
1674 const unsigned int size = checked_cast<unsigned>(
1675 (*localvariable_table_length) * sizeof(Classfile_LVT_Element) / sizeof(u2));
1676
1677 const ConstantPool* const cp = _cp;
1678
1679 // Verify local variable table attribute has right length
1680 if (_need_verify) {
1681 guarantee_property(code_attribute_length == (sizeof(*localvariable_table_length) + size * sizeof(u2)),
1682 "%s has wrong length in class file %s", tbl_name, CHECK_NULL);
1683 }
1684
1685 const unsafe_u2* const localvariable_table_start = cfs->current();
1686 assert(localvariable_table_start != nullptr, "null local variable table");
1687 if (!_need_verify) {
1688 cfs->skip_u2_fast(size);
1689 } else {
1690 cfs->guarantee_more(size * 2, CHECK_NULL);
1691 for(int i = 0; i < (*localvariable_table_length); i++) {
1692 const u2 start_pc = cfs->get_u2_fast();
1693 const u2 length = cfs->get_u2_fast();
1694 const u2 name_index = cfs->get_u2_fast();
1695 const u2 descriptor_index = cfs->get_u2_fast();
1696 const u2 index = cfs->get_u2_fast();
1697 // Assign to a u4 to avoid overflow
1698 const u4 end_pc = (u4)start_pc + (u4)length;
1699
1700 if (start_pc >= code_length) {
1701 classfile_parse_error(
1702 "Invalid start_pc %u in %s in class file %s",
1703 start_pc, tbl_name, THREAD);
1704 return nullptr;
1705 }
1706 if (end_pc > code_length) {
1707 classfile_parse_error(
1708 "Invalid length %u in %s in class file %s",
1709 length, tbl_name, THREAD);
1710 return nullptr;
1711 }
1712 const int cp_size = cp->length();
1713 guarantee_property(valid_symbol_at(name_index),
1714 "Name index %u in %s has bad constant type in class file %s",
1715 name_index, tbl_name, CHECK_NULL);
1716 guarantee_property(valid_symbol_at(descriptor_index),
1717 "Signature index %u in %s has bad constant type in class file %s",
1718 descriptor_index, tbl_name, CHECK_NULL);
1719
1720 const Symbol* const name = cp->symbol_at(name_index);
1721 const Symbol* const sig = cp->symbol_at(descriptor_index);
1722 verify_legal_field_name(name, CHECK_NULL);
1723 u2 extra_slot = 0;
1724 if (!isLVTT) {
1725 verify_legal_field_signature(name, sig, CHECK_NULL);
1726
1727 // 4894874: check special cases for double and long local variables
1728 if (sig == vmSymbols::type_signature(T_DOUBLE) ||
1729 sig == vmSymbols::type_signature(T_LONG)) {
1730 extra_slot = 1;
1731 }
1732 }
1733 guarantee_property((index + extra_slot) < max_locals,
1734 "Invalid index %u in %s in class file %s",
1735 index, tbl_name, CHECK_NULL);
1736 }
1737 }
1738 return localvariable_table_start;
1739 }
1740
1741 static const u1* parse_stackmap_table(const ClassFileStream* const cfs,
1742 u4 code_attribute_length,
1743 TRAPS) {
1744 assert(cfs != nullptr, "invariant");
1745
1746 if (0 == code_attribute_length) {
1747 return nullptr;
1748 }
1749
1750 const u1* const stackmap_table_start = cfs->current();
1751 assert(stackmap_table_start != nullptr, "null stackmap table");
1752
1753 // check code_attribute_length
1754 cfs->skip_u1(code_attribute_length, CHECK_NULL);
1755
1756 return stackmap_table_start;
1757 }
1758
1759 const ClassFileParser::unsafe_u2* ClassFileParser::parse_checked_exceptions(const ClassFileStream* const cfs,
1760 u2* const checked_exceptions_length,
1761 u4 method_attribute_length,
1762 TRAPS) {
1763 assert(cfs != nullptr, "invariant");
1764 assert(checked_exceptions_length != nullptr, "invariant");
1765
1766 cfs->guarantee_more(2, CHECK_NULL); // checked_exceptions_length
1767 *checked_exceptions_length = cfs->get_u2_fast();
1768 const unsigned int size =
1769 (*checked_exceptions_length) * sizeof(CheckedExceptionElement) / sizeof(u2);
1770 const unsafe_u2* const checked_exceptions_start = cfs->current();
1771 assert(checked_exceptions_start != nullptr, "null checked exceptions");
1772 if (!_need_verify) {
1773 cfs->skip_u2_fast(size);
1774 } else {
1775 // Verify each value in the checked exception table
1776 u2 checked_exception;
1777 const u2 len = *checked_exceptions_length;
1778 cfs->guarantee_more(2 * len, CHECK_NULL);
1779 for (int i = 0; i < len; i++) {
1780 checked_exception = cfs->get_u2_fast();
1781 guarantee_property(
1782 valid_klass_reference_at(checked_exception),
1783 "Exception name has bad type at constant pool %u in class file %s",
1784 checked_exception, CHECK_NULL);
1785 }
1786 }
1787 // check exceptions attribute length
1788 if (_need_verify) {
1789 guarantee_property(method_attribute_length == (sizeof(*checked_exceptions_length) +
1790 sizeof(u2) * size),
1791 "Exceptions attribute has wrong length in class file %s", CHECK_NULL);
1792 }
1793 return checked_exceptions_start;
1794 }
1795
1796 void ClassFileParser::throwIllegalSignature(const char* type,
1797 const Symbol* name,
1798 const Symbol* sig,
1799 TRAPS) const {
1800 assert(name != nullptr, "invariant");
1801 assert(sig != nullptr, "invariant");
1802
1803 ResourceMark rm(THREAD);
1804 // Names are all known to be < 64k so we know this formatted message is not excessively large.
1805 Exceptions::fthrow(THREAD_AND_LOCATION,
1806 vmSymbols::java_lang_ClassFormatError(),
1807 "%s \"%s\" in class %s has illegal signature \"%s\"", type,
1808 name->as_C_string(), _class_name->as_C_string(), sig->as_C_string());
1809 }
1810
1811 AnnotationCollector::ID
1812 AnnotationCollector::annotation_index(const ClassLoaderData* loader_data,
1813 const Symbol* name,
1814 const bool can_access_vm_annotations) {
1815 const vmSymbolID sid = vmSymbols::find_sid(name);
1816 // Privileged code can use all annotations. Other code silently drops some.
1817 const bool privileged = loader_data->is_boot_class_loader_data() ||
1818 loader_data->is_platform_class_loader_data() ||
1819 can_access_vm_annotations;
1820 switch (sid) {
1821 case VM_SYMBOL_ENUM_NAME(reflect_CallerSensitive_signature): {
1822 if (_location != _in_method) break; // only allow for methods
1823 if (!privileged) break; // only allow in privileged code
1824 return _method_CallerSensitive;
1825 }
1826 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ForceInline_signature): {
1827 if (_location != _in_method) break; // only allow for methods
1828 if (!privileged) break; // only allow in privileged code
1829 return _method_ForceInline;
1830 }
1831 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_DontInline_signature): {
1832 if (_location != _in_method) break; // only allow for methods
1833 if (!privileged) break; // only allow in privileged code
1834 return _method_DontInline;
1835 }
1836 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ChangesCurrentThread_signature): {
1837 if (_location != _in_method) break; // only allow for methods
1838 if (!privileged) break; // only allow in privileged code
1839 return _method_ChangesCurrentThread;
1840 }
1841 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_JvmtiHideEvents_signature): {
1842 if (_location != _in_method) break; // only allow for methods
1843 if (!privileged) break; // only allow in privileged code
1844 return _method_JvmtiHideEvents;
1845 }
1846 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_JvmtiMountTransition_signature): {
1847 if (_location != _in_method) break; // only allow for methods
1848 if (!privileged) break; // only allow in privileged code
1849 return _method_JvmtiMountTransition;
1850 }
1851 case VM_SYMBOL_ENUM_NAME(java_lang_invoke_InjectedProfile_signature): {
1852 if (_location != _in_method) break; // only allow for methods
1853 if (!privileged) break; // only allow in privileged code
1854 return _method_InjectedProfile;
1855 }
1856 case VM_SYMBOL_ENUM_NAME(java_lang_invoke_LambdaForm_Compiled_signature): {
1857 if (_location != _in_method) break; // only allow for methods
1858 if (!privileged) break; // only allow in privileged code
1859 return _method_LambdaForm_Compiled;
1860 }
1861 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Hidden_signature): {
1862 if (_location != _in_method) break; // only allow for methods
1863 if (!privileged) break; // only allow in privileged code
1864 return _method_Hidden;
1865 }
1866 case VM_SYMBOL_ENUM_NAME(jdk_internal_misc_Scoped_signature): {
1867 if (_location != _in_method) break; // only allow for methods
1868 if (!privileged) break; // only allow in privileged code
1869 return _method_Scoped;
1870 }
1871 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_IntrinsicCandidate_signature): {
1872 if (_location != _in_method) break; // only allow for methods
1873 if (!privileged) break; // only allow in privileged code
1874 return _method_IntrinsicCandidate;
1875 }
1876 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Stable_signature): {
1877 if (_location != _in_field) break; // only allow for fields
1878 if (!privileged) break; // only allow in privileged code
1879 return _field_Stable;
1880 }
1881 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Contended_signature): {
1882 if (_location != _in_field && _location != _in_class) {
1883 break; // only allow for fields and classes
1884 }
1885 if (!EnableContended || (RestrictContended && !privileged)) {
1886 break; // honor privileges
1887 }
1888 return _jdk_internal_vm_annotation_Contended;
1889 }
1890 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ReservedStackAccess_signature): {
1891 if (_location != _in_method) break; // only allow for methods
1892 if (RestrictReservedStack && !privileged) break; // honor privileges
1893 return _jdk_internal_vm_annotation_ReservedStackAccess;
1894 }
1895 case VM_SYMBOL_ENUM_NAME(jdk_internal_ValueBased_signature): {
1896 if (_location != _in_class) break; // only allow for classes
1897 if (!privileged) break; // only allow in privileged code
1898 return _jdk_internal_ValueBased;
1899 }
1900 case VM_SYMBOL_ENUM_NAME(java_lang_Deprecated): {
1901 return _java_lang_Deprecated;
1902 }
1903 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_AOTSafeClassInitializer_signature): {
1904 if (_location != _in_class) break; // only allow for classes
1905 if (!privileged) break; // only allow in privileged code
1906 return _jdk_internal_vm_annotation_AOTSafeClassInitializer;
1907 }
1908 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_AOTRuntimeSetup_signature): {
1909 if (_location != _in_method) break; // only allow for methods
1910 if (!privileged) break; // only allow in privileged code
1911 return _method_AOTRuntimeSetup;
1912 }
1913 default: {
1914 break;
1915 }
1916 }
1917 return AnnotationCollector::_unknown;
1918 }
1919
1920 void ClassFileParser::FieldAnnotationCollector::apply_to(FieldInfo* f) {
1921 if (is_contended())
1922 // Setting the contended group also sets the contended bit in field flags
1923 f->set_contended_group(contended_group());
1924 if (is_stable())
1925 (f->field_flags_addr())->update_stable(true);
1926 }
1927
1928 ClassFileParser::FieldAnnotationCollector::~FieldAnnotationCollector() {
1929 // If there's an error deallocate metadata for field annotations
1930 MetadataFactory::free_array<u1>(_loader_data, _field_annotations);
1931 MetadataFactory::free_array<u1>(_loader_data, _field_type_annotations);
1932 }
1933
1934 void MethodAnnotationCollector::apply_to(const methodHandle& m) {
1935 if (has_annotation(_method_CallerSensitive))
1936 m->set_caller_sensitive();
1937 if (has_annotation(_method_ForceInline))
1938 m->set_force_inline();
1939 if (has_annotation(_method_DontInline))
1940 m->set_dont_inline();
1941 if (has_annotation(_method_ChangesCurrentThread))
1942 m->set_changes_current_thread();
1943 if (has_annotation(_method_JvmtiHideEvents))
1944 m->set_jvmti_hide_events();
1945 if (has_annotation(_method_JvmtiMountTransition))
1946 m->set_jvmti_mount_transition();
1947 if (has_annotation(_method_InjectedProfile))
1948 m->set_has_injected_profile();
1949 if (has_annotation(_method_LambdaForm_Compiled) && m->intrinsic_id() == vmIntrinsics::_none)
1950 m->set_intrinsic_id(vmIntrinsics::_compiledLambdaForm);
1951 if (has_annotation(_method_Hidden))
1952 m->set_is_hidden();
1953 if (has_annotation(_method_Scoped))
1954 m->set_scoped();
1955 if (has_annotation(_method_IntrinsicCandidate) && !m->is_synthetic())
1956 m->set_intrinsic_candidate();
1957 if (has_annotation(_jdk_internal_vm_annotation_ReservedStackAccess))
1958 m->set_has_reserved_stack_access();
1959 if (has_annotation(_java_lang_Deprecated))
1960 m->set_deprecated();
1961 if (has_annotation(_java_lang_Deprecated_for_removal))
1962 m->set_deprecated_for_removal();
1963 }
1964
1965 void ClassFileParser::ClassAnnotationCollector::apply_to(InstanceKlass* ik) {
1966 assert(ik != nullptr, "invariant");
1967 if (has_annotation(_jdk_internal_vm_annotation_Contended)) {
1968 ik->set_is_contended(is_contended());
1969 }
1970 if (has_annotation(_jdk_internal_ValueBased)) {
1971 ik->set_has_value_based_class_annotation();
1972 if (DiagnoseSyncOnValueBasedClasses) {
1973 ik->set_is_value_based();
1974 }
1975 }
1976 if (has_annotation(_java_lang_Deprecated)) {
1977 Array<Method*>* methods = ik->methods();
1978 int length = ik->methods()->length();
1979 for (int i = 0; i < length; i++) {
1980 Method* m = methods->at(i);
1981 m->set_deprecated();
1982 }
1983 }
1984 if (has_annotation(_java_lang_Deprecated_for_removal)) {
1985 Array<Method*>* methods = ik->methods();
1986 int length = ik->methods()->length();
1987 for (int i = 0; i < length; i++) {
1988 Method* m = methods->at(i);
1989 m->set_deprecated_for_removal();
1990 }
1991 }
1992 if (has_annotation(_jdk_internal_vm_annotation_AOTSafeClassInitializer)) {
1993 ik->set_has_aot_safe_initializer();
1994 }
1995 }
1996
1997 #define MAX_ARGS_SIZE 255
1998 #define MAX_CODE_SIZE 65535
1999 #define INITIAL_MAX_LVT_NUMBER 256
2000
2001 /* Copy class file LVT's/LVTT's into the HotSpot internal LVT.
2002 *
2003 * Rules for LVT's and LVTT's are:
2004 * - There can be any number of LVT's and LVTT's.
2005 * - If there are n LVT's, it is the same as if there was just
2006 * one LVT containing all the entries from the n LVT's.
2007 * - There may be no more than one LVT entry per local variable.
2008 * Two LVT entries are 'equal' if these fields are the same:
2009 * start_pc, length, name, slot
2010 * - There may be no more than one LVTT entry per each LVT entry.
2011 * Each LVTT entry has to match some LVT entry.
2012 * - HotSpot internal LVT keeps natural ordering of class file LVT entries.
2013 */
2014 void ClassFileParser::copy_localvariable_table(const ConstMethod* cm,
2015 int lvt_cnt,
2016 u2* const localvariable_table_length,
2017 const unsafe_u2** const localvariable_table_start,
2018 int lvtt_cnt,
2019 u2* const localvariable_type_table_length,
2020 const unsafe_u2** const localvariable_type_table_start,
2021 TRAPS) {
2022
2023 ResourceMark rm(THREAD);
2024
2025 typedef HashTable<LocalVariableTableElement, LocalVariableTableElement*,
2026 256, AnyObj::RESOURCE_AREA, mtInternal,
2027 &LVT_Hash::hash, &LVT_Hash::equals> LVT_HashTable;
2028
2029 LVT_HashTable* const table = new LVT_HashTable();
2030
2031 // To fill LocalVariableTable in
2032 const Classfile_LVT_Element* cf_lvt;
2033 LocalVariableTableElement* lvt = cm->localvariable_table_start();
2034
2035 for (int tbl_no = 0; tbl_no < lvt_cnt; tbl_no++) {
2036 cf_lvt = (Classfile_LVT_Element *) localvariable_table_start[tbl_no];
2037 for (int idx = 0; idx < localvariable_table_length[tbl_no]; idx++, lvt++) {
2038 copy_lvt_element(&cf_lvt[idx], lvt);
2039 // If no duplicates, add LVT elem in hashtable.
2040 if (table->put(*lvt, lvt) == false
2041 && _need_verify
2042 && _major_version >= JAVA_1_5_VERSION) {
2043 classfile_parse_error("Duplicated LocalVariableTable attribute "
2044 "entry for '%s' in class file %s",
2045 _cp->symbol_at(lvt->name_cp_index)->as_utf8(),
2046 THREAD);
2047 return;
2048 }
2049 }
2050 }
2051
2052 // To merge LocalVariableTable and LocalVariableTypeTable
2053 const Classfile_LVT_Element* cf_lvtt;
2054 LocalVariableTableElement lvtt_elem;
2055
2056 for (int tbl_no = 0; tbl_no < lvtt_cnt; tbl_no++) {
2057 cf_lvtt = (Classfile_LVT_Element *) localvariable_type_table_start[tbl_no];
2058 for (int idx = 0; idx < localvariable_type_table_length[tbl_no]; idx++) {
2059 copy_lvt_element(&cf_lvtt[idx], &lvtt_elem);
2060 LocalVariableTableElement** entry = table->get(lvtt_elem);
2061 if (entry == nullptr) {
2062 if (_need_verify) {
2063 classfile_parse_error("LVTT entry for '%s' in class file %s "
2064 "does not match any LVT entry",
2065 _cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(),
2066 THREAD);
2067 return;
2068 }
2069 } else if ((*entry)->signature_cp_index != 0 && _need_verify) {
2070 classfile_parse_error("Duplicated LocalVariableTypeTable attribute "
2071 "entry for '%s' in class file %s",
2072 _cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(),
2073 THREAD);
2074 return;
2075 } else {
2076 // to add generic signatures into LocalVariableTable
2077 (*entry)->signature_cp_index = lvtt_elem.descriptor_cp_index;
2078 }
2079 }
2080 }
2081 }
2082
2083
2084 void ClassFileParser::copy_method_annotations(ConstMethod* cm,
2085 const u1* runtime_visible_annotations,
2086 int runtime_visible_annotations_length,
2087 const u1* runtime_visible_parameter_annotations,
2088 int runtime_visible_parameter_annotations_length,
2089 const u1* runtime_visible_type_annotations,
2090 int runtime_visible_type_annotations_length,
2091 const u1* annotation_default,
2092 int annotation_default_length,
2093 TRAPS) {
2094
2095 AnnotationArray* a;
2096
2097 if (runtime_visible_annotations_length > 0) {
2098 a = allocate_annotations(runtime_visible_annotations,
2099 runtime_visible_annotations_length,
2100 CHECK);
2101 cm->set_method_annotations(a);
2102 }
2103
2104 if (runtime_visible_parameter_annotations_length > 0) {
2105 a = allocate_annotations(runtime_visible_parameter_annotations,
2106 runtime_visible_parameter_annotations_length,
2107 CHECK);
2108 cm->set_parameter_annotations(a);
2109 }
2110
2111 if (annotation_default_length > 0) {
2112 a = allocate_annotations(annotation_default,
2113 annotation_default_length,
2114 CHECK);
2115 cm->set_default_annotations(a);
2116 }
2117
2118 if (runtime_visible_type_annotations_length > 0) {
2119 a = allocate_annotations(runtime_visible_type_annotations,
2120 runtime_visible_type_annotations_length,
2121 CHECK);
2122 cm->set_type_annotations(a);
2123 }
2124 }
2125
2126
2127 // Note: the parse_method below is big and clunky because all parsing of the code and exceptions
2128 // attribute is inlined. This is cumbersome to avoid since we inline most of the parts in the
2129 // Method* to save footprint, so we only know the size of the resulting Method* when the
2130 // entire method attribute is parsed.
2131 //
2132 // The has_localvariable_table parameter is used to pass up the value to InstanceKlass.
2133
2134 Method* ClassFileParser::parse_method(const ClassFileStream* const cfs,
2135 bool is_interface,
2136 const ConstantPool* cp,
2137 bool* const has_localvariable_table,
2138 TRAPS) {
2139 assert(cfs != nullptr, "invariant");
2140 assert(cp != nullptr, "invariant");
2141 assert(has_localvariable_table != nullptr, "invariant");
2142
2143 ResourceMark rm(THREAD);
2144 // Parse fixed parts:
2145 // access_flags, name_index, descriptor_index, attributes_count
2146 cfs->guarantee_more(8, CHECK_NULL);
2147
2148 u2 flags = cfs->get_u2_fast();
2149 const u2 name_index = cfs->get_u2_fast();
2150 const int cp_size = cp->length();
2151 guarantee_property(
2152 valid_symbol_at(name_index),
2153 "Illegal constant pool index %u for method name in class file %s",
2154 name_index, CHECK_NULL);
2155 const Symbol* const name = cp->symbol_at(name_index);
2156 verify_legal_method_name(name, CHECK_NULL);
2157
2158 const u2 signature_index = cfs->get_u2_fast();
2159 guarantee_property(
2160 valid_symbol_at(signature_index),
2161 "Illegal constant pool index %u for method signature in class file %s",
2162 signature_index, CHECK_NULL);
2163 const Symbol* const signature = cp->symbol_at(signature_index);
2164
2165 if (name == vmSymbols::class_initializer_name()) {
2166 // We ignore the other access flags for a valid class initializer.
2167 // (JVM Spec 2nd ed., chapter 4.6)
2168 if (_major_version < 51) { // backward compatibility
2169 flags = JVM_ACC_STATIC;
2170 } else if ((flags & JVM_ACC_STATIC) == JVM_ACC_STATIC) {
2171 flags &= JVM_ACC_STATIC | (_major_version <= JAVA_16_VERSION ? JVM_ACC_STRICT : 0);
2172 } else {
2173 classfile_parse_error("Method <clinit> is not static in class file %s", THREAD);
2174 return nullptr;
2175 }
2176 } else {
2177 verify_legal_method_modifiers(flags, is_interface, name, CHECK_NULL);
2178 }
2179
2180 if (name == vmSymbols::object_initializer_name() && is_interface) {
2181 classfile_parse_error("Interface cannot have a method named <init>, class file %s", THREAD);
2182 return nullptr;
2183 }
2184
2185 int args_size = -1; // only used when _need_verify is true
2186 if (_need_verify) {
2187 verify_legal_name_with_signature(name, signature, CHECK_NULL);
2188 args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) +
2189 verify_legal_method_signature(name, signature, CHECK_NULL);
2190 if (args_size > MAX_ARGS_SIZE) {
2191 classfile_parse_error("Too many arguments in method signature in class file %s", THREAD);
2192 return nullptr;
2193 }
2194 }
2195
2196 AccessFlags access_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS);
2197
2198 // Default values for code and exceptions attribute elements
2199 u2 max_stack = 0;
2200 u2 max_locals = 0;
2201 u4 code_length = 0;
2202 const u1* code_start = nullptr;
2203 u2 exception_table_length = 0;
2204 const unsafe_u2* exception_table_start = nullptr; // (potentially unaligned) pointer to array of u2 elements
2205 Array<int>* exception_handlers = Universe::the_empty_int_array();
2206 u2 checked_exceptions_length = 0;
2207 const unsafe_u2* checked_exceptions_start = nullptr; // (potentially unaligned) pointer to array of u2 elements
2208 CompressedLineNumberWriteStream* linenumber_table = nullptr;
2209 int linenumber_table_length = 0;
2210 int total_lvt_length = 0;
2211 u2 lvt_cnt = 0;
2212 u2 lvtt_cnt = 0;
2213 bool lvt_allocated = false;
2214 u2 max_lvt_cnt = INITIAL_MAX_LVT_NUMBER;
2215 u2 max_lvtt_cnt = INITIAL_MAX_LVT_NUMBER;
2216 u2* localvariable_table_length = nullptr;
2217 const unsafe_u2** localvariable_table_start = nullptr; // (potentially unaligned) pointer to array of LVT attributes
2218 u2* localvariable_type_table_length = nullptr;
2219 const unsafe_u2** localvariable_type_table_start = nullptr; // (potentially unaligned) pointer to LVTT attributes
2220 int method_parameters_length = -1;
2221 const u1* method_parameters_data = nullptr;
2222 bool method_parameters_seen = false;
2223 bool parsed_code_attribute = false;
2224 bool parsed_checked_exceptions_attribute = false;
2225 bool parsed_stackmap_attribute = false;
2226 // stackmap attribute - JDK1.5
2227 const u1* stackmap_data = nullptr;
2228 int stackmap_data_length = 0;
2229 u2 generic_signature_index = 0;
2230 MethodAnnotationCollector parsed_annotations;
2231 const u1* runtime_visible_annotations = nullptr;
2232 int runtime_visible_annotations_length = 0;
2233 const u1* runtime_visible_parameter_annotations = nullptr;
2234 int runtime_visible_parameter_annotations_length = 0;
2235 const u1* runtime_visible_type_annotations = nullptr;
2236 int runtime_visible_type_annotations_length = 0;
2237 bool runtime_invisible_annotations_exists = false;
2238 bool runtime_invisible_type_annotations_exists = false;
2239 bool runtime_invisible_parameter_annotations_exists = false;
2240 const u1* annotation_default = nullptr;
2241 int annotation_default_length = 0;
2242
2243 // Parse code and exceptions attribute
2244 u2 method_attributes_count = cfs->get_u2_fast();
2245 while (method_attributes_count--) {
2246 cfs->guarantee_more(6, CHECK_NULL); // method_attribute_name_index, method_attribute_length
2247 const u2 method_attribute_name_index = cfs->get_u2_fast();
2248 const u4 method_attribute_length = cfs->get_u4_fast();
2249 guarantee_property(
2250 valid_symbol_at(method_attribute_name_index),
2251 "Invalid method attribute name index %u in class file %s",
2252 method_attribute_name_index, CHECK_NULL);
2253
2254 const Symbol* const method_attribute_name = cp->symbol_at(method_attribute_name_index);
2255 if (method_attribute_name == vmSymbols::tag_code()) {
2256 // Parse Code attribute
2257 if (_need_verify) {
2258 guarantee_property(
2259 !access_flags.is_native() && !access_flags.is_abstract(),
2260 "Code attribute in native or abstract methods in class file %s",
2261 CHECK_NULL);
2262 }
2263 if (parsed_code_attribute) {
2264 classfile_parse_error("Multiple Code attributes in class file %s",
2265 THREAD);
2266 return nullptr;
2267 }
2268 parsed_code_attribute = true;
2269
2270 // Stack size, locals size, and code size
2271 cfs->guarantee_more(8, CHECK_NULL);
2272 max_stack = cfs->get_u2_fast();
2273 max_locals = cfs->get_u2_fast();
2274 code_length = cfs->get_u4_fast();
2275 if (_need_verify) {
2276 guarantee_property(args_size <= max_locals,
2277 "Arguments can't fit into locals in class file %s",
2278 CHECK_NULL);
2279 guarantee_property(code_length > 0 && code_length <= MAX_CODE_SIZE,
2280 "Invalid method Code length %u in class file %s",
2281 code_length, CHECK_NULL);
2282 }
2283 // Code pointer
2284 code_start = cfs->current();
2285 assert(code_start != nullptr, "null code start");
2286 cfs->guarantee_more(code_length, CHECK_NULL);
2287 cfs->skip_u1_fast(code_length);
2288
2289 // Exception handler table
2290 cfs->guarantee_more(2, CHECK_NULL); // exception_table_length
2291 exception_table_length = cfs->get_u2_fast();
2292 if (exception_table_length > 0) {
2293 exception_table_start = parse_exception_table(cfs,
2294 code_length,
2295 exception_table_length,
2296 CHECK_NULL);
2297 }
2298
2299 // Parse additional attributes in code attribute
2300 cfs->guarantee_more(2, CHECK_NULL); // code_attributes_count
2301 u2 code_attributes_count = cfs->get_u2_fast();
2302
2303 unsigned int calculated_attribute_length = 0;
2304
2305 calculated_attribute_length =
2306 sizeof(max_stack) + sizeof(max_locals) + sizeof(code_length);
2307 calculated_attribute_length += checked_cast<unsigned int>(
2308 code_length +
2309 sizeof(exception_table_length) +
2310 sizeof(code_attributes_count) +
2311 exception_table_length *
2312 ( sizeof(u2) + // start_pc
2313 sizeof(u2) + // end_pc
2314 sizeof(u2) + // handler_pc
2315 sizeof(u2) )); // catch_type_index
2316
2317 while (code_attributes_count--) {
2318 cfs->guarantee_more(6, CHECK_NULL); // code_attribute_name_index, code_attribute_length
2319 const u2 code_attribute_name_index = cfs->get_u2_fast();
2320 const u4 code_attribute_length = cfs->get_u4_fast();
2321 calculated_attribute_length += code_attribute_length +
2322 (unsigned)sizeof(code_attribute_name_index) +
2323 (unsigned)sizeof(code_attribute_length);
2324 guarantee_property(valid_symbol_at(code_attribute_name_index),
2325 "Invalid code attribute name index %u in class file %s",
2326 code_attribute_name_index,
2327 CHECK_NULL);
2328 if (LoadLineNumberTables &&
2329 cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_line_number_table()) {
2330 // Parse and compress line number table
2331 parse_linenumber_table(code_attribute_length,
2332 code_length,
2333 &linenumber_table,
2334 CHECK_NULL);
2335
2336 } else if (LoadLocalVariableTables &&
2337 cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_table()) {
2338 // Parse local variable table
2339 if (!lvt_allocated) {
2340 localvariable_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2341 THREAD, u2, INITIAL_MAX_LVT_NUMBER);
2342 localvariable_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2343 THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER);
2344 localvariable_type_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2345 THREAD, u2, INITIAL_MAX_LVT_NUMBER);
2346 localvariable_type_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2347 THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER);
2348 lvt_allocated = true;
2349 }
2350 if (lvt_cnt == max_lvt_cnt) {
2351 max_lvt_cnt <<= 1;
2352 localvariable_table_length = REALLOC_RESOURCE_ARRAY(u2, localvariable_table_length, lvt_cnt, max_lvt_cnt);
2353 localvariable_table_start = REALLOC_RESOURCE_ARRAY(const unsafe_u2*, localvariable_table_start, lvt_cnt, max_lvt_cnt);
2354 }
2355 localvariable_table_start[lvt_cnt] =
2356 parse_localvariable_table(cfs,
2357 code_length,
2358 max_locals,
2359 code_attribute_length,
2360 &localvariable_table_length[lvt_cnt],
2361 false, // is not LVTT
2362 CHECK_NULL);
2363 total_lvt_length += localvariable_table_length[lvt_cnt];
2364 lvt_cnt++;
2365 } else if (LoadLocalVariableTypeTables &&
2366 _major_version >= JAVA_1_5_VERSION &&
2367 cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_type_table()) {
2368 if (!lvt_allocated) {
2369 localvariable_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2370 THREAD, u2, INITIAL_MAX_LVT_NUMBER);
2371 localvariable_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2372 THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER);
2373 localvariable_type_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2374 THREAD, u2, INITIAL_MAX_LVT_NUMBER);
2375 localvariable_type_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2376 THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER);
2377 lvt_allocated = true;
2378 }
2379 // Parse local variable type table
2380 if (lvtt_cnt == max_lvtt_cnt) {
2381 max_lvtt_cnt <<= 1;
2382 localvariable_type_table_length = REALLOC_RESOURCE_ARRAY(u2, localvariable_type_table_length, lvtt_cnt, max_lvtt_cnt);
2383 localvariable_type_table_start = REALLOC_RESOURCE_ARRAY(const unsafe_u2*, localvariable_type_table_start, lvtt_cnt, max_lvtt_cnt);
2384 }
2385 localvariable_type_table_start[lvtt_cnt] =
2386 parse_localvariable_table(cfs,
2387 code_length,
2388 max_locals,
2389 code_attribute_length,
2390 &localvariable_type_table_length[lvtt_cnt],
2391 true, // is LVTT
2392 CHECK_NULL);
2393 lvtt_cnt++;
2394 } else if (_major_version >= Verifier::STACKMAP_ATTRIBUTE_MAJOR_VERSION &&
2395 cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_stack_map_table()) {
2396 // Stack map is only needed by the new verifier in JDK1.5.
2397 if (parsed_stackmap_attribute) {
2398 classfile_parse_error("Multiple StackMapTable attributes in class file %s", THREAD);
2399 return nullptr;
2400 }
2401 stackmap_data = parse_stackmap_table(cfs, code_attribute_length, CHECK_NULL);
2402 stackmap_data_length = code_attribute_length;
2403 parsed_stackmap_attribute = true;
2404 } else {
2405 // Skip unknown attributes
2406 cfs->skip_u1(code_attribute_length, CHECK_NULL);
2407 }
2408 }
2409 // check method attribute length
2410 if (_need_verify) {
2411 guarantee_property(method_attribute_length == calculated_attribute_length,
2412 "Code segment has wrong length in class file %s",
2413 CHECK_NULL);
2414 }
2415 } else if (method_attribute_name == vmSymbols::tag_exceptions()) {
2416 // Parse Exceptions attribute
2417 if (parsed_checked_exceptions_attribute) {
2418 classfile_parse_error("Multiple Exceptions attributes in class file %s",
2419 THREAD);
2420 return nullptr;
2421 }
2422 parsed_checked_exceptions_attribute = true;
2423 checked_exceptions_start =
2424 parse_checked_exceptions(cfs,
2425 &checked_exceptions_length,
2426 method_attribute_length,
2427 CHECK_NULL);
2428 } else if (method_attribute_name == vmSymbols::tag_method_parameters()) {
2429 // reject multiple method parameters
2430 if (method_parameters_seen) {
2431 classfile_parse_error("Multiple MethodParameters attributes in class file %s",
2432 THREAD);
2433 return nullptr;
2434 }
2435 method_parameters_seen = true;
2436 method_parameters_length = cfs->get_u1_fast();
2437 const u4 real_length = (method_parameters_length * 4u) + 1u;
2438 if (method_attribute_length != real_length) {
2439 classfile_parse_error(
2440 "Invalid MethodParameters method attribute length %u in class file",
2441 method_attribute_length, THREAD);
2442 return nullptr;
2443 }
2444 method_parameters_data = cfs->current();
2445 cfs->skip_u2_fast(method_parameters_length);
2446 cfs->skip_u2_fast(method_parameters_length);
2447 // ignore this attribute if it cannot be reflected
2448 if (!vmClasses::reflect_Parameter_klass_is_loaded())
2449 method_parameters_length = -1;
2450 } else if (method_attribute_name == vmSymbols::tag_synthetic()) {
2451 if (method_attribute_length != 0) {
2452 classfile_parse_error(
2453 "Invalid Synthetic method attribute length %u in class file %s",
2454 method_attribute_length, THREAD);
2455 return nullptr;
2456 }
2457 // Should we check that there hasn't already been a synthetic attribute?
2458 access_flags.set_is_synthetic();
2459 } else if (method_attribute_name == vmSymbols::tag_deprecated()) { // 4276120
2460 if (method_attribute_length != 0) {
2461 classfile_parse_error(
2462 "Invalid Deprecated method attribute length %u in class file %s",
2463 method_attribute_length, THREAD);
2464 return nullptr;
2465 }
2466 } else if (_major_version >= JAVA_1_5_VERSION) {
2467 if (method_attribute_name == vmSymbols::tag_signature()) {
2468 if (generic_signature_index != 0) {
2469 classfile_parse_error(
2470 "Multiple Signature attributes for method in class file %s",
2471 THREAD);
2472 return nullptr;
2473 }
2474 if (method_attribute_length != 2) {
2475 classfile_parse_error(
2476 "Invalid Signature attribute length %u in class file %s",
2477 method_attribute_length, THREAD);
2478 return nullptr;
2479 }
2480 generic_signature_index = parse_generic_signature_attribute(cfs, CHECK_NULL);
2481 } else if (method_attribute_name == vmSymbols::tag_runtime_visible_annotations()) {
2482 if (runtime_visible_annotations != nullptr) {
2483 classfile_parse_error(
2484 "Multiple RuntimeVisibleAnnotations attributes for method in class file %s",
2485 THREAD);
2486 return nullptr;
2487 }
2488 runtime_visible_annotations_length = method_attribute_length;
2489 runtime_visible_annotations = cfs->current();
2490 assert(runtime_visible_annotations != nullptr, "null visible annotations");
2491 cfs->guarantee_more(runtime_visible_annotations_length, CHECK_NULL);
2492 parse_annotations(cp,
2493 runtime_visible_annotations,
2494 runtime_visible_annotations_length,
2495 &parsed_annotations,
2496 _loader_data,
2497 _can_access_vm_annotations);
2498 cfs->skip_u1_fast(runtime_visible_annotations_length);
2499 } else if (method_attribute_name == vmSymbols::tag_runtime_invisible_annotations()) {
2500 if (runtime_invisible_annotations_exists) {
2501 classfile_parse_error(
2502 "Multiple RuntimeInvisibleAnnotations attributes for method in class file %s",
2503 THREAD);
2504 return nullptr;
2505 }
2506 runtime_invisible_annotations_exists = true;
2507 cfs->skip_u1(method_attribute_length, CHECK_NULL);
2508 } else if (method_attribute_name == vmSymbols::tag_runtime_visible_parameter_annotations()) {
2509 if (runtime_visible_parameter_annotations != nullptr) {
2510 classfile_parse_error(
2511 "Multiple RuntimeVisibleParameterAnnotations attributes for method in class file %s",
2512 THREAD);
2513 return nullptr;
2514 }
2515 runtime_visible_parameter_annotations_length = method_attribute_length;
2516 runtime_visible_parameter_annotations = cfs->current();
2517 assert(runtime_visible_parameter_annotations != nullptr, "null visible parameter annotations");
2518 cfs->skip_u1(runtime_visible_parameter_annotations_length, CHECK_NULL);
2519 } else if (method_attribute_name == vmSymbols::tag_runtime_invisible_parameter_annotations()) {
2520 if (runtime_invisible_parameter_annotations_exists) {
2521 classfile_parse_error(
2522 "Multiple RuntimeInvisibleParameterAnnotations attributes for method in class file %s",
2523 THREAD);
2524 return nullptr;
2525 }
2526 runtime_invisible_parameter_annotations_exists = true;
2527 cfs->skip_u1(method_attribute_length, CHECK_NULL);
2528 } else if (method_attribute_name == vmSymbols::tag_annotation_default()) {
2529 if (annotation_default != nullptr) {
2530 classfile_parse_error(
2531 "Multiple AnnotationDefault attributes for method in class file %s",
2532 THREAD);
2533 return nullptr;
2534 }
2535 annotation_default_length = method_attribute_length;
2536 annotation_default = cfs->current();
2537 assert(annotation_default != nullptr, "null annotation default");
2538 cfs->skip_u1(annotation_default_length, CHECK_NULL);
2539 } else if (method_attribute_name == vmSymbols::tag_runtime_visible_type_annotations()) {
2540 if (runtime_visible_type_annotations != nullptr) {
2541 classfile_parse_error(
2542 "Multiple RuntimeVisibleTypeAnnotations attributes for method in class file %s",
2543 THREAD);
2544 return nullptr;
2545 }
2546 runtime_visible_type_annotations_length = method_attribute_length;
2547 runtime_visible_type_annotations = cfs->current();
2548 assert(runtime_visible_type_annotations != nullptr, "null visible type annotations");
2549 // No need for the VM to parse Type annotations
2550 cfs->skip_u1(runtime_visible_type_annotations_length, CHECK_NULL);
2551 } else if (method_attribute_name == vmSymbols::tag_runtime_invisible_type_annotations()) {
2552 if (runtime_invisible_type_annotations_exists) {
2553 classfile_parse_error(
2554 "Multiple RuntimeInvisibleTypeAnnotations attributes for method in class file %s",
2555 THREAD);
2556 return nullptr;
2557 }
2558 runtime_invisible_type_annotations_exists = true;
2559 cfs->skip_u1(method_attribute_length, CHECK_NULL);
2560 } else {
2561 // Skip unknown attributes
2562 cfs->skip_u1(method_attribute_length, CHECK_NULL);
2563 }
2564 } else {
2565 // Skip unknown attributes
2566 cfs->skip_u1(method_attribute_length, CHECK_NULL);
2567 }
2568 }
2569
2570 if (linenumber_table != nullptr) {
2571 linenumber_table->write_terminator();
2572 linenumber_table_length = linenumber_table->position();
2573 }
2574
2575 // Make sure there's at least one Code attribute in non-native/non-abstract method
2576 if (_need_verify) {
2577 guarantee_property(access_flags.is_native() ||
2578 access_flags.is_abstract() ||
2579 parsed_code_attribute,
2580 "Absent Code attribute in method that is not native or abstract in class file %s",
2581 CHECK_NULL);
2582 }
2583
2584 // All sizing information for a Method* is finally available, now create it
2585 InlineTableSizes sizes(
2586 total_lvt_length,
2587 linenumber_table_length,
2588 exception_table_length,
2589 checked_exceptions_length,
2590 method_parameters_length,
2591 generic_signature_index,
2592 runtime_visible_annotations_length,
2593 runtime_visible_parameter_annotations_length,
2594 runtime_visible_type_annotations_length,
2595 annotation_default_length,
2596 0);
2597
2598 Method* const m = Method::allocate(_loader_data,
2599 code_length,
2600 access_flags,
2601 &sizes,
2602 ConstMethod::NORMAL,
2603 _cp->symbol_at(name_index),
2604 CHECK_NULL);
2605
2606 ClassLoadingService::add_class_method_size(m->size()*wordSize);
2607
2608 // Fill in information from fixed part (access_flags already set)
2609 m->set_constants(_cp);
2610 m->set_name_index(name_index);
2611 m->set_signature_index(signature_index);
2612 m->constMethod()->compute_from_signature(cp->symbol_at(signature_index), access_flags.is_static());
2613 assert(args_size < 0 || args_size == m->size_of_parameters(), "");
2614
2615 // Fill in code attribute information
2616 m->set_max_stack(max_stack);
2617 m->set_max_locals(max_locals);
2618 if (stackmap_data != nullptr) {
2619 m->constMethod()->copy_stackmap_data(_loader_data,
2620 (u1*)stackmap_data,
2621 stackmap_data_length,
2622 CHECK_NULL);
2623 }
2624
2625 // Copy byte codes
2626 m->set_code((u1*)code_start);
2627
2628 // Copy line number table
2629 if (linenumber_table != nullptr) {
2630 memcpy(m->compressed_linenumber_table(),
2631 linenumber_table->buffer(),
2632 linenumber_table_length);
2633 }
2634
2635 // Copy exception table
2636 if (exception_table_length > 0) {
2637 Copy::conjoint_swap_if_needed<Endian::JAVA>(exception_table_start,
2638 m->exception_table_start(),
2639 exception_table_length * sizeof(ExceptionTableElement),
2640 sizeof(u2));
2641 }
2642
2643 // Copy method parameters
2644 if (method_parameters_length > 0) {
2645 MethodParametersElement* elem = m->constMethod()->method_parameters_start();
2646 for (int i = 0; i < method_parameters_length; i++) {
2647 elem[i].name_cp_index = Bytes::get_Java_u2((address)method_parameters_data);
2648 method_parameters_data += 2;
2649 elem[i].flags = Bytes::get_Java_u2((address)method_parameters_data);
2650 method_parameters_data += 2;
2651 }
2652 }
2653
2654 // Copy checked exceptions
2655 if (checked_exceptions_length > 0) {
2656 Copy::conjoint_swap_if_needed<Endian::JAVA>(checked_exceptions_start,
2657 m->checked_exceptions_start(),
2658 checked_exceptions_length * sizeof(CheckedExceptionElement),
2659 sizeof(u2));
2660 }
2661
2662 // Copy class file LVT's/LVTT's into the HotSpot internal LVT.
2663 if (total_lvt_length > 0) {
2664 *has_localvariable_table = true;
2665 copy_localvariable_table(m->constMethod(),
2666 lvt_cnt,
2667 localvariable_table_length,
2668 localvariable_table_start,
2669 lvtt_cnt,
2670 localvariable_type_table_length,
2671 localvariable_type_table_start,
2672 CHECK_NULL);
2673 }
2674
2675 if (parsed_annotations.has_any_annotations())
2676 parsed_annotations.apply_to(methodHandle(THREAD, m));
2677
2678 if (is_hidden()) { // Mark methods in hidden classes as 'hidden'.
2679 m->set_is_hidden();
2680 }
2681 if (parsed_annotations.has_aot_runtime_setup()) {
2682 if (name != vmSymbols::runtimeSetup() || signature != vmSymbols::void_method_signature() ||
2683 !access_flags.is_private() || !access_flags.is_static()) {
2684 classfile_parse_error("@AOTRuntimeSetup method must be declared private static void runtimeSetup() for class %s", CHECK_NULL);
2685 }
2686 _has_aot_runtime_setup_method = true;
2687 }
2688
2689 // Copy annotations
2690 copy_method_annotations(m->constMethod(),
2691 runtime_visible_annotations,
2692 runtime_visible_annotations_length,
2693 runtime_visible_parameter_annotations,
2694 runtime_visible_parameter_annotations_length,
2695 runtime_visible_type_annotations,
2696 runtime_visible_type_annotations_length,
2697 annotation_default,
2698 annotation_default_length,
2699 CHECK_NULL);
2700
2701 if (InstanceKlass::is_finalization_enabled() &&
2702 name == vmSymbols::finalize_method_name() &&
2703 signature == vmSymbols::void_method_signature()) {
2704 if (m->is_empty_method()) {
2705 _has_empty_finalizer = true;
2706 } else {
2707 _has_finalizer = true;
2708 }
2709 }
2710
2711 NOT_PRODUCT(m->verify());
2712 return m;
2713 }
2714
2715
2716 // Side-effects: populates the _methods field in the parser
2717 void ClassFileParser::parse_methods(const ClassFileStream* const cfs,
2718 bool is_interface,
2719 bool* const has_localvariable_table,
2720 bool* has_final_method,
2721 bool* declares_nonstatic_concrete_methods,
2722 TRAPS) {
2723 assert(cfs != nullptr, "invariant");
2724 assert(has_localvariable_table != nullptr, "invariant");
2725 assert(has_final_method != nullptr, "invariant");
2726 assert(declares_nonstatic_concrete_methods != nullptr, "invariant");
2727
2728 assert(nullptr == _methods, "invariant");
2729
2730 cfs->guarantee_more(2, CHECK); // length
2731 const u2 length = cfs->get_u2_fast();
2732 if (length == 0) {
2733 _methods = Universe::the_empty_method_array();
2734 } else {
2735 _methods = MetadataFactory::new_array<Method*>(_loader_data,
2736 length,
2737 nullptr,
2738 CHECK);
2739
2740 for (int index = 0; index < length; index++) {
2741 Method* method = parse_method(cfs,
2742 is_interface,
2743 _cp,
2744 has_localvariable_table,
2745 CHECK);
2746
2747 if (method->is_final()) {
2748 *has_final_method = true;
2749 }
2750 // declares_nonstatic_concrete_methods: declares concrete instance methods, any access flags
2751 // used for interface initialization, and default method inheritance analysis
2752 if (is_interface && !(*declares_nonstatic_concrete_methods)
2753 && !method->is_abstract() && !method->is_static()) {
2754 *declares_nonstatic_concrete_methods = true;
2755 }
2756 _methods->at_put(index, method);
2757 }
2758
2759 if (_need_verify && length > 1) {
2760 // Check duplicated methods
2761 ResourceMark rm(THREAD);
2762 // Set containing name-signature pairs
2763 NameSigHashtable* names_and_sigs = new NameSigHashtable();
2764 for (int i = 0; i < length; i++) {
2765 const Method* const m = _methods->at(i);
2766 NameSigHash name_and_sig(m->name(), m->signature());
2767 // If no duplicates, add name/signature in hashtable names_and_sigs.
2768 if(!names_and_sigs->put(name_and_sig, 0)) {
2769 classfile_parse_error("Duplicate method name \"%s\" with signature \"%s\" in class file %s",
2770 name_and_sig._name->as_C_string(), name_and_sig._sig->as_klass_external_name(), THREAD);
2771 return;
2772 }
2773 }
2774 }
2775 }
2776 }
2777
2778 static const intArray* sort_methods(Array<Method*>* methods) {
2779 const int length = methods->length();
2780 // If JVMTI original method ordering or sharing is enabled we have to
2781 // remember the original class file ordering.
2782 // We temporarily use the vtable_index field in the Method* to store the
2783 // class file index, so we can read in after calling qsort.
2784 // Put the method ordering in the shared archive.
2785 if (JvmtiExport::can_maintain_original_method_order() || CDSConfig::is_dumping_archive()) {
2786 for (int index = 0; index < length; index++) {
2787 Method* const m = methods->at(index);
2788 assert(!m->valid_vtable_index(), "vtable index should not be set");
2789 m->set_vtable_index(index);
2790 }
2791 }
2792 // Sort method array by ascending method name (for faster lookups & vtable construction)
2793 // Note that the ordering is not alphabetical, see Symbol::fast_compare
2794 Method::sort_methods(methods);
2795
2796 intArray* method_ordering = nullptr;
2797 // If JVMTI original method ordering or sharing is enabled construct int
2798 // array remembering the original ordering
2799 if (JvmtiExport::can_maintain_original_method_order() || CDSConfig::is_dumping_archive()) {
2800 method_ordering = new intArray(length, length, -1);
2801 for (int index = 0; index < length; index++) {
2802 Method* const m = methods->at(index);
2803 const int old_index = m->vtable_index();
2804 assert(old_index >= 0 && old_index < length, "invalid method index");
2805 method_ordering->at_put(index, old_index);
2806 m->set_vtable_index(Method::invalid_vtable_index);
2807 }
2808 }
2809 return method_ordering;
2810 }
2811
2812 // Parse generic_signature attribute for methods and fields
2813 u2 ClassFileParser::parse_generic_signature_attribute(const ClassFileStream* const cfs,
2814 TRAPS) {
2815 assert(cfs != nullptr, "invariant");
2816
2817 cfs->guarantee_more(2, CHECK_0); // generic_signature_index
2818 const u2 generic_signature_index = cfs->get_u2_fast();
2819 guarantee_property(
2820 valid_symbol_at(generic_signature_index),
2821 "Invalid Signature attribute at constant pool index %u in class file %s",
2822 generic_signature_index, CHECK_0);
2823 return generic_signature_index;
2824 }
2825
2826 void ClassFileParser::parse_classfile_sourcefile_attribute(const ClassFileStream* const cfs,
2827 TRAPS) {
2828
2829 assert(cfs != nullptr, "invariant");
2830
2831 cfs->guarantee_more(2, CHECK); // sourcefile_index
2832 const u2 sourcefile_index = cfs->get_u2_fast();
2833 guarantee_property(
2834 valid_symbol_at(sourcefile_index),
2835 "Invalid SourceFile attribute at constant pool index %u in class file %s",
2836 sourcefile_index, CHECK);
2837 set_class_sourcefile_index(sourcefile_index);
2838 }
2839
2840 void ClassFileParser::parse_classfile_source_debug_extension_attribute(const ClassFileStream* const cfs,
2841 int length,
2842 TRAPS) {
2843 assert(cfs != nullptr, "invariant");
2844
2845 const u1* const sde_buffer = cfs->current();
2846 assert(sde_buffer != nullptr, "null sde buffer");
2847
2848 // Don't bother storing it if there is no way to retrieve it
2849 if (JvmtiExport::can_get_source_debug_extension()) {
2850 assert((length+1) > length, "Overflow checking");
2851 u1* const sde = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, u1, length+1);
2852 for (int i = 0; i < length; i++) {
2853 sde[i] = sde_buffer[i];
2854 }
2855 sde[length] = '\0';
2856 set_class_sde_buffer((const char*)sde, length);
2857 }
2858 // Got utf8 string, set stream position forward
2859 cfs->skip_u1(length, CHECK);
2860 }
2861
2862
2863 // Inner classes can be static, private or protected (classic VM does this)
2864 #define RECOGNIZED_INNER_CLASS_MODIFIERS ( JVM_RECOGNIZED_CLASS_MODIFIERS | \
2865 JVM_ACC_PRIVATE | \
2866 JVM_ACC_PROTECTED | \
2867 JVM_ACC_STATIC \
2868 )
2869
2870 // Find index of the InnerClasses entry for the specified inner_class_info_index.
2871 // Return -1 if none is found.
2872 static int inner_classes_find_index(const Array<u2>* inner_classes, int inner, const ConstantPool* cp, int length) {
2873 Symbol* cp_klass_name = cp->klass_name_at(inner);
2874 for (int idx = 0; idx < length; idx += InstanceKlass::inner_class_next_offset) {
2875 int idx_inner = inner_classes->at(idx + InstanceKlass::inner_class_inner_class_info_offset);
2876 if (cp->klass_name_at(idx_inner) == cp_klass_name) {
2877 return idx;
2878 }
2879 }
2880 return -1;
2881 }
2882
2883 // Return the outer_class_info_index for the InnerClasses entry containing the
2884 // specified inner_class_info_index. Return -1 if no InnerClasses entry is found.
2885 static int inner_classes_jump_to_outer(const Array<u2>* inner_classes, int inner, const ConstantPool* cp, int length) {
2886 if (inner == 0) return -1;
2887 int idx = inner_classes_find_index(inner_classes, inner, cp, length);
2888 if (idx == -1) return -1;
2889 int result = inner_classes->at(idx + InstanceKlass::inner_class_outer_class_info_offset);
2890 return result;
2891 }
2892
2893 // Return true if circularity is found, false if no circularity is found.
2894 // Use Floyd's cycle finding algorithm.
2895 static bool inner_classes_check_loop_through_outer(const Array<u2>* inner_classes, int idx, const ConstantPool* cp, int length) {
2896 int slow = inner_classes->at(idx + InstanceKlass::inner_class_inner_class_info_offset);
2897 int fast = inner_classes->at(idx + InstanceKlass::inner_class_outer_class_info_offset);
2898
2899 while (fast != -1 && fast != 0) {
2900 if (slow != 0 && (cp->klass_name_at(slow) == cp->klass_name_at(fast))) {
2901 return true; // found a circularity
2902 }
2903 fast = inner_classes_jump_to_outer(inner_classes, fast, cp, length);
2904 if (fast == -1) return false;
2905 fast = inner_classes_jump_to_outer(inner_classes, fast, cp, length);
2906 if (fast == -1) return false;
2907 slow = inner_classes_jump_to_outer(inner_classes, slow, cp, length);
2908 assert(slow != -1, "sanity check");
2909 }
2910 return false;
2911 }
2912
2913 // Loop through each InnerClasses entry checking for circularities and duplications
2914 // with other entries. If duplicate entries are found then throw CFE. Otherwise,
2915 // return true if a circularity or entries with duplicate inner_class_info_indexes
2916 // are found.
2917 bool ClassFileParser::check_inner_classes_circularity(const ConstantPool* cp, int length, TRAPS) {
2918 // Loop through each InnerClasses entry.
2919 for (int idx = 0; idx < length; idx += InstanceKlass::inner_class_next_offset) {
2920 // Return true if there are circular entries.
2921 if (inner_classes_check_loop_through_outer(_inner_classes, idx, cp, length)) {
2922 return true;
2923 }
2924 // Check if there are duplicate entries or entries with the same inner_class_info_index.
2925 for (int y = idx + InstanceKlass::inner_class_next_offset; y < length;
2926 y += InstanceKlass::inner_class_next_offset) {
2927
2928 // 4347400: make sure there's no duplicate entry in the classes array
2929 if (_major_version >= JAVA_1_5_VERSION) {
2930 guarantee_property((_inner_classes->at(idx) != _inner_classes->at(y) ||
2931 _inner_classes->at(idx+1) != _inner_classes->at(y+1) ||
2932 _inner_classes->at(idx+2) != _inner_classes->at(y+2) ||
2933 _inner_classes->at(idx+3) != _inner_classes->at(y+3)),
2934 "Duplicate entry in InnerClasses attribute in class file %s",
2935 CHECK_(true));
2936 }
2937 // Return true if there are two entries with the same inner_class_info_index.
2938 if (_inner_classes->at(y) == _inner_classes->at(idx)) {
2939 return true;
2940 }
2941 }
2942 }
2943 return false;
2944 }
2945
2946 // Return number of classes in the inner classes attribute table
2947 u2 ClassFileParser::parse_classfile_inner_classes_attribute(const ClassFileStream* const cfs,
2948 const ConstantPool* cp,
2949 const u1* const inner_classes_attribute_start,
2950 bool parsed_enclosingmethod_attribute,
2951 u2 enclosing_method_class_index,
2952 u2 enclosing_method_method_index,
2953 TRAPS) {
2954 const u1* const current_mark = cfs->current();
2955 u2 length = 0;
2956 if (inner_classes_attribute_start != nullptr) {
2957 cfs->set_current(inner_classes_attribute_start);
2958 cfs->guarantee_more(2, CHECK_0); // length
2959 length = cfs->get_u2_fast();
2960 }
2961
2962 // 4-tuples of shorts of inner classes data and 2 shorts of enclosing
2963 // method data:
2964 // [inner_class_info_index,
2965 // outer_class_info_index,
2966 // inner_name_index,
2967 // inner_class_access_flags,
2968 // ...
2969 // enclosing_method_class_index,
2970 // enclosing_method_method_index]
2971 const int size = length * 4 + (parsed_enclosingmethod_attribute ? 2 : 0);
2972 Array<u2>* inner_classes = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
2973 _inner_classes = inner_classes;
2974
2975 int index = 0;
2976 cfs->guarantee_more(8 * length, CHECK_0); // 4-tuples of u2
2977 for (int n = 0; n < length; n++) {
2978 // Inner class index
2979 const u2 inner_class_info_index = cfs->get_u2_fast();
2980 guarantee_property(
2981 valid_klass_reference_at(inner_class_info_index),
2982 "inner_class_info_index %u has bad constant type in class file %s",
2983 inner_class_info_index, CHECK_0);
2984 // Outer class index
2985 const u2 outer_class_info_index = cfs->get_u2_fast();
2986 guarantee_property(
2987 outer_class_info_index == 0 ||
2988 valid_klass_reference_at(outer_class_info_index),
2989 "outer_class_info_index %u has bad constant type in class file %s",
2990 outer_class_info_index, CHECK_0);
2991
2992 if (outer_class_info_index != 0) {
2993 const Symbol* const outer_class_name = cp->klass_name_at(outer_class_info_index);
2994 char* bytes = (char*)outer_class_name->bytes();
2995 guarantee_property(bytes[0] != JVM_SIGNATURE_ARRAY,
2996 "Outer class is an array class in class file %s", CHECK_0);
2997 }
2998 // Inner class name
2999 const u2 inner_name_index = cfs->get_u2_fast();
3000 guarantee_property(
3001 inner_name_index == 0 || valid_symbol_at(inner_name_index),
3002 "inner_name_index %u has bad constant type in class file %s",
3003 inner_name_index, CHECK_0);
3004 if (_need_verify) {
3005 guarantee_property(inner_class_info_index != outer_class_info_index,
3006 "Class is both outer and inner class in class file %s", CHECK_0);
3007 }
3008 // Access flags
3009 u2 flags;
3010 // JVM_ACC_MODULE is defined in JDK-9 and later.
3011 if (_major_version >= JAVA_9_VERSION) {
3012 flags = cfs->get_u2_fast() & (RECOGNIZED_INNER_CLASS_MODIFIERS | JVM_ACC_MODULE);
3013 } else {
3014 flags = cfs->get_u2_fast() & RECOGNIZED_INNER_CLASS_MODIFIERS;
3015 }
3016 if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
3017 // Set abstract bit for old class files for backward compatibility
3018 flags |= JVM_ACC_ABSTRACT;
3019 }
3020
3021 Symbol* inner_name_symbol = inner_name_index == 0 ? nullptr : cp->symbol_at(inner_name_index);
3022 verify_legal_class_modifiers(flags, inner_name_symbol, inner_name_index == 0, CHECK_0);
3023 AccessFlags inner_access_flags(flags);
3024
3025 inner_classes->at_put(index++, inner_class_info_index);
3026 inner_classes->at_put(index++, outer_class_info_index);
3027 inner_classes->at_put(index++, inner_name_index);
3028 inner_classes->at_put(index++, inner_access_flags.as_unsigned_short());
3029 }
3030
3031 // Check for circular and duplicate entries.
3032 bool has_circularity = false;
3033 if (_need_verify) {
3034 has_circularity = check_inner_classes_circularity(cp, length * 4, CHECK_0);
3035 if (has_circularity) {
3036 // If circularity check failed then ignore InnerClasses attribute.
3037 MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
3038 index = 0;
3039 if (parsed_enclosingmethod_attribute) {
3040 inner_classes = MetadataFactory::new_array<u2>(_loader_data, 2, CHECK_0);
3041 _inner_classes = inner_classes;
3042 } else {
3043 _inner_classes = Universe::the_empty_short_array();
3044 }
3045 }
3046 }
3047 // Set EnclosingMethod class and method indexes.
3048 if (parsed_enclosingmethod_attribute) {
3049 inner_classes->at_put(index++, enclosing_method_class_index);
3050 inner_classes->at_put(index++, enclosing_method_method_index);
3051 }
3052 assert(index == size || has_circularity, "wrong size");
3053
3054 // Restore buffer's current position.
3055 cfs->set_current(current_mark);
3056
3057 return length;
3058 }
3059
3060 u2 ClassFileParser::parse_classfile_nest_members_attribute(const ClassFileStream* const cfs,
3061 const u1* const nest_members_attribute_start,
3062 TRAPS) {
3063 const u1* const current_mark = cfs->current();
3064 u2 length = 0;
3065 if (nest_members_attribute_start != nullptr) {
3066 cfs->set_current(nest_members_attribute_start);
3067 cfs->guarantee_more(2, CHECK_0); // length
3068 length = cfs->get_u2_fast();
3069 }
3070 const int size = length;
3071 Array<u2>* const nest_members = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
3072 _nest_members = nest_members;
3073
3074 int index = 0;
3075 cfs->guarantee_more(2 * length, CHECK_0);
3076 for (int n = 0; n < length; n++) {
3077 const u2 class_info_index = cfs->get_u2_fast();
3078 guarantee_property(
3079 valid_klass_reference_at(class_info_index),
3080 "Nest member class_info_index %u has bad constant type in class file %s",
3081 class_info_index, CHECK_0);
3082 nest_members->at_put(index++, class_info_index);
3083 }
3084 assert(index == size, "wrong size");
3085
3086 // Restore buffer's current position.
3087 cfs->set_current(current_mark);
3088
3089 return length;
3090 }
3091
3092 u2 ClassFileParser::parse_classfile_permitted_subclasses_attribute(const ClassFileStream* const cfs,
3093 const u1* const permitted_subclasses_attribute_start,
3094 TRAPS) {
3095 const u1* const current_mark = cfs->current();
3096 u2 length = 0;
3097 if (permitted_subclasses_attribute_start != nullptr) {
3098 cfs->set_current(permitted_subclasses_attribute_start);
3099 cfs->guarantee_more(2, CHECK_0); // length
3100 length = cfs->get_u2_fast();
3101 }
3102 const int size = length;
3103 Array<u2>* const permitted_subclasses = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
3104 _permitted_subclasses = permitted_subclasses;
3105
3106 if (length > 0) {
3107 int index = 0;
3108 cfs->guarantee_more(2 * length, CHECK_0);
3109 for (int n = 0; n < length; n++) {
3110 const u2 class_info_index = cfs->get_u2_fast();
3111 guarantee_property(
3112 valid_klass_reference_at(class_info_index),
3113 "Permitted subclass class_info_index %u has bad constant type in class file %s",
3114 class_info_index, CHECK_0);
3115 permitted_subclasses->at_put(index++, class_info_index);
3116 }
3117 assert(index == size, "wrong size");
3118 }
3119
3120 // Restore buffer's current position.
3121 cfs->set_current(current_mark);
3122
3123 return length;
3124 }
3125
3126 // Record {
3127 // u2 attribute_name_index;
3128 // u4 attribute_length;
3129 // u2 components_count;
3130 // component_info components[components_count];
3131 // }
3132 // component_info {
3133 // u2 name_index;
3134 // u2 descriptor_index
3135 // u2 attributes_count;
3136 // attribute_info_attributes[attributes_count];
3137 // }
3138 u4 ClassFileParser::parse_classfile_record_attribute(const ClassFileStream* const cfs,
3139 const ConstantPool* cp,
3140 const u1* const record_attribute_start,
3141 TRAPS) {
3142 const u1* const current_mark = cfs->current();
3143 int components_count = 0;
3144 unsigned int calculate_attr_size = 0;
3145 if (record_attribute_start != nullptr) {
3146 cfs->set_current(record_attribute_start);
3147 cfs->guarantee_more(2, CHECK_0); // num of components
3148 components_count = (int)cfs->get_u2_fast();
3149 calculate_attr_size = 2;
3150 }
3151
3152 Array<RecordComponent*>* const record_components =
3153 MetadataFactory::new_array<RecordComponent*>(_loader_data, components_count, nullptr, CHECK_0);
3154 _record_components = record_components;
3155
3156 for (int x = 0; x < components_count; x++) {
3157 cfs->guarantee_more(6, CHECK_0); // name_index, descriptor_index, attributes_count
3158
3159 const u2 name_index = cfs->get_u2_fast();
3160 guarantee_property(valid_symbol_at(name_index),
3161 "Invalid constant pool index %u for name in Record attribute in class file %s",
3162 name_index, CHECK_0);
3163 const Symbol* const name = cp->symbol_at(name_index);
3164 verify_legal_field_name(name, CHECK_0);
3165
3166 const u2 descriptor_index = cfs->get_u2_fast();
3167 guarantee_property(valid_symbol_at(descriptor_index),
3168 "Invalid constant pool index %u for descriptor in Record attribute in class file %s",
3169 descriptor_index, CHECK_0);
3170 const Symbol* const descr = cp->symbol_at(descriptor_index);
3171 verify_legal_field_signature(name, descr, CHECK_0);
3172
3173 const u2 attributes_count = cfs->get_u2_fast();
3174 calculate_attr_size += 6;
3175 u2 generic_sig_index = 0;
3176 const u1* runtime_visible_annotations = nullptr;
3177 int runtime_visible_annotations_length = 0;
3178 bool runtime_invisible_annotations_exists = false;
3179 const u1* runtime_visible_type_annotations = nullptr;
3180 int runtime_visible_type_annotations_length = 0;
3181 bool runtime_invisible_type_annotations_exists = false;
3182
3183 // Expected attributes for record components are Signature, Runtime(In)VisibleAnnotations,
3184 // and Runtime(In)VisibleTypeAnnotations. Other attributes are ignored.
3185 for (int y = 0; y < attributes_count; y++) {
3186 cfs->guarantee_more(6, CHECK_0); // attribute_name_index, attribute_length
3187 const u2 attribute_name_index = cfs->get_u2_fast();
3188 const u4 attribute_length = cfs->get_u4_fast();
3189 calculate_attr_size += 6;
3190 guarantee_property(
3191 valid_symbol_at(attribute_name_index),
3192 "Invalid Record attribute name index %u in class file %s",
3193 attribute_name_index, CHECK_0);
3194
3195 const Symbol* const attribute_name = cp->symbol_at(attribute_name_index);
3196 if (attribute_name == vmSymbols::tag_signature()) {
3197 if (generic_sig_index != 0) {
3198 classfile_parse_error(
3199 "Multiple Signature attributes for Record component in class file %s",
3200 THREAD);
3201 return 0;
3202 }
3203 if (attribute_length != 2) {
3204 classfile_parse_error(
3205 "Invalid Signature attribute length %u in Record component in class file %s",
3206 attribute_length, THREAD);
3207 return 0;
3208 }
3209 generic_sig_index = parse_generic_signature_attribute(cfs, CHECK_0);
3210
3211 } else if (attribute_name == vmSymbols::tag_runtime_visible_annotations()) {
3212 if (runtime_visible_annotations != nullptr) {
3213 classfile_parse_error(
3214 "Multiple RuntimeVisibleAnnotations attributes for Record component in class file %s", THREAD);
3215 return 0;
3216 }
3217 runtime_visible_annotations_length = attribute_length;
3218 runtime_visible_annotations = cfs->current();
3219
3220 assert(runtime_visible_annotations != nullptr, "null record component visible annotation");
3221 cfs->guarantee_more(runtime_visible_annotations_length, CHECK_0);
3222 cfs->skip_u1_fast(runtime_visible_annotations_length);
3223
3224 } else if (attribute_name == vmSymbols::tag_runtime_invisible_annotations()) {
3225 if (runtime_invisible_annotations_exists) {
3226 classfile_parse_error(
3227 "Multiple RuntimeInvisibleAnnotations attributes for Record component in class file %s", THREAD);
3228 return 0;
3229 }
3230 runtime_invisible_annotations_exists = true;
3231 cfs->skip_u1(attribute_length, CHECK_0);
3232
3233 } else if (attribute_name == vmSymbols::tag_runtime_visible_type_annotations()) {
3234 if (runtime_visible_type_annotations != nullptr) {
3235 classfile_parse_error(
3236 "Multiple RuntimeVisibleTypeAnnotations attributes for Record component in class file %s", THREAD);
3237 return 0;
3238 }
3239 runtime_visible_type_annotations_length = attribute_length;
3240 runtime_visible_type_annotations = cfs->current();
3241
3242 assert(runtime_visible_type_annotations != nullptr, "null record component visible type annotation");
3243 cfs->guarantee_more(runtime_visible_type_annotations_length, CHECK_0);
3244 cfs->skip_u1_fast(runtime_visible_type_annotations_length);
3245
3246 } else if (attribute_name == vmSymbols::tag_runtime_invisible_type_annotations()) {
3247 if (runtime_invisible_type_annotations_exists) {
3248 classfile_parse_error(
3249 "Multiple RuntimeInvisibleTypeAnnotations attributes for Record component in class file %s", THREAD);
3250 return 0;
3251 }
3252 runtime_invisible_type_annotations_exists = true;
3253 cfs->skip_u1(attribute_length, CHECK_0);
3254
3255 } else {
3256 // Skip unknown attributes
3257 cfs->skip_u1(attribute_length, CHECK_0);
3258 }
3259 calculate_attr_size += attribute_length;
3260 } // End of attributes For loop
3261
3262 AnnotationArray* annotations = allocate_annotations(runtime_visible_annotations,
3263 runtime_visible_annotations_length,
3264 CHECK_0);
3265 AnnotationArray* type_annotations = allocate_annotations(runtime_visible_type_annotations,
3266 runtime_visible_type_annotations_length,
3267 CHECK_0);
3268
3269 RecordComponent* record_component =
3270 RecordComponent::allocate(_loader_data, name_index, descriptor_index, generic_sig_index,
3271 annotations, type_annotations, CHECK_0);
3272 record_components->at_put(x, record_component);
3273 } // End of component processing loop
3274
3275 // Restore buffer's current position.
3276 cfs->set_current(current_mark);
3277 return calculate_attr_size;
3278 }
3279
3280 void ClassFileParser::parse_classfile_synthetic_attribute() {
3281 set_class_synthetic_flag(true);
3282 }
3283
3284 void ClassFileParser::parse_classfile_signature_attribute(const ClassFileStream* const cfs, TRAPS) {
3285 assert(cfs != nullptr, "invariant");
3286
3287 const u2 signature_index = cfs->get_u2(CHECK);
3288 guarantee_property(
3289 valid_symbol_at(signature_index),
3290 "Invalid constant pool index %u in Signature attribute in class file %s",
3291 signature_index, CHECK);
3292 set_class_generic_signature_index(signature_index);
3293 }
3294
3295 void ClassFileParser::parse_classfile_bootstrap_methods_attribute(const ClassFileStream* const cfs,
3296 ConstantPool* cp,
3297 u4 attribute_byte_length,
3298 TRAPS) {
3299 assert(cfs != nullptr, "invariant");
3300 assert(cp != nullptr, "invariant");
3301
3302 const u1* const current_start = cfs->current();
3303
3304 guarantee_property(attribute_byte_length >= sizeof(u2),
3305 "Invalid BootstrapMethods attribute length %u in class file %s",
3306 attribute_byte_length,
3307 CHECK);
3308
3309 cfs->guarantee_more(attribute_byte_length, CHECK);
3310
3311 const int attribute_array_length = cfs->get_u2_fast();
3312
3313 guarantee_property(_max_bootstrap_specifier_index < attribute_array_length,
3314 "Short length on BootstrapMethods in class file %s",
3315 CHECK);
3316
3317
3318 // The attribute contains a counted array of counted tuples of shorts,
3319 // represending bootstrap specifiers:
3320 // length*{bootstrap_method_index, argument_count*{argument_index}}
3321 const unsigned int operand_count = (attribute_byte_length - (unsigned)sizeof(u2)) / (unsigned)sizeof(u2);
3322 // operand_count = number of shorts in attr, except for leading length
3323
3324 // The attribute is copied into a short[] array.
3325 // The array begins with a series of short[2] pairs, one for each tuple.
3326 const int index_size = (attribute_array_length * 2);
3327
3328 Array<u2>* const operands =
3329 MetadataFactory::new_array<u2>(_loader_data, index_size + operand_count, CHECK);
3330
3331 // Eagerly assign operands so they will be deallocated with the constant
3332 // pool if there is an error.
3333 cp->set_operands(operands);
3334
3335 int operand_fill_index = index_size;
3336 const int cp_size = cp->length();
3337
3338 for (int n = 0; n < attribute_array_length; n++) {
3339 // Store a 32-bit offset into the header of the operand array.
3340 ConstantPool::operand_offset_at_put(operands, n, operand_fill_index);
3341
3342 // Read a bootstrap specifier.
3343 cfs->guarantee_more(sizeof(u2) * 2, CHECK); // bsm, argc
3344 const u2 bootstrap_method_index = cfs->get_u2_fast();
3345 const u2 argument_count = cfs->get_u2_fast();
3346 guarantee_property(
3347 valid_cp_range(bootstrap_method_index, cp_size) &&
3348 cp->tag_at(bootstrap_method_index).is_method_handle(),
3349 "bootstrap_method_index %u has bad constant type in class file %s",
3350 bootstrap_method_index,
3351 CHECK);
3352
3353 guarantee_property((operand_fill_index + 1 + argument_count) < operands->length(),
3354 "Invalid BootstrapMethods num_bootstrap_methods or num_bootstrap_arguments value in class file %s",
3355 CHECK);
3356
3357 operands->at_put(operand_fill_index++, bootstrap_method_index);
3358 operands->at_put(operand_fill_index++, argument_count);
3359
3360 cfs->guarantee_more(sizeof(u2) * argument_count, CHECK); // argv[argc]
3361 for (int j = 0; j < argument_count; j++) {
3362 const u2 argument_index = cfs->get_u2_fast();
3363 guarantee_property(
3364 valid_cp_range(argument_index, cp_size) &&
3365 cp->tag_at(argument_index).is_loadable_constant(),
3366 "argument_index %u has bad constant type in class file %s",
3367 argument_index,
3368 CHECK);
3369 operands->at_put(operand_fill_index++, argument_index);
3370 }
3371 }
3372 guarantee_property(current_start + attribute_byte_length == cfs->current(),
3373 "Bad length on BootstrapMethods in class file %s",
3374 CHECK);
3375 }
3376
3377 void ClassFileParser::parse_classfile_attributes(const ClassFileStream* const cfs,
3378 ConstantPool* cp,
3379 ClassFileParser::ClassAnnotationCollector* parsed_annotations,
3380 TRAPS) {
3381 assert(cfs != nullptr, "invariant");
3382 assert(cp != nullptr, "invariant");
3383 assert(parsed_annotations != nullptr, "invariant");
3384
3385 // Set inner classes attribute to default sentinel
3386 _inner_classes = Universe::the_empty_short_array();
3387 // Set nest members attribute to default sentinel
3388 _nest_members = Universe::the_empty_short_array();
3389 // Set _permitted_subclasses attribute to default sentinel
3390 _permitted_subclasses = Universe::the_empty_short_array();
3391 cfs->guarantee_more(2, CHECK); // attributes_count
3392 u2 attributes_count = cfs->get_u2_fast();
3393 bool parsed_sourcefile_attribute = false;
3394 bool parsed_innerclasses_attribute = false;
3395 bool parsed_nest_members_attribute = false;
3396 bool parsed_permitted_subclasses_attribute = false;
3397 bool parsed_nest_host_attribute = false;
3398 bool parsed_record_attribute = false;
3399 bool parsed_enclosingmethod_attribute = false;
3400 bool parsed_bootstrap_methods_attribute = false;
3401 const u1* runtime_visible_annotations = nullptr;
3402 int runtime_visible_annotations_length = 0;
3403 const u1* runtime_visible_type_annotations = nullptr;
3404 int runtime_visible_type_annotations_length = 0;
3405 bool runtime_invisible_type_annotations_exists = false;
3406 bool runtime_invisible_annotations_exists = false;
3407 bool parsed_source_debug_ext_annotations_exist = false;
3408 const u1* inner_classes_attribute_start = nullptr;
3409 u4 inner_classes_attribute_length = 0;
3410 u2 enclosing_method_class_index = 0;
3411 u2 enclosing_method_method_index = 0;
3412 const u1* nest_members_attribute_start = nullptr;
3413 u4 nest_members_attribute_length = 0;
3414 const u1* record_attribute_start = nullptr;
3415 u4 record_attribute_length = 0;
3416 const u1* permitted_subclasses_attribute_start = nullptr;
3417 u4 permitted_subclasses_attribute_length = 0;
3418
3419 // Iterate over attributes
3420 while (attributes_count--) {
3421 cfs->guarantee_more(6, CHECK); // attribute_name_index, attribute_length
3422 const u2 attribute_name_index = cfs->get_u2_fast();
3423 const u4 attribute_length = cfs->get_u4_fast();
3424 guarantee_property(
3425 valid_symbol_at(attribute_name_index),
3426 "Attribute name has bad constant pool index %u in class file %s",
3427 attribute_name_index, CHECK);
3428 const Symbol* const tag = cp->symbol_at(attribute_name_index);
3429 if (tag == vmSymbols::tag_source_file()) {
3430 // Check for SourceFile tag
3431 if (_need_verify) {
3432 guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
3433 }
3434 if (parsed_sourcefile_attribute) {
3435 classfile_parse_error("Multiple SourceFile attributes in class file %s", THREAD);
3436 return;
3437 } else {
3438 parsed_sourcefile_attribute = true;
3439 }
3440 parse_classfile_sourcefile_attribute(cfs, CHECK);
3441 } else if (tag == vmSymbols::tag_source_debug_extension()) {
3442 // Check for SourceDebugExtension tag
3443 if (parsed_source_debug_ext_annotations_exist) {
3444 classfile_parse_error(
3445 "Multiple SourceDebugExtension attributes in class file %s", THREAD);
3446 return;
3447 }
3448 parsed_source_debug_ext_annotations_exist = true;
3449 parse_classfile_source_debug_extension_attribute(cfs, (int)attribute_length, CHECK);
3450 } else if (tag == vmSymbols::tag_inner_classes()) {
3451 // Check for InnerClasses tag
3452 if (parsed_innerclasses_attribute) {
3453 classfile_parse_error("Multiple InnerClasses attributes in class file %s", THREAD);
3454 return;
3455 } else {
3456 parsed_innerclasses_attribute = true;
3457 }
3458 inner_classes_attribute_start = cfs->current();
3459 inner_classes_attribute_length = attribute_length;
3460 cfs->skip_u1(inner_classes_attribute_length, CHECK);
3461 } else if (tag == vmSymbols::tag_synthetic()) {
3462 // Check for Synthetic tag
3463 // Shouldn't we check that the synthetic flags wasn't already set? - not required in spec
3464 if (attribute_length != 0) {
3465 classfile_parse_error(
3466 "Invalid Synthetic classfile attribute length %u in class file %s",
3467 attribute_length, THREAD);
3468 return;
3469 }
3470 parse_classfile_synthetic_attribute();
3471 } else if (tag == vmSymbols::tag_deprecated()) {
3472 // Check for Deprecated tag - 4276120
3473 if (attribute_length != 0) {
3474 classfile_parse_error(
3475 "Invalid Deprecated classfile attribute length %u in class file %s",
3476 attribute_length, THREAD);
3477 return;
3478 }
3479 } else if (_major_version >= JAVA_1_5_VERSION) {
3480 if (tag == vmSymbols::tag_signature()) {
3481 if (_generic_signature_index != 0) {
3482 classfile_parse_error(
3483 "Multiple Signature attributes in class file %s", THREAD);
3484 return;
3485 }
3486 if (attribute_length != 2) {
3487 classfile_parse_error(
3488 "Wrong Signature attribute length %u in class file %s",
3489 attribute_length, THREAD);
3490 return;
3491 }
3492 parse_classfile_signature_attribute(cfs, CHECK);
3493 } else if (tag == vmSymbols::tag_runtime_visible_annotations()) {
3494 if (runtime_visible_annotations != nullptr) {
3495 classfile_parse_error(
3496 "Multiple RuntimeVisibleAnnotations attributes in class file %s", THREAD);
3497 return;
3498 }
3499 runtime_visible_annotations_length = attribute_length;
3500 runtime_visible_annotations = cfs->current();
3501 assert(runtime_visible_annotations != nullptr, "null visible annotations");
3502 cfs->guarantee_more(runtime_visible_annotations_length, CHECK);
3503 parse_annotations(cp,
3504 runtime_visible_annotations,
3505 runtime_visible_annotations_length,
3506 parsed_annotations,
3507 _loader_data,
3508 _can_access_vm_annotations);
3509 cfs->skip_u1_fast(runtime_visible_annotations_length);
3510 } else if (tag == vmSymbols::tag_runtime_invisible_annotations()) {
3511 if (runtime_invisible_annotations_exists) {
3512 classfile_parse_error(
3513 "Multiple RuntimeInvisibleAnnotations attributes in class file %s", THREAD);
3514 return;
3515 }
3516 runtime_invisible_annotations_exists = true;
3517 cfs->skip_u1(attribute_length, CHECK);
3518 } else if (tag == vmSymbols::tag_enclosing_method()) {
3519 if (parsed_enclosingmethod_attribute) {
3520 classfile_parse_error("Multiple EnclosingMethod attributes in class file %s", THREAD);
3521 return;
3522 } else {
3523 parsed_enclosingmethod_attribute = true;
3524 }
3525 guarantee_property(attribute_length == 4,
3526 "Wrong EnclosingMethod attribute length %u in class file %s",
3527 attribute_length, CHECK);
3528 cfs->guarantee_more(4, CHECK); // class_index, method_index
3529 enclosing_method_class_index = cfs->get_u2_fast();
3530 enclosing_method_method_index = cfs->get_u2_fast();
3531 if (enclosing_method_class_index == 0) {
3532 classfile_parse_error("Invalid class index in EnclosingMethod attribute in class file %s", THREAD);
3533 return;
3534 }
3535 // Validate the constant pool indices and types
3536 guarantee_property(valid_klass_reference_at(enclosing_method_class_index),
3537 "Invalid or out-of-bounds class index in EnclosingMethod attribute in class file %s", CHECK);
3538 if (enclosing_method_method_index != 0 &&
3539 (!cp->is_within_bounds(enclosing_method_method_index) ||
3540 !cp->tag_at(enclosing_method_method_index).is_name_and_type())) {
3541 classfile_parse_error("Invalid or out-of-bounds method index in EnclosingMethod attribute in class file %s", THREAD);
3542 return;
3543 }
3544 } else if (tag == vmSymbols::tag_bootstrap_methods() &&
3545 _major_version >= Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {
3546 if (parsed_bootstrap_methods_attribute) {
3547 classfile_parse_error("Multiple BootstrapMethods attributes in class file %s", THREAD);
3548 return;
3549 }
3550 parsed_bootstrap_methods_attribute = true;
3551 parse_classfile_bootstrap_methods_attribute(cfs, cp, attribute_length, CHECK);
3552 } else if (tag == vmSymbols::tag_runtime_visible_type_annotations()) {
3553 if (runtime_visible_type_annotations != nullptr) {
3554 classfile_parse_error(
3555 "Multiple RuntimeVisibleTypeAnnotations attributes in class file %s", THREAD);
3556 return;
3557 }
3558 runtime_visible_type_annotations_length = attribute_length;
3559 runtime_visible_type_annotations = cfs->current();
3560 assert(runtime_visible_type_annotations != nullptr, "null visible type annotations");
3561 // No need for the VM to parse Type annotations
3562 cfs->skip_u1(runtime_visible_type_annotations_length, CHECK);
3563 } else if (tag == vmSymbols::tag_runtime_invisible_type_annotations()) {
3564 if (runtime_invisible_type_annotations_exists) {
3565 classfile_parse_error(
3566 "Multiple RuntimeInvisibleTypeAnnotations attributes in class file %s", THREAD);
3567 return;
3568 }
3569 runtime_invisible_type_annotations_exists = true;
3570 cfs->skip_u1(attribute_length, CHECK);
3571 } else if (_major_version >= JAVA_11_VERSION) {
3572 if (tag == vmSymbols::tag_nest_members()) {
3573 // Check for NestMembers tag
3574 if (parsed_nest_members_attribute) {
3575 classfile_parse_error("Multiple NestMembers attributes in class file %s", THREAD);
3576 return;
3577 } else {
3578 parsed_nest_members_attribute = true;
3579 }
3580 if (parsed_nest_host_attribute) {
3581 classfile_parse_error("Conflicting NestHost and NestMembers attributes in class file %s", THREAD);
3582 return;
3583 }
3584 nest_members_attribute_start = cfs->current();
3585 nest_members_attribute_length = attribute_length;
3586 cfs->skip_u1(nest_members_attribute_length, CHECK);
3587 } else if (tag == vmSymbols::tag_nest_host()) {
3588 if (parsed_nest_host_attribute) {
3589 classfile_parse_error("Multiple NestHost attributes in class file %s", THREAD);
3590 return;
3591 } else {
3592 parsed_nest_host_attribute = true;
3593 }
3594 if (parsed_nest_members_attribute) {
3595 classfile_parse_error("Conflicting NestMembers and NestHost attributes in class file %s", THREAD);
3596 return;
3597 }
3598 if (_need_verify) {
3599 guarantee_property(attribute_length == 2, "Wrong NestHost attribute length in class file %s", CHECK);
3600 }
3601 cfs->guarantee_more(2, CHECK);
3602 u2 class_info_index = cfs->get_u2_fast();
3603 guarantee_property(
3604 valid_klass_reference_at(class_info_index),
3605 "Nest-host class_info_index %u has bad constant type in class file %s",
3606 class_info_index, CHECK);
3607 _nest_host = class_info_index;
3608
3609 } else if (_major_version >= JAVA_16_VERSION) {
3610 if (tag == vmSymbols::tag_record()) {
3611 if (parsed_record_attribute) {
3612 classfile_parse_error("Multiple Record attributes in class file %s", THREAD);
3613 return;
3614 }
3615 parsed_record_attribute = true;
3616 record_attribute_start = cfs->current();
3617 record_attribute_length = attribute_length;
3618 } else if (_major_version >= JAVA_17_VERSION) {
3619 if (tag == vmSymbols::tag_permitted_subclasses()) {
3620 if (parsed_permitted_subclasses_attribute) {
3621 classfile_parse_error("Multiple PermittedSubclasses attributes in class file %s", CHECK);
3622 return;
3623 }
3624 // Classes marked ACC_FINAL cannot have a PermittedSubclasses attribute.
3625 if (_access_flags.is_final()) {
3626 classfile_parse_error("PermittedSubclasses attribute in final class file %s", CHECK);
3627 return;
3628 }
3629 parsed_permitted_subclasses_attribute = true;
3630 permitted_subclasses_attribute_start = cfs->current();
3631 permitted_subclasses_attribute_length = attribute_length;
3632 }
3633 }
3634 // Skip attribute_length for any attribute where major_verson >= JAVA_17_VERSION
3635 cfs->skip_u1(attribute_length, CHECK);
3636 } else {
3637 // Unknown attribute
3638 cfs->skip_u1(attribute_length, CHECK);
3639 }
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 }
3649 _class_annotations = allocate_annotations(runtime_visible_annotations,
3650 runtime_visible_annotations_length,
3651 CHECK);
3652 _class_type_annotations = allocate_annotations(runtime_visible_type_annotations,
3653 runtime_visible_type_annotations_length,
3654 CHECK);
3655
3656 if (parsed_innerclasses_attribute || parsed_enclosingmethod_attribute) {
3657 const u2 num_of_classes = parse_classfile_inner_classes_attribute(
3658 cfs,
3659 cp,
3660 inner_classes_attribute_start,
3661 parsed_innerclasses_attribute,
3662 enclosing_method_class_index,
3663 enclosing_method_method_index,
3664 CHECK);
3665 if (parsed_innerclasses_attribute && _need_verify && _major_version >= JAVA_1_5_VERSION) {
3666 guarantee_property(
3667 inner_classes_attribute_length == sizeof(num_of_classes) + 4 * sizeof(u2) * num_of_classes,
3668 "Wrong InnerClasses attribute length in class file %s", CHECK);
3669 }
3670 }
3671
3672 if (parsed_nest_members_attribute) {
3673 const u2 num_of_classes = parse_classfile_nest_members_attribute(
3674 cfs,
3675 nest_members_attribute_start,
3676 CHECK);
3677 if (_need_verify) {
3678 guarantee_property(
3679 nest_members_attribute_length == sizeof(num_of_classes) + sizeof(u2) * num_of_classes,
3680 "Wrong NestMembers attribute length in class file %s", CHECK);
3681 }
3682 }
3683
3684 if (parsed_record_attribute) {
3685 const unsigned int calculated_attr_length = parse_classfile_record_attribute(
3686 cfs,
3687 cp,
3688 record_attribute_start,
3689 CHECK);
3690 if (_need_verify) {
3691 guarantee_property(record_attribute_length == calculated_attr_length,
3692 "Record attribute has wrong length in class file %s",
3693 CHECK);
3694 }
3695 }
3696
3697 if (parsed_permitted_subclasses_attribute) {
3698 const u2 num_subclasses = parse_classfile_permitted_subclasses_attribute(
3699 cfs,
3700 permitted_subclasses_attribute_start,
3701 CHECK);
3702 if (_need_verify) {
3703 guarantee_property(
3704 permitted_subclasses_attribute_length == sizeof(num_subclasses) + sizeof(u2) * num_subclasses,
3705 "Wrong PermittedSubclasses attribute length in class file %s", CHECK);
3706 }
3707 }
3708
3709 if (_max_bootstrap_specifier_index >= 0) {
3710 guarantee_property(parsed_bootstrap_methods_attribute,
3711 "Missing BootstrapMethods attribute in class file %s", CHECK);
3712 }
3713 }
3714
3715 void ClassFileParser::apply_parsed_class_attributes(InstanceKlass* k) {
3716 assert(k != nullptr, "invariant");
3717
3718 if (_synthetic_flag)
3719 k->set_is_synthetic();
3720 if (_sourcefile_index != 0) {
3721 k->set_source_file_name_index(_sourcefile_index);
3722 }
3723 if (_generic_signature_index != 0) {
3724 k->set_generic_signature_index(_generic_signature_index);
3725 }
3726 if (_sde_buffer != nullptr) {
3727 k->set_source_debug_extension(_sde_buffer, _sde_length);
3728 }
3729 }
3730
3731 // Create the Annotations object that will
3732 // hold the annotations array for the Klass.
3733 void ClassFileParser::create_combined_annotations(TRAPS) {
3734 if (_class_annotations == nullptr &&
3735 _class_type_annotations == nullptr &&
3736 _fields_annotations == nullptr &&
3737 _fields_type_annotations == nullptr) {
3738 // Don't create the Annotations object unnecessarily.
3739 return;
3740 }
3741
3742 Annotations* const annotations = Annotations::allocate(_loader_data, CHECK);
3743 annotations->set_class_annotations(_class_annotations);
3744 annotations->set_class_type_annotations(_class_type_annotations);
3745 annotations->set_fields_annotations(_fields_annotations);
3746 annotations->set_fields_type_annotations(_fields_type_annotations);
3747
3748 // This is the Annotations object that will be
3749 // assigned to InstanceKlass being constructed.
3750 _combined_annotations = annotations;
3751
3752 // The annotations arrays below has been transferred the
3753 // _combined_annotations so these fields can now be cleared.
3754 _class_annotations = nullptr;
3755 _class_type_annotations = nullptr;
3756 _fields_annotations = nullptr;
3757 _fields_type_annotations = nullptr;
3758 }
3759
3760 // Transfer ownership of metadata allocated to the InstanceKlass.
3761 void ClassFileParser::apply_parsed_class_metadata(
3762 InstanceKlass* this_klass,
3763 int java_fields_count) {
3764 assert(this_klass != nullptr, "invariant");
3765
3766 _cp->set_pool_holder(this_klass);
3767 this_klass->set_constants(_cp);
3768 this_klass->set_fieldinfo_stream(_fieldinfo_stream);
3769 this_klass->set_fieldinfo_search_table(_fieldinfo_search_table);
3770 this_klass->set_fields_status(_fields_status);
3771 this_klass->set_methods(_methods);
3772 this_klass->set_inner_classes(_inner_classes);
3773 this_klass->set_nest_members(_nest_members);
3774 this_klass->set_nest_host_index(_nest_host);
3775 this_klass->set_annotations(_combined_annotations);
3776 this_klass->set_permitted_subclasses(_permitted_subclasses);
3777 this_klass->set_record_components(_record_components);
3778
3779 DEBUG_ONLY(FieldInfoStream::validate_search_table(_cp, _fieldinfo_stream, _fieldinfo_search_table));
3780
3781 // Delay the setting of _local_interfaces and _transitive_interfaces until after
3782 // initialize_supers() in fill_instance_klass(). It is because the _local_interfaces could
3783 // be shared with _transitive_interfaces and _transitive_interfaces may be shared with
3784 // its _super. If an OOM occurs while loading the current klass, its _super field
3785 // may not have been set. When GC tries to free the klass, the _transitive_interfaces
3786 // may be deallocated mistakenly in InstanceKlass::deallocate_interfaces(). Subsequent
3787 // dereferences to the deallocated _transitive_interfaces will result in a crash.
3788
3789 // Clear out these fields so they don't get deallocated by the destructor
3790 clear_class_metadata();
3791 }
3792
3793 AnnotationArray* ClassFileParser::allocate_annotations(const u1* const anno,
3794 int anno_length,
3795 TRAPS) {
3796 AnnotationArray* annotations = nullptr;
3797 if (anno != nullptr) {
3798 annotations = MetadataFactory::new_array<u1>(_loader_data,
3799 anno_length,
3800 CHECK_(annotations));
3801 for (int i = 0; i < anno_length; i++) {
3802 annotations->at_put(i, anno[i]);
3803 }
3804 }
3805 return annotations;
3806 }
3807
3808 void ClassFileParser::check_super_class(ConstantPool* const cp,
3809 const int super_class_index,
3810 const bool need_verify,
3811 TRAPS) {
3812 assert(cp != nullptr, "invariant");
3813
3814 if (super_class_index == 0) {
3815 guarantee_property(_class_name == vmSymbols::java_lang_Object(),
3816 "Invalid superclass index %u in class file %s",
3817 super_class_index,
3818 CHECK);
3819 } else {
3820 guarantee_property(valid_klass_reference_at(super_class_index),
3821 "Invalid superclass index %u in class file %s",
3822 super_class_index,
3823 CHECK);
3824
3825 // The class name should be legal because it is checked when parsing constant pool.
3826 // However, make sure it is not an array type.
3827 if (need_verify) {
3828 guarantee_property(cp->klass_name_at(super_class_index)->char_at(0) != JVM_SIGNATURE_ARRAY,
3829 "Bad superclass name in class file %s", CHECK);
3830 }
3831 }
3832 }
3833
3834 OopMapBlocksBuilder::OopMapBlocksBuilder(unsigned int max_blocks) {
3835 _max_nonstatic_oop_maps = max_blocks;
3836 _nonstatic_oop_map_count = 0;
3837 if (max_blocks == 0) {
3838 _nonstatic_oop_maps = nullptr;
3839 } else {
3840 _nonstatic_oop_maps =
3841 NEW_RESOURCE_ARRAY(OopMapBlock, _max_nonstatic_oop_maps);
3842 memset(_nonstatic_oop_maps, 0, sizeof(OopMapBlock) * max_blocks);
3843 }
3844 }
3845
3846 OopMapBlock* OopMapBlocksBuilder::last_oop_map() const {
3847 assert(_nonstatic_oop_map_count > 0, "Has no oop maps");
3848 return _nonstatic_oop_maps + (_nonstatic_oop_map_count - 1);
3849 }
3850
3851 // addition of super oop maps
3852 void OopMapBlocksBuilder::initialize_inherited_blocks(OopMapBlock* blocks, unsigned int nof_blocks) {
3853 assert(nof_blocks && _nonstatic_oop_map_count == 0 &&
3854 nof_blocks <= _max_nonstatic_oop_maps, "invariant");
3855
3856 memcpy(_nonstatic_oop_maps, blocks, sizeof(OopMapBlock) * nof_blocks);
3857 _nonstatic_oop_map_count += nof_blocks;
3858 }
3859
3860 // collection of oops
3861 void OopMapBlocksBuilder::add(int offset, int count) {
3862 if (_nonstatic_oop_map_count == 0) {
3863 _nonstatic_oop_map_count++;
3864 }
3865 OopMapBlock* nonstatic_oop_map = last_oop_map();
3866 if (nonstatic_oop_map->count() == 0) { // Unused map, set it up
3867 nonstatic_oop_map->set_offset(offset);
3868 nonstatic_oop_map->set_count(count);
3869 } else if (nonstatic_oop_map->is_contiguous(offset)) { // contiguous, add
3870 nonstatic_oop_map->increment_count(count);
3871 } else { // Need a new one...
3872 _nonstatic_oop_map_count++;
3873 assert(_nonstatic_oop_map_count <= _max_nonstatic_oop_maps, "range check");
3874 nonstatic_oop_map = last_oop_map();
3875 nonstatic_oop_map->set_offset(offset);
3876 nonstatic_oop_map->set_count(count);
3877 }
3878 }
3879
3880 // general purpose copy, e.g. into allocated instanceKlass
3881 void OopMapBlocksBuilder::copy(OopMapBlock* dst) {
3882 if (_nonstatic_oop_map_count != 0) {
3883 memcpy(dst, _nonstatic_oop_maps, sizeof(OopMapBlock) * _nonstatic_oop_map_count);
3884 }
3885 }
3886
3887 // Sort and compact adjacent blocks
3888 void OopMapBlocksBuilder::compact() {
3889 if (_nonstatic_oop_map_count <= 1) {
3890 return;
3891 }
3892 /*
3893 * Since field layout sneaks in oops before values, we will be able to condense
3894 * blocks. There is potential to compact between super, own refs and values
3895 * containing refs.
3896 *
3897 * Currently compaction is slightly limited due to values being 8 byte aligned.
3898 * This may well change: FixMe if it doesn't, the code below is fairly general purpose
3899 * and maybe it doesn't need to be.
3900 */
3901 qsort(_nonstatic_oop_maps, _nonstatic_oop_map_count, sizeof(OopMapBlock),
3902 (_sort_Fn)OopMapBlock::compare_offset);
3903 if (_nonstatic_oop_map_count < 2) {
3904 return;
3905 }
3906
3907 // Make a temp copy, and iterate through and copy back into the original
3908 ResourceMark rm;
3909 OopMapBlock* oop_maps_copy =
3910 NEW_RESOURCE_ARRAY(OopMapBlock, _nonstatic_oop_map_count);
3911 OopMapBlock* oop_maps_copy_end = oop_maps_copy + _nonstatic_oop_map_count;
3912 copy(oop_maps_copy);
3913 OopMapBlock* nonstatic_oop_map = _nonstatic_oop_maps;
3914 unsigned int new_count = 1;
3915 oop_maps_copy++;
3916 while(oop_maps_copy < oop_maps_copy_end) {
3917 assert(nonstatic_oop_map->offset() < oop_maps_copy->offset(), "invariant");
3918 if (nonstatic_oop_map->is_contiguous(oop_maps_copy->offset())) {
3919 nonstatic_oop_map->increment_count(oop_maps_copy->count());
3920 } else {
3921 nonstatic_oop_map++;
3922 new_count++;
3923 nonstatic_oop_map->set_offset(oop_maps_copy->offset());
3924 nonstatic_oop_map->set_count(oop_maps_copy->count());
3925 }
3926 oop_maps_copy++;
3927 }
3928 assert(new_count <= _nonstatic_oop_map_count, "end up with more maps after compact() ?");
3929 _nonstatic_oop_map_count = new_count;
3930 }
3931
3932 void OopMapBlocksBuilder::print_on(outputStream* st) const {
3933 st->print_cr(" OopMapBlocks: %3d /%3d", _nonstatic_oop_map_count, _max_nonstatic_oop_maps);
3934 if (_nonstatic_oop_map_count > 0) {
3935 OopMapBlock* map = _nonstatic_oop_maps;
3936 OopMapBlock* last_map = last_oop_map();
3937 assert(map <= last_map, "Last less than first");
3938 while (map <= last_map) {
3939 st->print_cr(" Offset: %3d -%3d Count: %3d", map->offset(),
3940 map->offset() + map->offset_span() - heapOopSize, map->count());
3941 map++;
3942 }
3943 }
3944 }
3945
3946 void OopMapBlocksBuilder::print_value_on(outputStream* st) const {
3947 print_on(st);
3948 }
3949
3950 void ClassFileParser::set_precomputed_flags(InstanceKlass* ik) {
3951 assert(ik != nullptr, "invariant");
3952
3953 const InstanceKlass* const super = ik->super();
3954
3955 // Check if this klass has an empty finalize method (i.e. one with return bytecode only),
3956 // in which case we don't have to register objects as finalizable
3957 if (!_has_empty_finalizer) {
3958 if (_has_finalizer ||
3959 (super != nullptr && super->has_finalizer())) {
3960 ik->set_has_finalizer();
3961 }
3962 }
3963
3964 #ifdef ASSERT
3965 bool f = false;
3966 const Method* const m = ik->lookup_method(vmSymbols::finalize_method_name(),
3967 vmSymbols::void_method_signature());
3968 if (InstanceKlass::is_finalization_enabled() &&
3969 (m != nullptr) && !m->is_empty_method()) {
3970 f = true;
3971 }
3972
3973 // Spec doesn't prevent agent from redefinition of empty finalizer.
3974 // Despite the fact that it's generally bad idea and redefined finalizer
3975 // will not work as expected we shouldn't abort vm in this case
3976 if (!ik->has_redefined_this_or_super()) {
3977 assert(ik->has_finalizer() == f, "inconsistent has_finalizer");
3978 }
3979 #endif
3980
3981 // Check if this klass supports the java.lang.Cloneable interface
3982 if (vmClasses::Cloneable_klass_is_loaded()) {
3983 if (ik->is_subtype_of(vmClasses::Cloneable_klass())) {
3984 ik->set_is_cloneable();
3985 }
3986 }
3987
3988 // If it cannot be fast-path allocated, set a bit in the layout helper.
3989 // See documentation of InstanceKlass::can_be_fastpath_allocated().
3990 assert(ik->size_helper() > 0, "layout_helper is initialized");
3991 if (ik->is_abstract() || ik->is_interface()
3992 || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == nullptr)
3993 || ik->size_helper() >= FastAllocateSizeLimit) {
3994 // Forbid fast-path allocation.
3995 const jint lh = Klass::instance_layout_helper(ik->size_helper(), true);
3996 ik->set_layout_helper(lh);
3997 }
3998
3999 // Propagate the AOT runtimeSetup method discovery
4000 if (_has_aot_runtime_setup_method) {
4001 ik->set_is_runtime_setup_required();
4002 if (log_is_enabled(Info, aot, init)) {
4003 ResourceMark rm;
4004 log_info(aot, init)("Found @AOTRuntimeSetup class %s", ik->external_name());
4005 }
4006 }
4007 }
4008
4009 // utility methods for appending an array with check for duplicates
4010
4011 static void append_interfaces(GrowableArray<InstanceKlass*>* result,
4012 const Array<InstanceKlass*>* const ifs) {
4013 // iterate over new interfaces
4014 for (int i = 0; i < ifs->length(); i++) {
4015 InstanceKlass* const e = ifs->at(i);
4016 assert(e->is_klass() && e->is_interface(), "just checking");
4017 // add new interface
4018 result->append_if_missing(e);
4019 }
4020 }
4021
4022 static Array<InstanceKlass*>* compute_transitive_interfaces(const InstanceKlass* super,
4023 Array<InstanceKlass*>* local_ifs,
4024 ClassLoaderData* loader_data,
4025 TRAPS) {
4026 assert(local_ifs != nullptr, "invariant");
4027 assert(loader_data != nullptr, "invariant");
4028
4029 // Compute maximum size for transitive interfaces
4030 int max_transitive_size = 0;
4031 int super_size = 0;
4032 // Add superclass transitive interfaces size
4033 if (super != nullptr) {
4034 super_size = super->transitive_interfaces()->length();
4035 max_transitive_size += super_size;
4036 }
4037 // Add local interfaces' super interfaces
4038 const int local_size = local_ifs->length();
4039 for (int i = 0; i < local_size; i++) {
4040 InstanceKlass* const l = local_ifs->at(i);
4041 max_transitive_size += l->transitive_interfaces()->length();
4042 }
4043 // Finally add local interfaces
4044 max_transitive_size += local_size;
4045 // Construct array
4046 if (max_transitive_size == 0) {
4047 // no interfaces, use canonicalized array
4048 return Universe::the_empty_instance_klass_array();
4049 } else if (max_transitive_size == super_size) {
4050 // no new local interfaces added, share superklass' transitive interface array
4051 return super->transitive_interfaces();
4052 } else if (max_transitive_size == local_size) {
4053 // only local interfaces added, share local interface array
4054 return local_ifs;
4055 } else {
4056 ResourceMark rm;
4057 GrowableArray<InstanceKlass*>* const result = new GrowableArray<InstanceKlass*>(max_transitive_size);
4058
4059 // Copy down from superclass
4060 if (super != nullptr) {
4061 append_interfaces(result, super->transitive_interfaces());
4062 }
4063
4064 // Copy down from local interfaces' superinterfaces
4065 for (int i = 0; i < local_size; i++) {
4066 InstanceKlass* const l = local_ifs->at(i);
4067 append_interfaces(result, l->transitive_interfaces());
4068 }
4069 // Finally add local interfaces
4070 append_interfaces(result, local_ifs);
4071
4072 // length will be less than the max_transitive_size if duplicates were removed
4073 const int length = result->length();
4074 assert(length <= max_transitive_size, "just checking");
4075 Array<InstanceKlass*>* const new_result =
4076 MetadataFactory::new_array<InstanceKlass*>(loader_data, length, CHECK_NULL);
4077 for (int i = 0; i < length; i++) {
4078 InstanceKlass* const e = result->at(i);
4079 assert(e != nullptr, "just checking");
4080 new_result->at_put(i, e);
4081 }
4082 return new_result;
4083 }
4084 }
4085
4086 void ClassFileParser::check_super_class_access(const InstanceKlass* this_klass, TRAPS) {
4087 assert(this_klass != nullptr, "invariant");
4088 const InstanceKlass* const super = this_klass->super();
4089
4090 if (super != nullptr) {
4091 if (super->is_final()) {
4092 classfile_icce_error("class %s cannot inherit from final class %s", super, THREAD);
4093 return;
4094 }
4095
4096 if (super->is_sealed()) {
4097 stringStream ss;
4098 ResourceMark rm(THREAD);
4099 if (!super->has_as_permitted_subclass(this_klass, ss)) {
4100 classfile_icce_error(ss.as_string(), THREAD);
4101 return;
4102 }
4103 }
4104
4105 Reflection::VerifyClassAccessResults vca_result =
4106 Reflection::verify_class_access(this_klass, super, false);
4107 if (vca_result != Reflection::ACCESS_OK) {
4108 ResourceMark rm(THREAD);
4109 char* msg = Reflection::verify_class_access_msg(this_klass,
4110 super,
4111 vca_result);
4112
4113 // Names are all known to be < 64k so we know this formatted message is not excessively large.
4114 if (msg == nullptr) {
4115 bool same_module = (this_klass->module() == super->module());
4116 Exceptions::fthrow(
4117 THREAD_AND_LOCATION,
4118 vmSymbols::java_lang_IllegalAccessError(),
4119 "class %s cannot access its %ssuperclass %s (%s%s%s)",
4120 this_klass->external_name(),
4121 super->is_abstract() ? "abstract " : "",
4122 super->external_name(),
4123 (same_module) ? this_klass->joint_in_module_of_loader(super) : this_klass->class_in_module_of_loader(),
4124 (same_module) ? "" : "; ",
4125 (same_module) ? "" : super->class_in_module_of_loader());
4126 } else {
4127 // Add additional message content.
4128 Exceptions::fthrow(
4129 THREAD_AND_LOCATION,
4130 vmSymbols::java_lang_IllegalAccessError(),
4131 "superclass access check failed: %s",
4132 msg);
4133 }
4134 }
4135 }
4136 }
4137
4138
4139 void ClassFileParser::check_super_interface_access(const InstanceKlass* this_klass, TRAPS) {
4140 assert(this_klass != nullptr, "invariant");
4141 const Array<InstanceKlass*>* const local_interfaces = this_klass->local_interfaces();
4142 const int lng = local_interfaces->length();
4143 for (int i = lng - 1; i >= 0; i--) {
4144 InstanceKlass* const k = local_interfaces->at(i);
4145 assert (k != nullptr && k->is_interface(), "invalid interface");
4146
4147 if (k->is_sealed()) {
4148 stringStream ss;
4149 ResourceMark rm(THREAD);
4150 if (!k->has_as_permitted_subclass(this_klass, ss)) {
4151 classfile_icce_error(ss.as_string(), THREAD);
4152 return;
4153 }
4154 }
4155
4156 Reflection::VerifyClassAccessResults vca_result =
4157 Reflection::verify_class_access(this_klass, k, false);
4158 if (vca_result != Reflection::ACCESS_OK) {
4159 ResourceMark rm(THREAD);
4160 char* msg = Reflection::verify_class_access_msg(this_klass,
4161 k,
4162 vca_result);
4163
4164 // Names are all known to be < 64k so we know this formatted message is not excessively large.
4165 if (msg == nullptr) {
4166 bool same_module = (this_klass->module() == k->module());
4167 Exceptions::fthrow(
4168 THREAD_AND_LOCATION,
4169 vmSymbols::java_lang_IllegalAccessError(),
4170 "class %s cannot access its superinterface %s (%s%s%s)",
4171 this_klass->external_name(),
4172 k->external_name(),
4173 (same_module) ? this_klass->joint_in_module_of_loader(k) : this_klass->class_in_module_of_loader(),
4174 (same_module) ? "" : "; ",
4175 (same_module) ? "" : k->class_in_module_of_loader());
4176 return;
4177 } else {
4178 // Add additional message content.
4179 Exceptions::fthrow(
4180 THREAD_AND_LOCATION,
4181 vmSymbols::java_lang_IllegalAccessError(),
4182 "superinterface check failed: %s",
4183 msg);
4184 return;
4185 }
4186 }
4187 }
4188 }
4189
4190
4191 static void check_final_method_override(const InstanceKlass* this_klass, TRAPS) {
4192 assert(this_klass != nullptr, "invariant");
4193 const Array<Method*>* const methods = this_klass->methods();
4194 const int num_methods = methods->length();
4195
4196 // go thru each method and check if it overrides a final method
4197 for (int index = 0; index < num_methods; index++) {
4198 const Method* const m = methods->at(index);
4199
4200 // skip private, static, and <init> methods
4201 if ((!m->is_private() && !m->is_static()) &&
4202 (m->name() != vmSymbols::object_initializer_name())) {
4203
4204 const Symbol* const name = m->name();
4205 const Symbol* const signature = m->signature();
4206 const InstanceKlass* k = this_klass->super();
4207 const Method* super_m = nullptr;
4208 while (k != nullptr) {
4209 // skip supers that don't have final methods.
4210 if (k->has_final_method()) {
4211 // lookup a matching method in the super class hierarchy
4212 super_m = k->lookup_method(name, signature);
4213 if (super_m == nullptr) {
4214 break; // didn't find any match; get out
4215 }
4216
4217 if (super_m->is_final() && !super_m->is_static() &&
4218 !super_m->access_flags().is_private()) {
4219 // matching method in super is final, and not static or private
4220 bool can_access = Reflection::verify_member_access(this_klass,
4221 super_m->method_holder(),
4222 super_m->method_holder(),
4223 super_m->access_flags(),
4224 false, false, CHECK);
4225 if (can_access) {
4226 // this class can access super final method and therefore override
4227 ResourceMark rm(THREAD);
4228 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
4229 err_msg("class %s overrides final method %s.%s%s",
4230 this_klass->external_name(),
4231 super_m->method_holder()->external_name(),
4232 name->as_C_string(),
4233 signature->as_C_string()));
4234 }
4235 }
4236
4237 // continue to look from super_m's holder's super.
4238 k = super_m->method_holder()->super();
4239 continue;
4240 }
4241
4242 k = k->super();
4243 }
4244 }
4245 }
4246 }
4247
4248
4249 // assumes that this_klass is an interface
4250 static void check_illegal_static_method(const InstanceKlass* this_klass, TRAPS) {
4251 assert(this_klass != nullptr, "invariant");
4252 assert(this_klass->is_interface(), "not an interface");
4253 const Array<Method*>* methods = this_klass->methods();
4254 const int num_methods = methods->length();
4255
4256 for (int index = 0; index < num_methods; index++) {
4257 const Method* const m = methods->at(index);
4258 // if m is static and not the init method, throw a verify error
4259 if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) {
4260 ResourceMark rm(THREAD);
4261
4262 // Names are all known to be < 64k so we know this formatted message is not excessively large.
4263 Exceptions::fthrow(
4264 THREAD_AND_LOCATION,
4265 vmSymbols::java_lang_VerifyError(),
4266 "Illegal static method %s in interface %s",
4267 m->name()->as_C_string(),
4268 this_klass->external_name()
4269 );
4270 return;
4271 }
4272 }
4273 }
4274
4275 // utility methods for format checking
4276
4277 // Verify the class modifiers for the current class, or an inner class if inner_name is non-null.
4278 void ClassFileParser::verify_legal_class_modifiers(jint flags, Symbol* inner_name, bool is_anonymous_inner_class, TRAPS) const {
4279 const bool is_module = (flags & JVM_ACC_MODULE) != 0;
4280 assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");
4281 if (is_module) {
4282 ResourceMark rm(THREAD);
4283 // Names are all known to be < 64k so we know this formatted message is not excessively large.
4284 Exceptions::fthrow(
4285 THREAD_AND_LOCATION,
4286 vmSymbols::java_lang_NoClassDefFoundError(),
4287 "%s is not a class because access_flag ACC_MODULE is set",
4288 _class_name->as_C_string());
4289 return;
4290 }
4291
4292 if (!_need_verify) { return; }
4293
4294 const bool is_interface = (flags & JVM_ACC_INTERFACE) != 0;
4295 const bool is_abstract = (flags & JVM_ACC_ABSTRACT) != 0;
4296 const bool is_final = (flags & JVM_ACC_FINAL) != 0;
4297 const bool is_super = (flags & JVM_ACC_SUPER) != 0;
4298 const bool is_enum = (flags & JVM_ACC_ENUM) != 0;
4299 const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4300 const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4301
4302 if ((is_abstract && is_final) ||
4303 (is_interface && !is_abstract) ||
4304 (is_interface && major_gte_1_5 && (is_super || is_enum)) ||
4305 (!is_interface && major_gte_1_5 && is_annotation)) {
4306 ResourceMark rm(THREAD);
4307 // Names are all known to be < 64k so we know this formatted message is not excessively large.
4308 if (inner_name == nullptr && !is_anonymous_inner_class) {
4309 Exceptions::fthrow(
4310 THREAD_AND_LOCATION,
4311 vmSymbols::java_lang_ClassFormatError(),
4312 "Illegal class modifiers in class %s: 0x%X",
4313 _class_name->as_C_string(), flags
4314 );
4315 } else {
4316 if (is_anonymous_inner_class) {
4317 Exceptions::fthrow(
4318 THREAD_AND_LOCATION,
4319 vmSymbols::java_lang_ClassFormatError(),
4320 "Illegal class modifiers in anonymous inner class of class %s: 0x%X",
4321 _class_name->as_C_string(), flags
4322 );
4323 } else {
4324 Exceptions::fthrow(
4325 THREAD_AND_LOCATION,
4326 vmSymbols::java_lang_ClassFormatError(),
4327 "Illegal class modifiers in inner class %s of class %s: 0x%X",
4328 inner_name->as_C_string(), _class_name->as_C_string(), flags
4329 );
4330 }
4331 }
4332 return;
4333 }
4334 }
4335
4336 static bool has_illegal_visibility(jint flags) {
4337 const bool is_public = (flags & JVM_ACC_PUBLIC) != 0;
4338 const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4339 const bool is_private = (flags & JVM_ACC_PRIVATE) != 0;
4340
4341 return ((is_public && is_protected) ||
4342 (is_public && is_private) ||
4343 (is_protected && is_private));
4344 }
4345
4346 // A legal major_version.minor_version must be one of the following:
4347 //
4348 // Major_version >= 45 and major_version < 56, any minor_version.
4349 // Major_version >= 56 and major_version <= JVM_CLASSFILE_MAJOR_VERSION and minor_version = 0.
4350 // Major_version = JVM_CLASSFILE_MAJOR_VERSION and minor_version = 65535 and --enable-preview is present.
4351 //
4352 void ClassFileParser::verify_class_version(u2 major, u2 minor, Symbol* class_name, TRAPS){
4353 ResourceMark rm(THREAD);
4354 const u2 max_version = JVM_CLASSFILE_MAJOR_VERSION;
4355 if (major < JAVA_MIN_SUPPORTED_VERSION) {
4356 classfile_ucve_error("%s (class file version %u.%u) was compiled with an invalid major version",
4357 class_name, major, minor, THREAD);
4358 return;
4359 }
4360
4361 if (major > max_version) {
4362 // Names are all known to be < 64k so we know this formatted message is not excessively large.
4363 Exceptions::fthrow(
4364 THREAD_AND_LOCATION,
4365 vmSymbols::java_lang_UnsupportedClassVersionError(),
4366 "%s has been compiled by a more recent version of the Java Runtime (class file version %u.%u), "
4367 "this version of the Java Runtime only recognizes class file versions up to %u.0",
4368 class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION);
4369 return;
4370 }
4371
4372 if (major < JAVA_12_VERSION || minor == 0) {
4373 return;
4374 }
4375
4376 if (minor == JAVA_PREVIEW_MINOR_VERSION) {
4377 if (major != max_version) {
4378 // Names are all known to be < 64k so we know this formatted message is not excessively large.
4379 Exceptions::fthrow(
4380 THREAD_AND_LOCATION,
4381 vmSymbols::java_lang_UnsupportedClassVersionError(),
4382 "%s (class file version %u.%u) was compiled with preview features that are unsupported. "
4383 "This version of the Java Runtime only recognizes preview features for class file version %u.%u",
4384 class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION, JAVA_PREVIEW_MINOR_VERSION);
4385 return;
4386 }
4387
4388 if (!Arguments::enable_preview()) {
4389 classfile_ucve_error("Preview features are not enabled for %s (class file version %u.%u). Try running with '--enable-preview'",
4390 class_name, major, minor, THREAD);
4391 return;
4392 }
4393
4394 } else { // minor != JAVA_PREVIEW_MINOR_VERSION
4395 classfile_ucve_error("%s (class file version %u.%u) was compiled with an invalid non-zero minor version",
4396 class_name, major, minor, THREAD);
4397 }
4398 }
4399
4400 void ClassFileParser::verify_legal_field_modifiers(jint flags,
4401 bool is_interface,
4402 TRAPS) const {
4403 if (!_need_verify) { return; }
4404
4405 const bool is_public = (flags & JVM_ACC_PUBLIC) != 0;
4406 const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4407 const bool is_private = (flags & JVM_ACC_PRIVATE) != 0;
4408 const bool is_static = (flags & JVM_ACC_STATIC) != 0;
4409 const bool is_final = (flags & JVM_ACC_FINAL) != 0;
4410 const bool is_volatile = (flags & JVM_ACC_VOLATILE) != 0;
4411 const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
4412 const bool is_enum = (flags & JVM_ACC_ENUM) != 0;
4413 const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4414
4415 bool is_illegal = false;
4416
4417 if (is_interface) {
4418 if (!is_public || !is_static || !is_final || is_private ||
4419 is_protected || is_volatile || is_transient ||
4420 (major_gte_1_5 && is_enum)) {
4421 is_illegal = true;
4422 }
4423 } else { // not interface
4424 if (has_illegal_visibility(flags) || (is_final && is_volatile)) {
4425 is_illegal = true;
4426 }
4427 }
4428
4429 if (is_illegal) {
4430 ResourceMark rm(THREAD);
4431 // Names are all known to be < 64k so we know this formatted message is not excessively large.
4432 Exceptions::fthrow(
4433 THREAD_AND_LOCATION,
4434 vmSymbols::java_lang_ClassFormatError(),
4435 "Illegal field modifiers in class %s: 0x%X",
4436 _class_name->as_C_string(), flags);
4437 return;
4438 }
4439 }
4440
4441 void ClassFileParser::verify_legal_method_modifiers(jint flags,
4442 bool is_interface,
4443 const Symbol* name,
4444 TRAPS) const {
4445 if (!_need_verify) { return; }
4446
4447 const bool is_public = (flags & JVM_ACC_PUBLIC) != 0;
4448 const bool is_private = (flags & JVM_ACC_PRIVATE) != 0;
4449 const bool is_static = (flags & JVM_ACC_STATIC) != 0;
4450 const bool is_final = (flags & JVM_ACC_FINAL) != 0;
4451 const bool is_native = (flags & JVM_ACC_NATIVE) != 0;
4452 const bool is_abstract = (flags & JVM_ACC_ABSTRACT) != 0;
4453 const bool is_bridge = (flags & JVM_ACC_BRIDGE) != 0;
4454 const bool is_strict = (flags & JVM_ACC_STRICT) != 0;
4455 const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
4456 const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4457 const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4458 const bool major_gte_8 = _major_version >= JAVA_8_VERSION;
4459 const bool major_gte_17 = _major_version >= JAVA_17_VERSION;
4460 const bool is_initializer = (name == vmSymbols::object_initializer_name());
4461
4462 bool is_illegal = false;
4463
4464 if (is_interface) {
4465 if (major_gte_8) {
4466 // Class file version is JAVA_8_VERSION or later Methods of
4467 // interfaces may set any of the flags except ACC_PROTECTED,
4468 // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must
4469 // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.
4470 if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
4471 (is_native || is_protected || is_final || is_synchronized) ||
4472 // If a specific method of a class or interface has its
4473 // ACC_ABSTRACT flag set, it must not have any of its
4474 // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,
4475 // ACC_STRICT, or ACC_SYNCHRONIZED flags set. No need to
4476 // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as
4477 // those flags are illegal irrespective of ACC_ABSTRACT being set or not.
4478 (is_abstract && (is_private || is_static || (!major_gte_17 && is_strict)))) {
4479 is_illegal = true;
4480 }
4481 } else if (major_gte_1_5) {
4482 // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)
4483 if (!is_public || is_private || is_protected || is_static || is_final ||
4484 is_synchronized || is_native || !is_abstract || is_strict) {
4485 is_illegal = true;
4486 }
4487 } else {
4488 // Class file version is pre-JAVA_1_5_VERSION
4489 if (!is_public || is_static || is_final || is_native || !is_abstract) {
4490 is_illegal = true;
4491 }
4492 }
4493 } else { // not interface
4494 if (has_illegal_visibility(flags)) {
4495 is_illegal = true;
4496 } else {
4497 if (is_initializer) {
4498 if (is_static || is_final || is_synchronized || is_native ||
4499 is_abstract || (major_gte_1_5 && is_bridge)) {
4500 is_illegal = true;
4501 }
4502 } else { // not initializer
4503 if (is_abstract) {
4504 if ((is_final || is_native || is_private || is_static ||
4505 (major_gte_1_5 && (is_synchronized || (!major_gte_17 && is_strict))))) {
4506 is_illegal = true;
4507 }
4508 }
4509 }
4510 }
4511 }
4512
4513 if (is_illegal) {
4514 ResourceMark rm(THREAD);
4515 // Names are all known to be < 64k so we know this formatted message is not excessively large.
4516 Exceptions::fthrow(
4517 THREAD_AND_LOCATION,
4518 vmSymbols::java_lang_ClassFormatError(),
4519 "Method %s in class %s has illegal modifiers: 0x%X",
4520 name->as_C_string(), _class_name->as_C_string(), flags);
4521 return;
4522 }
4523 }
4524
4525 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer,
4526 int length,
4527 TRAPS) const {
4528 assert(_need_verify, "only called when _need_verify is true");
4529 // Note: 0 <= length < 64K, as it comes from a u2 entry in the CP.
4530 if (!UTF8::is_legal_utf8(buffer, static_cast<size_t>(length), _major_version <= 47)) {
4531 classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", THREAD);
4532 }
4533 }
4534
4535 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
4536 // In class names, '/' separates unqualified names. This is verified in this function also.
4537 // Method names also may not contain the characters '<' or '>', unless <init>
4538 // or <clinit>. Note that method names may not be <init> or <clinit> in this
4539 // method. Because these names have been checked as special cases before
4540 // calling this method in verify_legal_method_name.
4541 //
4542 // This method is also called from the modular system APIs in modules.cpp
4543 // to verify the validity of module and package names.
4544 bool ClassFileParser::verify_unqualified_name(const char* name,
4545 unsigned int length,
4546 int type) {
4547 if (length == 0) return false; // Must have at least one char.
4548 for (const char* p = name; p != name + length; p++) {
4549 switch(*p) {
4550 case JVM_SIGNATURE_DOT:
4551 case JVM_SIGNATURE_ENDCLASS:
4552 case JVM_SIGNATURE_ARRAY:
4553 // do not permit '.', ';', or '['
4554 return false;
4555 case JVM_SIGNATURE_SLASH:
4556 // check for '//' or leading or trailing '/' which are not legal
4557 // unqualified name must not be empty
4558 if (type == ClassFileParser::LegalClass) {
4559 if (p == name || p+1 >= name+length ||
4560 *(p+1) == JVM_SIGNATURE_SLASH) {
4561 return false;
4562 }
4563 } else {
4564 return false; // do not permit '/' unless it's class name
4565 }
4566 break;
4567 case JVM_SIGNATURE_SPECIAL:
4568 case JVM_SIGNATURE_ENDSPECIAL:
4569 // do not permit '<' or '>' in method names
4570 if (type == ClassFileParser::LegalMethod) {
4571 return false;
4572 }
4573 }
4574 }
4575 return true;
4576 }
4577
4578 // Take pointer to a UTF8 byte string (not NUL-terminated).
4579 // Skip over the longest part of the string that could
4580 // be taken as a fieldname. Allow non-trailing '/'s if slash_ok is true.
4581 // Return a pointer to just past the fieldname.
4582 // Return null if no fieldname at all was found, or in the case of slash_ok
4583 // being true, we saw consecutive slashes (meaning we were looking for a
4584 // qualified path but found something that was badly-formed).
4585 static const char* skip_over_field_name(const char* const name,
4586 bool slash_ok,
4587 unsigned int length) {
4588 const char* p;
4589 jboolean last_is_slash = false;
4590 jboolean not_first_ch = false;
4591
4592 for (p = name; p != name + length; not_first_ch = true) {
4593 const char* old_p = p;
4594 jchar ch = *p;
4595 if (ch < 128) {
4596 p++;
4597 // quick check for ascii
4598 if ((ch >= 'a' && ch <= 'z') ||
4599 (ch >= 'A' && ch <= 'Z') ||
4600 (ch == '_' || ch == '$') ||
4601 (not_first_ch && ch >= '0' && ch <= '9')) {
4602 last_is_slash = false;
4603 continue;
4604 }
4605 if (slash_ok && ch == JVM_SIGNATURE_SLASH) {
4606 if (last_is_slash) {
4607 return nullptr; // Don't permit consecutive slashes
4608 }
4609 last_is_slash = true;
4610 continue;
4611 }
4612 }
4613 else {
4614 jint unicode_ch;
4615 char* tmp_p = UTF8::next_character(p, &unicode_ch);
4616 p = tmp_p;
4617 last_is_slash = false;
4618 // Check if ch is Java identifier start or is Java identifier part
4619 // 4672820: call java.lang.Character methods directly without generating separate tables.
4620 EXCEPTION_MARK;
4621 // return value
4622 JavaValue result(T_BOOLEAN);
4623 // Set up the arguments to isJavaIdentifierStart or isJavaIdentifierPart
4624 JavaCallArguments args;
4625 args.push_int(unicode_ch);
4626
4627 if (not_first_ch) {
4628 // public static boolean isJavaIdentifierPart(char ch);
4629 JavaCalls::call_static(&result,
4630 vmClasses::Character_klass(),
4631 vmSymbols::isJavaIdentifierPart_name(),
4632 vmSymbols::int_bool_signature(),
4633 &args,
4634 THREAD);
4635 } else {
4636 // public static boolean isJavaIdentifierStart(char ch);
4637 JavaCalls::call_static(&result,
4638 vmClasses::Character_klass(),
4639 vmSymbols::isJavaIdentifierStart_name(),
4640 vmSymbols::int_bool_signature(),
4641 &args,
4642 THREAD);
4643 }
4644 if (HAS_PENDING_EXCEPTION) {
4645 CLEAR_PENDING_EXCEPTION;
4646 return nullptr;
4647 }
4648 if(result.get_jboolean()) {
4649 continue;
4650 }
4651 }
4652 return (not_first_ch) ? old_p : nullptr;
4653 }
4654 return (not_first_ch && !last_is_slash) ? p : nullptr;
4655 }
4656
4657 // Take pointer to a UTF8 byte string (not NUL-terminated).
4658 // Skip over the longest part of the string that could
4659 // be taken as a field signature. Allow "void" if void_ok.
4660 // Return a pointer to just past the signature.
4661 // Return null if no legal signature is found.
4662 const char* ClassFileParser::skip_over_field_signature(const char* signature,
4663 bool void_ok,
4664 unsigned int length,
4665 TRAPS) const {
4666 unsigned int array_dim = 0;
4667 while (length > 0) {
4668 switch (signature[0]) {
4669 case JVM_SIGNATURE_VOID: if (!void_ok) { return nullptr; }
4670 case JVM_SIGNATURE_BOOLEAN:
4671 case JVM_SIGNATURE_BYTE:
4672 case JVM_SIGNATURE_CHAR:
4673 case JVM_SIGNATURE_SHORT:
4674 case JVM_SIGNATURE_INT:
4675 case JVM_SIGNATURE_FLOAT:
4676 case JVM_SIGNATURE_LONG:
4677 case JVM_SIGNATURE_DOUBLE:
4678 return signature + 1;
4679 case JVM_SIGNATURE_CLASS: {
4680 if (_major_version < JAVA_1_5_VERSION) {
4681 signature++;
4682 length--;
4683 // Skip over the class name if one is there
4684 const char* const p = skip_over_field_name(signature, true, length);
4685 assert(p == nullptr || p > signature, "must parse one character at least");
4686 // The next character better be a semicolon
4687 if (p != nullptr && // Parse of field name succeeded.
4688 p - signature < static_cast<int>(length) && // There is at least one character left to parse.
4689 p[0] == JVM_SIGNATURE_ENDCLASS) {
4690 return p + 1;
4691 }
4692 }
4693 else {
4694 // Skip leading 'L' and ignore first appearance of ';'
4695 signature++;
4696 const char* c = (const char*) memchr(signature, JVM_SIGNATURE_ENDCLASS, length - 1);
4697 // Format check signature
4698 if (c != nullptr) {
4699 int newlen = pointer_delta_as_int(c, (char*) signature);
4700 bool legal = verify_unqualified_name(signature, newlen, LegalClass);
4701 if (!legal) {
4702 classfile_parse_error("Class name is empty or contains illegal character "
4703 "in descriptor in class file %s",
4704 THREAD);
4705 return nullptr;
4706 }
4707 return signature + newlen + 1;
4708 }
4709 }
4710 return nullptr;
4711 }
4712 case JVM_SIGNATURE_ARRAY:
4713 array_dim++;
4714 if (array_dim > 255) {
4715 // 4277370: array descriptor is valid only if it represents 255 or fewer dimensions.
4716 classfile_parse_error("Array type descriptor has more than 255 dimensions in class file %s", THREAD);
4717 return nullptr;
4718 }
4719 // The rest of what's there better be a legal signature
4720 signature++;
4721 length--;
4722 void_ok = false;
4723 break;
4724 default:
4725 return nullptr;
4726 }
4727 }
4728 return nullptr;
4729 }
4730
4731 // Checks if name is a legal class name.
4732 void ClassFileParser::verify_legal_class_name(const Symbol* name, TRAPS) const {
4733 if (!_need_verify) { return; }
4734
4735 assert(name->refcount() > 0, "symbol must be kept alive");
4736 char* bytes = (char*)name->bytes();
4737 unsigned int length = name->utf8_length();
4738 bool legal = false;
4739
4740 if (length > 0) {
4741 const char* p;
4742 if (bytes[0] == JVM_SIGNATURE_ARRAY) {
4743 p = skip_over_field_signature(bytes, false, length, CHECK);
4744 legal = (p != nullptr) && ((p - bytes) == (int)length);
4745 } else if (_major_version < JAVA_1_5_VERSION) {
4746 if (bytes[0] != JVM_SIGNATURE_SPECIAL) {
4747 p = skip_over_field_name(bytes, true, length);
4748 legal = (p != nullptr) && ((p - bytes) == (int)length);
4749 }
4750 } else {
4751 // 4900761: relax the constraints based on JSR202 spec
4752 // Class names may be drawn from the entire Unicode character set.
4753 // Identifiers between '/' must be unqualified names.
4754 // The utf8 string has been verified when parsing cpool entries.
4755 legal = verify_unqualified_name(bytes, length, LegalClass);
4756 }
4757 }
4758 if (!legal) {
4759 ResourceMark rm(THREAD);
4760 assert(_class_name != nullptr, "invariant");
4761 // Names are all known to be < 64k so we know this formatted message is not excessively large.
4762 Exceptions::fthrow(
4763 THREAD_AND_LOCATION,
4764 vmSymbols::java_lang_ClassFormatError(),
4765 "Illegal class name \"%.*s\" in class file %s", length, bytes,
4766 _class_name->as_C_string()
4767 );
4768 return;
4769 }
4770 }
4771
4772 // Checks if name is a legal field name.
4773 void ClassFileParser::verify_legal_field_name(const Symbol* name, TRAPS) const {
4774 if (!_need_verify) { return; }
4775
4776 char* bytes = (char*)name->bytes();
4777 unsigned int length = name->utf8_length();
4778 bool legal = false;
4779
4780 if (length > 0) {
4781 if (_major_version < JAVA_1_5_VERSION) {
4782 if (bytes[0] != JVM_SIGNATURE_SPECIAL) {
4783 const char* p = skip_over_field_name(bytes, false, length);
4784 legal = (p != nullptr) && ((p - bytes) == (int)length);
4785 }
4786 } else {
4787 // 4881221: relax the constraints based on JSR202 spec
4788 legal = verify_unqualified_name(bytes, length, LegalField);
4789 }
4790 }
4791
4792 if (!legal) {
4793 ResourceMark rm(THREAD);
4794 assert(_class_name != nullptr, "invariant");
4795 // Names are all known to be < 64k so we know this formatted message is not excessively large.
4796 Exceptions::fthrow(
4797 THREAD_AND_LOCATION,
4798 vmSymbols::java_lang_ClassFormatError(),
4799 "Illegal field name \"%.*s\" in class %s", length, bytes,
4800 _class_name->as_C_string()
4801 );
4802 return;
4803 }
4804 }
4805
4806 // Checks if name is a legal method name.
4807 void ClassFileParser::verify_legal_method_name(const Symbol* name, TRAPS) const {
4808 if (!_need_verify) { return; }
4809
4810 assert(name != nullptr, "method name is null");
4811 char* bytes = (char*)name->bytes();
4812 unsigned int length = name->utf8_length();
4813 bool legal = false;
4814
4815 if (length > 0) {
4816 if (bytes[0] == JVM_SIGNATURE_SPECIAL) {
4817 if (name == vmSymbols::object_initializer_name() || name == vmSymbols::class_initializer_name()) {
4818 legal = true;
4819 }
4820 } else if (_major_version < JAVA_1_5_VERSION) {
4821 const char* p;
4822 p = skip_over_field_name(bytes, false, length);
4823 legal = (p != nullptr) && ((p - bytes) == (int)length);
4824 } else {
4825 // 4881221: relax the constraints based on JSR202 spec
4826 legal = verify_unqualified_name(bytes, length, LegalMethod);
4827 }
4828 }
4829
4830 if (!legal) {
4831 ResourceMark rm(THREAD);
4832 assert(_class_name != nullptr, "invariant");
4833 // Names are all known to be < 64k so we know this formatted message is not excessively large.
4834 Exceptions::fthrow(
4835 THREAD_AND_LOCATION,
4836 vmSymbols::java_lang_ClassFormatError(),
4837 "Illegal method name \"%.*s\" in class %s", length, bytes,
4838 _class_name->as_C_string()
4839 );
4840 return;
4841 }
4842 }
4843
4844
4845 // Checks if signature is a legal field signature.
4846 void ClassFileParser::verify_legal_field_signature(const Symbol* name,
4847 const Symbol* signature,
4848 TRAPS) const {
4849 if (!_need_verify) { return; }
4850
4851 const char* const bytes = (const char*)signature->bytes();
4852 const unsigned int length = signature->utf8_length();
4853 const char* const p = skip_over_field_signature(bytes, false, length, CHECK);
4854
4855 if (p == nullptr || (p - bytes) != (int)length) {
4856 throwIllegalSignature("Field", name, signature, CHECK);
4857 }
4858 }
4859
4860 // Check that the signature is compatible with the method name. For example,
4861 // check that <init> has a void signature.
4862 void ClassFileParser::verify_legal_name_with_signature(const Symbol* name,
4863 const Symbol* signature,
4864 TRAPS) const {
4865 if (!_need_verify) {
4866 return;
4867 }
4868
4869 // Class initializers cannot have args for class format version >= 51.
4870 if (name == vmSymbols::class_initializer_name() &&
4871 signature != vmSymbols::void_method_signature() &&
4872 _major_version >= JAVA_7_VERSION) {
4873 throwIllegalSignature("Method", name, signature, THREAD);
4874 return;
4875 }
4876
4877 int sig_length = signature->utf8_length();
4878 if (name->utf8_length() > 0 &&
4879 name->char_at(0) == JVM_SIGNATURE_SPECIAL &&
4880 sig_length > 0 &&
4881 signature->char_at(sig_length - 1) != JVM_SIGNATURE_VOID) {
4882 throwIllegalSignature("Method", name, signature, THREAD);
4883 }
4884 }
4885
4886 // Checks if signature is a legal method signature.
4887 // Returns number of parameters
4888 int ClassFileParser::verify_legal_method_signature(const Symbol* name,
4889 const Symbol* signature,
4890 TRAPS) const {
4891 if (!_need_verify) {
4892 // make sure caller's args_size will be less than 0 even for non-static
4893 // method so it will be recomputed in compute_size_of_parameters().
4894 return -2;
4895 }
4896
4897 unsigned int args_size = 0;
4898 const char* p = (const char*)signature->bytes();
4899 unsigned int length = signature->utf8_length();
4900 const char* nextp;
4901
4902 // The first character must be a '('
4903 if ((length > 0) && (*p++ == JVM_SIGNATURE_FUNC)) {
4904 length--;
4905 // Skip over legal field signatures
4906 nextp = skip_over_field_signature(p, false, length, CHECK_0);
4907 while ((length > 0) && (nextp != nullptr)) {
4908 args_size++;
4909 if (p[0] == 'J' || p[0] == 'D') {
4910 args_size++;
4911 }
4912 length -= pointer_delta_as_int(nextp, p);
4913 p = nextp;
4914 nextp = skip_over_field_signature(p, false, length, CHECK_0);
4915 }
4916 // The first non-signature thing better be a ')'
4917 if ((length > 0) && (*p++ == JVM_SIGNATURE_ENDFUNC)) {
4918 length--;
4919 // Now we better just have a return value
4920 nextp = skip_over_field_signature(p, true, length, CHECK_0);
4921 if (nextp && ((int)length == (nextp - p))) {
4922 return args_size;
4923 }
4924 }
4925 }
4926 // Report error
4927 throwIllegalSignature("Method", name, signature, THREAD);
4928 return 0;
4929 }
4930
4931 int ClassFileParser::static_field_size() const {
4932 assert(_field_info != nullptr, "invariant");
4933 return _field_info->_static_field_size;
4934 }
4935
4936 int ClassFileParser::total_oop_map_count() const {
4937 assert(_field_info != nullptr, "invariant");
4938 return _field_info->oop_map_blocks->_nonstatic_oop_map_count;
4939 }
4940
4941 jint ClassFileParser::layout_size() const {
4942 assert(_field_info != nullptr, "invariant");
4943 return _field_info->_instance_size;
4944 }
4945
4946 static void check_methods_for_intrinsics(const InstanceKlass* ik,
4947 const Array<Method*>* methods) {
4948 assert(ik != nullptr, "invariant");
4949 assert(methods != nullptr, "invariant");
4950
4951 // Set up Method*::intrinsic_id as soon as we know the names of methods.
4952 // (We used to do this lazily, but now we query it in Rewriter,
4953 // which is eagerly done for every method, so we might as well do it now,
4954 // when everything is fresh in memory.)
4955 const vmSymbolID klass_id = Method::klass_id_for_intrinsics(ik);
4956
4957 if (klass_id != vmSymbolID::NO_SID) {
4958 for (int j = 0; j < methods->length(); ++j) {
4959 Method* method = methods->at(j);
4960 method->init_intrinsic_id(klass_id);
4961
4962 if (CheckIntrinsics) {
4963 // Check if an intrinsic is defined for method 'method',
4964 // but the method is not annotated with @IntrinsicCandidate.
4965 if (method->intrinsic_id() != vmIntrinsics::_none &&
4966 !method->intrinsic_candidate()) {
4967 tty->print("Compiler intrinsic is defined for method [%s], "
4968 "but the method is not annotated with @IntrinsicCandidate.%s",
4969 method->name_and_sig_as_C_string(),
4970 NOT_DEBUG(" Method will not be inlined.") DEBUG_ONLY(" Exiting.")
4971 );
4972 tty->cr();
4973 DEBUG_ONLY(vm_exit(1));
4974 }
4975 // Check is the method 'method' is annotated with @IntrinsicCandidate,
4976 // but there is no intrinsic available for it.
4977 if (method->intrinsic_candidate() &&
4978 method->intrinsic_id() == vmIntrinsics::_none) {
4979 tty->print("Method [%s] is annotated with @IntrinsicCandidate, "
4980 "but no compiler intrinsic is defined for the method.%s",
4981 method->name_and_sig_as_C_string(),
4982 NOT_DEBUG("") DEBUG_ONLY(" Exiting.")
4983 );
4984 tty->cr();
4985 DEBUG_ONLY(vm_exit(1));
4986 }
4987 }
4988 } // end for
4989
4990 #ifdef ASSERT
4991 if (CheckIntrinsics) {
4992 // Check for orphan methods in the current class. A method m
4993 // of a class C is orphan if an intrinsic is defined for method m,
4994 // but class C does not declare m.
4995 // The check is potentially expensive, therefore it is available
4996 // only in debug builds.
4997
4998 for (auto id : EnumRange<vmIntrinsicID>{}) {
4999 if (vmIntrinsics::_compiledLambdaForm == id) {
5000 // The _compiledLamdbdaForm intrinsic is a special marker for bytecode
5001 // generated for the JVM from a LambdaForm and therefore no method
5002 // is defined for it.
5003 continue;
5004 }
5005 if (vmIntrinsics::_blackhole == id) {
5006 // The _blackhole intrinsic is a special marker. No explicit method
5007 // is defined for it.
5008 continue;
5009 }
5010
5011 if (vmIntrinsics::class_for(id) == klass_id) {
5012 // Check if the current class contains a method with the same
5013 // name, flags, signature.
5014 bool match = false;
5015 for (int j = 0; j < methods->length(); ++j) {
5016 const Method* method = methods->at(j);
5017 if (method->intrinsic_id() == id) {
5018 match = true;
5019 break;
5020 }
5021 }
5022
5023 if (!match) {
5024 char buf[1000];
5025 tty->print("Compiler intrinsic is defined for method [%s], "
5026 "but the method is not available in class [%s].%s",
5027 vmIntrinsics::short_name_as_C_string(id, buf, sizeof(buf)),
5028 ik->name()->as_C_string(),
5029 NOT_DEBUG("") DEBUG_ONLY(" Exiting.")
5030 );
5031 tty->cr();
5032 DEBUG_ONLY(vm_exit(1));
5033 }
5034 }
5035 } // end for
5036 } // CheckIntrinsics
5037 #endif // ASSERT
5038 }
5039 }
5040
5041 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook,
5042 const ClassInstanceInfo& cl_inst_info,
5043 TRAPS) {
5044 if (_klass != nullptr) {
5045 return _klass;
5046 }
5047
5048 InstanceKlass* const ik =
5049 InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
5050
5051 if (is_hidden()) {
5052 mangle_hidden_class_name(ik);
5053 }
5054
5055 fill_instance_klass(ik, changed_by_loadhook, cl_inst_info, CHECK_NULL);
5056
5057 assert(_klass == ik, "invariant");
5058
5059 return ik;
5060 }
5061
5062 void ClassFileParser::fill_instance_klass(InstanceKlass* ik,
5063 bool changed_by_loadhook,
5064 const ClassInstanceInfo& cl_inst_info,
5065 TRAPS) {
5066 assert(ik != nullptr, "invariant");
5067
5068 // Set name and CLD before adding to CLD
5069 ik->set_class_loader_data(_loader_data);
5070 ik->set_class_loader_type();
5071 ik->set_name(_class_name);
5072
5073 // Add all classes to our internal class loader list here,
5074 // including classes in the bootstrap (null) class loader.
5075 const bool publicize = !is_internal();
5076
5077 _loader_data->add_class(ik, publicize);
5078
5079 set_klass_to_deallocate(ik);
5080
5081 assert(_field_info != nullptr, "invariant");
5082 assert(ik->static_field_size() == _field_info->_static_field_size, "sanity");
5083 assert(ik->nonstatic_oop_map_count() == _field_info->oop_map_blocks->_nonstatic_oop_map_count,
5084 "sanity");
5085
5086 assert(ik->is_instance_klass(), "sanity");
5087 assert(ik->size_helper() == _field_info->_instance_size, "sanity");
5088
5089 // Fill in information already parsed
5090 ik->set_should_verify_class(_need_verify);
5091
5092 // Not yet: supers are done below to support the new subtype-checking fields
5093 ik->set_nonstatic_field_size(_field_info->_nonstatic_field_size);
5094 ik->set_has_nonstatic_fields(_field_info->_has_nonstatic_fields);
5095 ik->set_static_oop_field_count(_static_oop_count);
5096
5097 // this transfers ownership of a lot of arrays from
5098 // the parser onto the InstanceKlass*
5099 apply_parsed_class_metadata(ik, _java_fields_count);
5100
5101 // can only set dynamic nest-host after static nest information is set
5102 if (cl_inst_info.dynamic_nest_host() != nullptr) {
5103 ik->set_nest_host(cl_inst_info.dynamic_nest_host());
5104 }
5105
5106 // note that is not safe to use the fields in the parser from this point on
5107 assert(nullptr == _cp, "invariant");
5108 assert(nullptr == _fieldinfo_stream, "invariant");
5109 assert(nullptr == _fieldinfo_search_table, "invariant");
5110 assert(nullptr == _fields_status, "invariant");
5111 assert(nullptr == _methods, "invariant");
5112 assert(nullptr == _inner_classes, "invariant");
5113 assert(nullptr == _nest_members, "invariant");
5114 assert(nullptr == _combined_annotations, "invariant");
5115 assert(nullptr == _record_components, "invariant");
5116 assert(nullptr == _permitted_subclasses, "invariant");
5117
5118 if (_has_localvariable_table) {
5119 ik->set_has_localvariable_table(true);
5120 }
5121
5122 if (_has_final_method) {
5123 ik->set_has_final_method();
5124 }
5125
5126 ik->copy_method_ordering(_method_ordering, CHECK);
5127 // The InstanceKlass::_methods_jmethod_ids cache
5128 // is managed on the assumption that the initial cache
5129 // size is equal to the number of methods in the class. If
5130 // that changes, then InstanceKlass::idnum_can_increment()
5131 // has to be changed accordingly.
5132 ik->set_initial_method_idnum(checked_cast<u2>(ik->methods()->length()));
5133
5134 ik->set_this_class_index(_this_class_index);
5135
5136 if (_is_hidden) {
5137 // _this_class_index is a CONSTANT_Class entry that refers to this
5138 // hidden class itself. If this class needs to refer to its own methods
5139 // or fields, it would use a CONSTANT_MethodRef, etc, which would reference
5140 // _this_class_index. However, because this class is hidden (it's
5141 // not stored in SystemDictionary), _this_class_index cannot be resolved
5142 // with ConstantPool::klass_at_impl, which does a SystemDictionary lookup.
5143 // Therefore, we must eagerly resolve _this_class_index now.
5144 ik->constants()->klass_at_put(_this_class_index, ik);
5145 }
5146
5147 ik->set_minor_version(_minor_version);
5148 ik->set_major_version(_major_version);
5149 ik->set_has_nonstatic_concrete_methods(_has_nonstatic_concrete_methods);
5150 ik->set_declares_nonstatic_concrete_methods(_declares_nonstatic_concrete_methods);
5151
5152 assert(!_is_hidden || ik->is_hidden(), "must be set already");
5153
5154 // Set PackageEntry for this_klass
5155 oop cl = ik->class_loader();
5156 Handle clh = Handle(THREAD, cl);
5157 ClassLoaderData* cld = ClassLoaderData::class_loader_data_or_null(clh());
5158 ik->set_package(cld, nullptr, CHECK);
5159
5160 const Array<Method*>* const methods = ik->methods();
5161 assert(methods != nullptr, "invariant");
5162 const int methods_len = methods->length();
5163
5164 check_methods_for_intrinsics(ik, methods);
5165
5166 // Fill in field values obtained by parse_classfile_attributes
5167 if (_parsed_annotations->has_any_annotations())
5168 _parsed_annotations->apply_to(ik);
5169
5170 apply_parsed_class_attributes(ik);
5171
5172 // Miranda methods
5173 if ((_num_miranda_methods > 0) ||
5174 // if this class introduced new miranda methods or
5175 (_super_klass != nullptr && _super_klass->has_miranda_methods())
5176 // super class exists and this class inherited miranda methods
5177 ) {
5178 ik->set_has_miranda_methods(); // then set a flag
5179 }
5180
5181 // Fill in information needed to compute superclasses.
5182 ik->initialize_supers(const_cast<InstanceKlass*>(_super_klass), _transitive_interfaces, CHECK);
5183 ik->set_transitive_interfaces(_transitive_interfaces);
5184 ik->set_local_interfaces(_local_interfaces);
5185 _transitive_interfaces = nullptr;
5186 _local_interfaces = nullptr;
5187
5188 // Initialize itable offset tables
5189 klassItable::setup_itable_offset_table(ik);
5190
5191 // Compute transitive closure of interfaces this class implements
5192 // Do final class setup
5193 OopMapBlocksBuilder* oop_map_blocks = _field_info->oop_map_blocks;
5194 if (oop_map_blocks->_nonstatic_oop_map_count > 0) {
5195 oop_map_blocks->copy(ik->start_of_nonstatic_oop_maps());
5196 }
5197
5198 if (_has_contended_fields || _parsed_annotations->is_contended() ||
5199 ( _super_klass != nullptr && _super_klass->has_contended_annotations())) {
5200 ik->set_has_contended_annotations(true);
5201 }
5202
5203 // Fill in has_finalizer and layout_helper
5204 set_precomputed_flags(ik);
5205
5206 // check if this class can access its super class
5207 check_super_class_access(ik, CHECK);
5208
5209 // check if this class can access its superinterfaces
5210 check_super_interface_access(ik, CHECK);
5211
5212 // check if this class overrides any final method
5213 check_final_method_override(ik, CHECK);
5214
5215 // reject static interface methods prior to Java 8
5216 if (ik->is_interface() && _major_version < JAVA_8_VERSION) {
5217 check_illegal_static_method(ik, CHECK);
5218 }
5219
5220 // Obtain this_klass' module entry
5221 ModuleEntry* module_entry = ik->module();
5222 assert(module_entry != nullptr, "module_entry should always be set");
5223
5224 // Obtain java.lang.Module
5225 Handle module_handle(THREAD, module_entry->module_oop());
5226
5227 // Allocate mirror and initialize static fields
5228 java_lang_Class::create_mirror(ik,
5229 Handle(THREAD, _loader_data->class_loader()),
5230 module_handle,
5231 _protection_domain,
5232 cl_inst_info.class_data(),
5233 CHECK);
5234
5235 assert(_all_mirandas != nullptr, "invariant");
5236
5237 // Generate any default methods - default methods are public interface methods
5238 // that have a default implementation. This is new with Java 8.
5239 if (_has_nonstatic_concrete_methods) {
5240 DefaultMethods::generate_default_methods(ik,
5241 _all_mirandas,
5242 CHECK);
5243 }
5244
5245 // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5246 if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5247 !module_entry->has_default_read_edges()) {
5248 if (!module_entry->set_has_default_read_edges()) {
5249 // We won a potential race
5250 JvmtiExport::add_default_read_edges(module_handle, THREAD);
5251 }
5252 }
5253
5254 ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5255
5256 if (!is_internal()) {
5257 ik->print_class_load_logging(_loader_data, module_entry, _stream);
5258
5259 if (ik->minor_version() == JAVA_PREVIEW_MINOR_VERSION &&
5260 ik->major_version() == JVM_CLASSFILE_MAJOR_VERSION &&
5261 log_is_enabled(Info, class, preview)) {
5262 ResourceMark rm;
5263 log_info(class, preview)("Loading class %s that depends on preview features (class file version %d.65535)",
5264 ik->external_name(), JVM_CLASSFILE_MAJOR_VERSION);
5265 }
5266
5267 if (log_is_enabled(Debug, class, resolve)) {
5268 ResourceMark rm;
5269 // print out the superclass.
5270 const char * from = ik->external_name();
5271 if (ik->super() != nullptr) {
5272 log_debug(class, resolve)("%s %s (super)",
5273 from,
5274 ik->super()->external_name());
5275 }
5276 // print out each of the interface classes referred to by this class.
5277 const Array<InstanceKlass*>* const local_interfaces = ik->local_interfaces();
5278 if (local_interfaces != nullptr) {
5279 const int length = local_interfaces->length();
5280 for (int i = 0; i < length; i++) {
5281 const InstanceKlass* const k = local_interfaces->at(i);
5282 const char * to = k->external_name();
5283 log_debug(class, resolve)("%s %s (interface)", from, to);
5284 }
5285 }
5286 }
5287 }
5288
5289 JFR_ONLY(INIT_ID(ik);)
5290
5291 // If we reach here, all is well.
5292 // Now remove the InstanceKlass* from the _klass_to_deallocate field
5293 // in order for it to not be destroyed in the ClassFileParser destructor.
5294 set_klass_to_deallocate(nullptr);
5295
5296 // it's official
5297 set_klass(ik);
5298
5299 DEBUG_ONLY(ik->verify();)
5300 }
5301
5302 void ClassFileParser::update_class_name(Symbol* new_class_name) {
5303 // Decrement the refcount in the old name, since we're clobbering it.
5304 _class_name->decrement_refcount();
5305
5306 _class_name = new_class_name;
5307 // Increment the refcount of the new name.
5308 // Now the ClassFileParser owns this name and will decrement in
5309 // the destructor.
5310 _class_name->increment_refcount();
5311 }
5312
5313 ClassFileParser::ClassFileParser(ClassFileStream* stream,
5314 Symbol* name,
5315 ClassLoaderData* loader_data,
5316 const ClassLoadInfo* cl_info,
5317 Publicity pub_level,
5318 TRAPS) :
5319 _stream(stream),
5320 _class_name(nullptr),
5321 _loader_data(loader_data),
5322 _is_hidden(cl_info->is_hidden()),
5323 _can_access_vm_annotations(cl_info->can_access_vm_annotations()),
5324 _orig_cp_size(0),
5325 _static_oop_count(0),
5326 _super_klass(),
5327 _cp(nullptr),
5328 _fieldinfo_stream(nullptr),
5329 _fieldinfo_search_table(nullptr),
5330 _fields_status(nullptr),
5331 _methods(nullptr),
5332 _inner_classes(nullptr),
5333 _nest_members(nullptr),
5334 _nest_host(0),
5335 _permitted_subclasses(nullptr),
5336 _record_components(nullptr),
5337 _local_interfaces(nullptr),
5338 _transitive_interfaces(nullptr),
5339 _combined_annotations(nullptr),
5340 _class_annotations(nullptr),
5341 _class_type_annotations(nullptr),
5342 _fields_annotations(nullptr),
5343 _fields_type_annotations(nullptr),
5344 _klass(nullptr),
5345 _klass_to_deallocate(nullptr),
5346 _parsed_annotations(nullptr),
5347 _field_info(nullptr),
5348 _temp_field_info(nullptr),
5349 _method_ordering(nullptr),
5350 _all_mirandas(nullptr),
5351 _vtable_size(0),
5352 _itable_size(0),
5353 _num_miranda_methods(0),
5354 _protection_domain(cl_info->protection_domain()),
5355 _access_flags(),
5356 _pub_level(pub_level),
5357 _bad_constant_seen(0),
5358 _synthetic_flag(false),
5359 _sde_length(false),
5360 _sde_buffer(nullptr),
5361 _sourcefile_index(0),
5362 _generic_signature_index(0),
5363 _major_version(0),
5364 _minor_version(0),
5365 _this_class_index(0),
5366 _super_class_index(0),
5367 _itfs_len(0),
5368 _java_fields_count(0),
5369 _need_verify(false),
5370 _has_nonstatic_concrete_methods(false),
5371 _declares_nonstatic_concrete_methods(false),
5372 _has_localvariable_table(false),
5373 _has_final_method(false),
5374 _has_contended_fields(false),
5375 _has_aot_runtime_setup_method(false),
5376 _has_finalizer(false),
5377 _has_empty_finalizer(false),
5378 _max_bootstrap_specifier_index(-1) {
5379
5380 _class_name = name != nullptr ? name : vmSymbols::unknown_class_name();
5381 _class_name->increment_refcount();
5382
5383 assert(_loader_data != nullptr, "invariant");
5384 assert(stream != nullptr, "invariant");
5385 assert(_stream != nullptr, "invariant");
5386 assert(_stream->buffer() == _stream->current(), "invariant");
5387 assert(_class_name != nullptr, "invariant");
5388 assert(0 == _access_flags.as_unsigned_short(), "invariant");
5389
5390 // Figure out whether we can skip format checking (matching classic VM behavior)
5391 // Always verify CFLH bytes from the user agents.
5392 _need_verify = stream->from_class_file_load_hook() ? true : Verifier::should_verify_for(_loader_data->class_loader());
5393
5394 // synch back verification state to stream to check for truncation.
5395 stream->set_need_verify(_need_verify);
5396
5397 parse_stream(stream, CHECK);
5398
5399 post_process_parsed_stream(stream, _cp, CHECK);
5400 }
5401
5402 void ClassFileParser::clear_class_metadata() {
5403 // metadata created before the instance klass is created. Must be
5404 // deallocated if classfile parsing returns an error.
5405 _cp = nullptr;
5406 _fieldinfo_stream = nullptr;
5407 _fieldinfo_search_table = nullptr;
5408 _fields_status = nullptr;
5409 _methods = nullptr;
5410 _inner_classes = nullptr;
5411 _nest_members = nullptr;
5412 _permitted_subclasses = nullptr;
5413 _combined_annotations = nullptr;
5414 _class_annotations = _class_type_annotations = nullptr;
5415 _fields_annotations = _fields_type_annotations = nullptr;
5416 _record_components = nullptr;
5417 }
5418
5419 // Destructor to clean up
5420 ClassFileParser::~ClassFileParser() {
5421 _class_name->decrement_refcount();
5422
5423 if (_cp != nullptr) {
5424 MetadataFactory::free_metadata(_loader_data, _cp);
5425 }
5426
5427 if (_fieldinfo_stream != nullptr) {
5428 MetadataFactory::free_array<u1>(_loader_data, _fieldinfo_stream);
5429 }
5430 MetadataFactory::free_array<u1>(_loader_data, _fieldinfo_search_table);
5431
5432 if (_fields_status != nullptr) {
5433 MetadataFactory::free_array<FieldStatus>(_loader_data, _fields_status);
5434 }
5435
5436 if (_methods != nullptr) {
5437 // Free methods
5438 InstanceKlass::deallocate_methods(_loader_data, _methods);
5439 }
5440
5441 // beware of the Universe::empty_blah_array!!
5442 if (_inner_classes != nullptr && _inner_classes != Universe::the_empty_short_array()) {
5443 MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
5444 }
5445
5446 if (_nest_members != nullptr && _nest_members != Universe::the_empty_short_array()) {
5447 MetadataFactory::free_array<u2>(_loader_data, _nest_members);
5448 }
5449
5450 if (_record_components != nullptr) {
5451 InstanceKlass::deallocate_record_components(_loader_data, _record_components);
5452 }
5453
5454 if (_permitted_subclasses != nullptr && _permitted_subclasses != Universe::the_empty_short_array()) {
5455 MetadataFactory::free_array<u2>(_loader_data, _permitted_subclasses);
5456 }
5457
5458 // Free interfaces
5459 InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
5460 _local_interfaces, _transitive_interfaces);
5461
5462 if (_combined_annotations != nullptr) {
5463 // After all annotations arrays have been created, they are installed into the
5464 // Annotations object that will be assigned to the InstanceKlass being created.
5465
5466 // Deallocate the Annotations object and the installed annotations arrays.
5467 _combined_annotations->deallocate_contents(_loader_data);
5468
5469 // If the _combined_annotations pointer is non-null,
5470 // then the other annotations fields should have been cleared.
5471 assert(_class_annotations == nullptr, "Should have been cleared");
5472 assert(_class_type_annotations == nullptr, "Should have been cleared");
5473 assert(_fields_annotations == nullptr, "Should have been cleared");
5474 assert(_fields_type_annotations == nullptr, "Should have been cleared");
5475 } else {
5476 // If the annotations arrays were not installed into the Annotations object,
5477 // then they have to be deallocated explicitly.
5478 MetadataFactory::free_array<u1>(_loader_data, _class_annotations);
5479 MetadataFactory::free_array<u1>(_loader_data, _class_type_annotations);
5480 Annotations::free_contents(_loader_data, _fields_annotations);
5481 Annotations::free_contents(_loader_data, _fields_type_annotations);
5482 }
5483
5484 clear_class_metadata();
5485 _transitive_interfaces = nullptr;
5486 _local_interfaces = nullptr;
5487
5488 // deallocate the klass if already created. Don't directly deallocate, but add
5489 // to the deallocate list so that the klass is removed from the CLD::_klasses list
5490 // at a safepoint.
5491 if (_klass_to_deallocate != nullptr) {
5492 _loader_data->add_to_deallocate_list(_klass_to_deallocate);
5493 }
5494 }
5495
5496 void ClassFileParser::parse_stream(const ClassFileStream* const stream,
5497 TRAPS) {
5498
5499 assert(stream != nullptr, "invariant");
5500 assert(_class_name != nullptr, "invariant");
5501
5502 // BEGIN STREAM PARSING
5503 stream->guarantee_more(8, CHECK); // magic, major, minor
5504 // Magic value
5505 const u4 magic = stream->get_u4_fast();
5506 guarantee_property(magic == JAVA_CLASSFILE_MAGIC,
5507 "Incompatible magic value %u in class file %s",
5508 magic, CHECK);
5509
5510 // Version numbers
5511 _minor_version = stream->get_u2_fast();
5512 _major_version = stream->get_u2_fast();
5513
5514 // Check version numbers - we check this even with verifier off
5515 verify_class_version(_major_version, _minor_version, _class_name, CHECK);
5516
5517 stream->guarantee_more(3, CHECK); // length, first cp tag
5518 u2 cp_size = stream->get_u2_fast();
5519
5520 guarantee_property(
5521 cp_size >= 1, "Illegal constant pool size %u in class file %s",
5522 cp_size, CHECK);
5523
5524 _orig_cp_size = cp_size;
5525 if (is_hidden()) { // Add a slot for hidden class name.
5526 cp_size++;
5527 }
5528
5529 _cp = ConstantPool::allocate(_loader_data,
5530 cp_size,
5531 CHECK);
5532
5533 ConstantPool* const cp = _cp;
5534
5535 parse_constant_pool(stream, cp, _orig_cp_size, CHECK);
5536
5537 assert(cp_size == (u2)cp->length(), "invariant");
5538
5539 // ACCESS FLAGS
5540 stream->guarantee_more(8, CHECK); // flags, this_class, super_class, infs_len
5541
5542 // Access flags
5543 u2 flags;
5544 // JVM_ACC_MODULE is defined in JDK-9 and later.
5545 if (_major_version >= JAVA_9_VERSION) {
5546 flags = stream->get_u2_fast() & (JVM_RECOGNIZED_CLASS_MODIFIERS | JVM_ACC_MODULE);
5547 } else {
5548 flags = stream->get_u2_fast() & JVM_RECOGNIZED_CLASS_MODIFIERS;
5549 }
5550
5551 if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
5552 // Set abstract bit for old class files for backward compatibility
5553 flags |= JVM_ACC_ABSTRACT;
5554 }
5555
5556 verify_legal_class_modifiers(flags, nullptr, false, CHECK);
5557
5558 short bad_constant = class_bad_constant_seen();
5559 if (bad_constant != 0) {
5560 // Do not throw CFE until after the access_flags are checked because if
5561 // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
5562 classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, THREAD);
5563 return;
5564 }
5565
5566 _access_flags.set_flags(flags);
5567
5568 // This class and superclass
5569 _this_class_index = stream->get_u2_fast();
5570 guarantee_property(
5571 valid_cp_range(_this_class_index, cp_size) &&
5572 cp->tag_at(_this_class_index).is_unresolved_klass(),
5573 "Invalid this class index %u in constant pool in class file %s",
5574 _this_class_index, CHECK);
5575
5576 Symbol* const class_name_in_cp = cp->klass_name_at(_this_class_index);
5577 assert(class_name_in_cp != nullptr, "class_name can't be null");
5578
5579 // Don't need to check whether this class name is legal or not.
5580 // It has been checked when constant pool is parsed.
5581 // However, make sure it is not an array type.
5582 if (_need_verify) {
5583 guarantee_property(class_name_in_cp->char_at(0) != JVM_SIGNATURE_ARRAY,
5584 "Bad class name in class file %s",
5585 CHECK);
5586 }
5587
5588 #ifdef ASSERT
5589 // Basic sanity checks
5590 if (_is_hidden) {
5591 assert(_class_name != vmSymbols::unknown_class_name(), "hidden classes should have a special name");
5592 }
5593 #endif
5594
5595 // Update the _class_name as needed depending on whether this is a named, un-named, or hidden class.
5596
5597 if (_is_hidden) {
5598 assert(_class_name != nullptr, "Unexpected null _class_name");
5599 #ifdef ASSERT
5600 if (_need_verify) {
5601 verify_legal_class_name(_class_name, CHECK);
5602 }
5603 #endif
5604
5605 } else {
5606 // Check if name in class file matches given name
5607 if (_class_name != class_name_in_cp) {
5608 if (_class_name != vmSymbols::unknown_class_name()) {
5609 ResourceMark rm(THREAD);
5610 // Names are all known to be < 64k so we know this formatted message is not excessively large.
5611 Exceptions::fthrow(THREAD_AND_LOCATION,
5612 vmSymbols::java_lang_NoClassDefFoundError(),
5613 "%s (wrong name: %s)",
5614 _class_name->as_C_string(),
5615 class_name_in_cp->as_C_string()
5616 );
5617 return;
5618 } else {
5619 // The class name was not known by the caller so we set it from
5620 // the value in the CP.
5621 update_class_name(class_name_in_cp);
5622 }
5623 // else nothing to do: the expected class name matches what is in the CP
5624 }
5625 }
5626
5627 // Verification prevents us from creating names with dots in them, this
5628 // asserts that that's the case.
5629 assert(is_internal_format(_class_name), "external class name format used internally");
5630
5631 if (!is_internal()) {
5632 LogTarget(Debug, class, preorder) lt;
5633 if (lt.is_enabled()){
5634 ResourceMark rm(THREAD);
5635 LogStream ls(lt);
5636 ls.print("%s", _class_name->as_klass_external_name());
5637 if (stream->source() != nullptr) {
5638 ls.print(" source: %s", stream->source());
5639 }
5640 ls.cr();
5641 }
5642 }
5643
5644 // SUPERKLASS
5645 _super_class_index = stream->get_u2_fast();
5646 check_super_class(cp,
5647 _super_class_index,
5648 _need_verify,
5649 CHECK);
5650
5651 // Interfaces
5652 _itfs_len = stream->get_u2_fast();
5653 parse_interfaces(stream,
5654 _itfs_len,
5655 cp,
5656 &_has_nonstatic_concrete_methods,
5657 CHECK);
5658
5659 assert(_local_interfaces != nullptr, "invariant");
5660
5661 // Fields (offsets are filled in later)
5662 parse_fields(stream,
5663 _access_flags.is_interface(),
5664 cp,
5665 cp_size,
5666 &_java_fields_count,
5667 CHECK);
5668
5669 assert(_temp_field_info != nullptr, "invariant");
5670
5671 // Methods
5672 parse_methods(stream,
5673 _access_flags.is_interface(),
5674 &_has_localvariable_table,
5675 &_has_final_method,
5676 &_declares_nonstatic_concrete_methods,
5677 CHECK);
5678
5679 assert(_methods != nullptr, "invariant");
5680
5681 if (_declares_nonstatic_concrete_methods) {
5682 _has_nonstatic_concrete_methods = true;
5683 }
5684
5685 // Additional attributes/annotations
5686 _parsed_annotations = new ClassAnnotationCollector();
5687 parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK);
5688
5689 assert(_inner_classes != nullptr, "invariant");
5690
5691 // Finalize the Annotations metadata object,
5692 // now that all annotation arrays have been created.
5693 create_combined_annotations(CHECK);
5694
5695 // Make sure this is the end of class file stream
5696 guarantee_property(stream->at_eos(),
5697 "Extra bytes at the end of class file %s",
5698 CHECK);
5699
5700 // all bytes in stream read and parsed
5701 }
5702
5703 void ClassFileParser::mangle_hidden_class_name(InstanceKlass* const ik) {
5704 ResourceMark rm;
5705 // Construct hidden name from _class_name, "+", and &ik. Note that we can't
5706 // use a '/' because that confuses finding the class's package. Also, can't
5707 // use an illegal char such as ';' because that causes serialization issues
5708 // and issues with hidden classes that create their own hidden classes.
5709 char addr_buf[20];
5710 if (CDSConfig::is_dumping_static_archive()) {
5711 // We want stable names for the archived hidden classes (only for static
5712 // archive for now). Spaces under default_SharedBaseAddress() will be
5713 // occupied by the archive at run time, so we know that no dynamically
5714 // loaded InstanceKlass will be placed under there.
5715 static volatile size_t counter = 0;
5716 AtomicAccess::cmpxchg(&counter, (size_t)0, Arguments::default_SharedBaseAddress()); // initialize it
5717 size_t new_id = AtomicAccess::add(&counter, (size_t)1);
5718 jio_snprintf(addr_buf, 20, "0x%zx", new_id);
5719 } else {
5720 jio_snprintf(addr_buf, 20, INTPTR_FORMAT, p2i(ik));
5721 }
5722 size_t new_name_len = _class_name->utf8_length() + 2 + strlen(addr_buf);
5723 char* new_name = NEW_RESOURCE_ARRAY(char, new_name_len);
5724 jio_snprintf(new_name, new_name_len, "%s+%s",
5725 _class_name->as_C_string(), addr_buf);
5726 update_class_name(SymbolTable::new_symbol(new_name));
5727
5728 // Add a Utf8 entry containing the hidden name.
5729 assert(_class_name != nullptr, "Unexpected null _class_name");
5730 int hidden_index = _orig_cp_size; // this is an extra slot we added
5731 _cp->symbol_at_put(hidden_index, _class_name);
5732
5733 // Update this_class_index's slot in the constant pool with the new Utf8 entry.
5734 // We have to update the resolved_klass_index and the name_index together
5735 // so extract the existing resolved_klass_index first.
5736 CPKlassSlot cp_klass_slot = _cp->klass_slot_at(_this_class_index);
5737 int resolved_klass_index = cp_klass_slot.resolved_klass_index();
5738 _cp->unresolved_klass_at_put(_this_class_index, hidden_index, resolved_klass_index);
5739 assert(_cp->klass_slot_at(_this_class_index).name_index() == _orig_cp_size,
5740 "Bad name_index");
5741 }
5742
5743 void ClassFileParser::post_process_parsed_stream(const ClassFileStream* const stream,
5744 ConstantPool* cp,
5745 TRAPS) {
5746 assert(stream != nullptr, "invariant");
5747 assert(stream->at_eos(), "invariant");
5748 assert(cp != nullptr, "invariant");
5749 assert(_loader_data != nullptr, "invariant");
5750
5751 if (_class_name == vmSymbols::java_lang_Object()) {
5752 precond(_super_class_index == 0);
5753 precond(_super_klass == nullptr);
5754 guarantee_property(_local_interfaces == Universe::the_empty_instance_klass_array(),
5755 "java.lang.Object cannot implement an interface in class file %s",
5756 CHECK);
5757 } else {
5758 // Set _super_klass after class file is parsed and format is checked
5759 assert(_super_class_index > 0, "any class other than Object must have a super class");
5760 Symbol* const super_class_name = cp->klass_name_at(_super_class_index);
5761 if (_access_flags.is_interface()) {
5762 // Before attempting to resolve the superclass, check for class format
5763 // errors not checked yet.
5764 guarantee_property(super_class_name == vmSymbols::java_lang_Object(),
5765 "Interfaces must have java.lang.Object as superclass in class file %s",
5766 CHECK);
5767 }
5768 Handle loader(THREAD, _loader_data->class_loader());
5769 if (loader.is_null() && super_class_name == vmSymbols::java_lang_Object()) {
5770 // fast path to avoid lookup
5771 _super_klass = vmClasses::Object_klass();
5772 } else {
5773 _super_klass = (const InstanceKlass*)
5774 SystemDictionary::resolve_super_or_fail(_class_name,
5775 super_class_name,
5776 loader,
5777 true,
5778 CHECK);
5779 }
5780 }
5781
5782 if (_super_klass != nullptr) {
5783 if (_super_klass->has_nonstatic_concrete_methods()) {
5784 _has_nonstatic_concrete_methods = true;
5785 }
5786
5787 if (_super_klass->is_interface()) {
5788 classfile_icce_error("class %s has interface %s as super class", _super_klass, THREAD);
5789 return;
5790 }
5791 }
5792
5793 // Compute the transitive list of all unique interfaces implemented by this class
5794 _transitive_interfaces =
5795 compute_transitive_interfaces(_super_klass,
5796 _local_interfaces,
5797 _loader_data,
5798 CHECK);
5799
5800 assert(_transitive_interfaces != nullptr, "invariant");
5801
5802 // sort methods
5803 _method_ordering = sort_methods(_methods);
5804
5805 _all_mirandas = new GrowableArray<Method*>(20);
5806
5807 Handle loader(THREAD, _loader_data->class_loader());
5808 klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
5809 &_num_miranda_methods,
5810 _all_mirandas,
5811 _super_klass,
5812 _methods,
5813 _access_flags,
5814 _major_version,
5815 loader,
5816 _class_name,
5817 _local_interfaces);
5818
5819 // Size of Java itable (in words)
5820 _itable_size = _access_flags.is_interface() ? 0 :
5821 klassItable::compute_itable_size(_transitive_interfaces);
5822
5823 assert(_parsed_annotations != nullptr, "invariant");
5824
5825 _field_info = new FieldLayoutInfo();
5826 FieldLayoutBuilder lb(class_name(), super_klass(), _cp, /*_fields*/ _temp_field_info,
5827 _parsed_annotations->is_contended(), _field_info);
5828 lb.build_layout();
5829
5830 int injected_fields_count = _temp_field_info->length() - _java_fields_count;
5831 _fieldinfo_stream =
5832 FieldInfoStream::create_FieldInfoStream(_temp_field_info, _java_fields_count,
5833 injected_fields_count, loader_data(), CHECK);
5834 _fieldinfo_search_table = FieldInfoStream::create_search_table(_cp, _fieldinfo_stream, _loader_data, CHECK);
5835 _fields_status =
5836 MetadataFactory::new_array<FieldStatus>(_loader_data, _temp_field_info->length(),
5837 FieldStatus(0), CHECK);
5838 }
5839
5840 void ClassFileParser::set_klass(InstanceKlass* klass) {
5841
5842 #ifdef ASSERT
5843 if (klass != nullptr) {
5844 assert(nullptr == _klass, "leaking?");
5845 }
5846 #endif
5847
5848 _klass = klass;
5849 }
5850
5851 void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) {
5852
5853 #ifdef ASSERT
5854 if (klass != nullptr) {
5855 assert(nullptr == _klass_to_deallocate, "leaking?");
5856 }
5857 #endif
5858
5859 _klass_to_deallocate = klass;
5860 }
5861
5862 // Caller responsible for ResourceMark
5863 // clone stream with rewound position
5864 const ClassFileStream* ClassFileParser::clone_stream() const {
5865 assert(_stream != nullptr, "invariant");
5866
5867 return _stream->clone();
5868 }
5869
5870 ReferenceType ClassFileParser::super_reference_type() const {
5871 return _super_klass == nullptr ? REF_NONE : _super_klass->reference_type();
5872 }
5873
5874 bool ClassFileParser::is_instance_ref_klass() const {
5875 // Only the subclasses of j.l.r.Reference are InstanceRefKlass.
5876 // j.l.r.Reference itself is InstanceKlass because InstanceRefKlass denotes a
5877 // klass requiring special treatment in ref-processing. The abstract
5878 // j.l.r.Reference cannot be instantiated so doesn't partake in
5879 // ref-processing.
5880 return is_java_lang_ref_Reference_subclass();
5881 }
5882
5883 bool ClassFileParser::is_java_lang_ref_Reference_subclass() const {
5884 if (_super_klass == nullptr) {
5885 return false;
5886 }
5887
5888 if (_super_klass->name() == vmSymbols::java_lang_ref_Reference()) {
5889 // Direct subclass of j.l.r.Reference: Soft|Weak|Final|Phantom
5890 return true;
5891 }
5892
5893 return _super_klass->reference_type() != REF_NONE;
5894 }
5895
5896 // ----------------------------------------------------------------------------
5897 // debugging
5898
5899 #ifdef ASSERT
5900
5901 // return true if class_name contains no '.' (internal format is '/')
5902 bool ClassFileParser::is_internal_format(Symbol* class_name) {
5903 if (class_name != nullptr) {
5904 ResourceMark rm;
5905 char* name = class_name->as_C_string();
5906 return strchr(name, JVM_SIGNATURE_DOT) == nullptr;
5907 } else {
5908 return true;
5909 }
5910 }
5911
5912 #endif