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