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