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