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