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