1 /*
  2  * Copyright (c) 1998, 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_VERIFIER_HPP
 26 #define SHARE_CLASSFILE_VERIFIER_HPP
 27 
 28 #include "classfile/verificationType.hpp"
 29 #include "oops/klass.hpp"
 30 #include "oops/method.hpp"
 31 #include "runtime/handles.hpp"
 32 #include "utilities/exceptions.hpp"
 33 #include "utilities/growableArray.hpp"
 34 #include "utilities/resourceHash.hpp"
 35 
 36 // The verifier class
 37 class Verifier : AllStatic {
 38  public:
 39   enum {
 40     STACKMAP_ATTRIBUTE_MAJOR_VERSION    = 50,
 41     INVOKEDYNAMIC_MAJOR_VERSION         = 51,
 42     NO_RELAX_ACCESS_CTRL_CHECK_VERSION  = 52,
 43     DYNAMICCONSTANT_MAJOR_VERSION       = 55
 44   };
 45 
 46   // Verify the bytecodes for a class.
 47   static bool verify(InstanceKlass* klass, bool should_verify_class, TRAPS);
 48 
 49   static void log_end_verification(outputStream* st, const char* klassName, Symbol* exception_name,
 50                                     oop pending_exception);
 51 
 52   // Return false if the class is loaded by the bootstrap loader,
 53   // or if defineClass was called requesting skipping verification
 54   // -Xverify:all overrides this value
 55   static bool should_verify_for(oop class_loader);
 56 
 57   // Relax certain access checks to enable some broken 1.1 apps to run on 1.2.
 58   static bool relax_access_for(oop class_loader);
 59 
 60   // Print output for class+resolve
 61   static void trace_class_resolution(Klass* resolve_class, InstanceKlass* verify_class);
 62 
 63  private:
 64   static Symbol* inference_verify(
 65     InstanceKlass* klass, char* msg, size_t msg_len, TRAPS);
 66 };
 67 
 68 class RawBytecodeStream;
 69 class StackMapFrame;
 70 class StackMapTable;
 71 
 72 // Summary of verifier's memory usage:
 73 // StackMapTable is stack allocated.
 74 // StackMapFrame are resource allocated. There is only one ResourceMark
 75 // for each class verification, which is created at the top level.
 76 // There is one mutable StackMapFrame (current_frame) which is updated
 77 // by abstract bytecode interpretation. frame_in_exception_handler() returns
 78 // a frame that has a mutable one-item stack (ready for pushing the
 79 // catch type exception object). All the other StackMapFrame's
 80 // are immutable (including their locals and stack arrays) after
 81 // their constructions.
 82 // locals/stack arrays in StackMapFrame are resource allocated.
 83 // locals/stack arrays can be shared between StackMapFrame's, except
 84 // the mutable StackMapFrame (current_frame).
 85 
 86 // These macros are used similarly to CHECK macros but also check
 87 // the status of the verifier and return if that has an error.
 88 #define CHECK_VERIFY(verifier) \
 89   CHECK); if ((verifier)->has_error()) return; ((void)0
 90 #define CHECK_VERIFY_(verifier, result) \
 91   CHECK_(result)); if ((verifier)->has_error()) return (result); ((void)0
 92 
 93 class TypeOrigin {
 94  private:
 95   typedef enum {
 96     CF_LOCALS,  // Comes from the current frame locals
 97     CF_STACK,   // Comes from the current frame expression stack
 98     SM_LOCALS,  // Comes from stackmap locals
 99     SM_STACK,   // Comes from stackmap expression stack
100     CONST_POOL, // Comes from the constant pool
101     SIG,        // Comes from method signature
102     IMPLICIT,   // Comes implicitly from code or context
103     BAD_INDEX,  // No type, but the index is bad
104     FRAME_ONLY, // No type, context just contains the frame
105     NONE
106   } Origin;
107 
108   Origin _origin;
109   int _index;              // local, stack, or constant pool index
110   StackMapFrame* _frame;  // source frame if CF or SM
111   VerificationType _type; // The actual type
112 
113   TypeOrigin(
114       Origin origin, int index, StackMapFrame* frame, VerificationType type)
115       : _origin(origin), _index(index), _frame(frame), _type(type) {}
116 
117  public:
118   TypeOrigin() : _origin(NONE), _index(0), _frame(nullptr) {}
119 
120   static TypeOrigin null();
121   static TypeOrigin local(int index, StackMapFrame* frame);
122   static TypeOrigin stack(int index, StackMapFrame* frame);
123   static TypeOrigin sm_local(int index, StackMapFrame* frame);
124   static TypeOrigin sm_stack(int index, StackMapFrame* frame);
125   static TypeOrigin cp(int index, VerificationType vt);
126   static TypeOrigin signature(VerificationType vt);
127   static TypeOrigin bad_index(int index);
128   static TypeOrigin implicit(VerificationType t);
129   static TypeOrigin frame(StackMapFrame* frame);
130 
131   void reset_frame();
132   void details(outputStream* ss) const;
133   void print_frame(outputStream* ss) const;
134   const StackMapFrame* frame() const { return _frame; }
135   bool is_valid() const { return _origin != NONE; }
136   int index() const { return _index; }
137 
138 #ifdef ASSERT
139   void print_on(outputStream* str) const;
140 #endif
141 };
142 
143 class ErrorContext {
144  private:
145   typedef enum {
146     INVALID_BYTECODE,     // There was a problem with the bytecode
147     WRONG_TYPE,           // Type value was not as expected
148     FLAGS_MISMATCH,       // Frame flags are not assignable
149     BAD_CP_INDEX,         // Invalid constant pool index
150     BAD_LOCAL_INDEX,      // Invalid local index
151     LOCALS_SIZE_MISMATCH, // Frames have differing local counts
152     STACK_SIZE_MISMATCH,  // Frames have different stack sizes
153     STACK_OVERFLOW,       // Attempt to push onto a full expression stack
154     STACK_UNDERFLOW,      // Attempt to pop and empty expression stack
155     MISSING_STACKMAP,     // No stackmap for this location and there should be
156     BAD_STACKMAP,         // Format error in stackmap
157     NO_FAULT,             // No error
158     UNKNOWN
159   } FaultType;
160 
161   int _bci;
162   FaultType _fault;
163   TypeOrigin _type;
164   TypeOrigin _expected;
165 
166   ErrorContext(int bci, FaultType fault) :
167       _bci(bci), _fault(fault)  {}
168   ErrorContext(int bci, FaultType fault, TypeOrigin type) :
169       _bci(bci), _fault(fault), _type(type)  {}
170   ErrorContext(int bci, FaultType fault, TypeOrigin type, TypeOrigin exp) :
171       _bci(bci), _fault(fault), _type(type), _expected(exp)  {}
172 
173  public:
174   ErrorContext() : _bci(-1), _fault(NO_FAULT) {}
175 
176   static ErrorContext bad_code(int bci) {
177     return ErrorContext(bci, INVALID_BYTECODE);
178   }
179   static ErrorContext bad_type(int bci, TypeOrigin type) {
180     return ErrorContext(bci, WRONG_TYPE, type);
181   }
182   static ErrorContext bad_type(int bci, TypeOrigin type, TypeOrigin exp) {
183     return ErrorContext(bci, WRONG_TYPE, type, exp);
184   }
185   static ErrorContext bad_flags(int bci, StackMapFrame* frame) {
186     return ErrorContext(bci, FLAGS_MISMATCH, TypeOrigin::frame(frame));
187   }
188   static ErrorContext bad_flags(int bci, StackMapFrame* cur, StackMapFrame* sm) {
189     return ErrorContext(bci, FLAGS_MISMATCH,
190                         TypeOrigin::frame(cur), TypeOrigin::frame(sm));
191   }
192   static ErrorContext bad_cp_index(int bci, int index) {
193     return ErrorContext(bci, BAD_CP_INDEX, TypeOrigin::bad_index(index));
194   }
195   static ErrorContext bad_local_index(int bci, int index) {
196     return ErrorContext(bci, BAD_LOCAL_INDEX, TypeOrigin::bad_index(index));
197   }
198   static ErrorContext locals_size_mismatch(
199       int bci, StackMapFrame* frame0, StackMapFrame* frame1) {
200     return ErrorContext(bci, LOCALS_SIZE_MISMATCH,
201         TypeOrigin::frame(frame0), TypeOrigin::frame(frame1));
202   }
203   static ErrorContext stack_size_mismatch(
204       int bci, StackMapFrame* frame0, StackMapFrame* frame1) {
205     return ErrorContext(bci, STACK_SIZE_MISMATCH,
206         TypeOrigin::frame(frame0), TypeOrigin::frame(frame1));
207   }
208   static ErrorContext stack_overflow(int bci, StackMapFrame* frame) {
209     return ErrorContext(bci, STACK_OVERFLOW, TypeOrigin::frame(frame));
210   }
211   static ErrorContext stack_underflow(int bci, StackMapFrame* frame) {
212     return ErrorContext(bci, STACK_UNDERFLOW, TypeOrigin::frame(frame));
213   }
214   static ErrorContext missing_stackmap(int bci) {
215     return ErrorContext(bci, MISSING_STACKMAP);
216   }
217   static ErrorContext bad_stackmap(int index, StackMapFrame* frame) {
218     return ErrorContext(0, BAD_STACKMAP, TypeOrigin::frame(frame));
219   }
220 
221   bool is_valid() const { return _fault != NO_FAULT; }
222   int bci() const { return _bci; }
223 
224   void reset_frames() {
225     _type.reset_frame();
226     _expected.reset_frame();
227   }
228 
229   void details(outputStream* ss, const Method* method) const;
230 
231 #ifdef ASSERT
232   void print_on(outputStream* str) const {
233     str->print("error_context(%d, %d,", _bci, _fault);
234     _type.print_on(str);
235     str->print(",");
236     _expected.print_on(str);
237     str->print(")");
238   }
239 #endif
240 
241  private:
242   void location_details(outputStream* ss, const Method* method) const;
243   void reason_details(outputStream* ss) const;
244   void frame_details(outputStream* ss) const;
245   void bytecode_details(outputStream* ss, const Method* method) const;
246   void handler_details(outputStream* ss, const Method* method) const;
247   void stackmap_details(outputStream* ss, const Method* method) const;
248 };
249 
250 class sig_as_verification_types : public ResourceObj {
251  private:
252   int _num_args;  // Number of arguments, not including return type.
253   GrowableArray<VerificationType>* _sig_verif_types;
254 
255  public:
256 
257   sig_as_verification_types(GrowableArray<VerificationType>* sig_verif_types) :
258     _num_args(0), _sig_verif_types(sig_verif_types) {
259   }
260 
261   int num_args() const { return _num_args; }
262   void set_num_args(int num_args) { _num_args = num_args; }
263 
264   GrowableArray<VerificationType>* sig_verif_types() { return _sig_verif_types; }
265   void set_sig_verif_types(GrowableArray<VerificationType>* sig_verif_types) {
266     _sig_verif_types = sig_verif_types;
267   }
268 
269 };
270 
271 // This hashtable is indexed by the Utf8 constant pool indexes pointed to
272 // by constant pool (Interface)Method_refs' NameAndType signature entries.
273 typedef ResourceHashtable<int, sig_as_verification_types*, 1007>
274                           method_signatures_table_type;
275 
276 // A new instance of this class is created for each class being verified
277 class ClassVerifier : public StackObj {
278  private:
279   Thread* _thread;
280 
281   Symbol* _previous_symbol;          // cache of the previously looked up symbol
282   GrowableArray<Symbol*>* _symbols;  // keep a list of symbols created
283 
284   Symbol* _exception_type;
285   char* _message;
286 
287   method_signatures_table_type _method_signatures_table;
288 
289   ErrorContext _error_context;  // contains information about an error
290 
291   void verify_method(const methodHandle& method, TRAPS);
292   char* generate_code_data(const methodHandle& m, u4 code_length, TRAPS);
293   void verify_exception_handler_table(u4 code_length, char* code_data,
294                                       int& min, int& max, TRAPS);
295   void verify_local_variable_table(u4 code_length, char* code_data, TRAPS);
296 
297   VerificationType cp_ref_index_to_type(
298       int index, const constantPoolHandle& cp, TRAPS) {
299     return cp_index_to_type(cp->uncached_klass_ref_index_at(index), cp, THREAD);
300   }
301 
302   bool is_protected_access(
303     InstanceKlass* this_class, Klass* target_class,
304     Symbol* field_name, Symbol* field_sig, bool is_method);
305 
306   void verify_cp_index(int bci, const constantPoolHandle& cp, u2 index, TRAPS);
307   void verify_cp_type(int bci, u2 index, const constantPoolHandle& cp,
308       unsigned int types, TRAPS);
309   void verify_cp_class_type(int bci, u2 index, const constantPoolHandle& cp, TRAPS);
310 
311   u2 verify_stackmap_table(
312     u2 stackmap_index, int bci, StackMapFrame* current_frame,
313     StackMapTable* stackmap_table, bool no_control_flow, TRAPS);
314 
315   void verify_exception_handler_targets(
316     int bci, bool this_uninit, StackMapFrame* current_frame,
317     StackMapTable* stackmap_table, TRAPS);
318 
319   void verify_ldc(
320     int opcode, u2 index, StackMapFrame *current_frame,
321     const constantPoolHandle& cp, int bci, TRAPS);
322 
323   void verify_switch(
324     RawBytecodeStream* bcs, u4 code_length, char* code_data,
325     StackMapFrame* current_frame, StackMapTable* stackmap_table, TRAPS);
326 
327   void verify_field_instructions(
328     RawBytecodeStream* bcs, StackMapFrame* current_frame,
329     const constantPoolHandle& cp, bool allow_arrays, TRAPS);
330 
331   void verify_invoke_init(
332     RawBytecodeStream* bcs, u2 ref_index, VerificationType ref_class_type,
333     StackMapFrame* current_frame, u4 code_length, bool in_try_block,
334     bool* this_uninit, const constantPoolHandle& cp, StackMapTable* stackmap_table,
335     TRAPS);
336 
337   // Used by ends_in_athrow() to push all handlers that contain bci onto the
338   // handler_stack, if the handler has not already been pushed on the stack.
339   void push_handlers(ExceptionTable* exhandlers,
340                      GrowableArray<u4>* handler_list,
341                      GrowableArray<u4>* handler_stack,
342                      u4 bci);
343 
344   // Returns true if all paths starting with start_bc_offset end in athrow
345   // bytecode or loop.
346   bool ends_in_athrow(u4 start_bc_offset);
347 
348   void verify_invoke_instructions(
349     RawBytecodeStream* bcs, u4 code_length, StackMapFrame* current_frame,
350     bool in_try_block, bool* this_uninit, VerificationType return_type,
351     const constantPoolHandle& cp, StackMapTable* stackmap_table, TRAPS);
352 
353   VerificationType get_newarray_type(u2 index, int bci, TRAPS);
354   void verify_anewarray(int bci, u2 index, const constantPoolHandle& cp,
355       StackMapFrame* current_frame, TRAPS);
356   void verify_return_value(
357       VerificationType return_type, VerificationType type, int bci,
358       StackMapFrame* current_frame, TRAPS);
359 
360   void verify_iload (int index, StackMapFrame* current_frame, TRAPS);
361   void verify_lload (int index, StackMapFrame* current_frame, TRAPS);
362   void verify_fload (int index, StackMapFrame* current_frame, TRAPS);
363   void verify_dload (int index, StackMapFrame* current_frame, TRAPS);
364   void verify_aload (int index, StackMapFrame* current_frame, TRAPS);
365   void verify_istore(int index, StackMapFrame* current_frame, TRAPS);
366   void verify_lstore(int index, StackMapFrame* current_frame, TRAPS);
367   void verify_fstore(int index, StackMapFrame* current_frame, TRAPS);
368   void verify_dstore(int index, StackMapFrame* current_frame, TRAPS);
369   void verify_astore(int index, StackMapFrame* current_frame, TRAPS);
370   void verify_iinc  (int index, StackMapFrame* current_frame, TRAPS);
371 
372   bool name_in_supers(Symbol* ref_name, InstanceKlass* current);
373 
374   VerificationType object_type() const;
375 
376   InstanceKlass*      _klass;  // the class being verified
377   methodHandle        _method; // current method being verified
378   VerificationType    _this_type; // the verification type of the current class
379 
380   // Some recursive calls from the verifier to the name resolver
381   // can cause the current class to be re-verified and rewritten.
382   // If this happens, the original verification should not continue,
383   // because constant pool indexes will have changed.
384   // The rewriter is preceded by the verifier.  If the verifier throws
385   // an error, rewriting is prevented.  Also, rewriting always precedes
386   // bytecode execution or compilation.  Thus, is_rewritten implies
387   // that a class has been verified and prepared for execution.
388   bool was_recursively_verified() { return _klass->is_rewritten(); }
389 
390   bool is_same_or_direct_interface(InstanceKlass* klass,
391     VerificationType klass_type, VerificationType ref_class_type);
392 
393  public:
394   enum {
395     BYTECODE_OFFSET = 1,
396     NEW_OFFSET = 2
397   };
398 
399   // constructor
400   ClassVerifier(JavaThread* current, InstanceKlass* klass);
401 
402   // destructor
403   ~ClassVerifier();
404 
405   Thread* thread()             { return _thread; }
406   const methodHandle& method() { return _method; }
407   InstanceKlass* current_class() const { return _klass; }
408   VerificationType current_type() const { return _this_type; }
409 
410   // Verifies the class.  If a verify or class file format error occurs,
411   // the '_exception_name' symbols will set to the exception name and
412   // the message_buffer will be filled in with the exception message.
413   void verify_class(TRAPS);
414 
415   // Translates method signature entries into verificationTypes and saves them
416   // in the growable array.
417   void translate_signature(Symbol* const method_sig, sig_as_verification_types* sig_verif_types);
418 
419   // Initializes a sig_as_verification_types entry and puts it in the hash table.
420   void create_method_sig_entry(sig_as_verification_types* sig_verif_types, int sig_index);
421 
422   // Return status modes
423   Symbol* result() const { return _exception_type; }
424   bool has_error() const { return result() != nullptr; }
425   char* exception_message() {
426     stringStream ss;
427     ss.print("%s", _message);
428     _error_context.details(&ss, _method());
429     return ss.as_string();
430   }
431 
432   // Called when verify or class format errors are encountered.
433   // May throw an exception based upon the mode.
434   void verify_error(ErrorContext ctx, const char* fmt, ...) ATTRIBUTE_PRINTF(3, 4);
435   void class_format_error(const char* fmt, ...) ATTRIBUTE_PRINTF(2, 3);
436 
437   Klass* load_class(Symbol* name, TRAPS);
438 
439   method_signatures_table_type* method_signatures_table() {
440     return &_method_signatures_table;
441   }
442 
443   int change_sig_to_verificationType(
444     SignatureStream* sig_type, VerificationType* inference_type);
445 
446   VerificationType cp_index_to_type(int index, const constantPoolHandle& cp, TRAPS) {
447     return VerificationType::reference_type(cp->klass_name_at(index));
448   }
449 
450   // Keep a list of temporary symbols created during verification because
451   // their reference counts need to be decremented when the verifier object
452   // goes out of scope.  Since these symbols escape the scope in which they're
453   // created, we can't use a TempNewSymbol.
454   Symbol* create_temporary_symbol(const char *s, int length);
455   Symbol* create_temporary_symbol(Symbol* s) {
456     if (s == _previous_symbol) {
457       return s;
458     }
459     if (!s->is_permanent()) {
460       s->increment_refcount();
461       if (_symbols == nullptr) {
462         _symbols = new GrowableArray<Symbol*>(50, 0, nullptr);
463       }
464       _symbols->push(s);
465     }
466     _previous_symbol = s;
467     return s;
468   }
469 
470   TypeOrigin ref_ctx(const char* str);
471 
472 };
473 
474 inline int ClassVerifier::change_sig_to_verificationType(
475     SignatureStream* sig_type, VerificationType* inference_type) {
476   BasicType bt = sig_type->type();
477   switch (bt) {
478     case T_OBJECT:
479     case T_ARRAY:
480       {
481         Symbol* name = sig_type->as_symbol();
482         // Create another symbol to save as signature stream unreferences this symbol.
483         Symbol* name_copy = create_temporary_symbol(name);
484         assert(name_copy == name, "symbols don't match");
485         *inference_type =
486           VerificationType::reference_type(name_copy);
487         return 1;
488       }
489     case T_LONG:
490       *inference_type = VerificationType::long_type();
491       *++inference_type = VerificationType::long2_type();
492       return 2;
493     case T_DOUBLE:
494       *inference_type = VerificationType::double_type();
495       *++inference_type = VerificationType::double2_type();
496       return 2;
497     case T_INT:
498     case T_BOOLEAN:
499     case T_BYTE:
500     case T_CHAR:
501     case T_SHORT:
502       *inference_type = VerificationType::integer_type();
503       return 1;
504     case T_FLOAT:
505       *inference_type = VerificationType::float_type();
506       return 1;
507     default:
508       ShouldNotReachHere();
509       return 1;
510   }
511 }
512 
513 #endif // SHARE_CLASSFILE_VERIFIER_HPP