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