1 /*
  2  * Copyright (c) 1997, 2025, 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_CLASSFILE_CLASSFILEPARSER_HPP
 26 #define SHARE_CLASSFILE_CLASSFILEPARSER_HPP
 27 
 28 #include "memory/referenceType.hpp"
 29 #include "oops/annotations.hpp"
 30 #include "oops/constantPool.hpp"
 31 #include "oops/fieldInfo.hpp"
 32 #include "oops/instanceKlass.hpp"
 33 #include "oops/typeArrayOop.hpp"
 34 #include "utilities/accessFlags.hpp"
 35 #include "utilities/pair.hpp"
 36 
 37 class Annotations;
 38 template <typename T>
 39 class Array;
 40 class ClassFileStream;
 41 class ClassLoaderData;
 42 class ClassLoadInfo;
 43 class ClassInstanceInfo;
 44 class CompressedLineNumberWriteStream;
 45 class ConstMethod;
 46 class FieldInfo;
 47 template <typename T>
 48 class GrowableArray;
 49 class InstanceKlass;
 50 class RecordComponent;
 51 class Symbol;
 52 class FieldLayoutBuilder;
 53 
 54 // Utility to collect and compact oop maps during layout
 55 class OopMapBlocksBuilder : public ResourceObj {
 56  public:
 57   OopMapBlock* _nonstatic_oop_maps;
 58   unsigned int _nonstatic_oop_map_count;
 59   unsigned int _max_nonstatic_oop_maps;
 60 
 61   OopMapBlocksBuilder(unsigned int  max_blocks);
 62   OopMapBlock* last_oop_map() const;
 63   void initialize_inherited_blocks(OopMapBlock* blocks, unsigned int nof_blocks);
 64   void add(int offset, int count);
 65   void copy(OopMapBlock* dst);
 66   void compact();
 67   void print_on(outputStream* st) const;
 68   void print_value_on(outputStream* st) const;
 69 };
 70 
 71 // Values needed for oopmap and InstanceKlass creation
 72 class FieldLayoutInfo : public ResourceObj {
 73  public:
 74   OopMapBlocksBuilder* oop_map_blocks;
 75   GrowableArray<Pair<int,int>>* _nonoop_acmp_map;
 76   GrowableArray<int>* _oop_acmp_map;
 77   int _instance_size;
 78   int _nonstatic_field_size;
 79   int _static_field_size;
 80   int _payload_alignment;
 81   int _payload_offset;
 82   int _payload_size_in_bytes;
 83   int _non_atomic_size_in_bytes;
 84   int _non_atomic_alignment;
 85   int _atomic_layout_size_in_bytes;
 86   int _nullable_layout_size_in_bytes;
 87   int _null_marker_offset;
 88   int _null_reset_value_offset;
 89   int _acmp_maps_offset;
 90   bool _has_nonstatic_fields;
 91   bool _is_naturally_atomic;
 92   bool _must_be_atomic;
 93   bool _has_inline_fields;
 94   bool _is_empty_inline_klass;
 95   FieldLayoutInfo() : oop_map_blocks(nullptr), _nonoop_acmp_map(nullptr), _oop_acmp_map(nullptr),
 96                       _instance_size(-1), _nonstatic_field_size(-1), _static_field_size(-1),
 97                       _payload_alignment(-1), _payload_offset(-1), _payload_size_in_bytes(-1),
 98                       _non_atomic_size_in_bytes(-1), _non_atomic_alignment(-1),
 99                       _atomic_layout_size_in_bytes(-1), _nullable_layout_size_in_bytes(-1),
100                       _null_marker_offset(-1), _null_reset_value_offset(-1), _acmp_maps_offset(-1),
101                       _has_nonstatic_fields(false), _is_naturally_atomic(false), _must_be_atomic(false),
102                       _has_inline_fields(false), _is_empty_inline_klass(false) { }
103 };
104 
105 // Parser for for .class files
106 //
107 // The bytes describing the class file structure is read from a Stream object
108 
109 class ClassFileParser {
110   friend class FieldLayoutBuilder;
111   friend class FieldLayout;
112 
113   class ClassAnnotationCollector;
114   class FieldAnnotationCollector;
115 
116  public:
117   // The ClassFileParser has an associated "publicity" level
118   // It is used to control which subsystems (if any)
119   // will observe the parsing (logging, events, tracing).
120   // Default level is "BROADCAST", which is equivalent to
121   // a "public" parsing attempt.
122   //
123   // "INTERNAL" level should be entirely private to the
124   // caller - this allows for internal reuse of ClassFileParser
125   //
126   enum Publicity {
127     INTERNAL,
128     BROADCAST
129   };
130 
131   enum { LegalClass, LegalField, LegalMethod }; // used to verify unqualified names
132 
133  private:
134   // Potentially unaligned pointer to various 16-bit entries in the class file
135   typedef void unsafe_u2;
136 
137   const ClassFileStream* _stream; // Actual input stream
138   Symbol* _class_name;
139   mutable ClassLoaderData* _loader_data;
140   const bool _is_hidden;
141   const bool _can_access_vm_annotations;
142   int _orig_cp_size;
143   unsigned int _static_oop_count;
144 
145   // Metadata created before the instance klass is created.  Must be deallocated
146   // if not transferred to the InstanceKlass upon successful class loading
147   // in which case these pointers have been set to null.
148   const InstanceKlass* _super_klass;
149   ConstantPool* _cp;
150   Array<u1>* _fieldinfo_stream;
151   Array<u1>* _fieldinfo_search_table;
152   Array<FieldStatus>* _fields_status;
153   Array<Method*>* _methods;
154   Array<u2>* _inner_classes;
155   Array<u2>* _nest_members;
156   u2 _nest_host;
157   Array<u2>* _permitted_subclasses;
158   Array<u2>* _loadable_descriptors;
159   Array<RecordComponent*>* _record_components;
160   Array<InstanceKlass*>* _local_interfaces;
161   GrowableArray<u2>* _local_interface_indexes;
162   Array<InstanceKlass*>* _transitive_interfaces;
163   Annotations* _combined_annotations;
164   AnnotationArray* _class_annotations;
165   AnnotationArray* _class_type_annotations;
166   Array<AnnotationArray*>* _fields_annotations;
167   Array<AnnotationArray*>* _fields_type_annotations;
168   InstanceKlass* _klass;  // InstanceKlass* once created.
169   InstanceKlass* _klass_to_deallocate; // an InstanceKlass* to be destroyed
170 
171   ClassAnnotationCollector* _parsed_annotations;
172   FieldLayoutInfo* _layout_info;
173   Array<InlineLayoutInfo>* _inline_layout_info_array;
174   GrowableArray<FieldInfo>* _temp_field_info;
175   const intArray* _method_ordering;
176   GrowableArray<Method*>* _all_mirandas;
177 
178   enum { fixed_buffer_size = 128 };
179   u_char _linenumbertable_buffer[fixed_buffer_size];
180 
181   // Size of Java vtable (in words)
182   int _vtable_size;
183   int _itable_size;
184 
185   int _num_miranda_methods;
186 
187 
188   Handle _protection_domain;
189   AccessFlags _access_flags;
190 
191   // for tracing and notifications
192   Publicity _pub_level;
193 
194   // Used to keep track of whether a constant pool item 19 or 20 is found.  These
195   // correspond to CONSTANT_Module and CONSTANT_Package tags and are not allowed
196   // in regular class files.  For class file version >= 53, a CFE cannot be thrown
197   // immediately when these are seen because a NCDFE must be thrown if the class's
198   // access_flags have ACC_MODULE set.  But, the access_flags haven't been looked
199   // at yet.  So, the bad constant pool item is cached here.  A value of zero
200   // means that no constant pool item 19 or 20 was found.
201   short _bad_constant_seen;
202 
203   // class attributes parsed before the instance klass is created:
204   bool _synthetic_flag;
205   int _sde_length;
206   const char* _sde_buffer;
207   u2 _sourcefile_index;
208   u2 _generic_signature_index;
209 
210   u2 _major_version;
211   u2 _minor_version;
212   u2 _this_class_index;
213   u2 _super_class_index;
214   u2 _itfs_len;
215   u2 _java_fields_count;
216 
217   bool _need_verify;
218 
219   bool _has_nonstatic_concrete_methods;
220   bool _declares_nonstatic_concrete_methods;
221   bool _has_localvariable_table;
222   bool _has_final_method;
223   bool _has_contended_fields;
224   bool _has_aot_runtime_setup_method;
225   bool _has_strict_static_fields;
226 
227   bool _has_inline_type_fields;
228   bool _is_naturally_atomic;
229   bool _must_be_atomic;
230   bool _has_loosely_consistent_annotation;
231 
232   // precomputed flags
233   bool _has_finalizer;
234   bool _has_empty_finalizer;
235   int _max_bootstrap_specifier_index;  // detects BSS values
236 
237   void parse_stream(const ClassFileStream* const stream, TRAPS);
238 
239   void mangle_hidden_class_name(InstanceKlass* const ik);
240 
241   void post_process_parsed_stream(const ClassFileStream* const stream,
242                                   ConstantPool* cp,
243                                   TRAPS);
244 
245   void fill_instance_klass(InstanceKlass* ik, bool cf_changed_in_CFLH,
246                            const ClassInstanceInfo& cl_inst_info, TRAPS);
247 
248   void set_klass(InstanceKlass* instance);
249 
250   void set_class_bad_constant_seen(short bad_constant);
251   short class_bad_constant_seen() { return  _bad_constant_seen; }
252   void set_class_synthetic_flag(bool x)        { _synthetic_flag = x; }
253   void set_class_sourcefile_index(u2 x)        { _sourcefile_index = x; }
254   void set_class_generic_signature_index(u2 x) { _generic_signature_index = x; }
255   void set_class_sde_buffer(const char* x, int len)  { _sde_buffer = x; _sde_length = len; }
256 
257   void create_combined_annotations(TRAPS);
258   void apply_parsed_class_attributes(InstanceKlass* k);  // update k
259   void apply_parsed_class_metadata(InstanceKlass* k, int fields_count);
260   void clear_class_metadata();
261 
262   // Constant pool parsing
263   void parse_constant_pool_entries(const ClassFileStream* const stream,
264                                    ConstantPool* cp,
265                                    const int length,
266                                    TRAPS);
267 
268   void parse_constant_pool(const ClassFileStream* const cfs,
269                            ConstantPool* const cp,
270                            const int length,
271                            TRAPS);
272 
273   // Interface parsing
274   void parse_interfaces(const ClassFileStream* const stream,
275                         const int itfs_len,
276                         ConstantPool* const cp,
277                         bool* has_nonstatic_concrete_methods,
278                         TRAPS);
279 
280   void check_super_class(ConstantPool* const cp,
281                          const int super_class_index,
282                          const bool need_verify,
283                          TRAPS);
284 
285   // Field parsing
286   void parse_field_attributes(const ClassFileStream* const cfs,
287                               u2 attributes_count,
288                               bool is_static,
289                               u2 signature_index,
290                               u2* const constantvalue_index_addr,
291                               bool* const is_synthetic_addr,
292                               u2* const generic_signature_index_addr,
293                               FieldAnnotationCollector* parsed_annotations,
294                               TRAPS);
295 
296   void parse_fields(const ClassFileStream* const cfs,
297                     AccessFlags class_access_flags,
298                     ConstantPool* cp,
299                     const int cp_size,
300                     u2* const java_fields_count_ptr,
301                     TRAPS);
302 
303   // Method parsing
304   Method* parse_method(const ClassFileStream* const cfs,
305                        bool is_interface,
306                        bool is_value_class,
307                        bool is_abstract_class,
308                        const ConstantPool* cp,
309                        bool* const has_localvariable_table,
310                        TRAPS);
311 
312   void parse_methods(const ClassFileStream* const cfs,
313                      bool is_interface,
314                      bool is_value_class,
315                      bool is_abstract_class,
316                      bool* const has_localvariable_table,
317                      bool* const has_final_method,
318                      bool* const declares_nonstatic_concrete_methods,
319                      TRAPS);
320 
321   const unsafe_u2* parse_exception_table(const ClassFileStream* const stream,
322                                          u4 code_length,
323                                          u4 exception_table_length,
324                                          TRAPS);
325 
326   void parse_linenumber_table(u4 code_attribute_length,
327                               u4 code_length,
328                               CompressedLineNumberWriteStream**const write_stream,
329                               TRAPS);
330 
331   const unsafe_u2* parse_localvariable_table(const ClassFileStream* const cfs,
332                                              u4 code_length,
333                                              u2 max_locals,
334                                              u4 code_attribute_length,
335                                              u2* const localvariable_table_length,
336                                              bool isLVTT,
337                                              TRAPS);
338 
339   const unsafe_u2* parse_checked_exceptions(const ClassFileStream* const cfs,
340                                             u2* const checked_exceptions_length,
341                                             u4 method_attribute_length,
342                                             TRAPS);
343 
344   // Classfile attribute parsing
345   u2 parse_generic_signature_attribute(const ClassFileStream* const cfs, TRAPS);
346   void parse_classfile_sourcefile_attribute(const ClassFileStream* const cfs, TRAPS);
347   void parse_classfile_source_debug_extension_attribute(const ClassFileStream* const cfs,
348                                                         int length,
349                                                         TRAPS);
350 
351   // Check for circularity in InnerClasses attribute.
352   bool check_inner_classes_circularity(const ConstantPool* cp, int length, TRAPS);
353 
354   u2   parse_classfile_inner_classes_attribute(const ClassFileStream* const cfs,
355                                                const ConstantPool* cp,
356                                                const u1* const inner_classes_attribute_start,
357                                                bool parsed_enclosingmethod_attribute,
358                                                u2 enclosing_method_class_index,
359                                                u2 enclosing_method_method_index,
360                                                TRAPS);
361 
362   u2 parse_classfile_nest_members_attribute(const ClassFileStream* const cfs,
363                                             const u1* const nest_members_attribute_start,
364                                             TRAPS);
365 
366   u2 parse_classfile_permitted_subclasses_attribute(const ClassFileStream* const cfs,
367                                                     const u1* const permitted_subclasses_attribute_start,
368                                                     TRAPS);
369 
370   u2 parse_classfile_loadable_descriptors_attribute(const ClassFileStream* const cfs,
371                                                     const u1* const loadable_descriptors_attribute_start,
372                                                     TRAPS);
373 
374   u4 parse_classfile_record_attribute(const ClassFileStream* const cfs,
375                                       const ConstantPool* cp,
376                                       const u1* const record_attribute_start,
377                                       TRAPS);
378 
379   void parse_classfile_attributes(const ClassFileStream* const cfs,
380                                   ConstantPool* cp,
381                                   ClassAnnotationCollector* parsed_annotations,
382                                   TRAPS);
383 
384   void parse_classfile_synthetic_attribute();
385   void parse_classfile_signature_attribute(const ClassFileStream* const cfs, TRAPS);
386   void parse_classfile_bootstrap_methods_attribute(const ClassFileStream* const cfs,
387                                                    ConstantPool* cp,
388                                                    u4 attribute_length,
389                                                    TRAPS);
390 
391   // Annotations handling
392   AnnotationArray* allocate_annotations(const u1* const anno,
393                                         int anno_length,
394                                         TRAPS);
395 
396   void set_precomputed_flags(InstanceKlass* k);
397 
398   // Format checker methods
399   void classfile_parse_error(const char* msg, TRAPS) const;
400   void classfile_parse_error(const char* msg, int index, TRAPS) const;
401   void classfile_parse_error(const char* msg, const char *name, TRAPS) const;
402   void classfile_parse_error(const char* msg,
403                              int index,
404                              const char *name,
405                              TRAPS) const;
406   void classfile_parse_error(const char* msg,
407                              const char* name,
408                              const char* signature,
409                              TRAPS) const;
410 
411   void classfile_icce_error(const char* msg,
412                             const Klass* k,
413                             TRAPS) const;
414 
415   // Uses msg directly in the ICCE, with no additional content
416   void classfile_icce_error(const char* msg,
417                             TRAPS) const;
418 
419   void classfile_ucve_error(const char* msg,
420                             const Symbol* class_name,
421                             u2 major,
422                             u2 minor,
423                             TRAPS) const;
424 
425   inline void guarantee_property(bool b, const char* msg, TRAPS) const {
426     if (!b) { classfile_parse_error(msg, THREAD); return; }
427   }
428 
429   inline void guarantee_property(bool b,
430                                  const char* msg,
431                                  int index,
432                                  TRAPS) const {
433     if (!b) { classfile_parse_error(msg, index, THREAD); return; }
434   }
435 
436   inline void guarantee_property(bool b,
437                                  const char* msg,
438                                  const char *name,
439                                  TRAPS) const {
440     if (!b) { classfile_parse_error(msg, name, THREAD); return; }
441   }
442 
443   inline void guarantee_property(bool b,
444                                  const char* msg,
445                                  int index,
446                                  const char *name,
447                                  TRAPS) const {
448     if (!b) { classfile_parse_error(msg, index, name, THREAD); return; }
449   }
450 
451   void throwIllegalSignature(const char* type,
452                              const Symbol* name,
453                              const Symbol* sig,
454                              TRAPS) const;
455 
456   void verify_constantvalue(const ConstantPool* const cp,
457                             int constantvalue_index,
458                             int signature_index,
459                             TRAPS) const;
460 
461   void verify_legal_utf8(const unsigned char* buffer, int length, TRAPS) const;
462   void verify_legal_class_name(const Symbol* name, TRAPS) const;
463   void verify_legal_field_name(const Symbol* name, TRAPS) const;
464   void verify_legal_method_name(const Symbol* name, TRAPS) const;
465 
466   bool legal_field_signature(const Symbol* signature, TRAPS) const;
467 
468   void verify_legal_field_signature(const Symbol* fieldname,
469                                     const Symbol* signature,
470                                     TRAPS) const;
471   int  verify_legal_method_signature(const Symbol* methodname,
472                                      const Symbol* signature,
473                                      TRAPS) const;
474   void verify_legal_name_with_signature(const Symbol* name,
475                                         const Symbol* signature,
476                                         TRAPS) const;
477 
478   void verify_class_version(u2 major, u2 minor, Symbol* class_name, TRAPS);
479 
480   void verify_legal_class_modifiers(jint flags, Symbol* inner_name,
481                                     bool is_anonymous_inner_class, TRAPS) const;
482   void verify_legal_field_modifiers(jint flags, AccessFlags class_access_flags, TRAPS) const;
483   void verify_legal_method_modifiers(jint flags,
484                                      AccessFlags class_access_flags,
485                                      const Symbol* name,
486                                      TRAPS) const;
487 
488   void check_super_class_access(const InstanceKlass* this_klass,
489                                 TRAPS);
490 
491   void check_super_interface_access(const InstanceKlass* this_klass,
492                                     TRAPS);
493 
494   const char* skip_over_field_signature(const char* signature,
495                                         bool void_ok,
496                                         unsigned int length,
497                                         TRAPS) const;
498 
499   // Wrapper for constantTag.is_klass_[or_]reference.
500   // In older versions of the VM, Klass*s cannot sneak into early phases of
501   // constant pool construction, but in later versions they can.
502   // %%% Let's phase out the old is_klass_reference.
503   bool valid_klass_reference_at(int index) const {
504     return _cp->is_within_bounds(index) &&
505              _cp->tag_at(index).is_klass_or_reference();
506   }
507 
508   // Checks that the cpool index is in range and is a utf8
509   bool valid_symbol_at(int cpool_index) const {
510     return _cp->is_within_bounds(cpool_index) &&
511              _cp->tag_at(cpool_index).is_utf8();
512   }
513 
514   void copy_localvariable_table(const ConstMethod* cm,
515                                 int lvt_cnt,
516                                 u2* const localvariable_table_length,
517                                 const unsafe_u2** const localvariable_table_start,
518                                 int lvtt_cnt,
519                                 u2* const localvariable_type_table_length,
520                                 const unsafe_u2** const localvariable_type_table_start,
521                                 TRAPS);
522 
523   void copy_method_annotations(ConstMethod* cm,
524                                const u1* runtime_visible_annotations,
525                                int runtime_visible_annotations_length,
526                                const u1* runtime_visible_parameter_annotations,
527                                int runtime_visible_parameter_annotations_length,
528                                const u1* runtime_visible_type_annotations,
529                                int runtime_visible_type_annotations_length,
530                                const u1* annotation_default,
531                                int annotation_default_length,
532                                TRAPS);
533 
534   void update_class_name(Symbol* new_name);
535 
536   // Check if the class file supports inline types
537   bool supports_inline_types() const;
538 
539  public:
540   ClassFileParser(ClassFileStream* stream,
541                   Symbol* name,
542                   ClassLoaderData* loader_data,
543                   const ClassLoadInfo* cl_info,
544                   Publicity pub_level,
545                   TRAPS);
546 
547   ~ClassFileParser();
548 
549   InstanceKlass* create_instance_klass(bool cf_changed_in_CFLH, const ClassInstanceInfo& cl_inst_info, TRAPS);
550 
551   const ClassFileStream* clone_stream() const;
552 
553   void set_klass_to_deallocate(InstanceKlass* klass);
554 
555   int static_field_size() const;
556   int total_oop_map_count() const;
557   jint layout_size() const;
558 
559   int vtable_size() const { return _vtable_size; }
560   int itable_size() const { return _itable_size; }
561 
562   u2 this_class_index() const { return _this_class_index; }
563 
564   bool is_hidden() const { return _is_hidden; }
565   bool is_interface() const { return _access_flags.is_interface(); }
566   // Being an inline type means being a concrete value class
567   bool is_inline_type() const { return !_access_flags.is_identity_class() && !_access_flags.is_interface() && !_access_flags.is_abstract(); }
568   bool is_abstract_class() const { return _access_flags.is_abstract(); }
569   bool is_identity_class() const { return _access_flags.is_identity_class(); }
570   bool has_inline_fields() const { return _has_inline_type_fields; }
571 
572   u2 java_fields_count() const { return _java_fields_count; }
573   bool is_abstract() const { return _access_flags.is_abstract(); }
574 
575   ClassLoaderData* loader_data() const { return _loader_data; }
576   const Symbol* class_name() const { return _class_name; }
577   const InstanceKlass* super_klass() const { return _super_klass; }
578 
579   ReferenceType super_reference_type() const;
580   bool is_instance_ref_klass() const;
581   bool is_java_lang_ref_Reference_subclass() const;
582 
583   AccessFlags access_flags() const { return _access_flags; }
584 
585   bool is_internal() const { return INTERNAL == _pub_level; }
586 
587   bool is_class_in_loadable_descriptors_attribute(Symbol *klass);
588 
589   static bool verify_unqualified_name(const char* name, unsigned int length, int type);
590 
591 #ifdef ASSERT
592   static bool is_internal_format(Symbol* class_name);
593 #endif
594 
595 };
596 
597 #endif // SHARE_CLASSFILE_CLASSFILEPARSER_HPP