1 /*
  2  * Copyright (c) 1997, 2023, 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   bool  _has_nonstatic_fields;
 78   bool  _is_naturally_atomic;
 79   bool _has_inline_fields;
 80 };
 81 
 82 // Parser for for .class files
 83 //
 84 // The bytes describing the class file structure is read from a Stream object
 85 
 86 class ClassFileParser {
 87   friend class FieldLayoutBuilder;
 88   friend class FieldLayout;
 89 
 90   class ClassAnnotationCollector;
 91   class FieldAllocationCount;
 92   class FieldAnnotationCollector;
 93 
 94  public:
 95   // The ClassFileParser has an associated "publicity" level
 96   // It is used to control which subsystems (if any)
 97   // will observe the parsing (logging, events, tracing).
 98   // Default level is "BROADCAST", which is equivalent to
 99   // a "public" parsing attempt.
100   //
101   // "INTERNAL" level should be entirely private to the
102   // caller - this allows for internal reuse of ClassFileParser
103   //
104   enum Publicity {
105     INTERNAL,
106     BROADCAST
107   };
108 
109   enum { LegalClass, LegalField, LegalMethod }; // used to verify unqualified names
110 
111  private:
112   // Potentially unaligned pointer to various 16-bit entries in the class file
113   typedef void unsafe_u2;
114 
115   const ClassFileStream* _stream; // Actual input stream
116   Symbol* _class_name;
117   mutable ClassLoaderData* _loader_data;
118   const bool _is_hidden;
119   const bool _can_access_vm_annotations;
120   int _orig_cp_size;
121 
122   // Metadata created before the instance klass is created.  Must be deallocated
123   // if not transferred to the InstanceKlass upon successful class loading
124   // in which case these pointers have been set to null.
125   const InstanceKlass* _super_klass;
126   ConstantPool* _cp;
127   Array<u1>* _fieldinfo_stream;
128   Array<FieldStatus>* _fields_status;
129   Array<Method*>* _methods;
130   Array<u2>* _inner_classes;
131   Array<u2>* _nest_members;
132   u2 _nest_host;
133   Array<u2>* _permitted_subclasses;
134   Array<u2>* _preload_classes;
135   Array<RecordComponent*>* _record_components;
136   Array<InstanceKlass*>* _local_interfaces;
137   GrowableArray<u2>* _local_interface_indexes;
138   Array<InstanceKlass*>* _transitive_interfaces;
139   Annotations* _combined_annotations;
140   AnnotationArray* _class_annotations;
141   AnnotationArray* _class_type_annotations;
142   Array<AnnotationArray*>* _fields_annotations;
143   Array<AnnotationArray*>* _fields_type_annotations;
144   InstanceKlass* _klass;  // InstanceKlass* once created.
145   InstanceKlass* _klass_to_deallocate; // an InstanceKlass* to be destroyed
146 
147   ClassAnnotationCollector* _parsed_annotations;
148   FieldAllocationCount* _fac;
149   FieldLayoutInfo* _field_info;
150   Array<InlineKlass*>* _inline_type_field_klasses;
151   GrowableArray<FieldInfo>* _temp_field_info;
152   const intArray* _method_ordering;
153   GrowableArray<Method*>* _all_mirandas;
154 
155   enum { fixed_buffer_size = 128 };
156   u_char _linenumbertable_buffer[fixed_buffer_size];
157 
158   // Size of Java vtable (in words)
159   int _vtable_size;
160   int _itable_size;
161 
162   int _num_miranda_methods;
163 
164   int _alignment;
165   int _first_field_offset;
166   int _exact_size_in_bytes;
167 
168   Handle _protection_domain;
169   AccessFlags _access_flags;
170 
171   // for tracing and notifications
172   Publicity _pub_level;
173 
174   // Used to keep track of whether a constant pool item 19 or 20 is found.  These
175   // correspond to CONSTANT_Module and CONSTANT_Package tags and are not allowed
176   // in regular class files.  For class file version >= 53, a CFE cannot be thrown
177   // immediately when these are seen because a NCDFE must be thrown if the class's
178   // access_flags have ACC_MODULE set.  But, the access_flags haven't been looked
179   // at yet.  So, the bad constant pool item is cached here.  A value of zero
180   // means that no constant pool item 19 or 20 was found.
181   short _bad_constant_seen;
182 
183   // class attributes parsed before the instance klass is created:
184   bool _synthetic_flag;
185   int _sde_length;
186   const char* _sde_buffer;
187   u2 _sourcefile_index;
188   u2 _generic_signature_index;
189 
190   u2 _major_version;
191   u2 _minor_version;
192   u2 _this_class_index;
193   u2 _super_class_index;
194   u2 _itfs_len;
195   u2 _java_fields_count;
196 
197   bool _need_verify;
198   bool _relax_verify;
199 
200   bool _has_nonstatic_concrete_methods;
201   bool _declares_nonstatic_concrete_methods;
202   bool _has_localvariable_table;
203   bool _has_final_method;
204   bool _has_contended_fields;
205 
206   bool _has_inline_type_fields;
207   bool _has_nonstatic_fields;
208   bool _is_empty_inline_type;
209   bool _is_naturally_atomic;
210   bool _must_be_atomic;
211   bool _is_implicitly_constructible;
212   bool _carries_value_modifier;      // Has ACC_VALUE mddifier or one of its super types has
213   bool _carries_identity_modifier;   // Has ACC_IDENTITY modifier or one of its super types has
214   bool _has_loosely_consistent_annotation;
215   bool _has_implicitly_constructible_annotation;
216 
217   // precomputed flags
218   bool _has_finalizer;
219   bool _has_empty_finalizer;
220   bool _has_vanilla_constructor;
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                     FieldAllocationCount* const fac,
285                     ConstantPool* cp,
286                     const int cp_size,
287                     u2* const java_fields_count_ptr,
288                     TRAPS);
289 
290   // Method parsing
291   Method* parse_method(const ClassFileStream* const cfs,
292                        bool is_interface,
293                        bool is_value_class,
294                        bool is_abstract_class,
295                        const ConstantPool* cp,
296                        bool* const has_localvariable_table,
297                        TRAPS);
298 
299   void parse_methods(const ClassFileStream* const cfs,
300                      bool is_interface,
301                      bool is_value_class,
302                      bool is_abstract_class,
303                      bool* const has_localvariable_table,
304                      bool* const has_final_method,
305                      bool* const declares_nonstatic_concrete_methods,
306                      TRAPS);
307 
308   const unsafe_u2* parse_exception_table(const ClassFileStream* const stream,
309                                          u4 code_length,
310                                          u4 exception_table_length,
311                                          TRAPS);
312 
313   void parse_linenumber_table(u4 code_attribute_length,
314                               u4 code_length,
315                               CompressedLineNumberWriteStream**const write_stream,
316                               TRAPS);
317 
318   const unsafe_u2* parse_localvariable_table(const ClassFileStream* const cfs,
319                                              u4 code_length,
320                                              u2 max_locals,
321                                              u4 code_attribute_length,
322                                              u2* const localvariable_table_length,
323                                              bool isLVTT,
324                                              TRAPS);
325 
326   const unsafe_u2* parse_checked_exceptions(const ClassFileStream* const cfs,
327                                             u2* const checked_exceptions_length,
328                                             u4 method_attribute_length,
329                                             TRAPS);
330 
331   // Classfile attribute parsing
332   u2 parse_generic_signature_attribute(const ClassFileStream* const cfs, TRAPS);
333   void parse_classfile_sourcefile_attribute(const ClassFileStream* const cfs, TRAPS);
334   void parse_classfile_source_debug_extension_attribute(const ClassFileStream* const cfs,
335                                                         int length,
336                                                         TRAPS);
337 
338   // Check for circularity in InnerClasses attribute.
339   bool check_inner_classes_circularity(const ConstantPool* cp, int length, TRAPS);
340 
341   u2   parse_classfile_inner_classes_attribute(const ClassFileStream* const cfs,
342                                                const ConstantPool* cp,
343                                                const u1* const inner_classes_attribute_start,
344                                                bool parsed_enclosingmethod_attribute,
345                                                u2 enclosing_method_class_index,
346                                                u2 enclosing_method_method_index,
347                                                TRAPS);
348 
349   u2 parse_classfile_nest_members_attribute(const ClassFileStream* const cfs,
350                                             const u1* const nest_members_attribute_start,
351                                             TRAPS);
352 
353   u2 parse_classfile_permitted_subclasses_attribute(const ClassFileStream* const cfs,
354                                                     const u1* const permitted_subclasses_attribute_start,
355                                                     TRAPS);
356 
357   u2 parse_classfile_preload_attribute(const ClassFileStream* const cfs,
358                                                     const u1* const preload_attribute_start,
359                                                     TRAPS);
360 
361   u4 parse_classfile_record_attribute(const ClassFileStream* const cfs,
362                                       const ConstantPool* cp,
363                                       const u1* const record_attribute_start,
364                                       TRAPS);
365 
366   void parse_classfile_attributes(const ClassFileStream* const cfs,
367                                   ConstantPool* cp,
368                                   ClassAnnotationCollector* parsed_annotations,
369                                   TRAPS);
370 
371   void parse_classfile_synthetic_attribute();
372   void parse_classfile_signature_attribute(const ClassFileStream* const cfs, TRAPS);
373   void parse_classfile_bootstrap_methods_attribute(const ClassFileStream* const cfs,
374                                                    ConstantPool* cp,
375                                                    u4 attribute_length,
376                                                    TRAPS);
377 
378   // Annotations handling
379   AnnotationArray* assemble_annotations(const u1* const runtime_visible_annotations,
380                                         int runtime_visible_annotations_length,
381                                         const u1* const runtime_invisible_annotations,
382                                         int runtime_invisible_annotations_length,
383                                         TRAPS);
384 
385   void set_precomputed_flags(InstanceKlass* k);
386 
387   // Format checker methods
388   void classfile_parse_error(const char* msg, TRAPS) const;
389   void classfile_parse_error(const char* msg, int index, TRAPS) const;
390   void classfile_parse_error(const char* msg, const char *name, TRAPS) const;
391   void classfile_parse_error(const char* msg,
392                              int index,
393                              const char *name,
394                              TRAPS) const;
395   void classfile_parse_error(const char* msg,
396                              const char* name,
397                              const char* signature,
398                              TRAPS) const;
399 
400   void classfile_icce_error(const char* msg,
401                             const Klass* k,
402                             TRAPS) const;
403 
404   void classfile_ucve_error(const char* msg,
405                             const Symbol* class_name,
406                             u2 major,
407                             u2 minor,
408                             TRAPS) const;
409 
410   inline void guarantee_property(bool b, const char* msg, TRAPS) const {
411     if (!b) { classfile_parse_error(msg, THREAD); return; }
412   }
413 
414   void report_assert_property_failure(const char* msg, TRAPS) const PRODUCT_RETURN;
415   void report_assert_property_failure(const char* msg, int index, TRAPS) const PRODUCT_RETURN;
416 
417   inline void assert_property(bool b, const char* msg, TRAPS) const {
418 #ifdef ASSERT
419     if (!b) {
420       report_assert_property_failure(msg, THREAD);
421     }
422 #endif
423   }
424 
425   inline void assert_property(bool b, const char* msg, int index, TRAPS) const {
426 #ifdef ASSERT
427     if (!b) {
428       report_assert_property_failure(msg, index, THREAD);
429     }
430 #endif
431   }
432 
433   inline void check_property(bool property,
434                              const char* msg,
435                              int index,
436                              TRAPS) const {
437     if (_need_verify) {
438       guarantee_property(property, msg, index, CHECK);
439     } else {
440       assert_property(property, msg, index, CHECK);
441     }
442   }
443 
444   inline void check_property(bool property, const char* msg, TRAPS) const {
445     if (_need_verify) {
446       guarantee_property(property, msg, CHECK);
447     } else {
448       assert_property(property, msg, CHECK);
449     }
450   }
451 
452   inline void guarantee_property(bool b,
453                                  const char* msg,
454                                  int index,
455                                  TRAPS) const {
456     if (!b) { classfile_parse_error(msg, index, THREAD); return; }
457   }
458 
459   inline void guarantee_property(bool b,
460                                  const char* msg,
461                                  const char *name,
462                                  TRAPS) const {
463     if (!b) { classfile_parse_error(msg, name, THREAD); return; }
464   }
465 
466   inline void guarantee_property(bool b,
467                                  const char* msg,
468                                  int index,
469                                  const char *name,
470                                  TRAPS) const {
471     if (!b) { classfile_parse_error(msg, index, name, THREAD); return; }
472   }
473 
474   void throwIllegalSignature(const char* type,
475                              const Symbol* name,
476                              const Symbol* sig,
477                              TRAPS) const;
478 
479   void throwInlineTypeLimitation(THREAD_AND_LOCATION_DECL,
480                                  const char* msg,
481                                  const Symbol* name = nullptr,
482                                  const Symbol* sig  = nullptr) const;
483 
484   void verify_constantvalue(const ConstantPool* const cp,
485                             int constantvalue_index,
486                             int signature_index,
487                             TRAPS) const;
488 
489   void verify_legal_utf8(const unsigned char* buffer, int length, TRAPS) const;
490   void verify_legal_class_name(const Symbol* name, TRAPS) const;
491   void verify_legal_field_name(const Symbol* name, TRAPS) const;
492   void verify_legal_method_name(const Symbol* name, TRAPS) const;
493 
494   void verify_legal_field_signature(const Symbol* fieldname,
495                                     const Symbol* signature,
496                                     TRAPS) const;
497   int  verify_legal_method_signature(const Symbol* methodname,
498                                      const Symbol* signature,
499                                      TRAPS) const;
500   void verify_legal_name_with_signature(const Symbol* name,
501                                         const Symbol* signature,
502                                         TRAPS) const;
503 
504   void verify_class_version(u2 major, u2 minor, Symbol* class_name, TRAPS);
505 
506   void verify_legal_class_modifiers(jint flags, const char* name, bool is_Object, TRAPS) const;
507   void verify_legal_field_modifiers(jint flags,
508                                     AccessFlags class_access_flags,
509                                     TRAPS) const;
510   void verify_legal_method_modifiers(jint flags,
511                                      AccessFlags class_access_flags,
512                                      const Symbol* name,
513                                      TRAPS) const;
514 
515   void check_super_class_access(const InstanceKlass* this_klass,
516                                 TRAPS);
517 
518   void check_super_interface_access(const InstanceKlass* this_klass,
519                                     TRAPS);
520 
521   const char* skip_over_field_signature(const char* signature,
522                                         bool void_ok,
523                                         unsigned int length,
524                                         TRAPS) const;
525 
526   // Wrapper for constantTag.is_klass_[or_]reference.
527   // In older versions of the VM, Klass*s cannot sneak into early phases of
528   // constant pool construction, but in later versions they can.
529   // %%% Let's phase out the old is_klass_reference.
530   bool valid_klass_reference_at(int index) const {
531     return _cp->is_within_bounds(index) &&
532              _cp->tag_at(index).is_klass_or_reference();
533   }
534 
535   // Checks that the cpool index is in range and is a utf8
536   bool valid_symbol_at(int cpool_index) const {
537     return _cp->is_within_bounds(cpool_index) &&
538              _cp->tag_at(cpool_index).is_utf8();
539   }
540 
541   void copy_localvariable_table(const ConstMethod* cm,
542                                 int lvt_cnt,
543                                 u2* const localvariable_table_length,
544                                 const unsafe_u2** const localvariable_table_start,
545                                 int lvtt_cnt,
546                                 u2* const localvariable_type_table_length,
547                                 const unsafe_u2** const localvariable_type_table_start,
548                                 TRAPS);
549 
550   void copy_method_annotations(ConstMethod* cm,
551                                const u1* runtime_visible_annotations,
552                                int runtime_visible_annotations_length,
553                                const u1* runtime_invisible_annotations,
554                                int runtime_invisible_annotations_length,
555                                const u1* runtime_visible_parameter_annotations,
556                                int runtime_visible_parameter_annotations_length,
557                                const u1* runtime_invisible_parameter_annotations,
558                                int runtime_invisible_parameter_annotations_length,
559                                const u1* runtime_visible_type_annotations,
560                                int runtime_visible_type_annotations_length,
561                                const u1* runtime_invisible_type_annotations,
562                                int runtime_invisible_type_annotations_length,
563                                const u1* annotation_default,
564                                int annotation_default_length,
565                                TRAPS);
566 
567   void update_class_name(Symbol* new_name);
568 
569   // Check if the class file supports inline types
570   bool supports_inline_types() const;
571 
572  public:
573   ClassFileParser(ClassFileStream* stream,
574                   Symbol* name,
575                   ClassLoaderData* loader_data,
576                   const ClassLoadInfo* cl_info,
577                   Publicity pub_level,
578                   TRAPS);
579 
580   ~ClassFileParser();
581 
582   InstanceKlass* create_instance_klass(bool cf_changed_in_CFLH, const ClassInstanceInfo& cl_inst_info, TRAPS);
583 
584   const ClassFileStream* clone_stream() const;
585 
586   void set_klass_to_deallocate(InstanceKlass* klass);
587 
588   int static_field_size() const;
589   int total_oop_map_count() const;
590   jint layout_size() const;
591 
592   int vtable_size() const { return _vtable_size; }
593   int itable_size() const { return _itable_size; }
594 
595   u2 this_class_index() const { return _this_class_index; }
596 
597   bool is_hidden() const { return _is_hidden; }
598   bool is_interface() const { return _access_flags.is_interface(); }
599   bool is_inline_type() const { return _access_flags.is_value_class() && !_access_flags.is_interface() && !_access_flags.is_abstract(); }
600   bool is_value_class() const { return _access_flags.is_value_class(); }
601   bool is_abstract_class() const { return _access_flags.is_abstract(); }
602   bool is_identity_class() const { return _access_flags.is_identity_class(); }
603   bool is_value_capable_class() const;
604   bool has_inline_fields() const { return _has_inline_type_fields; }
605   bool carries_identity_modifier() const { return _carries_identity_modifier; }
606   void set_carries_identity_modifier() { _carries_identity_modifier = true; }
607   bool carries_value_modifier() const { return _carries_value_modifier; }
608   void set_carries_value_modifier() { _carries_value_modifier = true; }
609 
610   u2 java_fields_count() const { return _java_fields_count; }
611 
612   ClassLoaderData* loader_data() const { return _loader_data; }
613   const Symbol* class_name() const { return _class_name; }
614   const InstanceKlass* super_klass() const { return _super_klass; }
615 
616   ReferenceType super_reference_type() const;
617   bool is_instance_ref_klass() const;
618   bool is_java_lang_ref_Reference_subclass() const;
619 
620   AccessFlags access_flags() const { return _access_flags; }
621 
622   bool is_internal() const { return INTERNAL == _pub_level; }
623 
624   bool is_class_in_preload_attribute(Symbol *klass);
625 
626   static bool verify_unqualified_name(const char* name, unsigned int length, int type);
627 
628 #ifdef ASSERT
629   static bool is_internal_format(Symbol* class_name);
630 #endif
631 
632 };
633 
634 #endif // SHARE_CLASSFILE_CLASSFILEPARSER_HPP