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