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