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 
25 #ifndef SHARE_VM_CLASSFILE_CLASSFILEPARSER_HPP
26 #define SHARE_VM_CLASSFILE_CLASSFILEPARSER_HPP
27 
28 #include "classfile/classFileStream.hpp"
29 #include "memory/resourceArea.hpp"
30 #include "oops/oop.inline.hpp"
31 #include "oops/typeArrayOop.hpp"
32 #include "runtime/handles.inline.hpp"
33 #include "utilities/accessFlags.hpp"
34 #include "classfile/symbolTable.hpp"
35 
36 class FieldAllocationCount;
37 class FieldLayoutInfo;
38 
39 
40 // Parser for for .class files
41 //
42 // The bytes describing the class file structure is read from a Stream object
43 
44 class ClassFileParser VALUE_OBJ_CLASS_SPEC {
45  private:
46   bool _need_verify;
47   bool _relax_verify;
48   u2   _major_version;
49   u2   _minor_version;
50   u2   _this_class_index;
51   Symbol* _class_name;
52   ClassLoaderData* _loader_data;
53   KlassHandle _host_klass;
54   GrowableArray<Handle>* _cp_patches; // overrides for CP entries
55 
56   // precomputed flags
57   bool _has_finalizer;
58   bool _has_empty_finalizer;
59   bool _has_vanilla_constructor;
60   int _max_bootstrap_specifier_index;  // detects BSS values
61 
62   // class attributes parsed before the instance klass is created:
63   bool       _synthetic_flag;
64   int        _sde_length;
65   char*      _sde_buffer;
66   u2         _sourcefile_index;
67   u2         _generic_signature_index;
68 
69   // Metadata created before the instance klass is created.  Must be deallocated
70   // if not transferred to the InstanceKlass upon successful class loading
71   // in which case these pointers have been set to NULL.
72   instanceKlassHandle _super_klass;
73   ConstantPool*    _cp;
74   Array<u2>*       _fields;
75   Array<Method*>*  _methods;
76   Array<u2>*       _inner_classes;
77   Array<Klass*>*   _local_interfaces;
78   Array<Klass*>*   _transitive_interfaces;
79   Annotations*     _combined_annotations;
80   AnnotationArray* _annotations;
81   AnnotationArray* _type_annotations;
82   Array<AnnotationArray*>* _fields_annotations;
83   Array<AnnotationArray*>* _fields_type_annotations;
84   InstanceKlass*   _klass;  // InstanceKlass once created.
85 
set_class_synthetic_flag(bool x)86   void set_class_synthetic_flag(bool x)        { _synthetic_flag = x; }
set_class_sourcefile_index(u2 x)87   void set_class_sourcefile_index(u2 x)        { _sourcefile_index = x; }
set_class_generic_signature_index(u2 x)88   void set_class_generic_signature_index(u2 x) { _generic_signature_index = x; }
set_class_sde_buffer(char * x,int len)89   void set_class_sde_buffer(char* x, int len)  { _sde_buffer = x; _sde_length = len; }
90 
91   void create_combined_annotations(TRAPS);
92 
init_parsed_class_attributes(ClassLoaderData * loader_data)93   void init_parsed_class_attributes(ClassLoaderData* loader_data) {
94     _loader_data = loader_data;
95     _synthetic_flag = false;
96     _sourcefile_index = 0;
97     _generic_signature_index = 0;
98     _sde_buffer = NULL;
99     _sde_length = 0;
100     // initialize the other flags too:
101     _has_finalizer = _has_empty_finalizer = _has_vanilla_constructor = false;
102     _max_bootstrap_specifier_index = -1;
103     clear_class_metadata();
104     _klass = NULL;
105   }
106   void apply_parsed_class_attributes(instanceKlassHandle k);  // update k
107   void apply_parsed_class_metadata(instanceKlassHandle k, int fields_count, TRAPS);
clear_class_metadata()108   void clear_class_metadata() {
109     // metadata created before the instance klass is created.  Must be
110     // deallocated if classfile parsing returns an error.
111     _cp = NULL;
112     _fields = NULL;
113     _methods = NULL;
114     _inner_classes = NULL;
115     _local_interfaces = NULL;
116     _transitive_interfaces = NULL;
117     _combined_annotations = NULL;
118     _annotations = _type_annotations = NULL;
119     _fields_annotations = _fields_type_annotations = NULL;
120   }
121 
122   class AnnotationCollector {
123   public:
124     enum Location { _in_field, _in_method, _in_class };
125     enum ID {
126       _unknown = 0,
127       _method_CallerSensitive,
128       _method_ForceInline,
129       _method_DontInline,
130       _method_InjectedProfile,
131       _method_LambdaForm_Compiled,
132       _method_LambdaForm_Hidden,
133       _sun_misc_Contended,
134       _field_Stable,
135       _annotation_LIMIT
136     };
137     const Location _location;
138     int _annotations_present;
139     u2 _contended_group;
140 
AnnotationCollector(Location location)141     AnnotationCollector(Location location)
142     : _location(location), _annotations_present(0), _contended_group(0)
143     {
144       assert((int)_annotation_LIMIT <= (int)sizeof(_annotations_present) * BitsPerByte, "");
145     }
146     // If this annotation name has an ID, report it (or _none).
147     ID annotation_index(ClassLoaderData* loader_data, Symbol* name);
148     // Set the annotation name:
set_annotation(ID id)149     void set_annotation(ID id) {
150       assert((int)id >= 0 && (int)id < (int)_annotation_LIMIT, "oob");
151       _annotations_present |= nth_bit((int)id);
152     }
153 
remove_annotation(ID id)154     void remove_annotation(ID id) {
155       assert((int)id >= 0 && (int)id < (int)_annotation_LIMIT, "oob");
156       _annotations_present &= ~nth_bit((int)id);
157     }
158 
159     // Report if the annotation is present.
has_any_annotations() const160     bool has_any_annotations() const { return _annotations_present != 0; }
has_annotation(ID id) const161     bool has_annotation(ID id) const { return (nth_bit((int)id) & _annotations_present) != 0; }
162 
set_contended_group(u2 group)163     void set_contended_group(u2 group) { _contended_group = group; }
contended_group() const164     u2 contended_group() const { return _contended_group; }
165 
is_contended() const166     bool is_contended() const { return has_annotation(_sun_misc_Contended); }
167 
set_stable(bool stable)168     void set_stable(bool stable) { set_annotation(_field_Stable); }
is_stable() const169     bool is_stable() const { return has_annotation(_field_Stable); }
170   };
171 
172   // This class also doubles as a holder for metadata cleanup.
173   class FieldAnnotationCollector: public AnnotationCollector {
174     ClassLoaderData* _loader_data;
175     AnnotationArray* _field_annotations;
176     AnnotationArray* _field_type_annotations;
177   public:
FieldAnnotationCollector(ClassLoaderData * loader_data)178     FieldAnnotationCollector(ClassLoaderData* loader_data) :
179                                  AnnotationCollector(_in_field),
180                                  _loader_data(loader_data),
181                                  _field_annotations(NULL),
182                                  _field_type_annotations(NULL) {}
183     void apply_to(FieldInfo* f);
184     ~FieldAnnotationCollector();
field_annotations()185     AnnotationArray* field_annotations()      { return _field_annotations; }
field_type_annotations()186     AnnotationArray* field_type_annotations() { return _field_type_annotations; }
187 
set_field_annotations(AnnotationArray * a)188     void set_field_annotations(AnnotationArray* a)      { _field_annotations = a; }
set_field_type_annotations(AnnotationArray * a)189     void set_field_type_annotations(AnnotationArray* a) { _field_type_annotations = a; }
190   };
191 
192   class MethodAnnotationCollector: public AnnotationCollector {
193   public:
MethodAnnotationCollector()194     MethodAnnotationCollector() : AnnotationCollector(_in_method) { }
195     void apply_to(methodHandle m);
196   };
197   class ClassAnnotationCollector: public AnnotationCollector {
198   public:
ClassAnnotationCollector()199     ClassAnnotationCollector() : AnnotationCollector(_in_class) { }
200     void apply_to(instanceKlassHandle k);
201   };
202 
203   enum { fixed_buffer_size = 128 };
204   u_char linenumbertable_buffer[fixed_buffer_size];
205 
206   ClassFileStream* _stream;              // Actual input stream
207 
208   enum { LegalClass, LegalField, LegalMethod }; // used to verify unqualified names
209 
210   // Accessors
stream()211   ClassFileStream* stream()                        { return _stream; }
set_stream(ClassFileStream * st)212   void set_stream(ClassFileStream* st)             { _stream = st; }
213 
214   // Constant pool parsing
215   void parse_constant_pool_entries(int length, TRAPS);
216 
217   constantPoolHandle parse_constant_pool(TRAPS);
218 
219   // Interface parsing
220   Array<Klass*>* parse_interfaces(int length,
221                                   Handle protection_domain,
222                                   Symbol* class_name,
223                                   bool* has_default_methods,
224                                   TRAPS);
225   void record_defined_class_dependencies(instanceKlassHandle defined_klass, TRAPS);
226 
227   instanceKlassHandle parse_super_class(int super_class_index, TRAPS);
228   // Field parsing
229   void parse_field_attributes(u2 attributes_count,
230                               bool is_static, u2 signature_index,
231                               u2* constantvalue_index_addr,
232                               bool* is_synthetic_addr,
233                               u2* generic_signature_index_addr,
234                               FieldAnnotationCollector* parsed_annotations,
235                               TRAPS);
236   Array<u2>* parse_fields(Symbol* class_name,
237                           bool is_interface,
238                           FieldAllocationCount *fac,
239                           u2* java_fields_count_ptr, TRAPS);
240 
241   void print_field_layout(Symbol* name,
242                           Array<u2>* fields,
243                           constantPoolHandle cp,
244                           int instance_size,
245                           int instance_fields_start,
246                           int instance_fields_end,
247                           int static_fields_end);
248 
249   // Method parsing
250   methodHandle parse_method(bool is_interface,
251                             AccessFlags* promoted_flags,
252                             TRAPS);
253   Array<Method*>* parse_methods(bool is_interface,
254                                 AccessFlags* promoted_flags,
255                                 bool* has_final_method,
256                                 bool* declares_default_methods,
257                                 TRAPS);
258   intArray* sort_methods(Array<Method*>* methods);
259 
260   u2* parse_exception_table(u4 code_length, u4 exception_table_length,
261                             TRAPS);
262   void parse_linenumber_table(
263       u4 code_attribute_length, u4 code_length,
264       CompressedLineNumberWriteStream** write_stream, TRAPS);
265   u2* parse_localvariable_table(u4 code_length, u2 max_locals, u4 code_attribute_length,
266                                 u2* localvariable_table_length,
267                                 bool isLVTT, TRAPS);
268   u2* parse_checked_exceptions(u2* checked_exceptions_length, u4 method_attribute_length,
269                                TRAPS);
270   void parse_type_array(u2 array_length, u4 code_length, u4* u1_index, u4* u2_index,
271                         u1* u1_array, u2* u2_array, TRAPS);
272   u1* parse_stackmap_table(u4 code_attribute_length, TRAPS);
273 
274   // Classfile attribute parsing
275   u2 parse_generic_signature_attribute(TRAPS);
276   void parse_classfile_sourcefile_attribute(TRAPS);
277   void parse_classfile_source_debug_extension_attribute(int length, TRAPS);
278 
279   // Check for circularity in InnerClasses attribute.
280   bool check_inner_classes_circularity(const ConstantPool* cp, int length, TRAPS);
281 
282   u2   parse_classfile_inner_classes_attribute(const ConstantPool* cp,
283                                                u1* inner_classes_attribute_start,
284                                                bool parsed_enclosingmethod_attribute,
285                                                u2 enclosing_method_class_index,
286                                                u2 enclosing_method_method_index,
287                                                TRAPS);
288   void parse_classfile_attributes(ClassAnnotationCollector* parsed_annotations,
289                                   TRAPS);
290   void parse_classfile_synthetic_attribute(TRAPS);
291   void parse_classfile_signature_attribute(TRAPS);
292   void parse_classfile_bootstrap_methods_attribute(u4 attribute_length, TRAPS);
293 
294   // Annotations handling
295   AnnotationArray* assemble_annotations(u1* runtime_visible_annotations,
296                                         int runtime_visible_annotations_length,
297                                         u1* runtime_invisible_annotations,
298                                         int runtime_invisible_annotations_length, TRAPS);
299   int skip_annotation(u1* buffer, int limit, int index);
300   int skip_annotation_value(u1* buffer, int limit, int index);
301   void parse_annotations(u1* buffer, int limit,
302                          /* Results (currently, only one result is supported): */
303                          AnnotationCollector* result,
304                          TRAPS);
305 
306   // Final setup
307   unsigned int compute_oop_map_count(instanceKlassHandle super,
308                                      unsigned int nonstatic_oop_count,
309                                      int first_nonstatic_oop_offset);
310   void fill_oop_maps(instanceKlassHandle k,
311                      unsigned int nonstatic_oop_map_count,
312                      int* nonstatic_oop_offsets,
313                      unsigned int* nonstatic_oop_counts);
314   void set_precomputed_flags(instanceKlassHandle k);
315   Array<Klass*>* compute_transitive_interfaces(instanceKlassHandle super,
316                                                Array<Klass*>* local_ifs, TRAPS);
317 
318   // Format checker methods
319   void classfile_parse_error(const char* msg, TRAPS);
320   void classfile_parse_error(const char* msg, int index, TRAPS);
321   void classfile_parse_error(const char* msg, const char *name, TRAPS);
322   void classfile_parse_error(const char* msg, int index, const char *name, TRAPS);
323   void classfile_parse_error(const char* msg, const char* name, const char* signature, TRAPS);
guarantee_property(bool b,const char * msg,TRAPS)324   inline void guarantee_property(bool b, const char* msg, TRAPS) {
325     if (!b) { classfile_parse_error(msg, CHECK); }
326   }
327 
328 PRAGMA_DIAG_PUSH
329 PRAGMA_FORMAT_NONLITERAL_IGNORED
assert_property(bool b,const char * msg,TRAPS)330 inline void assert_property(bool b, const char* msg, TRAPS) {
331 #ifdef ASSERT
332     if (!b) {
333       ResourceMark rm(THREAD);
334       fatal(err_msg(msg, _class_name->as_C_string()));
335     }
336 #endif
337   }
338 
assert_property(bool b,const char * msg,int index,TRAPS)339   inline void assert_property(bool b, const char* msg, int index, TRAPS) {
340 #ifdef ASSERT
341     if (!b) {
342       ResourceMark rm(THREAD);
343       fatal(err_msg(msg, index, _class_name->as_C_string()));
344     }
345 #endif
346   }
347 PRAGMA_DIAG_POP
348 
check_property(bool property,const char * msg,int index,TRAPS)349   inline void check_property(bool property, const char* msg, int index, TRAPS) {
350     if (_need_verify) {
351       guarantee_property(property, msg, index, CHECK);
352     } else {
353       assert_property(property, msg, index, CHECK);
354     }
355   }
356 
check_property(bool property,const char * msg,TRAPS)357   inline void check_property(bool property, const char* msg, TRAPS) {
358     if (_need_verify) {
359       guarantee_property(property, msg, CHECK);
360     } else {
361       assert_property(property, msg, CHECK);
362     }
363   }
364 
guarantee_property(bool b,const char * msg,int index,TRAPS)365   inline void guarantee_property(bool b, const char* msg, int index, TRAPS) {
366     if (!b) { classfile_parse_error(msg, index, CHECK); }
367   }
guarantee_property(bool b,const char * msg,const char * name,TRAPS)368   inline void guarantee_property(bool b, const char* msg, const char *name, TRAPS) {
369     if (!b) { classfile_parse_error(msg, name, CHECK); }
370   }
guarantee_property(bool b,const char * msg,int index,const char * name,TRAPS)371   inline void guarantee_property(bool b, const char* msg, int index, const char *name, TRAPS) {
372     if (!b) { classfile_parse_error(msg, index, name, CHECK); }
373   }
374 
375   void throwIllegalSignature(
376       const char* type, Symbol* name, Symbol* sig, TRAPS);
377 
378   bool is_supported_version(u2 major, u2 minor);
379   bool has_illegal_visibility(jint flags);
380 
381   void verify_constantvalue(int constantvalue_index, int signature_index, TRAPS);
382   void verify_legal_utf8(const unsigned char* buffer, int length, TRAPS);
383   void verify_legal_class_name(Symbol* name, TRAPS);
384   void verify_legal_field_name(Symbol* name, TRAPS);
385   void verify_legal_method_name(Symbol* name, TRAPS);
386   void verify_legal_field_signature(Symbol* fieldname, Symbol* signature, TRAPS);
387   int  verify_legal_method_signature(Symbol* methodname, Symbol* signature, TRAPS);
388   void verify_legal_class_modifiers(jint flags, TRAPS);
389   void verify_legal_field_modifiers(jint flags, bool is_interface, TRAPS);
390   void verify_legal_method_modifiers(jint flags, bool is_interface, Symbol* name, TRAPS);
391   bool verify_unqualified_name(char* name, unsigned int length, int type);
392   char* skip_over_field_name(char* name, bool slash_ok, unsigned int length);
393   char* skip_over_field_signature(char* signature, bool void_ok, unsigned int length, TRAPS);
394 
is_anonymous()395   bool is_anonymous() {
396     assert(EnableInvokeDynamic || _host_klass.is_null(), "");
397     return _host_klass.not_null();
398   }
has_cp_patch_at(int index)399   bool has_cp_patch_at(int index) {
400     assert(EnableInvokeDynamic, "");
401     assert(index >= 0, "oob");
402     return (_cp_patches != NULL
403             && index < _cp_patches->length()
404             && _cp_patches->adr_at(index)->not_null());
405   }
cp_patch_at(int index)406   Handle cp_patch_at(int index) {
407     assert(has_cp_patch_at(index), "oob");
408     return _cp_patches->at(index);
409   }
clear_cp_patch_at(int index)410   Handle clear_cp_patch_at(int index) {
411     Handle patch = cp_patch_at(index);
412     _cp_patches->at_put(index, Handle());
413     assert(!has_cp_patch_at(index), "");
414     return patch;
415   }
416   void patch_constant_pool(constantPoolHandle cp, int index, Handle patch, TRAPS);
417 
418   // Wrapper for constantTag.is_klass_[or_]reference.
419   // In older versions of the VM, Klass*s cannot sneak into early phases of
420   // constant pool construction, but in later versions they can.
421   // %%% Let's phase out the old is_klass_reference.
valid_klass_reference_at(int index)422   bool valid_klass_reference_at(int index) {
423     return _cp->is_within_bounds(index) &&
424          (EnableInvokeDynamic
425             ? _cp->tag_at(index).is_klass_or_reference()
426             : _cp->tag_at(index).is_klass_reference());
427   }
428 
429   // Checks that the cpool index is in range and is a utf8
valid_symbol_at(int cpool_index)430   bool valid_symbol_at(int cpool_index) {
431     return (_cp->is_within_bounds(cpool_index) &&
432             _cp->tag_at(cpool_index).is_utf8());
433   }
434 
435   void copy_localvariable_table(ConstMethod* cm, int lvt_cnt,
436                                 u2* localvariable_table_length,
437                                 u2** localvariable_table_start,
438                                 int lvtt_cnt,
439                                 u2* localvariable_type_table_length,
440                                 u2** localvariable_type_table_start,
441                                 TRAPS);
442 
443   void copy_method_annotations(ConstMethod* cm,
444                                u1* runtime_visible_annotations,
445                                int runtime_visible_annotations_length,
446                                u1* runtime_invisible_annotations,
447                                int runtime_invisible_annotations_length,
448                                u1* runtime_visible_parameter_annotations,
449                                int runtime_visible_parameter_annotations_length,
450                                u1* runtime_invisible_parameter_annotations,
451                                int runtime_invisible_parameter_annotations_length,
452                                u1* runtime_visible_type_annotations,
453                                int runtime_visible_type_annotations_length,
454                                u1* runtime_invisible_type_annotations,
455                                int runtime_invisible_type_annotations_length,
456                                u1* annotation_default,
457                                int annotation_default_length,
458                                TRAPS);
459 
460   // lays out fields in class and returns the total oopmap count
461   void layout_fields(Handle class_loader, FieldAllocationCount* fac,
462                      ClassAnnotationCollector* parsed_annotations,
463                      FieldLayoutInfo* info, TRAPS);
464 
465  public:
466   // Constructor
ClassFileParser(ClassFileStream * st)467   ClassFileParser(ClassFileStream* st) { set_stream(st); }
468   ~ClassFileParser();
469 
470   // Parse .class file and return new Klass*. The Klass* is not hooked up
471   // to the system dictionary or any other structures, so a .class file can
472   // be loaded several times if desired.
473   // The system dictionary hookup is done by the caller.
474   //
475   // "parsed_name" is updated by this method, and is the name found
476   // while parsing the stream.
parseClassFile(Symbol * name,ClassLoaderData * loader_data,Handle protection_domain,TempNewSymbol & parsed_name,bool verify,TRAPS)477   instanceKlassHandle parseClassFile(Symbol* name,
478                                      ClassLoaderData* loader_data,
479                                      Handle protection_domain,
480                                      TempNewSymbol& parsed_name,
481                                      bool verify,
482                                      TRAPS) {
483     KlassHandle no_host_klass;
484     return parseClassFile(name, loader_data, protection_domain, no_host_klass, NULL, parsed_name, verify, THREAD);
485   }
486   instanceKlassHandle parseClassFile(Symbol* name,
487                                      ClassLoaderData* loader_data,
488                                      Handle protection_domain,
489                                      KlassHandle host_klass,
490                                      GrowableArray<Handle>* cp_patches,
491                                      TempNewSymbol& parsed_name,
492                                      bool verify,
493                                      TRAPS);
494 
495   // Verifier checks
496   static void check_super_class_access(instanceKlassHandle this_klass, TRAPS);
497   static void check_super_interface_access(instanceKlassHandle this_klass, TRAPS);
498   static void check_final_method_override(instanceKlassHandle this_klass, TRAPS);
499   static void check_illegal_static_method(instanceKlassHandle this_klass, TRAPS);
500 
this_class_index() const501   u2 this_class_index() const { return _this_class_index; }
502 
503 #if INCLUDE_JFR
504   ClassFileStream* clone_stream() const;
505   void set_klass_to_deallocate(InstanceKlass* klass);
506 #endif // INCLUDE_JFR
507 };
508 
509 #endif // SHARE_VM_CLASSFILE_CLASSFILEPARSER_HPP
510