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