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