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