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/hashTable.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 = 70,
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 HashTable<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 void verify_invoke_instructions(
361 RawBytecodeStream* bcs, u4 code_length, StackMapFrame* current_frame,
362 bool in_try_block, bool* this_uninit,
363 const constantPoolHandle& cp, StackMapTable* stackmap_table, TRAPS);
364
365 VerificationType get_newarray_type(u2 index, int bci, TRAPS);
366 void verify_anewarray(int bci, u2 index, const constantPoolHandle& cp,
367 StackMapFrame* current_frame, TRAPS);
368 void verify_return_value(
369 VerificationType return_type, VerificationType type, int bci,
370 StackMapFrame* current_frame, TRAPS);
371
372 void verify_iload (int index, StackMapFrame* current_frame, TRAPS);
373 void verify_lload (int index, StackMapFrame* current_frame, TRAPS);
374 void verify_fload (int index, StackMapFrame* current_frame, TRAPS);
375 void verify_dload (int index, StackMapFrame* current_frame, TRAPS);
376 void verify_aload (int index, StackMapFrame* current_frame, TRAPS);
377 void verify_istore(int index, StackMapFrame* current_frame, TRAPS);
378 void verify_lstore(int index, StackMapFrame* current_frame, TRAPS);
379 void verify_fstore(int index, StackMapFrame* current_frame, TRAPS);
380 void verify_dstore(int index, StackMapFrame* current_frame, TRAPS);
381 void verify_astore(int index, StackMapFrame* current_frame, TRAPS);
382 void verify_iinc (int index, StackMapFrame* current_frame, TRAPS);
383
384 bool name_in_supers(Symbol* ref_name, InstanceKlass* current);
385
386 VerificationType object_type() const;
387
388 InstanceKlass* _klass; // the class being verified
389 methodHandle _method; // current method being verified
390 VerificationType _this_type; // the verification type of the current class
391
392 // Some recursive calls from the verifier to the name resolver
393 // can cause the current class to be re-verified and rewritten.
394 // If this happens, the original verification should not continue,
395 // because constant pool indexes will have changed.
396 // The rewriter is preceded by the verifier. If the verifier throws
397 // an error, rewriting is prevented. Also, rewriting always precedes
398 // bytecode execution or compilation. Thus, is_rewritten implies
399 // that a class has been verified and prepared for execution.
400 bool was_recursively_verified() { return _klass->is_rewritten(); }
401
402 bool is_same_or_direct_interface(InstanceKlass* klass,
403 VerificationType klass_type, VerificationType ref_class_type);
404
405 public:
406 enum {
407 BYTECODE_OFFSET = 1,
408 NEW_OFFSET = 2
409 };
410
411 // constructor
412 ClassVerifier(JavaThread* current, InstanceKlass* klass);
413
414 // destructor
415 ~ClassVerifier();
416
417 Thread* thread() { return _thread; }
418 const methodHandle& method() { return _method; }
419 InstanceKlass* current_class() const { return _klass; }
420 VerificationType current_type() const { return _this_type; }
421
422 // Verifies the class. If a verify or class file format error occurs,
423 // the '_exception_name' symbols will set to the exception name and
424 // the message_buffer will be filled in with the exception message.
425 void verify_class(TRAPS);
426
427 // Translates method signature entries into verificationTypes and saves them
428 // in the growable array.
429 void translate_signature(Symbol* const method_sig, sig_as_verification_types* sig_verif_types);
430
431 // Initializes a sig_as_verification_types entry and puts it in the hash table.
432 void create_method_sig_entry(sig_as_verification_types* sig_verif_types, int sig_index);
433
434 // Return status modes
435 Symbol* result() const { return _exception_type; }
436 bool has_error() const { return result() != nullptr; }
437 char* exception_message() {
438 stringStream ss;
439 ss.print("%s", _message);
440 _error_context.details(&ss, _method());
441 return ss.as_string();
442 }
443
444 // Called when verify or class format errors are encountered.
445 // May throw an exception based upon the mode.
446 void verify_error(ErrorContext ctx, const char* fmt, ...) ATTRIBUTE_PRINTF(3, 4);
447 void class_format_error(const char* fmt, ...) ATTRIBUTE_PRINTF(2, 3);
448
449 Klass* load_class(Symbol* name, TRAPS);
450
451 method_signatures_table_type* method_signatures_table() {
452 return &_method_signatures_table;
453 }
454
455 int change_sig_to_verificationType(
456 SignatureStream* sig_type, VerificationType* inference_type);
457
458 VerificationType cp_index_to_type(int index, const constantPoolHandle& cp, TRAPS) {
459 Symbol* name = cp->klass_name_at(index);
460 return VerificationType::reference_type(name);
461 }
462
463 // Keep a list of temporary symbols created during verification because
464 // their reference counts need to be decremented when the verifier object
465 // goes out of scope. Since these symbols escape the scope in which they're
466 // created, we can't use a TempNewSymbol.
467 Symbol* create_temporary_symbol(const char *s, int length);
468 Symbol* create_temporary_symbol(Symbol* s) {
469 if (s == _previous_symbol) {
470 return s;
471 }
472 if (!s->is_permanent()) {
473 s->increment_refcount();
474 if (_symbols == nullptr) {
475 _symbols = new GrowableArray<Symbol*>(50, 0, nullptr);
476 }
477 _symbols->push(s);
478 }
479 _previous_symbol = s;
480 return s;
481 }
482
483 TypeOrigin ref_ctx(const char* str);
484
485 };
486
487 inline int ClassVerifier::change_sig_to_verificationType(
488 SignatureStream* sig_type, VerificationType* inference_type) {
489 BasicType bt = sig_type->type();
490 switch (bt) {
491 case T_OBJECT:
492 case T_ARRAY:
493 {
494 Symbol* name = sig_type->as_symbol();
495 // Create another symbol to save as signature stream unreferences this symbol.
496 Symbol* name_copy = create_temporary_symbol(name);
497 assert(name_copy == name, "symbols don't match");
498 *inference_type = VerificationType::reference_type(name_copy);
499 return 1;
500 }
501 case T_LONG:
502 *inference_type = VerificationType::long_type();
503 *++inference_type = VerificationType::long2_type();
504 return 2;
505 case T_DOUBLE:
506 *inference_type = VerificationType::double_type();
507 *++inference_type = VerificationType::double2_type();
508 return 2;
509 case T_INT:
510 case T_BOOLEAN:
511 case T_BYTE:
512 case T_CHAR:
513 case T_SHORT:
514 *inference_type = VerificationType::integer_type();
515 return 1;
516 case T_FLOAT:
517 *inference_type = VerificationType::float_type();
518 return 1;
519 default:
520 ShouldNotReachHere();
521 return 1;
522 }
523 }
524
525 #endif // SHARE_CLASSFILE_VERIFIER_HPP