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