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