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