1 /*
2  * Copyright (c) 1998, 2019, 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 #include "precompiled.hpp"
26 #include "jvm.h"
27 #include "classfile/classFileStream.hpp"
28 #include "classfile/classLoader.hpp"
29 #include "classfile/javaClasses.hpp"
30 #include "classfile/stackMapTable.hpp"
31 #include "classfile/stackMapFrame.hpp"
32 #include "classfile/stackMapTableFormat.hpp"
33 #include "classfile/symbolTable.hpp"
34 #include "classfile/systemDictionary.hpp"
35 #include "classfile/verifier.hpp"
36 #include "classfile/vmSymbols.hpp"
37 #include "interpreter/bytecodes.hpp"
38 #include "interpreter/bytecodeStream.hpp"
39 #include "logging/log.hpp"
40 #include "logging/logStream.hpp"
41 #include "memory/oopFactory.hpp"
42 #include "memory/resourceArea.hpp"
43 #include "memory/universe.hpp"
44 #include "oops/constantPool.inline.hpp"
45 #include "oops/instanceKlass.hpp"
46 #include "oops/oop.inline.hpp"
47 #include "oops/typeArrayOop.hpp"
48 #include "runtime/fieldDescriptor.hpp"
49 #include "runtime/handles.inline.hpp"
50 #include "runtime/interfaceSupport.inline.hpp"
51 #include "runtime/javaCalls.hpp"
52 #include "runtime/jniHandles.inline.hpp"
53 #include "runtime/orderAccess.hpp"
54 #include "runtime/os.hpp"
55 #include "runtime/safepointVerifiers.hpp"
56 #include "runtime/thread.hpp"
57 #include "services/threadService.hpp"
58 #include "utilities/align.hpp"
59 #include "utilities/bytes.hpp"
60 
61 #define NOFAILOVER_MAJOR_VERSION                       51
62 #define NONZERO_PADDING_BYTES_IN_SWITCH_MAJOR_VERSION  51
63 #define STATIC_METHOD_IN_INTERFACE_MAJOR_VERSION       52
64 #define MAX_ARRAY_DIMENSIONS 255
65 
66 // Access to external entry for VerifyClassCodes - old byte code verifier
67 
68 extern "C" {
69   typedef jboolean (*verify_byte_codes_fn_t)(JNIEnv *, jclass, char *, jint);
70   typedef jboolean (*verify_byte_codes_fn_new_t)(JNIEnv *, jclass, char *, jint, jint);
71 }
72 
73 static void* volatile _verify_byte_codes_fn = NULL;
74 
75 static volatile jint _is_new_verify_byte_codes_fn = (jint) true;
76 
verify_byte_codes_fn()77 static void* verify_byte_codes_fn() {
78   if (OrderAccess::load_acquire(&_verify_byte_codes_fn) == NULL) {
79     void *lib_handle = os::native_java_library();
80     void *func = os::dll_lookup(lib_handle, "VerifyClassCodesForMajorVersion");
81     OrderAccess::release_store(&_verify_byte_codes_fn, func);
82     if (func == NULL) {
83       _is_new_verify_byte_codes_fn = false;
84       func = os::dll_lookup(lib_handle, "VerifyClassCodes");
85       OrderAccess::release_store(&_verify_byte_codes_fn, func);
86     }
87   }
88   return (void*)_verify_byte_codes_fn;
89 }
90 
91 
92 // Methods in Verifier
93 
should_verify_for(oop class_loader,bool should_verify_class)94 bool Verifier::should_verify_for(oop class_loader, bool should_verify_class) {
95   return (class_loader == NULL || !should_verify_class) ?
96     BytecodeVerificationLocal : BytecodeVerificationRemote;
97 }
98 
relax_access_for(oop loader)99 bool Verifier::relax_access_for(oop loader) {
100   bool trusted = java_lang_ClassLoader::is_trusted_loader(loader);
101   bool need_verify =
102     // verifyAll
103     (BytecodeVerificationLocal && BytecodeVerificationRemote) ||
104     // verifyRemote
105     (!BytecodeVerificationLocal && BytecodeVerificationRemote && !trusted);
106   return !need_verify;
107 }
108 
trace_class_resolution(Klass * resolve_class,InstanceKlass * verify_class)109 void Verifier::trace_class_resolution(Klass* resolve_class, InstanceKlass* verify_class) {
110   assert(verify_class != NULL, "Unexpected null verify_class");
111   ResourceMark rm;
112   Symbol* s = verify_class->source_file_name();
113   const char* source_file = (s != NULL ? s->as_C_string() : NULL);
114   const char* verify = verify_class->external_name();
115   const char* resolve = resolve_class->external_name();
116   // print in a single call to reduce interleaving between threads
117   if (source_file != NULL) {
118     log_debug(class, resolve)("%s %s %s (verification)", verify, resolve, source_file);
119   } else {
120     log_debug(class, resolve)("%s %s (verification)", verify, resolve);
121   }
122 }
123 
124 // Prints the end-verification message to the appropriate output.
log_end_verification(outputStream * st,const char * klassName,Symbol * exception_name,TRAPS)125 void Verifier::log_end_verification(outputStream* st, const char* klassName, Symbol* exception_name, TRAPS) {
126   if (HAS_PENDING_EXCEPTION) {
127     st->print("Verification for %s has", klassName);
128     oop message = java_lang_Throwable::message(PENDING_EXCEPTION);
129     if (message != NULL) {
130       char* ex_msg = java_lang_String::as_utf8_string(message);
131       st->print_cr(" exception pending '%s %s'",
132                  PENDING_EXCEPTION->klass()->external_name(), ex_msg);
133     } else {
134       st->print_cr(" exception pending %s ",
135                  PENDING_EXCEPTION->klass()->external_name());
136     }
137   } else if (exception_name != NULL) {
138     st->print_cr("Verification for %s failed", klassName);
139   }
140   st->print_cr("End class verification for: %s", klassName);
141 }
142 
verify(InstanceKlass * klass,bool should_verify_class,TRAPS)143 bool Verifier::verify(InstanceKlass* klass, bool should_verify_class, TRAPS) {
144   HandleMark hm(THREAD);
145   ResourceMark rm(THREAD);
146 
147   // Eagerly allocate the identity hash code for a klass. This is a fallout
148   // from 6320749 and 8059924: hash code generator is not supposed to be called
149   // during the safepoint, but it allows to sneak the hashcode in during
150   // verification. Without this eager hashcode generation, we may end up
151   // installing the hashcode during some other operation, which may be at
152   // safepoint -- blowing up the checks. It was previously done as the side
153   // effect (sic!) for external_name(), but instead of doing that, we opt to
154   // explicitly push the hashcode in here. This is signify the following block
155   // is IMPORTANT:
156   if (klass->java_mirror() != NULL) {
157     klass->java_mirror()->identity_hash();
158   }
159 
160   if (!is_eligible_for_verification(klass, should_verify_class)) {
161     return true;
162   }
163 
164   // Timer includes any side effects of class verification (resolution,
165   // etc), but not recursive calls to Verifier::verify().
166   JavaThread* jt = (JavaThread*)THREAD;
167   PerfClassTraceTime timer(ClassLoader::perf_class_verify_time(),
168                            ClassLoader::perf_class_verify_selftime(),
169                            ClassLoader::perf_classes_verified(),
170                            jt->get_thread_stat()->perf_recursion_counts_addr(),
171                            jt->get_thread_stat()->perf_timers_addr(),
172                            PerfClassTraceTime::CLASS_VERIFY);
173 
174   // If the class should be verified, first see if we can use the split
175   // verifier.  If not, or if verification fails and FailOverToOldVerifier
176   // is set, then call the inference verifier.
177   Symbol* exception_name = NULL;
178   const size_t message_buffer_len = klass->name()->utf8_length() + 1024;
179   char* message_buffer = NULL;
180   char* exception_message = NULL;
181 
182   bool can_failover = FailOverToOldVerifier &&
183      klass->major_version() < NOFAILOVER_MAJOR_VERSION;
184 
185   log_info(class, init)("Start class verification for: %s", klass->external_name());
186   if (klass->major_version() >= STACKMAP_ATTRIBUTE_MAJOR_VERSION) {
187     ClassVerifier split_verifier(klass, THREAD);
188     split_verifier.verify_class(THREAD);
189     exception_name = split_verifier.result();
190     if (can_failover && !HAS_PENDING_EXCEPTION &&
191         (exception_name == vmSymbols::java_lang_VerifyError() ||
192          exception_name == vmSymbols::java_lang_ClassFormatError())) {
193       log_info(verification)("Fail over class verification to old verifier for: %s", klass->external_name());
194       log_info(class, init)("Fail over class verification to old verifier for: %s", klass->external_name());
195       message_buffer = NEW_RESOURCE_ARRAY(char, message_buffer_len);
196       exception_message = message_buffer;
197       exception_name = inference_verify(
198         klass, message_buffer, message_buffer_len, THREAD);
199     }
200     if (exception_name != NULL) {
201       exception_message = split_verifier.exception_message();
202     }
203   } else {
204     message_buffer = NEW_RESOURCE_ARRAY(char, message_buffer_len);
205     exception_message = message_buffer;
206     exception_name = inference_verify(
207         klass, message_buffer, message_buffer_len, THREAD);
208   }
209 
210   LogTarget(Info, class, init) lt1;
211   if (lt1.is_enabled()) {
212     LogStream ls(lt1);
213     log_end_verification(&ls, klass->external_name(), exception_name, THREAD);
214   }
215   LogTarget(Info, verification) lt2;
216   if (lt2.is_enabled()) {
217     LogStream ls(lt2);
218     log_end_verification(&ls, klass->external_name(), exception_name, THREAD);
219   }
220 
221   if (HAS_PENDING_EXCEPTION) {
222     return false; // use the existing exception
223   } else if (exception_name == NULL) {
224     return true; // verification succeeded
225   } else { // VerifyError or ClassFormatError to be created and thrown
226     Klass* kls =
227       SystemDictionary::resolve_or_fail(exception_name, true, CHECK_false);
228     if (log_is_enabled(Debug, class, resolve)) {
229       Verifier::trace_class_resolution(kls, klass);
230     }
231 
232     while (kls != NULL) {
233       if (kls == klass) {
234         // If the class being verified is the exception we're creating
235         // or one of it's superclasses, we're in trouble and are going
236         // to infinitely recurse when we try to initialize the exception.
237         // So bail out here by throwing the preallocated VM error.
238         THROW_OOP_(Universe::virtual_machine_error_instance(), false);
239       }
240       kls = kls->super();
241     }
242     if (message_buffer != NULL) {
243       message_buffer[message_buffer_len - 1] = '\0'; // just to be sure
244     }
245     assert(exception_message != NULL, "");
246     THROW_MSG_(exception_name, exception_message, false);
247   }
248 }
249 
is_eligible_for_verification(InstanceKlass * klass,bool should_verify_class)250 bool Verifier::is_eligible_for_verification(InstanceKlass* klass, bool should_verify_class) {
251   Symbol* name = klass->name();
252   Klass* refl_magic_klass = SystemDictionary::reflect_MagicAccessorImpl_klass();
253 
254   bool is_reflect = refl_magic_klass != NULL && klass->is_subtype_of(refl_magic_klass);
255 
256   return (should_verify_for(klass->class_loader(), should_verify_class) &&
257     // return if the class is a bootstrapping class
258     // or defineClass specified not to verify by default (flags override passed arg)
259     // We need to skip the following four for bootstraping
260     name != vmSymbols::java_lang_Object() &&
261     name != vmSymbols::java_lang_Class() &&
262     name != vmSymbols::java_lang_String() &&
263     name != vmSymbols::java_lang_Throwable() &&
264 
265     // Can not verify the bytecodes for shared classes because they have
266     // already been rewritten to contain constant pool cache indices,
267     // which the verifier can't understand.
268     // Shared classes shouldn't have stackmaps either.
269     !klass->is_shared() &&
270 
271     // As of the fix for 4486457 we disable verification for all of the
272     // dynamically-generated bytecodes associated with the 1.4
273     // reflection implementation, not just those associated with
274     // jdk/internal/reflect/SerializationConstructorAccessor.
275     // NOTE: this is called too early in the bootstrapping process to be
276     // guarded by Universe::is_gte_jdk14x_version().
277     // Also for lambda generated code, gte jdk8
278     (!is_reflect));
279 }
280 
inference_verify(InstanceKlass * klass,char * message,size_t message_len,TRAPS)281 Symbol* Verifier::inference_verify(
282     InstanceKlass* klass, char* message, size_t message_len, TRAPS) {
283   JavaThread* thread = (JavaThread*)THREAD;
284   JNIEnv *env = thread->jni_environment();
285 
286   void* verify_func = verify_byte_codes_fn();
287 
288   if (verify_func == NULL) {
289     jio_snprintf(message, message_len, "Could not link verifier");
290     return vmSymbols::java_lang_VerifyError();
291   }
292 
293   ResourceMark rm(THREAD);
294   log_info(verification)("Verifying class %s with old format", klass->external_name());
295 
296   jclass cls = (jclass) JNIHandles::make_local(env, klass->java_mirror());
297   jint result;
298 
299   {
300     HandleMark hm(thread);
301     ThreadToNativeFromVM ttn(thread);
302     // ThreadToNativeFromVM takes care of changing thread_state, so safepoint
303     // code knows that we have left the VM
304 
305     if (_is_new_verify_byte_codes_fn) {
306       verify_byte_codes_fn_new_t func =
307         CAST_TO_FN_PTR(verify_byte_codes_fn_new_t, verify_func);
308       result = (*func)(env, cls, message, (int)message_len,
309           klass->major_version());
310     } else {
311       verify_byte_codes_fn_t func =
312         CAST_TO_FN_PTR(verify_byte_codes_fn_t, verify_func);
313       result = (*func)(env, cls, message, (int)message_len);
314     }
315   }
316 
317   JNIHandles::destroy_local(cls);
318 
319   // These numbers are chosen so that VerifyClassCodes interface doesn't need
320   // to be changed (still return jboolean (unsigned char)), and result is
321   // 1 when verification is passed.
322   if (result == 0) {
323     return vmSymbols::java_lang_VerifyError();
324   } else if (result == 1) {
325     return NULL; // verified.
326   } else if (result == 2) {
327     THROW_MSG_(vmSymbols::java_lang_OutOfMemoryError(), message, NULL);
328   } else if (result == 3) {
329     return vmSymbols::java_lang_ClassFormatError();
330   } else {
331     ShouldNotReachHere();
332     return NULL;
333   }
334 }
335 
null()336 TypeOrigin TypeOrigin::null() {
337   return TypeOrigin();
338 }
local(u2 index,StackMapFrame * frame)339 TypeOrigin TypeOrigin::local(u2 index, StackMapFrame* frame) {
340   assert(frame != NULL, "Must have a frame");
341   return TypeOrigin(CF_LOCALS, index, StackMapFrame::copy(frame),
342      frame->local_at(index));
343 }
stack(u2 index,StackMapFrame * frame)344 TypeOrigin TypeOrigin::stack(u2 index, StackMapFrame* frame) {
345   assert(frame != NULL, "Must have a frame");
346   return TypeOrigin(CF_STACK, index, StackMapFrame::copy(frame),
347       frame->stack_at(index));
348 }
sm_local(u2 index,StackMapFrame * frame)349 TypeOrigin TypeOrigin::sm_local(u2 index, StackMapFrame* frame) {
350   assert(frame != NULL, "Must have a frame");
351   return TypeOrigin(SM_LOCALS, index, StackMapFrame::copy(frame),
352       frame->local_at(index));
353 }
sm_stack(u2 index,StackMapFrame * frame)354 TypeOrigin TypeOrigin::sm_stack(u2 index, StackMapFrame* frame) {
355   assert(frame != NULL, "Must have a frame");
356   return TypeOrigin(SM_STACK, index, StackMapFrame::copy(frame),
357       frame->stack_at(index));
358 }
bad_index(u2 index)359 TypeOrigin TypeOrigin::bad_index(u2 index) {
360   return TypeOrigin(BAD_INDEX, index, NULL, VerificationType::bogus_type());
361 }
cp(u2 index,VerificationType vt)362 TypeOrigin TypeOrigin::cp(u2 index, VerificationType vt) {
363   return TypeOrigin(CONST_POOL, index, NULL, vt);
364 }
signature(VerificationType vt)365 TypeOrigin TypeOrigin::signature(VerificationType vt) {
366   return TypeOrigin(SIG, 0, NULL, vt);
367 }
implicit(VerificationType t)368 TypeOrigin TypeOrigin::implicit(VerificationType t) {
369   return TypeOrigin(IMPLICIT, 0, NULL, t);
370 }
frame(StackMapFrame * frame)371 TypeOrigin TypeOrigin::frame(StackMapFrame* frame) {
372   return TypeOrigin(FRAME_ONLY, 0, StackMapFrame::copy(frame),
373                     VerificationType::bogus_type());
374 }
375 
reset_frame()376 void TypeOrigin::reset_frame() {
377   if (_frame != NULL) {
378     _frame->restore();
379   }
380 }
381 
details(outputStream * ss) const382 void TypeOrigin::details(outputStream* ss) const {
383   _type.print_on(ss);
384   switch (_origin) {
385     case CF_LOCALS:
386       ss->print(" (current frame, locals[%d])", _index);
387       break;
388     case CF_STACK:
389       ss->print(" (current frame, stack[%d])", _index);
390       break;
391     case SM_LOCALS:
392       ss->print(" (stack map, locals[%d])", _index);
393       break;
394     case SM_STACK:
395       ss->print(" (stack map, stack[%d])", _index);
396       break;
397     case CONST_POOL:
398       ss->print(" (constant pool %d)", _index);
399       break;
400     case SIG:
401       ss->print(" (from method signature)");
402       break;
403     case IMPLICIT:
404     case FRAME_ONLY:
405     case NONE:
406     default:
407       ;
408   }
409 }
410 
411 #ifdef ASSERT
print_on(outputStream * str) const412 void TypeOrigin::print_on(outputStream* str) const {
413   str->print("{%d,%d,%p:", _origin, _index, _frame);
414   if (_frame != NULL) {
415     _frame->print_on(str);
416   } else {
417     str->print("null");
418   }
419   str->print(",");
420   _type.print_on(str);
421   str->print("}");
422 }
423 #endif
424 
details(outputStream * ss,const Method * method) const425 void ErrorContext::details(outputStream* ss, const Method* method) const {
426   if (is_valid()) {
427     ss->cr();
428     ss->print_cr("Exception Details:");
429     location_details(ss, method);
430     reason_details(ss);
431     frame_details(ss);
432     bytecode_details(ss, method);
433     handler_details(ss, method);
434     stackmap_details(ss, method);
435   }
436 }
437 
reason_details(outputStream * ss) const438 void ErrorContext::reason_details(outputStream* ss) const {
439   streamIndentor si(ss);
440   ss->indent().print_cr("Reason:");
441   streamIndentor si2(ss);
442   ss->indent().print("%s", "");
443   switch (_fault) {
444     case INVALID_BYTECODE:
445       ss->print("Error exists in the bytecode");
446       break;
447     case WRONG_TYPE:
448       if (_expected.is_valid()) {
449         ss->print("Type ");
450         _type.details(ss);
451         ss->print(" is not assignable to ");
452         _expected.details(ss);
453       } else {
454         ss->print("Invalid type: ");
455         _type.details(ss);
456       }
457       break;
458     case FLAGS_MISMATCH:
459       if (_expected.is_valid()) {
460         ss->print("Current frame's flags are not assignable "
461                   "to stack map frame's.");
462       } else {
463         ss->print("Current frame's flags are invalid in this context.");
464       }
465       break;
466     case BAD_CP_INDEX:
467       ss->print("Constant pool index %d is invalid", _type.index());
468       break;
469     case BAD_LOCAL_INDEX:
470       ss->print("Local index %d is invalid", _type.index());
471       break;
472     case LOCALS_SIZE_MISMATCH:
473       ss->print("Current frame's local size doesn't match stackmap.");
474       break;
475     case STACK_SIZE_MISMATCH:
476       ss->print("Current frame's stack size doesn't match stackmap.");
477       break;
478     case STACK_OVERFLOW:
479       ss->print("Exceeded max stack size.");
480       break;
481     case STACK_UNDERFLOW:
482       ss->print("Attempt to pop empty stack.");
483       break;
484     case MISSING_STACKMAP:
485       ss->print("Expected stackmap frame at this location.");
486       break;
487     case BAD_STACKMAP:
488       ss->print("Invalid stackmap specification.");
489       break;
490     case UNKNOWN:
491     default:
492       ShouldNotReachHere();
493       ss->print_cr("Unknown");
494   }
495   ss->cr();
496 }
497 
location_details(outputStream * ss,const Method * method) const498 void ErrorContext::location_details(outputStream* ss, const Method* method) const {
499   if (_bci != -1 && method != NULL) {
500     streamIndentor si(ss);
501     const char* bytecode_name = "<invalid>";
502     if (method->validate_bci(_bci) != -1) {
503       Bytecodes::Code code = Bytecodes::code_or_bp_at(method->bcp_from(_bci));
504       if (Bytecodes::is_defined(code)) {
505           bytecode_name = Bytecodes::name(code);
506       } else {
507           bytecode_name = "<illegal>";
508       }
509     }
510     InstanceKlass* ik = method->method_holder();
511     ss->indent().print_cr("Location:");
512     streamIndentor si2(ss);
513     ss->indent().print_cr("%s.%s%s @%d: %s",
514         ik->name()->as_C_string(), method->name()->as_C_string(),
515         method->signature()->as_C_string(), _bci, bytecode_name);
516   }
517 }
518 
frame_details(outputStream * ss) const519 void ErrorContext::frame_details(outputStream* ss) const {
520   streamIndentor si(ss);
521   if (_type.is_valid() && _type.frame() != NULL) {
522     ss->indent().print_cr("Current Frame:");
523     streamIndentor si2(ss);
524     _type.frame()->print_on(ss);
525   }
526   if (_expected.is_valid() && _expected.frame() != NULL) {
527     ss->indent().print_cr("Stackmap Frame:");
528     streamIndentor si2(ss);
529     _expected.frame()->print_on(ss);
530   }
531 }
532 
bytecode_details(outputStream * ss,const Method * method) const533 void ErrorContext::bytecode_details(outputStream* ss, const Method* method) const {
534   if (method != NULL) {
535     streamIndentor si(ss);
536     ss->indent().print_cr("Bytecode:");
537     streamIndentor si2(ss);
538     ss->print_data(method->code_base(), method->code_size(), false);
539   }
540 }
541 
handler_details(outputStream * ss,const Method * method) const542 void ErrorContext::handler_details(outputStream* ss, const Method* method) const {
543   if (method != NULL) {
544     streamIndentor si(ss);
545     ExceptionTable table(method);
546     if (table.length() > 0) {
547       ss->indent().print_cr("Exception Handler Table:");
548       streamIndentor si2(ss);
549       for (int i = 0; i < table.length(); ++i) {
550         ss->indent().print_cr("bci [%d, %d] => handler: %d", table.start_pc(i),
551             table.end_pc(i), table.handler_pc(i));
552       }
553     }
554   }
555 }
556 
stackmap_details(outputStream * ss,const Method * method) const557 void ErrorContext::stackmap_details(outputStream* ss, const Method* method) const {
558   if (method != NULL && method->has_stackmap_table()) {
559     streamIndentor si(ss);
560     ss->indent().print_cr("Stackmap Table:");
561     Array<u1>* data = method->stackmap_data();
562     stack_map_table* sm_table =
563         stack_map_table::at((address)data->adr_at(0));
564     stack_map_frame* sm_frame = sm_table->entries();
565     streamIndentor si2(ss);
566     int current_offset = -1;
567     address end_of_sm_table = (address)sm_table + method->stackmap_data()->length();
568     for (u2 i = 0; i < sm_table->number_of_entries(); ++i) {
569       ss->indent();
570       if (!sm_frame->verify((address)sm_frame, end_of_sm_table)) {
571         sm_frame->print_truncated(ss, current_offset);
572         return;
573       }
574       sm_frame->print_on(ss, current_offset);
575       ss->cr();
576       current_offset += sm_frame->offset_delta();
577       sm_frame = sm_frame->next();
578     }
579   }
580 }
581 
582 // Methods in ClassVerifier
583 
ClassVerifier(InstanceKlass * klass,TRAPS)584 ClassVerifier::ClassVerifier(
585     InstanceKlass* klass, TRAPS)
586     : _thread(THREAD), _previous_symbol(NULL), _symbols(NULL), _exception_type(NULL),
587       _message(NULL), _method_signatures_table(NULL), _klass(klass) {
588   _this_type = VerificationType::reference_type(klass->name());
589 }
590 
~ClassVerifier()591 ClassVerifier::~ClassVerifier() {
592   // Decrement the reference count for any symbols created.
593   if (_symbols != NULL) {
594     for (int i = 0; i < _symbols->length(); i++) {
595       Symbol* s = _symbols->at(i);
596       s->decrement_refcount();
597     }
598   }
599 }
600 
object_type() const601 VerificationType ClassVerifier::object_type() const {
602   return VerificationType::reference_type(vmSymbols::java_lang_Object());
603 }
604 
ref_ctx(const char * sig)605 TypeOrigin ClassVerifier::ref_ctx(const char* sig) {
606   VerificationType vt = VerificationType::reference_type(
607                          create_temporary_symbol(sig, (int)strlen(sig)));
608   return TypeOrigin::implicit(vt);
609 }
610 
verify_class(TRAPS)611 void ClassVerifier::verify_class(TRAPS) {
612   log_info(verification)("Verifying class %s with new format", _klass->external_name());
613 
614   // Either verifying both local and remote classes or just remote classes.
615   assert(BytecodeVerificationRemote, "Should not be here");
616 
617   // Create hash table containing method signatures.
618   method_signatures_table_type method_signatures_table;
619   set_method_signatures_table(&method_signatures_table);
620 
621   Array<Method*>* methods = _klass->methods();
622   int num_methods = methods->length();
623 
624   for (int index = 0; index < num_methods; index++) {
625     // Check for recursive re-verification before each method.
626     if (was_recursively_verified())  return;
627 
628     Method* m = methods->at(index);
629     if (m->is_native() || m->is_abstract() || m->is_overpass()) {
630       // If m is native or abstract, skip it.  It is checked in class file
631       // parser that methods do not override a final method.  Overpass methods
632       // are trusted since the VM generates them.
633       continue;
634     }
635     verify_method(methodHandle(THREAD, m), CHECK_VERIFY(this));
636   }
637 
638   if (was_recursively_verified()){
639     log_info(verification)("Recursive verification detected for: %s", _klass->external_name());
640     log_info(class, init)("Recursive verification detected for: %s",
641                         _klass->external_name());
642   }
643 }
644 
645 // Translate the signature entries into verification types and save them in
646 // the growable array.  Also, save the count of arguments.
translate_signature(Symbol * const method_sig,sig_as_verification_types * sig_verif_types,TRAPS)647 void ClassVerifier::translate_signature(Symbol* const method_sig,
648                                         sig_as_verification_types* sig_verif_types,
649                                         TRAPS) {
650   SignatureStream sig_stream(method_sig);
651   VerificationType sig_type[2];
652   int sig_i = 0;
653   GrowableArray<VerificationType>* verif_types = sig_verif_types->sig_verif_types();
654 
655   // Translate the signature arguments into verification types.
656   while (!sig_stream.at_return_type()) {
657     int n = change_sig_to_verificationType(&sig_stream, sig_type);
658     assert(n <= 2, "Unexpected signature type");
659 
660     // Store verification type(s).  Longs and Doubles each have two verificationTypes.
661     for (int x = 0; x < n; x++) {
662       verif_types->push(sig_type[x]);
663     }
664     sig_i += n;
665     sig_stream.next();
666   }
667 
668   // Set final arg count, not including the return type.  The final arg count will
669   // be compared with sig_verify_types' length to see if there is a return type.
670   sig_verif_types->set_num_args(sig_i);
671 
672   // Store verification type(s) for the return type, if there is one.
673   if (sig_stream.type() != T_VOID) {
674     int n = change_sig_to_verificationType(&sig_stream, sig_type);
675     assert(n <= 2, "Unexpected signature return type");
676     for (int y = 0; y < n; y++) {
677       verif_types->push(sig_type[y]);
678     }
679   }
680 }
681 
create_method_sig_entry(sig_as_verification_types * sig_verif_types,int sig_index,TRAPS)682 void ClassVerifier::create_method_sig_entry(sig_as_verification_types* sig_verif_types,
683                                             int sig_index, TRAPS) {
684   // Translate the signature into verification types.
685   ConstantPool* cp = _klass->constants();
686   Symbol* const method_sig = cp->symbol_at(sig_index);
687   translate_signature(method_sig, sig_verif_types, CHECK_VERIFY(this));
688 
689   // Add the list of this signature's verification types to the table.
690   bool is_unique = method_signatures_table()->put(sig_index, sig_verif_types);
691   assert(is_unique, "Duplicate entries in method_signature_table");
692 }
693 
verify_method(const methodHandle & m,TRAPS)694 void ClassVerifier::verify_method(const methodHandle& m, TRAPS) {
695   HandleMark hm(THREAD);
696   _method = m;   // initialize _method
697   log_info(verification)("Verifying method %s", m->name_and_sig_as_C_string());
698 
699 // For clang, the only good constant format string is a literal constant format string.
700 #define bad_type_msg "Bad type on operand stack in %s"
701 
702   int32_t max_stack = m->verifier_max_stack();
703   int32_t max_locals = m->max_locals();
704   constantPoolHandle cp(THREAD, m->constants());
705 
706   // Method signature was checked in ClassFileParser.
707   assert(SignatureVerifier::is_valid_method_signature(m->signature()),
708          "Invalid method signature");
709 
710   // Initial stack map frame: offset is 0, stack is initially empty.
711   StackMapFrame current_frame(max_locals, max_stack, this);
712   // Set initial locals
713   VerificationType return_type = current_frame.set_locals_from_arg(
714     m, current_type(), CHECK_VERIFY(this));
715 
716   int32_t stackmap_index = 0; // index to the stackmap array
717 
718   u4 code_length = m->code_size();
719 
720   // Scan the bytecode and map each instruction's start offset to a number.
721   char* code_data = generate_code_data(m, code_length, CHECK_VERIFY(this));
722 
723   int ex_min = code_length;
724   int ex_max = -1;
725   // Look through each item on the exception table. Each of the fields must refer
726   // to a legal instruction.
727   if (was_recursively_verified()) return;
728   verify_exception_handler_table(
729     code_length, code_data, ex_min, ex_max, CHECK_VERIFY(this));
730 
731   // Look through each entry on the local variable table and make sure
732   // its range of code array offsets is valid. (4169817)
733   if (m->has_localvariable_table()) {
734     verify_local_variable_table(code_length, code_data, CHECK_VERIFY(this));
735   }
736 
737   Array<u1>* stackmap_data = m->stackmap_data();
738   StackMapStream stream(stackmap_data);
739   StackMapReader reader(this, &stream, code_data, code_length, THREAD);
740   StackMapTable stackmap_table(&reader, &current_frame, max_locals, max_stack,
741                                code_data, code_length, CHECK_VERIFY(this));
742 
743   LogTarget(Info, verification) lt;
744   if (lt.is_enabled()) {
745     ResourceMark rm(THREAD);
746     LogStream ls(lt);
747     stackmap_table.print_on(&ls);
748   }
749 
750   RawBytecodeStream bcs(m);
751 
752   // Scan the byte code linearly from the start to the end
753   bool no_control_flow = false; // Set to true when there is no direct control
754                                 // flow from current instruction to the next
755                                 // instruction in sequence
756 
757   Bytecodes::Code opcode;
758   while (!bcs.is_last_bytecode()) {
759     // Check for recursive re-verification before each bytecode.
760     if (was_recursively_verified())  return;
761 
762     opcode = bcs.raw_next();
763     u2 bci = bcs.bci();
764 
765     // Set current frame's offset to bci
766     current_frame.set_offset(bci);
767     current_frame.set_mark();
768 
769     // Make sure every offset in stackmap table point to the beginning to
770     // an instruction. Match current_frame to stackmap_table entry with
771     // the same offset if exists.
772     stackmap_index = verify_stackmap_table(
773       stackmap_index, bci, &current_frame, &stackmap_table,
774       no_control_flow, CHECK_VERIFY(this));
775 
776 
777     bool this_uninit = false;  // Set to true when invokespecial <init> initialized 'this'
778     bool verified_exc_handlers = false;
779 
780     // Merge with the next instruction
781     {
782       u2 index;
783       int target;
784       VerificationType type, type2;
785       VerificationType atype;
786 
787       LogTarget(Info, verification) lt;
788       if (lt.is_enabled()) {
789         ResourceMark rm(THREAD);
790         LogStream ls(lt);
791         current_frame.print_on(&ls);
792         lt.print("offset = %d,  opcode = %s", bci,
793                  opcode == Bytecodes::_illegal ? "illegal" : Bytecodes::name(opcode));
794       }
795 
796       // Make sure wide instruction is in correct format
797       if (bcs.is_wide()) {
798         if (opcode != Bytecodes::_iinc   && opcode != Bytecodes::_iload  &&
799             opcode != Bytecodes::_aload  && opcode != Bytecodes::_lload  &&
800             opcode != Bytecodes::_istore && opcode != Bytecodes::_astore &&
801             opcode != Bytecodes::_lstore && opcode != Bytecodes::_fload  &&
802             opcode != Bytecodes::_dload  && opcode != Bytecodes::_fstore &&
803             opcode != Bytecodes::_dstore) {
804           /* Unreachable?  RawBytecodeStream's raw_next() returns 'illegal'
805            * if we encounter a wide instruction that modifies an invalid
806            * opcode (not one of the ones listed above) */
807           verify_error(ErrorContext::bad_code(bci), "Bad wide instruction");
808           return;
809         }
810       }
811 
812       // Look for possible jump target in exception handlers and see if it
813       // matches current_frame.  Do this check here for astore*, dstore*,
814       // fstore*, istore*, and lstore* opcodes because they can change the type
815       // state by adding a local.  JVM Spec says that the incoming type state
816       // should be used for this check.  So, do the check here before a possible
817       // local is added to the type state.
818       if (Bytecodes::is_store_into_local(opcode) && bci >= ex_min && bci < ex_max) {
819         if (was_recursively_verified()) return;
820         verify_exception_handler_targets(
821           bci, this_uninit, &current_frame, &stackmap_table, CHECK_VERIFY(this));
822         verified_exc_handlers = true;
823       }
824 
825       if (was_recursively_verified()) return;
826 
827       switch (opcode) {
828         case Bytecodes::_nop :
829           no_control_flow = false; break;
830         case Bytecodes::_aconst_null :
831           current_frame.push_stack(
832             VerificationType::null_type(), CHECK_VERIFY(this));
833           no_control_flow = false; break;
834         case Bytecodes::_iconst_m1 :
835         case Bytecodes::_iconst_0 :
836         case Bytecodes::_iconst_1 :
837         case Bytecodes::_iconst_2 :
838         case Bytecodes::_iconst_3 :
839         case Bytecodes::_iconst_4 :
840         case Bytecodes::_iconst_5 :
841           current_frame.push_stack(
842             VerificationType::integer_type(), CHECK_VERIFY(this));
843           no_control_flow = false; break;
844         case Bytecodes::_lconst_0 :
845         case Bytecodes::_lconst_1 :
846           current_frame.push_stack_2(
847             VerificationType::long_type(),
848             VerificationType::long2_type(), CHECK_VERIFY(this));
849           no_control_flow = false; break;
850         case Bytecodes::_fconst_0 :
851         case Bytecodes::_fconst_1 :
852         case Bytecodes::_fconst_2 :
853           current_frame.push_stack(
854             VerificationType::float_type(), CHECK_VERIFY(this));
855           no_control_flow = false; break;
856         case Bytecodes::_dconst_0 :
857         case Bytecodes::_dconst_1 :
858           current_frame.push_stack_2(
859             VerificationType::double_type(),
860             VerificationType::double2_type(), CHECK_VERIFY(this));
861           no_control_flow = false; break;
862         case Bytecodes::_sipush :
863         case Bytecodes::_bipush :
864           current_frame.push_stack(
865             VerificationType::integer_type(), CHECK_VERIFY(this));
866           no_control_flow = false; break;
867         case Bytecodes::_ldc :
868           verify_ldc(
869             opcode, bcs.get_index_u1(), &current_frame,
870             cp, bci, CHECK_VERIFY(this));
871           no_control_flow = false; break;
872         case Bytecodes::_ldc_w :
873         case Bytecodes::_ldc2_w :
874           verify_ldc(
875             opcode, bcs.get_index_u2(), &current_frame,
876             cp, bci, CHECK_VERIFY(this));
877           no_control_flow = false; break;
878         case Bytecodes::_iload :
879           verify_iload(bcs.get_index(), &current_frame, CHECK_VERIFY(this));
880           no_control_flow = false; break;
881         case Bytecodes::_iload_0 :
882         case Bytecodes::_iload_1 :
883         case Bytecodes::_iload_2 :
884         case Bytecodes::_iload_3 :
885           index = opcode - Bytecodes::_iload_0;
886           verify_iload(index, &current_frame, CHECK_VERIFY(this));
887           no_control_flow = false; break;
888         case Bytecodes::_lload :
889           verify_lload(bcs.get_index(), &current_frame, CHECK_VERIFY(this));
890           no_control_flow = false; break;
891         case Bytecodes::_lload_0 :
892         case Bytecodes::_lload_1 :
893         case Bytecodes::_lload_2 :
894         case Bytecodes::_lload_3 :
895           index = opcode - Bytecodes::_lload_0;
896           verify_lload(index, &current_frame, CHECK_VERIFY(this));
897           no_control_flow = false; break;
898         case Bytecodes::_fload :
899           verify_fload(bcs.get_index(), &current_frame, CHECK_VERIFY(this));
900           no_control_flow = false; break;
901         case Bytecodes::_fload_0 :
902         case Bytecodes::_fload_1 :
903         case Bytecodes::_fload_2 :
904         case Bytecodes::_fload_3 :
905           index = opcode - Bytecodes::_fload_0;
906           verify_fload(index, &current_frame, CHECK_VERIFY(this));
907           no_control_flow = false; break;
908         case Bytecodes::_dload :
909           verify_dload(bcs.get_index(), &current_frame, CHECK_VERIFY(this));
910           no_control_flow = false; break;
911         case Bytecodes::_dload_0 :
912         case Bytecodes::_dload_1 :
913         case Bytecodes::_dload_2 :
914         case Bytecodes::_dload_3 :
915           index = opcode - Bytecodes::_dload_0;
916           verify_dload(index, &current_frame, CHECK_VERIFY(this));
917           no_control_flow = false; break;
918         case Bytecodes::_aload :
919           verify_aload(bcs.get_index(), &current_frame, CHECK_VERIFY(this));
920           no_control_flow = false; break;
921         case Bytecodes::_aload_0 :
922         case Bytecodes::_aload_1 :
923         case Bytecodes::_aload_2 :
924         case Bytecodes::_aload_3 :
925           index = opcode - Bytecodes::_aload_0;
926           verify_aload(index, &current_frame, CHECK_VERIFY(this));
927           no_control_flow = false; break;
928         case Bytecodes::_iaload :
929           type = current_frame.pop_stack(
930             VerificationType::integer_type(), CHECK_VERIFY(this));
931           atype = current_frame.pop_stack(
932             VerificationType::reference_check(), CHECK_VERIFY(this));
933           if (!atype.is_int_array()) {
934             verify_error(ErrorContext::bad_type(bci,
935                 current_frame.stack_top_ctx(), ref_ctx("[I")),
936                 bad_type_msg, "iaload");
937             return;
938           }
939           current_frame.push_stack(
940             VerificationType::integer_type(), CHECK_VERIFY(this));
941           no_control_flow = false; break;
942         case Bytecodes::_baload :
943           type = current_frame.pop_stack(
944             VerificationType::integer_type(), CHECK_VERIFY(this));
945           atype = current_frame.pop_stack(
946             VerificationType::reference_check(), CHECK_VERIFY(this));
947           if (!atype.is_bool_array() && !atype.is_byte_array()) {
948             verify_error(
949                 ErrorContext::bad_type(bci, current_frame.stack_top_ctx()),
950                 bad_type_msg, "baload");
951             return;
952           }
953           current_frame.push_stack(
954             VerificationType::integer_type(), CHECK_VERIFY(this));
955           no_control_flow = false; break;
956         case Bytecodes::_caload :
957           type = current_frame.pop_stack(
958             VerificationType::integer_type(), CHECK_VERIFY(this));
959           atype = current_frame.pop_stack(
960             VerificationType::reference_check(), CHECK_VERIFY(this));
961           if (!atype.is_char_array()) {
962             verify_error(ErrorContext::bad_type(bci,
963                 current_frame.stack_top_ctx(), ref_ctx("[C")),
964                 bad_type_msg, "caload");
965             return;
966           }
967           current_frame.push_stack(
968             VerificationType::integer_type(), CHECK_VERIFY(this));
969           no_control_flow = false; break;
970         case Bytecodes::_saload :
971           type = current_frame.pop_stack(
972             VerificationType::integer_type(), CHECK_VERIFY(this));
973           atype = current_frame.pop_stack(
974             VerificationType::reference_check(), CHECK_VERIFY(this));
975           if (!atype.is_short_array()) {
976             verify_error(ErrorContext::bad_type(bci,
977                 current_frame.stack_top_ctx(), ref_ctx("[S")),
978                 bad_type_msg, "saload");
979             return;
980           }
981           current_frame.push_stack(
982             VerificationType::integer_type(), CHECK_VERIFY(this));
983           no_control_flow = false; break;
984         case Bytecodes::_laload :
985           type = current_frame.pop_stack(
986             VerificationType::integer_type(), CHECK_VERIFY(this));
987           atype = current_frame.pop_stack(
988             VerificationType::reference_check(), CHECK_VERIFY(this));
989           if (!atype.is_long_array()) {
990             verify_error(ErrorContext::bad_type(bci,
991                 current_frame.stack_top_ctx(), ref_ctx("[J")),
992                 bad_type_msg, "laload");
993             return;
994           }
995           current_frame.push_stack_2(
996             VerificationType::long_type(),
997             VerificationType::long2_type(), CHECK_VERIFY(this));
998           no_control_flow = false; break;
999         case Bytecodes::_faload :
1000           type = current_frame.pop_stack(
1001             VerificationType::integer_type(), CHECK_VERIFY(this));
1002           atype = current_frame.pop_stack(
1003             VerificationType::reference_check(), CHECK_VERIFY(this));
1004           if (!atype.is_float_array()) {
1005             verify_error(ErrorContext::bad_type(bci,
1006                 current_frame.stack_top_ctx(), ref_ctx("[F")),
1007                 bad_type_msg, "faload");
1008             return;
1009           }
1010           current_frame.push_stack(
1011             VerificationType::float_type(), CHECK_VERIFY(this));
1012           no_control_flow = false; break;
1013         case Bytecodes::_daload :
1014           type = current_frame.pop_stack(
1015             VerificationType::integer_type(), CHECK_VERIFY(this));
1016           atype = current_frame.pop_stack(
1017             VerificationType::reference_check(), CHECK_VERIFY(this));
1018           if (!atype.is_double_array()) {
1019             verify_error(ErrorContext::bad_type(bci,
1020                 current_frame.stack_top_ctx(), ref_ctx("[D")),
1021                 bad_type_msg, "daload");
1022             return;
1023           }
1024           current_frame.push_stack_2(
1025             VerificationType::double_type(),
1026             VerificationType::double2_type(), CHECK_VERIFY(this));
1027           no_control_flow = false; break;
1028         case Bytecodes::_aaload : {
1029           type = current_frame.pop_stack(
1030             VerificationType::integer_type(), CHECK_VERIFY(this));
1031           atype = current_frame.pop_stack(
1032             VerificationType::reference_check(), CHECK_VERIFY(this));
1033           if (!atype.is_reference_array()) {
1034             verify_error(ErrorContext::bad_type(bci,
1035                 current_frame.stack_top_ctx(),
1036                 TypeOrigin::implicit(VerificationType::reference_check())),
1037                 bad_type_msg, "aaload");
1038             return;
1039           }
1040           if (atype.is_null()) {
1041             current_frame.push_stack(
1042               VerificationType::null_type(), CHECK_VERIFY(this));
1043           } else {
1044             VerificationType component =
1045               atype.get_component(this, CHECK_VERIFY(this));
1046             current_frame.push_stack(component, CHECK_VERIFY(this));
1047           }
1048           no_control_flow = false; break;
1049         }
1050         case Bytecodes::_istore :
1051           verify_istore(bcs.get_index(), &current_frame, CHECK_VERIFY(this));
1052           no_control_flow = false; break;
1053         case Bytecodes::_istore_0 :
1054         case Bytecodes::_istore_1 :
1055         case Bytecodes::_istore_2 :
1056         case Bytecodes::_istore_3 :
1057           index = opcode - Bytecodes::_istore_0;
1058           verify_istore(index, &current_frame, CHECK_VERIFY(this));
1059           no_control_flow = false; break;
1060         case Bytecodes::_lstore :
1061           verify_lstore(bcs.get_index(), &current_frame, CHECK_VERIFY(this));
1062           no_control_flow = false; break;
1063         case Bytecodes::_lstore_0 :
1064         case Bytecodes::_lstore_1 :
1065         case Bytecodes::_lstore_2 :
1066         case Bytecodes::_lstore_3 :
1067           index = opcode - Bytecodes::_lstore_0;
1068           verify_lstore(index, &current_frame, CHECK_VERIFY(this));
1069           no_control_flow = false; break;
1070         case Bytecodes::_fstore :
1071           verify_fstore(bcs.get_index(), &current_frame, CHECK_VERIFY(this));
1072           no_control_flow = false; break;
1073         case Bytecodes::_fstore_0 :
1074         case Bytecodes::_fstore_1 :
1075         case Bytecodes::_fstore_2 :
1076         case Bytecodes::_fstore_3 :
1077           index = opcode - Bytecodes::_fstore_0;
1078           verify_fstore(index, &current_frame, CHECK_VERIFY(this));
1079           no_control_flow = false; break;
1080         case Bytecodes::_dstore :
1081           verify_dstore(bcs.get_index(), &current_frame, CHECK_VERIFY(this));
1082           no_control_flow = false; break;
1083         case Bytecodes::_dstore_0 :
1084         case Bytecodes::_dstore_1 :
1085         case Bytecodes::_dstore_2 :
1086         case Bytecodes::_dstore_3 :
1087           index = opcode - Bytecodes::_dstore_0;
1088           verify_dstore(index, &current_frame, CHECK_VERIFY(this));
1089           no_control_flow = false; break;
1090         case Bytecodes::_astore :
1091           verify_astore(bcs.get_index(), &current_frame, CHECK_VERIFY(this));
1092           no_control_flow = false; break;
1093         case Bytecodes::_astore_0 :
1094         case Bytecodes::_astore_1 :
1095         case Bytecodes::_astore_2 :
1096         case Bytecodes::_astore_3 :
1097           index = opcode - Bytecodes::_astore_0;
1098           verify_astore(index, &current_frame, CHECK_VERIFY(this));
1099           no_control_flow = false; break;
1100         case Bytecodes::_iastore :
1101           type = current_frame.pop_stack(
1102             VerificationType::integer_type(), CHECK_VERIFY(this));
1103           type2 = current_frame.pop_stack(
1104             VerificationType::integer_type(), CHECK_VERIFY(this));
1105           atype = current_frame.pop_stack(
1106             VerificationType::reference_check(), CHECK_VERIFY(this));
1107           if (!atype.is_int_array()) {
1108             verify_error(ErrorContext::bad_type(bci,
1109                 current_frame.stack_top_ctx(), ref_ctx("[I")),
1110                 bad_type_msg, "iastore");
1111             return;
1112           }
1113           no_control_flow = false; break;
1114         case Bytecodes::_bastore :
1115           type = current_frame.pop_stack(
1116             VerificationType::integer_type(), CHECK_VERIFY(this));
1117           type2 = current_frame.pop_stack(
1118             VerificationType::integer_type(), CHECK_VERIFY(this));
1119           atype = current_frame.pop_stack(
1120             VerificationType::reference_check(), CHECK_VERIFY(this));
1121           if (!atype.is_bool_array() && !atype.is_byte_array()) {
1122             verify_error(
1123                 ErrorContext::bad_type(bci, current_frame.stack_top_ctx()),
1124                 bad_type_msg, "bastore");
1125             return;
1126           }
1127           no_control_flow = false; break;
1128         case Bytecodes::_castore :
1129           current_frame.pop_stack(
1130             VerificationType::integer_type(), CHECK_VERIFY(this));
1131           current_frame.pop_stack(
1132             VerificationType::integer_type(), CHECK_VERIFY(this));
1133           atype = current_frame.pop_stack(
1134             VerificationType::reference_check(), CHECK_VERIFY(this));
1135           if (!atype.is_char_array()) {
1136             verify_error(ErrorContext::bad_type(bci,
1137                 current_frame.stack_top_ctx(), ref_ctx("[C")),
1138                 bad_type_msg, "castore");
1139             return;
1140           }
1141           no_control_flow = false; break;
1142         case Bytecodes::_sastore :
1143           current_frame.pop_stack(
1144             VerificationType::integer_type(), CHECK_VERIFY(this));
1145           current_frame.pop_stack(
1146             VerificationType::integer_type(), CHECK_VERIFY(this));
1147           atype = current_frame.pop_stack(
1148             VerificationType::reference_check(), CHECK_VERIFY(this));
1149           if (!atype.is_short_array()) {
1150             verify_error(ErrorContext::bad_type(bci,
1151                 current_frame.stack_top_ctx(), ref_ctx("[S")),
1152                 bad_type_msg, "sastore");
1153             return;
1154           }
1155           no_control_flow = false; break;
1156         case Bytecodes::_lastore :
1157           current_frame.pop_stack_2(
1158             VerificationType::long2_type(),
1159             VerificationType::long_type(), CHECK_VERIFY(this));
1160           current_frame.pop_stack(
1161             VerificationType::integer_type(), CHECK_VERIFY(this));
1162           atype = current_frame.pop_stack(
1163             VerificationType::reference_check(), CHECK_VERIFY(this));
1164           if (!atype.is_long_array()) {
1165             verify_error(ErrorContext::bad_type(bci,
1166                 current_frame.stack_top_ctx(), ref_ctx("[J")),
1167                 bad_type_msg, "lastore");
1168             return;
1169           }
1170           no_control_flow = false; break;
1171         case Bytecodes::_fastore :
1172           current_frame.pop_stack(
1173             VerificationType::float_type(), CHECK_VERIFY(this));
1174           current_frame.pop_stack
1175             (VerificationType::integer_type(), CHECK_VERIFY(this));
1176           atype = current_frame.pop_stack(
1177             VerificationType::reference_check(), CHECK_VERIFY(this));
1178           if (!atype.is_float_array()) {
1179             verify_error(ErrorContext::bad_type(bci,
1180                 current_frame.stack_top_ctx(), ref_ctx("[F")),
1181                 bad_type_msg, "fastore");
1182             return;
1183           }
1184           no_control_flow = false; break;
1185         case Bytecodes::_dastore :
1186           current_frame.pop_stack_2(
1187             VerificationType::double2_type(),
1188             VerificationType::double_type(), CHECK_VERIFY(this));
1189           current_frame.pop_stack(
1190             VerificationType::integer_type(), CHECK_VERIFY(this));
1191           atype = current_frame.pop_stack(
1192             VerificationType::reference_check(), CHECK_VERIFY(this));
1193           if (!atype.is_double_array()) {
1194             verify_error(ErrorContext::bad_type(bci,
1195                 current_frame.stack_top_ctx(), ref_ctx("[D")),
1196                 bad_type_msg, "dastore");
1197             return;
1198           }
1199           no_control_flow = false; break;
1200         case Bytecodes::_aastore :
1201           type = current_frame.pop_stack(object_type(), CHECK_VERIFY(this));
1202           type2 = current_frame.pop_stack(
1203             VerificationType::integer_type(), CHECK_VERIFY(this));
1204           atype = current_frame.pop_stack(
1205             VerificationType::reference_check(), CHECK_VERIFY(this));
1206           // more type-checking is done at runtime
1207           if (!atype.is_reference_array()) {
1208             verify_error(ErrorContext::bad_type(bci,
1209                 current_frame.stack_top_ctx(),
1210                 TypeOrigin::implicit(VerificationType::reference_check())),
1211                 bad_type_msg, "aastore");
1212             return;
1213           }
1214           // 4938384: relaxed constraint in JVMS 3nd edition.
1215           no_control_flow = false; break;
1216         case Bytecodes::_pop :
1217           current_frame.pop_stack(
1218             VerificationType::category1_check(), CHECK_VERIFY(this));
1219           no_control_flow = false; break;
1220         case Bytecodes::_pop2 :
1221           type = current_frame.pop_stack(CHECK_VERIFY(this));
1222           if (type.is_category1()) {
1223             current_frame.pop_stack(
1224               VerificationType::category1_check(), CHECK_VERIFY(this));
1225           } else if (type.is_category2_2nd()) {
1226             current_frame.pop_stack(
1227               VerificationType::category2_check(), CHECK_VERIFY(this));
1228           } else {
1229             /* Unreachable? Would need a category2_1st on TOS
1230              * which does not appear possible. */
1231             verify_error(
1232                 ErrorContext::bad_type(bci, current_frame.stack_top_ctx()),
1233                 bad_type_msg, "pop2");
1234             return;
1235           }
1236           no_control_flow = false; break;
1237         case Bytecodes::_dup :
1238           type = current_frame.pop_stack(
1239             VerificationType::category1_check(), CHECK_VERIFY(this));
1240           current_frame.push_stack(type, CHECK_VERIFY(this));
1241           current_frame.push_stack(type, CHECK_VERIFY(this));
1242           no_control_flow = false; break;
1243         case Bytecodes::_dup_x1 :
1244           type = current_frame.pop_stack(
1245             VerificationType::category1_check(), CHECK_VERIFY(this));
1246           type2 = current_frame.pop_stack(
1247             VerificationType::category1_check(), CHECK_VERIFY(this));
1248           current_frame.push_stack(type, CHECK_VERIFY(this));
1249           current_frame.push_stack(type2, CHECK_VERIFY(this));
1250           current_frame.push_stack(type, CHECK_VERIFY(this));
1251           no_control_flow = false; break;
1252         case Bytecodes::_dup_x2 :
1253         {
1254           VerificationType type3;
1255           type = current_frame.pop_stack(
1256             VerificationType::category1_check(), CHECK_VERIFY(this));
1257           type2 = current_frame.pop_stack(CHECK_VERIFY(this));
1258           if (type2.is_category1()) {
1259             type3 = current_frame.pop_stack(
1260               VerificationType::category1_check(), CHECK_VERIFY(this));
1261           } else if (type2.is_category2_2nd()) {
1262             type3 = current_frame.pop_stack(
1263               VerificationType::category2_check(), CHECK_VERIFY(this));
1264           } else {
1265             /* Unreachable? Would need a category2_1st at stack depth 2 with
1266              * a category1 on TOS which does not appear possible. */
1267             verify_error(ErrorContext::bad_type(
1268                 bci, current_frame.stack_top_ctx()), bad_type_msg, "dup_x2");
1269             return;
1270           }
1271           current_frame.push_stack(type, CHECK_VERIFY(this));
1272           current_frame.push_stack(type3, CHECK_VERIFY(this));
1273           current_frame.push_stack(type2, CHECK_VERIFY(this));
1274           current_frame.push_stack(type, CHECK_VERIFY(this));
1275           no_control_flow = false; break;
1276         }
1277         case Bytecodes::_dup2 :
1278           type = current_frame.pop_stack(CHECK_VERIFY(this));
1279           if (type.is_category1()) {
1280             type2 = current_frame.pop_stack(
1281               VerificationType::category1_check(), CHECK_VERIFY(this));
1282           } else if (type.is_category2_2nd()) {
1283             type2 = current_frame.pop_stack(
1284               VerificationType::category2_check(), CHECK_VERIFY(this));
1285           } else {
1286             /* Unreachable?  Would need a category2_1st on TOS which does not
1287              * appear possible. */
1288             verify_error(
1289                 ErrorContext::bad_type(bci, current_frame.stack_top_ctx()),
1290                 bad_type_msg, "dup2");
1291             return;
1292           }
1293           current_frame.push_stack(type2, CHECK_VERIFY(this));
1294           current_frame.push_stack(type, CHECK_VERIFY(this));
1295           current_frame.push_stack(type2, CHECK_VERIFY(this));
1296           current_frame.push_stack(type, CHECK_VERIFY(this));
1297           no_control_flow = false; break;
1298         case Bytecodes::_dup2_x1 :
1299         {
1300           VerificationType type3;
1301           type = current_frame.pop_stack(CHECK_VERIFY(this));
1302           if (type.is_category1()) {
1303             type2 = current_frame.pop_stack(
1304               VerificationType::category1_check(), CHECK_VERIFY(this));
1305           } else if (type.is_category2_2nd()) {
1306             type2 = current_frame.pop_stack(
1307               VerificationType::category2_check(), CHECK_VERIFY(this));
1308           } else {
1309             /* Unreachable?  Would need a category2_1st on TOS which does
1310              * not appear possible. */
1311             verify_error(
1312                 ErrorContext::bad_type(bci, current_frame.stack_top_ctx()),
1313                 bad_type_msg, "dup2_x1");
1314             return;
1315           }
1316           type3 = current_frame.pop_stack(
1317             VerificationType::category1_check(), CHECK_VERIFY(this));
1318           current_frame.push_stack(type2, CHECK_VERIFY(this));
1319           current_frame.push_stack(type, CHECK_VERIFY(this));
1320           current_frame.push_stack(type3, CHECK_VERIFY(this));
1321           current_frame.push_stack(type2, CHECK_VERIFY(this));
1322           current_frame.push_stack(type, CHECK_VERIFY(this));
1323           no_control_flow = false; break;
1324         }
1325         case Bytecodes::_dup2_x2 :
1326         {
1327           VerificationType type3, type4;
1328           type = current_frame.pop_stack(CHECK_VERIFY(this));
1329           if (type.is_category1()) {
1330             type2 = current_frame.pop_stack(
1331               VerificationType::category1_check(), CHECK_VERIFY(this));
1332           } else if (type.is_category2_2nd()) {
1333             type2 = current_frame.pop_stack(
1334               VerificationType::category2_check(), CHECK_VERIFY(this));
1335           } else {
1336             /* Unreachable?  Would need a category2_1st on TOS which does
1337              * not appear possible. */
1338             verify_error(
1339                 ErrorContext::bad_type(bci, current_frame.stack_top_ctx()),
1340                 bad_type_msg, "dup2_x2");
1341             return;
1342           }
1343           type3 = current_frame.pop_stack(CHECK_VERIFY(this));
1344           if (type3.is_category1()) {
1345             type4 = current_frame.pop_stack(
1346               VerificationType::category1_check(), CHECK_VERIFY(this));
1347           } else if (type3.is_category2_2nd()) {
1348             type4 = current_frame.pop_stack(
1349               VerificationType::category2_check(), CHECK_VERIFY(this));
1350           } else {
1351             /* Unreachable?  Would need a category2_1st on TOS after popping
1352              * a long/double or two category 1's, which does not
1353              * appear possible. */
1354             verify_error(
1355                 ErrorContext::bad_type(bci, current_frame.stack_top_ctx()),
1356                 bad_type_msg, "dup2_x2");
1357             return;
1358           }
1359           current_frame.push_stack(type2, CHECK_VERIFY(this));
1360           current_frame.push_stack(type, CHECK_VERIFY(this));
1361           current_frame.push_stack(type4, CHECK_VERIFY(this));
1362           current_frame.push_stack(type3, CHECK_VERIFY(this));
1363           current_frame.push_stack(type2, CHECK_VERIFY(this));
1364           current_frame.push_stack(type, CHECK_VERIFY(this));
1365           no_control_flow = false; break;
1366         }
1367         case Bytecodes::_swap :
1368           type = current_frame.pop_stack(
1369             VerificationType::category1_check(), CHECK_VERIFY(this));
1370           type2 = current_frame.pop_stack(
1371             VerificationType::category1_check(), CHECK_VERIFY(this));
1372           current_frame.push_stack(type, CHECK_VERIFY(this));
1373           current_frame.push_stack(type2, CHECK_VERIFY(this));
1374           no_control_flow = false; break;
1375         case Bytecodes::_iadd :
1376         case Bytecodes::_isub :
1377         case Bytecodes::_imul :
1378         case Bytecodes::_idiv :
1379         case Bytecodes::_irem :
1380         case Bytecodes::_ishl :
1381         case Bytecodes::_ishr :
1382         case Bytecodes::_iushr :
1383         case Bytecodes::_ior :
1384         case Bytecodes::_ixor :
1385         case Bytecodes::_iand :
1386           current_frame.pop_stack(
1387             VerificationType::integer_type(), CHECK_VERIFY(this));
1388           // fall through
1389         case Bytecodes::_ineg :
1390           current_frame.pop_stack(
1391             VerificationType::integer_type(), CHECK_VERIFY(this));
1392           current_frame.push_stack(
1393             VerificationType::integer_type(), CHECK_VERIFY(this));
1394           no_control_flow = false; break;
1395         case Bytecodes::_ladd :
1396         case Bytecodes::_lsub :
1397         case Bytecodes::_lmul :
1398         case Bytecodes::_ldiv :
1399         case Bytecodes::_lrem :
1400         case Bytecodes::_land :
1401         case Bytecodes::_lor :
1402         case Bytecodes::_lxor :
1403           current_frame.pop_stack_2(
1404             VerificationType::long2_type(),
1405             VerificationType::long_type(), CHECK_VERIFY(this));
1406           // fall through
1407         case Bytecodes::_lneg :
1408           current_frame.pop_stack_2(
1409             VerificationType::long2_type(),
1410             VerificationType::long_type(), CHECK_VERIFY(this));
1411           current_frame.push_stack_2(
1412             VerificationType::long_type(),
1413             VerificationType::long2_type(), CHECK_VERIFY(this));
1414           no_control_flow = false; break;
1415         case Bytecodes::_lshl :
1416         case Bytecodes::_lshr :
1417         case Bytecodes::_lushr :
1418           current_frame.pop_stack(
1419             VerificationType::integer_type(), CHECK_VERIFY(this));
1420           current_frame.pop_stack_2(
1421             VerificationType::long2_type(),
1422             VerificationType::long_type(), CHECK_VERIFY(this));
1423           current_frame.push_stack_2(
1424             VerificationType::long_type(),
1425             VerificationType::long2_type(), CHECK_VERIFY(this));
1426           no_control_flow = false; break;
1427         case Bytecodes::_fadd :
1428         case Bytecodes::_fsub :
1429         case Bytecodes::_fmul :
1430         case Bytecodes::_fdiv :
1431         case Bytecodes::_frem :
1432           current_frame.pop_stack(
1433             VerificationType::float_type(), CHECK_VERIFY(this));
1434           // fall through
1435         case Bytecodes::_fneg :
1436           current_frame.pop_stack(
1437             VerificationType::float_type(), CHECK_VERIFY(this));
1438           current_frame.push_stack(
1439             VerificationType::float_type(), CHECK_VERIFY(this));
1440           no_control_flow = false; break;
1441         case Bytecodes::_dadd :
1442         case Bytecodes::_dsub :
1443         case Bytecodes::_dmul :
1444         case Bytecodes::_ddiv :
1445         case Bytecodes::_drem :
1446           current_frame.pop_stack_2(
1447             VerificationType::double2_type(),
1448             VerificationType::double_type(), CHECK_VERIFY(this));
1449           // fall through
1450         case Bytecodes::_dneg :
1451           current_frame.pop_stack_2(
1452             VerificationType::double2_type(),
1453             VerificationType::double_type(), CHECK_VERIFY(this));
1454           current_frame.push_stack_2(
1455             VerificationType::double_type(),
1456             VerificationType::double2_type(), CHECK_VERIFY(this));
1457           no_control_flow = false; break;
1458         case Bytecodes::_iinc :
1459           verify_iinc(bcs.get_index(), &current_frame, CHECK_VERIFY(this));
1460           no_control_flow = false; break;
1461         case Bytecodes::_i2l :
1462           type = current_frame.pop_stack(
1463             VerificationType::integer_type(), CHECK_VERIFY(this));
1464           current_frame.push_stack_2(
1465             VerificationType::long_type(),
1466             VerificationType::long2_type(), CHECK_VERIFY(this));
1467           no_control_flow = false; break;
1468        case Bytecodes::_l2i :
1469           current_frame.pop_stack_2(
1470             VerificationType::long2_type(),
1471             VerificationType::long_type(), CHECK_VERIFY(this));
1472           current_frame.push_stack(
1473             VerificationType::integer_type(), CHECK_VERIFY(this));
1474           no_control_flow = false; break;
1475         case Bytecodes::_i2f :
1476           current_frame.pop_stack(
1477             VerificationType::integer_type(), CHECK_VERIFY(this));
1478           current_frame.push_stack(
1479             VerificationType::float_type(), CHECK_VERIFY(this));
1480           no_control_flow = false; break;
1481         case Bytecodes::_i2d :
1482           current_frame.pop_stack(
1483             VerificationType::integer_type(), CHECK_VERIFY(this));
1484           current_frame.push_stack_2(
1485             VerificationType::double_type(),
1486             VerificationType::double2_type(), CHECK_VERIFY(this));
1487           no_control_flow = false; break;
1488         case Bytecodes::_l2f :
1489           current_frame.pop_stack_2(
1490             VerificationType::long2_type(),
1491             VerificationType::long_type(), CHECK_VERIFY(this));
1492           current_frame.push_stack(
1493             VerificationType::float_type(), CHECK_VERIFY(this));
1494           no_control_flow = false; break;
1495         case Bytecodes::_l2d :
1496           current_frame.pop_stack_2(
1497             VerificationType::long2_type(),
1498             VerificationType::long_type(), CHECK_VERIFY(this));
1499           current_frame.push_stack_2(
1500             VerificationType::double_type(),
1501             VerificationType::double2_type(), CHECK_VERIFY(this));
1502           no_control_flow = false; break;
1503         case Bytecodes::_f2i :
1504           current_frame.pop_stack(
1505             VerificationType::float_type(), CHECK_VERIFY(this));
1506           current_frame.push_stack(
1507             VerificationType::integer_type(), CHECK_VERIFY(this));
1508           no_control_flow = false; break;
1509         case Bytecodes::_f2l :
1510           current_frame.pop_stack(
1511             VerificationType::float_type(), CHECK_VERIFY(this));
1512           current_frame.push_stack_2(
1513             VerificationType::long_type(),
1514             VerificationType::long2_type(), CHECK_VERIFY(this));
1515           no_control_flow = false; break;
1516         case Bytecodes::_f2d :
1517           current_frame.pop_stack(
1518             VerificationType::float_type(), CHECK_VERIFY(this));
1519           current_frame.push_stack_2(
1520             VerificationType::double_type(),
1521             VerificationType::double2_type(), CHECK_VERIFY(this));
1522           no_control_flow = false; break;
1523         case Bytecodes::_d2i :
1524           current_frame.pop_stack_2(
1525             VerificationType::double2_type(),
1526             VerificationType::double_type(), CHECK_VERIFY(this));
1527           current_frame.push_stack(
1528             VerificationType::integer_type(), CHECK_VERIFY(this));
1529           no_control_flow = false; break;
1530         case Bytecodes::_d2l :
1531           current_frame.pop_stack_2(
1532             VerificationType::double2_type(),
1533             VerificationType::double_type(), CHECK_VERIFY(this));
1534           current_frame.push_stack_2(
1535             VerificationType::long_type(),
1536             VerificationType::long2_type(), CHECK_VERIFY(this));
1537           no_control_flow = false; break;
1538         case Bytecodes::_d2f :
1539           current_frame.pop_stack_2(
1540             VerificationType::double2_type(),
1541             VerificationType::double_type(), CHECK_VERIFY(this));
1542           current_frame.push_stack(
1543             VerificationType::float_type(), CHECK_VERIFY(this));
1544           no_control_flow = false; break;
1545         case Bytecodes::_i2b :
1546         case Bytecodes::_i2c :
1547         case Bytecodes::_i2s :
1548           current_frame.pop_stack(
1549             VerificationType::integer_type(), CHECK_VERIFY(this));
1550           current_frame.push_stack(
1551             VerificationType::integer_type(), CHECK_VERIFY(this));
1552           no_control_flow = false; break;
1553         case Bytecodes::_lcmp :
1554           current_frame.pop_stack_2(
1555             VerificationType::long2_type(),
1556             VerificationType::long_type(), CHECK_VERIFY(this));
1557           current_frame.pop_stack_2(
1558             VerificationType::long2_type(),
1559             VerificationType::long_type(), CHECK_VERIFY(this));
1560           current_frame.push_stack(
1561             VerificationType::integer_type(), CHECK_VERIFY(this));
1562           no_control_flow = false; break;
1563         case Bytecodes::_fcmpl :
1564         case Bytecodes::_fcmpg :
1565           current_frame.pop_stack(
1566             VerificationType::float_type(), CHECK_VERIFY(this));
1567           current_frame.pop_stack(
1568             VerificationType::float_type(), CHECK_VERIFY(this));
1569           current_frame.push_stack(
1570             VerificationType::integer_type(), CHECK_VERIFY(this));
1571           no_control_flow = false; break;
1572         case Bytecodes::_dcmpl :
1573         case Bytecodes::_dcmpg :
1574           current_frame.pop_stack_2(
1575             VerificationType::double2_type(),
1576             VerificationType::double_type(), CHECK_VERIFY(this));
1577           current_frame.pop_stack_2(
1578             VerificationType::double2_type(),
1579             VerificationType::double_type(), CHECK_VERIFY(this));
1580           current_frame.push_stack(
1581             VerificationType::integer_type(), CHECK_VERIFY(this));
1582           no_control_flow = false; break;
1583         case Bytecodes::_if_icmpeq:
1584         case Bytecodes::_if_icmpne:
1585         case Bytecodes::_if_icmplt:
1586         case Bytecodes::_if_icmpge:
1587         case Bytecodes::_if_icmpgt:
1588         case Bytecodes::_if_icmple:
1589           current_frame.pop_stack(
1590             VerificationType::integer_type(), CHECK_VERIFY(this));
1591           // fall through
1592         case Bytecodes::_ifeq:
1593         case Bytecodes::_ifne:
1594         case Bytecodes::_iflt:
1595         case Bytecodes::_ifge:
1596         case Bytecodes::_ifgt:
1597         case Bytecodes::_ifle:
1598           current_frame.pop_stack(
1599             VerificationType::integer_type(), CHECK_VERIFY(this));
1600           target = bcs.dest();
1601           stackmap_table.check_jump_target(
1602             &current_frame, target, CHECK_VERIFY(this));
1603           no_control_flow = false; break;
1604         case Bytecodes::_if_acmpeq :
1605         case Bytecodes::_if_acmpne :
1606           current_frame.pop_stack(
1607             VerificationType::reference_check(), CHECK_VERIFY(this));
1608           // fall through
1609         case Bytecodes::_ifnull :
1610         case Bytecodes::_ifnonnull :
1611           current_frame.pop_stack(
1612             VerificationType::reference_check(), CHECK_VERIFY(this));
1613           target = bcs.dest();
1614           stackmap_table.check_jump_target
1615             (&current_frame, target, CHECK_VERIFY(this));
1616           no_control_flow = false; break;
1617         case Bytecodes::_goto :
1618           target = bcs.dest();
1619           stackmap_table.check_jump_target(
1620             &current_frame, target, CHECK_VERIFY(this));
1621           no_control_flow = true; break;
1622         case Bytecodes::_goto_w :
1623           target = bcs.dest_w();
1624           stackmap_table.check_jump_target(
1625             &current_frame, target, CHECK_VERIFY(this));
1626           no_control_flow = true; break;
1627         case Bytecodes::_tableswitch :
1628         case Bytecodes::_lookupswitch :
1629           verify_switch(
1630             &bcs, code_length, code_data, &current_frame,
1631             &stackmap_table, CHECK_VERIFY(this));
1632           no_control_flow = true; break;
1633         case Bytecodes::_ireturn :
1634           type = current_frame.pop_stack(
1635             VerificationType::integer_type(), CHECK_VERIFY(this));
1636           verify_return_value(return_type, type, bci,
1637                               &current_frame, CHECK_VERIFY(this));
1638           no_control_flow = true; break;
1639         case Bytecodes::_lreturn :
1640           type2 = current_frame.pop_stack(
1641             VerificationType::long2_type(), CHECK_VERIFY(this));
1642           type = current_frame.pop_stack(
1643             VerificationType::long_type(), CHECK_VERIFY(this));
1644           verify_return_value(return_type, type, bci,
1645                               &current_frame, CHECK_VERIFY(this));
1646           no_control_flow = true; break;
1647         case Bytecodes::_freturn :
1648           type = current_frame.pop_stack(
1649             VerificationType::float_type(), CHECK_VERIFY(this));
1650           verify_return_value(return_type, type, bci,
1651                               &current_frame, CHECK_VERIFY(this));
1652           no_control_flow = true; break;
1653         case Bytecodes::_dreturn :
1654           type2 = current_frame.pop_stack(
1655             VerificationType::double2_type(),  CHECK_VERIFY(this));
1656           type = current_frame.pop_stack(
1657             VerificationType::double_type(), CHECK_VERIFY(this));
1658           verify_return_value(return_type, type, bci,
1659                               &current_frame, CHECK_VERIFY(this));
1660           no_control_flow = true; break;
1661         case Bytecodes::_areturn :
1662           type = current_frame.pop_stack(
1663             VerificationType::reference_check(), CHECK_VERIFY(this));
1664           verify_return_value(return_type, type, bci,
1665                               &current_frame, CHECK_VERIFY(this));
1666           no_control_flow = true; break;
1667         case Bytecodes::_return :
1668           if (return_type != VerificationType::bogus_type()) {
1669             verify_error(ErrorContext::bad_code(bci),
1670                          "Method expects a return value");
1671             return;
1672           }
1673           // Make sure "this" has been initialized if current method is an
1674           // <init>.
1675           if (_method->name() == vmSymbols::object_initializer_name() &&
1676               current_frame.flag_this_uninit()) {
1677             verify_error(ErrorContext::bad_code(bci),
1678                          "Constructor must call super() or this() "
1679                          "before return");
1680             return;
1681           }
1682           no_control_flow = true; break;
1683         case Bytecodes::_getstatic :
1684         case Bytecodes::_putstatic :
1685           // pass TRUE, operand can be an array type for getstatic/putstatic.
1686           verify_field_instructions(
1687             &bcs, &current_frame, cp, true, CHECK_VERIFY(this));
1688           no_control_flow = false; break;
1689         case Bytecodes::_getfield :
1690         case Bytecodes::_putfield :
1691           // pass FALSE, operand can't be an array type for getfield/putfield.
1692           verify_field_instructions(
1693             &bcs, &current_frame, cp, false, CHECK_VERIFY(this));
1694           no_control_flow = false; break;
1695         case Bytecodes::_invokevirtual :
1696         case Bytecodes::_invokespecial :
1697         case Bytecodes::_invokestatic :
1698           verify_invoke_instructions(
1699             &bcs, code_length, &current_frame, (bci >= ex_min && bci < ex_max),
1700             &this_uninit, return_type, cp, &stackmap_table, CHECK_VERIFY(this));
1701           no_control_flow = false; break;
1702         case Bytecodes::_invokeinterface :
1703         case Bytecodes::_invokedynamic :
1704           verify_invoke_instructions(
1705             &bcs, code_length, &current_frame, (bci >= ex_min && bci < ex_max),
1706             &this_uninit, return_type, cp, &stackmap_table, CHECK_VERIFY(this));
1707           no_control_flow = false; break;
1708         case Bytecodes::_new :
1709         {
1710           index = bcs.get_index_u2();
1711           verify_cp_class_type(bci, index, cp, CHECK_VERIFY(this));
1712           VerificationType new_class_type =
1713             cp_index_to_type(index, cp, CHECK_VERIFY(this));
1714           if (!new_class_type.is_object()) {
1715             verify_error(ErrorContext::bad_type(bci,
1716                 TypeOrigin::cp(index, new_class_type)),
1717                 "Illegal new instruction");
1718             return;
1719           }
1720           type = VerificationType::uninitialized_type(bci);
1721           current_frame.push_stack(type, CHECK_VERIFY(this));
1722           no_control_flow = false; break;
1723         }
1724         case Bytecodes::_newarray :
1725           type = get_newarray_type(bcs.get_index(), bci, CHECK_VERIFY(this));
1726           current_frame.pop_stack(
1727             VerificationType::integer_type(),  CHECK_VERIFY(this));
1728           current_frame.push_stack(type, CHECK_VERIFY(this));
1729           no_control_flow = false; break;
1730         case Bytecodes::_anewarray :
1731           verify_anewarray(
1732             bci, bcs.get_index_u2(), cp, &current_frame, CHECK_VERIFY(this));
1733           no_control_flow = false; break;
1734         case Bytecodes::_arraylength :
1735           type = current_frame.pop_stack(
1736             VerificationType::reference_check(), CHECK_VERIFY(this));
1737           if (!(type.is_null() || type.is_array())) {
1738             verify_error(ErrorContext::bad_type(
1739                 bci, current_frame.stack_top_ctx()),
1740                 bad_type_msg, "arraylength");
1741           }
1742           current_frame.push_stack(
1743             VerificationType::integer_type(), CHECK_VERIFY(this));
1744           no_control_flow = false; break;
1745         case Bytecodes::_checkcast :
1746         {
1747           index = bcs.get_index_u2();
1748           verify_cp_class_type(bci, index, cp, CHECK_VERIFY(this));
1749           current_frame.pop_stack(object_type(), CHECK_VERIFY(this));
1750           VerificationType klass_type = cp_index_to_type(
1751             index, cp, CHECK_VERIFY(this));
1752           current_frame.push_stack(klass_type, CHECK_VERIFY(this));
1753           no_control_flow = false; break;
1754         }
1755         case Bytecodes::_instanceof : {
1756           index = bcs.get_index_u2();
1757           verify_cp_class_type(bci, index, cp, CHECK_VERIFY(this));
1758           current_frame.pop_stack(object_type(), CHECK_VERIFY(this));
1759           current_frame.push_stack(
1760             VerificationType::integer_type(), CHECK_VERIFY(this));
1761           no_control_flow = false; break;
1762         }
1763         case Bytecodes::_monitorenter :
1764         case Bytecodes::_monitorexit :
1765           current_frame.pop_stack(
1766             VerificationType::reference_check(), CHECK_VERIFY(this));
1767           no_control_flow = false; break;
1768         case Bytecodes::_multianewarray :
1769         {
1770           index = bcs.get_index_u2();
1771           u2 dim = *(bcs.bcp()+3);
1772           verify_cp_class_type(bci, index, cp, CHECK_VERIFY(this));
1773           VerificationType new_array_type =
1774             cp_index_to_type(index, cp, CHECK_VERIFY(this));
1775           if (!new_array_type.is_array()) {
1776             verify_error(ErrorContext::bad_type(bci,
1777                 TypeOrigin::cp(index, new_array_type)),
1778                 "Illegal constant pool index in multianewarray instruction");
1779             return;
1780           }
1781           if (dim < 1 || new_array_type.dimensions() < dim) {
1782             verify_error(ErrorContext::bad_code(bci),
1783                 "Illegal dimension in multianewarray instruction: %d", dim);
1784             return;
1785           }
1786           for (int i = 0; i < dim; i++) {
1787             current_frame.pop_stack(
1788               VerificationType::integer_type(), CHECK_VERIFY(this));
1789           }
1790           current_frame.push_stack(new_array_type, CHECK_VERIFY(this));
1791           no_control_flow = false; break;
1792         }
1793         case Bytecodes::_athrow :
1794           type = VerificationType::reference_type(
1795             vmSymbols::java_lang_Throwable());
1796           current_frame.pop_stack(type, CHECK_VERIFY(this));
1797           no_control_flow = true; break;
1798         default:
1799           // We only need to check the valid bytecodes in class file.
1800           // And jsr and ret are not in the new class file format in JDK1.5.
1801           verify_error(ErrorContext::bad_code(bci),
1802               "Bad instruction: %02x", opcode);
1803           no_control_flow = false;
1804           return;
1805       }  // end switch
1806     }  // end Merge with the next instruction
1807 
1808     // Look for possible jump target in exception handlers and see if it matches
1809     // current_frame.  Don't do this check if it has already been done (for
1810     // ([a,d,f,i,l]store* opcodes).  This check cannot be done earlier because
1811     // opcodes, such as invokespecial, may set the this_uninit flag.
1812     assert(!(verified_exc_handlers && this_uninit),
1813       "Exception handler targets got verified before this_uninit got set");
1814     if (!verified_exc_handlers && bci >= ex_min && bci < ex_max) {
1815       if (was_recursively_verified()) return;
1816       verify_exception_handler_targets(
1817         bci, this_uninit, &current_frame, &stackmap_table, CHECK_VERIFY(this));
1818     }
1819   } // end while
1820 
1821   // Make sure that control flow does not fall through end of the method
1822   if (!no_control_flow) {
1823     verify_error(ErrorContext::bad_code(code_length),
1824         "Control flow falls through code end");
1825     return;
1826   }
1827 }
1828 
1829 #undef bad_type_message
1830 
generate_code_data(const methodHandle & m,u4 code_length,TRAPS)1831 char* ClassVerifier::generate_code_data(const methodHandle& m, u4 code_length, TRAPS) {
1832   char* code_data = NEW_RESOURCE_ARRAY(char, code_length);
1833   memset(code_data, 0, sizeof(char) * code_length);
1834   RawBytecodeStream bcs(m);
1835 
1836   while (!bcs.is_last_bytecode()) {
1837     if (bcs.raw_next() != Bytecodes::_illegal) {
1838       int bci = bcs.bci();
1839       if (bcs.raw_code() == Bytecodes::_new) {
1840         code_data[bci] = NEW_OFFSET;
1841       } else {
1842         code_data[bci] = BYTECODE_OFFSET;
1843       }
1844     } else {
1845       verify_error(ErrorContext::bad_code(bcs.bci()), "Bad instruction");
1846       return NULL;
1847     }
1848   }
1849 
1850   return code_data;
1851 }
1852 
1853 // Since this method references the constant pool, call was_recursively_verified()
1854 // before calling this method to make sure a prior class load did not cause the
1855 // current class to get verified.
verify_exception_handler_table(u4 code_length,char * code_data,int & min,int & max,TRAPS)1856 void ClassVerifier::verify_exception_handler_table(u4 code_length, char* code_data, int& min, int& max, TRAPS) {
1857   ExceptionTable exhandlers(_method());
1858   int exlength = exhandlers.length();
1859   constantPoolHandle cp (THREAD, _method->constants());
1860 
1861   for(int i = 0; i < exlength; i++) {
1862     u2 start_pc = exhandlers.start_pc(i);
1863     u2 end_pc = exhandlers.end_pc(i);
1864     u2 handler_pc = exhandlers.handler_pc(i);
1865     if (start_pc >= code_length || code_data[start_pc] == 0) {
1866       class_format_error("Illegal exception table start_pc %d", start_pc);
1867       return;
1868     }
1869     if (end_pc != code_length) {   // special case: end_pc == code_length
1870       if (end_pc > code_length || code_data[end_pc] == 0) {
1871         class_format_error("Illegal exception table end_pc %d", end_pc);
1872         return;
1873       }
1874     }
1875     if (handler_pc >= code_length || code_data[handler_pc] == 0) {
1876       class_format_error("Illegal exception table handler_pc %d", handler_pc);
1877       return;
1878     }
1879     int catch_type_index = exhandlers.catch_type_index(i);
1880     if (catch_type_index != 0) {
1881       VerificationType catch_type = cp_index_to_type(
1882         catch_type_index, cp, CHECK_VERIFY(this));
1883       VerificationType throwable =
1884         VerificationType::reference_type(vmSymbols::java_lang_Throwable());
1885       bool is_subclass = throwable.is_assignable_from(
1886         catch_type, this, false, CHECK_VERIFY(this));
1887       if (!is_subclass) {
1888         // 4286534: should throw VerifyError according to recent spec change
1889         verify_error(ErrorContext::bad_type(handler_pc,
1890             TypeOrigin::cp(catch_type_index, catch_type),
1891             TypeOrigin::implicit(throwable)),
1892             "Catch type is not a subclass "
1893             "of Throwable in exception handler %d", handler_pc);
1894         return;
1895       }
1896     }
1897     if (start_pc < min) min = start_pc;
1898     if (end_pc > max) max = end_pc;
1899   }
1900 }
1901 
verify_local_variable_table(u4 code_length,char * code_data,TRAPS)1902 void ClassVerifier::verify_local_variable_table(u4 code_length, char* code_data, TRAPS) {
1903   int localvariable_table_length = _method->localvariable_table_length();
1904   if (localvariable_table_length > 0) {
1905     LocalVariableTableElement* table = _method->localvariable_table_start();
1906     for (int i = 0; i < localvariable_table_length; i++) {
1907       u2 start_bci = table[i].start_bci;
1908       u2 length = table[i].length;
1909 
1910       if (start_bci >= code_length || code_data[start_bci] == 0) {
1911         class_format_error(
1912           "Illegal local variable table start_pc %d", start_bci);
1913         return;
1914       }
1915       u4 end_bci = (u4)(start_bci + length);
1916       if (end_bci != code_length) {
1917         if (end_bci >= code_length || code_data[end_bci] == 0) {
1918           class_format_error( "Illegal local variable table length %d", length);
1919           return;
1920         }
1921       }
1922     }
1923   }
1924 }
1925 
verify_stackmap_table(u2 stackmap_index,u2 bci,StackMapFrame * current_frame,StackMapTable * stackmap_table,bool no_control_flow,TRAPS)1926 u2 ClassVerifier::verify_stackmap_table(u2 stackmap_index, u2 bci,
1927                                         StackMapFrame* current_frame,
1928                                         StackMapTable* stackmap_table,
1929                                         bool no_control_flow, TRAPS) {
1930   if (stackmap_index < stackmap_table->get_frame_count()) {
1931     u2 this_offset = stackmap_table->get_offset(stackmap_index);
1932     if (no_control_flow && this_offset > bci) {
1933       verify_error(ErrorContext::missing_stackmap(bci),
1934                    "Expecting a stack map frame");
1935       return 0;
1936     }
1937     if (this_offset == bci) {
1938       ErrorContext ctx;
1939       // See if current stack map can be assigned to the frame in table.
1940       // current_frame is the stackmap frame got from the last instruction.
1941       // If matched, current_frame will be updated by this method.
1942       bool matches = stackmap_table->match_stackmap(
1943         current_frame, this_offset, stackmap_index,
1944         !no_control_flow, true, &ctx, CHECK_VERIFY_(this, 0));
1945       if (!matches) {
1946         // report type error
1947         verify_error(ctx, "Instruction type does not match stack map");
1948         return 0;
1949       }
1950       stackmap_index++;
1951     } else if (this_offset < bci) {
1952       // current_offset should have met this_offset.
1953       class_format_error("Bad stack map offset %d", this_offset);
1954       return 0;
1955     }
1956   } else if (no_control_flow) {
1957     verify_error(ErrorContext::bad_code(bci), "Expecting a stack map frame");
1958     return 0;
1959   }
1960   return stackmap_index;
1961 }
1962 
1963 // Since this method references the constant pool, call was_recursively_verified()
1964 // before calling this method to make sure a prior class load did not cause the
1965 // current class to get verified.
verify_exception_handler_targets(u2 bci,bool this_uninit,StackMapFrame * current_frame,StackMapTable * stackmap_table,TRAPS)1966 void ClassVerifier::verify_exception_handler_targets(u2 bci, bool this_uninit,
1967                                                      StackMapFrame* current_frame,
1968                                                      StackMapTable* stackmap_table, TRAPS) {
1969   constantPoolHandle cp (THREAD, _method->constants());
1970   ExceptionTable exhandlers(_method());
1971   int exlength = exhandlers.length();
1972   for(int i = 0; i < exlength; i++) {
1973     u2 start_pc = exhandlers.start_pc(i);
1974     u2 end_pc = exhandlers.end_pc(i);
1975     u2 handler_pc = exhandlers.handler_pc(i);
1976     int catch_type_index = exhandlers.catch_type_index(i);
1977     if(bci >= start_pc && bci < end_pc) {
1978       u1 flags = current_frame->flags();
1979       if (this_uninit) {  flags |= FLAG_THIS_UNINIT; }
1980       StackMapFrame* new_frame = current_frame->frame_in_exception_handler(flags);
1981       if (catch_type_index != 0) {
1982         if (was_recursively_verified()) return;
1983         // We know that this index refers to a subclass of Throwable
1984         VerificationType catch_type = cp_index_to_type(
1985           catch_type_index, cp, CHECK_VERIFY(this));
1986         new_frame->push_stack(catch_type, CHECK_VERIFY(this));
1987       } else {
1988         VerificationType throwable =
1989           VerificationType::reference_type(vmSymbols::java_lang_Throwable());
1990         new_frame->push_stack(throwable, CHECK_VERIFY(this));
1991       }
1992       ErrorContext ctx;
1993       bool matches = stackmap_table->match_stackmap(
1994         new_frame, handler_pc, true, false, &ctx, CHECK_VERIFY(this));
1995       if (!matches) {
1996         verify_error(ctx, "Stack map does not match the one at "
1997             "exception handler %d", handler_pc);
1998         return;
1999       }
2000     }
2001   }
2002 }
2003 
verify_cp_index(u2 bci,const constantPoolHandle & cp,int index,TRAPS)2004 void ClassVerifier::verify_cp_index(
2005     u2 bci, const constantPoolHandle& cp, int index, TRAPS) {
2006   int nconstants = cp->length();
2007   if ((index <= 0) || (index >= nconstants)) {
2008     verify_error(ErrorContext::bad_cp_index(bci, index),
2009         "Illegal constant pool index %d in class %s",
2010         index, cp->pool_holder()->external_name());
2011     return;
2012   }
2013 }
2014 
verify_cp_type(u2 bci,int index,const constantPoolHandle & cp,unsigned int types,TRAPS)2015 void ClassVerifier::verify_cp_type(
2016     u2 bci, int index, const constantPoolHandle& cp, unsigned int types, TRAPS) {
2017 
2018   // In some situations, bytecode rewriting may occur while we're verifying.
2019   // In this case, a constant pool cache exists and some indices refer to that
2020   // instead.  Be sure we don't pick up such indices by accident.
2021   // We must check was_recursively_verified() before we get here.
2022   guarantee(cp->cache() == NULL, "not rewritten yet");
2023 
2024   verify_cp_index(bci, cp, index, CHECK_VERIFY(this));
2025   unsigned int tag = cp->tag_at(index).value();
2026   if ((types & (1 << tag)) == 0) {
2027     verify_error(ErrorContext::bad_cp_index(bci, index),
2028       "Illegal type at constant pool entry %d in class %s",
2029       index, cp->pool_holder()->external_name());
2030     return;
2031   }
2032 }
2033 
verify_cp_class_type(u2 bci,int index,const constantPoolHandle & cp,TRAPS)2034 void ClassVerifier::verify_cp_class_type(
2035     u2 bci, int index, const constantPoolHandle& cp, TRAPS) {
2036   verify_cp_index(bci, cp, index, CHECK_VERIFY(this));
2037   constantTag tag = cp->tag_at(index);
2038   if (!tag.is_klass() && !tag.is_unresolved_klass()) {
2039     verify_error(ErrorContext::bad_cp_index(bci, index),
2040         "Illegal type at constant pool entry %d in class %s",
2041         index, cp->pool_holder()->external_name());
2042     return;
2043   }
2044 }
2045 
verify_error(ErrorContext ctx,const char * msg,...)2046 void ClassVerifier::verify_error(ErrorContext ctx, const char* msg, ...) {
2047   stringStream ss;
2048 
2049   ctx.reset_frames();
2050   _exception_type = vmSymbols::java_lang_VerifyError();
2051   _error_context = ctx;
2052   va_list va;
2053   va_start(va, msg);
2054   ss.vprint(msg, va);
2055   va_end(va);
2056   _message = ss.as_string();
2057 #ifdef ASSERT
2058   ResourceMark rm;
2059   const char* exception_name = _exception_type->as_C_string();
2060   Exceptions::debug_check_abort(exception_name, NULL);
2061 #endif // ndef ASSERT
2062 }
2063 
class_format_error(const char * msg,...)2064 void ClassVerifier::class_format_error(const char* msg, ...) {
2065   stringStream ss;
2066   _exception_type = vmSymbols::java_lang_ClassFormatError();
2067   va_list va;
2068   va_start(va, msg);
2069   ss.vprint(msg, va);
2070   va_end(va);
2071   if (!_method.is_null()) {
2072     ss.print(" in method '");
2073     _method->print_external_name(&ss);
2074     ss.print("'");
2075   }
2076   _message = ss.as_string();
2077 }
2078 
load_class(Symbol * name,TRAPS)2079 Klass* ClassVerifier::load_class(Symbol* name, TRAPS) {
2080   HandleMark hm(THREAD);
2081   // Get current loader and protection domain first.
2082   oop loader = current_class()->class_loader();
2083   oop protection_domain = current_class()->protection_domain();
2084 
2085   Klass* kls = SystemDictionary::resolve_or_fail(
2086     name, Handle(THREAD, loader), Handle(THREAD, protection_domain),
2087     true, THREAD);
2088 
2089   if (kls != NULL) {
2090     if (log_is_enabled(Debug, class, resolve)) {
2091       Verifier::trace_class_resolution(kls, current_class());
2092     }
2093   }
2094   return kls;
2095 }
2096 
is_protected_access(InstanceKlass * this_class,Klass * target_class,Symbol * field_name,Symbol * field_sig,bool is_method)2097 bool ClassVerifier::is_protected_access(InstanceKlass* this_class,
2098                                         Klass* target_class,
2099                                         Symbol* field_name,
2100                                         Symbol* field_sig,
2101                                         bool is_method) {
2102   NoSafepointVerifier nosafepoint;
2103 
2104   // If target class isn't a super class of this class, we don't worry about this case
2105   if (!this_class->is_subclass_of(target_class)) {
2106     return false;
2107   }
2108   // Check if the specified method or field is protected
2109   InstanceKlass* target_instance = InstanceKlass::cast(target_class);
2110   fieldDescriptor fd;
2111   if (is_method) {
2112     Method* m = target_instance->uncached_lookup_method(field_name, field_sig, Klass::find_overpass);
2113     if (m != NULL && m->is_protected()) {
2114       if (!this_class->is_same_class_package(m->method_holder())) {
2115         return true;
2116       }
2117     }
2118   } else {
2119     Klass* member_klass = target_instance->find_field(field_name, field_sig, &fd);
2120     if (member_klass != NULL && fd.is_protected()) {
2121       if (!this_class->is_same_class_package(member_klass)) {
2122         return true;
2123       }
2124     }
2125   }
2126   return false;
2127 }
2128 
verify_ldc(int opcode,u2 index,StackMapFrame * current_frame,const constantPoolHandle & cp,u2 bci,TRAPS)2129 void ClassVerifier::verify_ldc(
2130     int opcode, u2 index, StackMapFrame* current_frame,
2131     const constantPoolHandle& cp, u2 bci, TRAPS) {
2132   verify_cp_index(bci, cp, index, CHECK_VERIFY(this));
2133   constantTag tag = cp->tag_at(index);
2134   unsigned int types = 0;
2135   if (opcode == Bytecodes::_ldc || opcode == Bytecodes::_ldc_w) {
2136     if (!tag.is_unresolved_klass()) {
2137       types = (1 << JVM_CONSTANT_Integer) | (1 << JVM_CONSTANT_Float)
2138             | (1 << JVM_CONSTANT_String)  | (1 << JVM_CONSTANT_Class)
2139             | (1 << JVM_CONSTANT_MethodHandle) | (1 << JVM_CONSTANT_MethodType)
2140             | (1 << JVM_CONSTANT_Dynamic);
2141       // Note:  The class file parser already verified the legality of
2142       // MethodHandle and MethodType constants.
2143       verify_cp_type(bci, index, cp, types, CHECK_VERIFY(this));
2144     }
2145   } else {
2146     assert(opcode == Bytecodes::_ldc2_w, "must be ldc2_w");
2147     types = (1 << JVM_CONSTANT_Double) | (1 << JVM_CONSTANT_Long)
2148           | (1 << JVM_CONSTANT_Dynamic);
2149     verify_cp_type(bci, index, cp, types, CHECK_VERIFY(this));
2150   }
2151   if (tag.is_string() && cp->is_pseudo_string_at(index)) {
2152     current_frame->push_stack(object_type(), CHECK_VERIFY(this));
2153   } else if (tag.is_string()) {
2154     current_frame->push_stack(
2155       VerificationType::reference_type(
2156         vmSymbols::java_lang_String()), CHECK_VERIFY(this));
2157   } else if (tag.is_klass() || tag.is_unresolved_klass()) {
2158     current_frame->push_stack(
2159       VerificationType::reference_type(
2160         vmSymbols::java_lang_Class()), CHECK_VERIFY(this));
2161   } else if (tag.is_int()) {
2162     current_frame->push_stack(
2163       VerificationType::integer_type(), CHECK_VERIFY(this));
2164   } else if (tag.is_float()) {
2165     current_frame->push_stack(
2166       VerificationType::float_type(), CHECK_VERIFY(this));
2167   } else if (tag.is_double()) {
2168     current_frame->push_stack_2(
2169       VerificationType::double_type(),
2170       VerificationType::double2_type(), CHECK_VERIFY(this));
2171   } else if (tag.is_long()) {
2172     current_frame->push_stack_2(
2173       VerificationType::long_type(),
2174       VerificationType::long2_type(), CHECK_VERIFY(this));
2175   } else if (tag.is_method_handle()) {
2176     current_frame->push_stack(
2177       VerificationType::reference_type(
2178         vmSymbols::java_lang_invoke_MethodHandle()), CHECK_VERIFY(this));
2179   } else if (tag.is_method_type()) {
2180     current_frame->push_stack(
2181       VerificationType::reference_type(
2182         vmSymbols::java_lang_invoke_MethodType()), CHECK_VERIFY(this));
2183   } else if (tag.is_dynamic_constant()) {
2184     Symbol* constant_type = cp->uncached_signature_ref_at(index);
2185     // Field signature was checked in ClassFileParser.
2186     assert(SignatureVerifier::is_valid_type_signature(constant_type),
2187            "Invalid type for dynamic constant");
2188     assert(sizeof(VerificationType) == sizeof(uintptr_t),
2189           "buffer type must match VerificationType size");
2190     uintptr_t constant_type_buffer[2];
2191     VerificationType* v_constant_type = (VerificationType*)constant_type_buffer;
2192     SignatureStream sig_stream(constant_type, false);
2193     int n = change_sig_to_verificationType(&sig_stream, v_constant_type);
2194     int opcode_n = (opcode == Bytecodes::_ldc2_w ? 2 : 1);
2195     if (n != opcode_n) {
2196       // wrong kind of ldc; reverify against updated type mask
2197       types &= ~(1 << JVM_CONSTANT_Dynamic);
2198       verify_cp_type(bci, index, cp, types, CHECK_VERIFY(this));
2199     }
2200     for (int i = 0; i < n; i++) {
2201       current_frame->push_stack(v_constant_type[i], CHECK_VERIFY(this));
2202     }
2203   } else {
2204     /* Unreachable? verify_cp_type has already validated the cp type. */
2205     verify_error(
2206         ErrorContext::bad_cp_index(bci, index), "Invalid index in ldc");
2207     return;
2208   }
2209 }
2210 
verify_switch(RawBytecodeStream * bcs,u4 code_length,char * code_data,StackMapFrame * current_frame,StackMapTable * stackmap_table,TRAPS)2211 void ClassVerifier::verify_switch(
2212     RawBytecodeStream* bcs, u4 code_length, char* code_data,
2213     StackMapFrame* current_frame, StackMapTable* stackmap_table, TRAPS) {
2214   int bci = bcs->bci();
2215   address bcp = bcs->bcp();
2216   address aligned_bcp = align_up(bcp + 1, jintSize);
2217 
2218   if (_klass->major_version() < NONZERO_PADDING_BYTES_IN_SWITCH_MAJOR_VERSION) {
2219     // 4639449 & 4647081: padding bytes must be 0
2220     u2 padding_offset = 1;
2221     while ((bcp + padding_offset) < aligned_bcp) {
2222       if(*(bcp + padding_offset) != 0) {
2223         verify_error(ErrorContext::bad_code(bci),
2224                      "Nonzero padding byte in lookupswitch or tableswitch");
2225         return;
2226       }
2227       padding_offset++;
2228     }
2229   }
2230 
2231   int default_offset = (int) Bytes::get_Java_u4(aligned_bcp);
2232   int keys, delta;
2233   current_frame->pop_stack(
2234     VerificationType::integer_type(), CHECK_VERIFY(this));
2235   if (bcs->raw_code() == Bytecodes::_tableswitch) {
2236     jint low = (jint)Bytes::get_Java_u4(aligned_bcp + jintSize);
2237     jint high = (jint)Bytes::get_Java_u4(aligned_bcp + 2*jintSize);
2238     if (low > high) {
2239       verify_error(ErrorContext::bad_code(bci),
2240           "low must be less than or equal to high in tableswitch");
2241       return;
2242     }
2243     keys = high - low + 1;
2244     if (keys < 0) {
2245       verify_error(ErrorContext::bad_code(bci), "too many keys in tableswitch");
2246       return;
2247     }
2248     delta = 1;
2249   } else {
2250     keys = (int)Bytes::get_Java_u4(aligned_bcp + jintSize);
2251     if (keys < 0) {
2252       verify_error(ErrorContext::bad_code(bci),
2253                    "number of keys in lookupswitch less than 0");
2254       return;
2255     }
2256     delta = 2;
2257     // Make sure that the lookupswitch items are sorted
2258     for (int i = 0; i < (keys - 1); i++) {
2259       jint this_key = Bytes::get_Java_u4(aligned_bcp + (2+2*i)*jintSize);
2260       jint next_key = Bytes::get_Java_u4(aligned_bcp + (2+2*i+2)*jintSize);
2261       if (this_key >= next_key) {
2262         verify_error(ErrorContext::bad_code(bci),
2263                      "Bad lookupswitch instruction");
2264         return;
2265       }
2266     }
2267   }
2268   int target = bci + default_offset;
2269   stackmap_table->check_jump_target(current_frame, target, CHECK_VERIFY(this));
2270   for (int i = 0; i < keys; i++) {
2271     // Because check_jump_target() may safepoint, the bytecode could have
2272     // moved, which means 'aligned_bcp' is no good and needs to be recalculated.
2273     aligned_bcp = align_up(bcs->bcp() + 1, jintSize);
2274     target = bci + (jint)Bytes::get_Java_u4(aligned_bcp+(3+i*delta)*jintSize);
2275     stackmap_table->check_jump_target(
2276       current_frame, target, CHECK_VERIFY(this));
2277   }
2278   NOT_PRODUCT(aligned_bcp = NULL);  // no longer valid at this point
2279 }
2280 
name_in_supers(Symbol * ref_name,InstanceKlass * current)2281 bool ClassVerifier::name_in_supers(
2282     Symbol* ref_name, InstanceKlass* current) {
2283   Klass* super = current->super();
2284   while (super != NULL) {
2285     if (super->name() == ref_name) {
2286       return true;
2287     }
2288     super = super->super();
2289   }
2290   return false;
2291 }
2292 
verify_field_instructions(RawBytecodeStream * bcs,StackMapFrame * current_frame,const constantPoolHandle & cp,bool allow_arrays,TRAPS)2293 void ClassVerifier::verify_field_instructions(RawBytecodeStream* bcs,
2294                                               StackMapFrame* current_frame,
2295                                               const constantPoolHandle& cp,
2296                                               bool allow_arrays,
2297                                               TRAPS) {
2298   u2 index = bcs->get_index_u2();
2299   verify_cp_type(bcs->bci(), index, cp,
2300       1 << JVM_CONSTANT_Fieldref, CHECK_VERIFY(this));
2301 
2302   // Get field name and signature
2303   Symbol* field_name = cp->name_ref_at(index);
2304   Symbol* field_sig = cp->signature_ref_at(index);
2305   bool is_getfield = false;
2306 
2307   // Field signature was checked in ClassFileParser.
2308   assert(SignatureVerifier::is_valid_type_signature(field_sig),
2309          "Invalid field signature");
2310 
2311   // Get referenced class type
2312   VerificationType ref_class_type = cp_ref_index_to_type(
2313     index, cp, CHECK_VERIFY(this));
2314   if (!ref_class_type.is_object() &&
2315     (!allow_arrays || !ref_class_type.is_array())) {
2316     verify_error(ErrorContext::bad_type(bcs->bci(),
2317         TypeOrigin::cp(index, ref_class_type)),
2318         "Expecting reference to class in class %s at constant pool index %d",
2319         _klass->external_name(), index);
2320     return;
2321   }
2322   VerificationType target_class_type = ref_class_type;
2323 
2324   assert(sizeof(VerificationType) == sizeof(uintptr_t),
2325         "buffer type must match VerificationType size");
2326   uintptr_t field_type_buffer[2];
2327   VerificationType* field_type = (VerificationType*)field_type_buffer;
2328   // If we make a VerificationType[2] array directly, the compiler calls
2329   // to the c-runtime library to do the allocation instead of just
2330   // stack allocating it.  Plus it would run constructors.  This shows up
2331   // in performance profiles.
2332 
2333   SignatureStream sig_stream(field_sig, false);
2334   VerificationType stack_object_type;
2335   int n = change_sig_to_verificationType(&sig_stream, field_type);
2336   u2 bci = bcs->bci();
2337   bool is_assignable;
2338   switch (bcs->raw_code()) {
2339     case Bytecodes::_getstatic: {
2340       for (int i = 0; i < n; i++) {
2341         current_frame->push_stack(field_type[i], CHECK_VERIFY(this));
2342       }
2343       break;
2344     }
2345     case Bytecodes::_putstatic: {
2346       for (int i = n - 1; i >= 0; i--) {
2347         current_frame->pop_stack(field_type[i], CHECK_VERIFY(this));
2348       }
2349       break;
2350     }
2351     case Bytecodes::_getfield: {
2352       is_getfield = true;
2353       stack_object_type = current_frame->pop_stack(
2354         target_class_type, CHECK_VERIFY(this));
2355       goto check_protected;
2356     }
2357     case Bytecodes::_putfield: {
2358       for (int i = n - 1; i >= 0; i--) {
2359         current_frame->pop_stack(field_type[i], CHECK_VERIFY(this));
2360       }
2361       stack_object_type = current_frame->pop_stack(CHECK_VERIFY(this));
2362 
2363       // The JVMS 2nd edition allows field initialization before the superclass
2364       // initializer, if the field is defined within the current class.
2365       fieldDescriptor fd;
2366       if (stack_object_type == VerificationType::uninitialized_this_type() &&
2367           target_class_type.equals(current_type()) &&
2368           _klass->find_local_field(field_name, field_sig, &fd)) {
2369         stack_object_type = current_type();
2370       }
2371       is_assignable = target_class_type.is_assignable_from(
2372         stack_object_type, this, false, CHECK_VERIFY(this));
2373       if (!is_assignable) {
2374         verify_error(ErrorContext::bad_type(bci,
2375             current_frame->stack_top_ctx(),
2376             TypeOrigin::cp(index, target_class_type)),
2377             "Bad type on operand stack in putfield");
2378         return;
2379       }
2380     }
2381     check_protected: {
2382       if (_this_type == stack_object_type)
2383         break; // stack_object_type must be assignable to _current_class_type
2384       if (was_recursively_verified()) {
2385         if (is_getfield) {
2386           // Push field type for getfield.
2387           for (int i = 0; i < n; i++) {
2388             current_frame->push_stack(field_type[i], CHECK_VERIFY(this));
2389           }
2390         }
2391         return;
2392       }
2393       Symbol* ref_class_name =
2394         cp->klass_name_at(cp->klass_ref_index_at(index));
2395       if (!name_in_supers(ref_class_name, current_class()))
2396         // stack_object_type must be assignable to _current_class_type since:
2397         // 1. stack_object_type must be assignable to ref_class.
2398         // 2. ref_class must be _current_class or a subclass of it. It can't
2399         //    be a superclass of it. See revised JVMS 5.4.4.
2400         break;
2401 
2402       Klass* ref_class_oop = load_class(ref_class_name, CHECK);
2403       if (is_protected_access(current_class(), ref_class_oop, field_name,
2404                               field_sig, false)) {
2405         // It's protected access, check if stack object is assignable to
2406         // current class.
2407         is_assignable = current_type().is_assignable_from(
2408           stack_object_type, this, true, CHECK_VERIFY(this));
2409         if (!is_assignable) {
2410           verify_error(ErrorContext::bad_type(bci,
2411               current_frame->stack_top_ctx(),
2412               TypeOrigin::implicit(current_type())),
2413               "Bad access to protected data in getfield");
2414           return;
2415         }
2416       }
2417       break;
2418     }
2419     default: ShouldNotReachHere();
2420   }
2421   if (is_getfield) {
2422     // Push field type for getfield after doing protection check.
2423     for (int i = 0; i < n; i++) {
2424       current_frame->push_stack(field_type[i], CHECK_VERIFY(this));
2425     }
2426   }
2427 }
2428 
2429 // Look at the method's handlers.  If the bci is in the handler's try block
2430 // then check if the handler_pc is already on the stack.  If not, push it
2431 // unless the handler has already been scanned.
push_handlers(ExceptionTable * exhandlers,GrowableArray<u4> * handler_list,GrowableArray<u4> * handler_stack,u4 bci)2432 void ClassVerifier::push_handlers(ExceptionTable* exhandlers,
2433                                   GrowableArray<u4>* handler_list,
2434                                   GrowableArray<u4>* handler_stack,
2435                                   u4 bci) {
2436   int exlength = exhandlers->length();
2437   for(int x = 0; x < exlength; x++) {
2438     if (bci >= exhandlers->start_pc(x) && bci < exhandlers->end_pc(x)) {
2439       u4 exhandler_pc = exhandlers->handler_pc(x);
2440       if (!handler_list->contains(exhandler_pc)) {
2441         handler_stack->append_if_missing(exhandler_pc);
2442         handler_list->append(exhandler_pc);
2443       }
2444     }
2445   }
2446 }
2447 
2448 // Return TRUE if all code paths starting with start_bc_offset end in
2449 // bytecode athrow or loop.
ends_in_athrow(u4 start_bc_offset)2450 bool ClassVerifier::ends_in_athrow(u4 start_bc_offset) {
2451   ResourceMark rm;
2452   // Create bytecode stream.
2453   RawBytecodeStream bcs(method());
2454   u4 code_length = method()->code_size();
2455   bcs.set_start(start_bc_offset);
2456   u4 target;
2457   // Create stack for storing bytecode start offsets for if* and *switch.
2458   GrowableArray<u4>* bci_stack = new GrowableArray<u4>(30);
2459   // Create stack for handlers for try blocks containing this handler.
2460   GrowableArray<u4>* handler_stack = new GrowableArray<u4>(30);
2461   // Create list of handlers that have been pushed onto the handler_stack
2462   // so that handlers embedded inside of their own TRY blocks only get
2463   // scanned once.
2464   GrowableArray<u4>* handler_list = new GrowableArray<u4>(30);
2465   // Create list of visited branch opcodes (goto* and if*).
2466   GrowableArray<u4>* visited_branches = new GrowableArray<u4>(30);
2467   ExceptionTable exhandlers(_method());
2468 
2469   while (true) {
2470     if (bcs.is_last_bytecode()) {
2471       // if no more starting offsets to parse or if at the end of the
2472       // method then return false.
2473       if ((bci_stack->is_empty()) || ((u4)bcs.end_bci() == code_length))
2474         return false;
2475       // Pop a bytecode starting offset and scan from there.
2476       bcs.set_start(bci_stack->pop());
2477     }
2478     Bytecodes::Code opcode = bcs.raw_next();
2479     u4 bci = bcs.bci();
2480 
2481     // If the bytecode is in a TRY block, push its handlers so they
2482     // will get parsed.
2483     push_handlers(&exhandlers, handler_list, handler_stack, bci);
2484 
2485     switch (opcode) {
2486       case Bytecodes::_if_icmpeq:
2487       case Bytecodes::_if_icmpne:
2488       case Bytecodes::_if_icmplt:
2489       case Bytecodes::_if_icmpge:
2490       case Bytecodes::_if_icmpgt:
2491       case Bytecodes::_if_icmple:
2492       case Bytecodes::_ifeq:
2493       case Bytecodes::_ifne:
2494       case Bytecodes::_iflt:
2495       case Bytecodes::_ifge:
2496       case Bytecodes::_ifgt:
2497       case Bytecodes::_ifle:
2498       case Bytecodes::_if_acmpeq:
2499       case Bytecodes::_if_acmpne:
2500       case Bytecodes::_ifnull:
2501       case Bytecodes::_ifnonnull:
2502         target = bcs.dest();
2503         if (visited_branches->contains(bci)) {
2504           if (bci_stack->is_empty()) {
2505             if (handler_stack->is_empty()) {
2506               return true;
2507             } else {
2508               // Parse the catch handlers for try blocks containing athrow.
2509               bcs.set_start(handler_stack->pop());
2510             }
2511           } else {
2512             // Pop a bytecode starting offset and scan from there.
2513             bcs.set_start(bci_stack->pop());
2514           }
2515         } else {
2516           if (target > bci) { // forward branch
2517             if (target >= code_length) return false;
2518             // Push the branch target onto the stack.
2519             bci_stack->push(target);
2520             // then, scan bytecodes starting with next.
2521             bcs.set_start(bcs.next_bci());
2522           } else { // backward branch
2523             // Push bytecode offset following backward branch onto the stack.
2524             bci_stack->push(bcs.next_bci());
2525             // Check bytecodes starting with branch target.
2526             bcs.set_start(target);
2527           }
2528           // Record target so we don't branch here again.
2529           visited_branches->append(bci);
2530         }
2531         break;
2532 
2533       case Bytecodes::_goto:
2534       case Bytecodes::_goto_w:
2535         target = (opcode == Bytecodes::_goto ? bcs.dest() : bcs.dest_w());
2536         if (visited_branches->contains(bci)) {
2537           if (bci_stack->is_empty()) {
2538             if (handler_stack->is_empty()) {
2539               return true;
2540             } else {
2541               // Parse the catch handlers for try blocks containing athrow.
2542               bcs.set_start(handler_stack->pop());
2543             }
2544           } else {
2545             // Been here before, pop new starting offset from stack.
2546             bcs.set_start(bci_stack->pop());
2547           }
2548         } else {
2549           if (target >= code_length) return false;
2550           // Continue scanning from the target onward.
2551           bcs.set_start(target);
2552           // Record target so we don't branch here again.
2553           visited_branches->append(bci);
2554         }
2555         break;
2556 
2557       // Check that all switch alternatives end in 'athrow' bytecodes. Since it
2558       // is  difficult to determine where each switch alternative ends, parse
2559       // each switch alternative until either hit a 'return', 'athrow', or reach
2560       // the end of the method's bytecodes.  This is gross but should be okay
2561       // because:
2562       // 1. tableswitch and lookupswitch byte codes in handlers for ctor explicit
2563       //    constructor invocations should be rare.
2564       // 2. if each switch alternative ends in an athrow then the parsing should be
2565       //    short.  If there is no athrow then it is bogus code, anyway.
2566       case Bytecodes::_lookupswitch:
2567       case Bytecodes::_tableswitch:
2568         {
2569           address aligned_bcp = align_up(bcs.bcp() + 1, jintSize);
2570           u4 default_offset = Bytes::get_Java_u4(aligned_bcp) + bci;
2571           int keys, delta;
2572           if (opcode == Bytecodes::_tableswitch) {
2573             jint low = (jint)Bytes::get_Java_u4(aligned_bcp + jintSize);
2574             jint high = (jint)Bytes::get_Java_u4(aligned_bcp + 2*jintSize);
2575             // This is invalid, but let the regular bytecode verifier
2576             // report this because the user will get a better error message.
2577             if (low > high) return true;
2578             keys = high - low + 1;
2579             delta = 1;
2580           } else {
2581             keys = (int)Bytes::get_Java_u4(aligned_bcp + jintSize);
2582             delta = 2;
2583           }
2584           // Invalid, let the regular bytecode verifier deal with it.
2585           if (keys < 0) return true;
2586 
2587           // Push the offset of the next bytecode onto the stack.
2588           bci_stack->push(bcs.next_bci());
2589 
2590           // Push the switch alternatives onto the stack.
2591           for (int i = 0; i < keys; i++) {
2592             u4 target = bci + (jint)Bytes::get_Java_u4(aligned_bcp+(3+i*delta)*jintSize);
2593             if (target > code_length) return false;
2594             bci_stack->push(target);
2595           }
2596 
2597           // Start bytecode parsing for the switch at the default alternative.
2598           if (default_offset > code_length) return false;
2599           bcs.set_start(default_offset);
2600           break;
2601         }
2602 
2603       case Bytecodes::_return:
2604         return false;
2605 
2606       case Bytecodes::_athrow:
2607         {
2608           if (bci_stack->is_empty()) {
2609             if (handler_stack->is_empty()) {
2610               return true;
2611             } else {
2612               // Parse the catch handlers for try blocks containing athrow.
2613               bcs.set_start(handler_stack->pop());
2614             }
2615           } else {
2616             // Pop a bytecode offset and starting scanning from there.
2617             bcs.set_start(bci_stack->pop());
2618           }
2619         }
2620         break;
2621 
2622       default:
2623         ;
2624     } // end switch
2625   } // end while loop
2626 
2627   return false;
2628 }
2629 
verify_invoke_init(RawBytecodeStream * bcs,u2 ref_class_index,VerificationType ref_class_type,StackMapFrame * current_frame,u4 code_length,bool in_try_block,bool * this_uninit,const constantPoolHandle & cp,StackMapTable * stackmap_table,TRAPS)2630 void ClassVerifier::verify_invoke_init(
2631     RawBytecodeStream* bcs, u2 ref_class_index, VerificationType ref_class_type,
2632     StackMapFrame* current_frame, u4 code_length, bool in_try_block,
2633     bool *this_uninit, const constantPoolHandle& cp, StackMapTable* stackmap_table,
2634     TRAPS) {
2635   u2 bci = bcs->bci();
2636   VerificationType type = current_frame->pop_stack(
2637     VerificationType::reference_check(), CHECK_VERIFY(this));
2638   if (type == VerificationType::uninitialized_this_type()) {
2639     // The method must be an <init> method of this class or its superclass
2640     Klass* superk = current_class()->super();
2641     if (ref_class_type.name() != current_class()->name() &&
2642         ref_class_type.name() != superk->name()) {
2643       verify_error(ErrorContext::bad_type(bci,
2644           TypeOrigin::implicit(ref_class_type),
2645           TypeOrigin::implicit(current_type())),
2646           "Bad <init> method call");
2647       return;
2648     }
2649 
2650     // If this invokespecial call is done from inside of a TRY block then make
2651     // sure that all catch clause paths end in a throw.  Otherwise, this can
2652     // result in returning an incomplete object.
2653     if (in_try_block) {
2654       ExceptionTable exhandlers(_method());
2655       int exlength = exhandlers.length();
2656       for(int i = 0; i < exlength; i++) {
2657         u2 start_pc = exhandlers.start_pc(i);
2658         u2 end_pc = exhandlers.end_pc(i);
2659 
2660         if (bci >= start_pc && bci < end_pc) {
2661           if (!ends_in_athrow(exhandlers.handler_pc(i))) {
2662             verify_error(ErrorContext::bad_code(bci),
2663               "Bad <init> method call from after the start of a try block");
2664             return;
2665           } else if (log_is_enabled(Info, verification)) {
2666             ResourceMark rm(THREAD);
2667             log_info(verification)("Survived call to ends_in_athrow(): %s",
2668                                           current_class()->name()->as_C_string());
2669           }
2670         }
2671       }
2672 
2673       // Check the exception handler target stackmaps with the locals from the
2674       // incoming stackmap (before initialize_object() changes them to outgoing
2675       // state).
2676       if (was_recursively_verified()) return;
2677       verify_exception_handler_targets(bci, true, current_frame,
2678                                        stackmap_table, CHECK_VERIFY(this));
2679     } // in_try_block
2680 
2681     current_frame->initialize_object(type, current_type());
2682     *this_uninit = true;
2683   } else if (type.is_uninitialized()) {
2684     u2 new_offset = type.bci();
2685     address new_bcp = bcs->bcp() - bci + new_offset;
2686     if (new_offset > (code_length - 3) || (*new_bcp) != Bytecodes::_new) {
2687       /* Unreachable?  Stack map parsing ensures valid type and new
2688        * instructions have a valid BCI. */
2689       verify_error(ErrorContext::bad_code(new_offset),
2690                    "Expecting new instruction");
2691       return;
2692     }
2693     u2 new_class_index = Bytes::get_Java_u2(new_bcp + 1);
2694     if (was_recursively_verified()) return;
2695     verify_cp_class_type(bci, new_class_index, cp, CHECK_VERIFY(this));
2696 
2697     // The method must be an <init> method of the indicated class
2698     VerificationType new_class_type = cp_index_to_type(
2699       new_class_index, cp, CHECK_VERIFY(this));
2700     if (!new_class_type.equals(ref_class_type)) {
2701       verify_error(ErrorContext::bad_type(bci,
2702           TypeOrigin::cp(new_class_index, new_class_type),
2703           TypeOrigin::cp(ref_class_index, ref_class_type)),
2704           "Call to wrong <init> method");
2705       return;
2706     }
2707     // According to the VM spec, if the referent class is a superclass of the
2708     // current class, and is in a different runtime package, and the method is
2709     // protected, then the objectref must be the current class or a subclass
2710     // of the current class.
2711     VerificationType objectref_type = new_class_type;
2712     if (name_in_supers(ref_class_type.name(), current_class())) {
2713       Klass* ref_klass = load_class(ref_class_type.name(), CHECK);
2714       if (was_recursively_verified()) return;
2715       Method* m = InstanceKlass::cast(ref_klass)->uncached_lookup_method(
2716         vmSymbols::object_initializer_name(),
2717         cp->signature_ref_at(bcs->get_index_u2()),
2718         Klass::find_overpass);
2719       // Do nothing if method is not found.  Let resolution detect the error.
2720       if (m != NULL) {
2721         InstanceKlass* mh = m->method_holder();
2722         if (m->is_protected() && !mh->is_same_class_package(_klass)) {
2723           bool assignable = current_type().is_assignable_from(
2724             objectref_type, this, true, CHECK_VERIFY(this));
2725           if (!assignable) {
2726             verify_error(ErrorContext::bad_type(bci,
2727                 TypeOrigin::cp(new_class_index, objectref_type),
2728                 TypeOrigin::implicit(current_type())),
2729                 "Bad access to protected <init> method");
2730             return;
2731           }
2732         }
2733       }
2734     }
2735     // Check the exception handler target stackmaps with the locals from the
2736     // incoming stackmap (before initialize_object() changes them to outgoing
2737     // state).
2738     if (in_try_block) {
2739       if (was_recursively_verified()) return;
2740       verify_exception_handler_targets(bci, *this_uninit, current_frame,
2741                                        stackmap_table, CHECK_VERIFY(this));
2742     }
2743     current_frame->initialize_object(type, new_class_type);
2744   } else {
2745     verify_error(ErrorContext::bad_type(bci, current_frame->stack_top_ctx()),
2746         "Bad operand type when invoking <init>");
2747     return;
2748   }
2749 }
2750 
is_same_or_direct_interface(InstanceKlass * klass,VerificationType klass_type,VerificationType ref_class_type)2751 bool ClassVerifier::is_same_or_direct_interface(
2752     InstanceKlass* klass,
2753     VerificationType klass_type,
2754     VerificationType ref_class_type) {
2755   if (ref_class_type.equals(klass_type)) return true;
2756   Array<InstanceKlass*>* local_interfaces = klass->local_interfaces();
2757   if (local_interfaces != NULL) {
2758     for (int x = 0; x < local_interfaces->length(); x++) {
2759       InstanceKlass* k = local_interfaces->at(x);
2760       assert (k != NULL && k->is_interface(), "invalid interface");
2761       if (ref_class_type.equals(VerificationType::reference_type(k->name()))) {
2762         return true;
2763       }
2764     }
2765   }
2766   return false;
2767 }
2768 
verify_invoke_instructions(RawBytecodeStream * bcs,u4 code_length,StackMapFrame * current_frame,bool in_try_block,bool * this_uninit,VerificationType return_type,const constantPoolHandle & cp,StackMapTable * stackmap_table,TRAPS)2769 void ClassVerifier::verify_invoke_instructions(
2770     RawBytecodeStream* bcs, u4 code_length, StackMapFrame* current_frame,
2771     bool in_try_block, bool *this_uninit, VerificationType return_type,
2772     const constantPoolHandle& cp, StackMapTable* stackmap_table, TRAPS) {
2773   // Make sure the constant pool item is the right type
2774   u2 index = bcs->get_index_u2();
2775   Bytecodes::Code opcode = bcs->raw_code();
2776   unsigned int types = 0;
2777   switch (opcode) {
2778     case Bytecodes::_invokeinterface:
2779       types = 1 << JVM_CONSTANT_InterfaceMethodref;
2780       break;
2781     case Bytecodes::_invokedynamic:
2782       types = 1 << JVM_CONSTANT_InvokeDynamic;
2783       break;
2784     case Bytecodes::_invokespecial:
2785     case Bytecodes::_invokestatic:
2786       types = (_klass->major_version() < STATIC_METHOD_IN_INTERFACE_MAJOR_VERSION) ?
2787         (1 << JVM_CONSTANT_Methodref) :
2788         ((1 << JVM_CONSTANT_InterfaceMethodref) | (1 << JVM_CONSTANT_Methodref));
2789       break;
2790     default:
2791       types = 1 << JVM_CONSTANT_Methodref;
2792   }
2793   verify_cp_type(bcs->bci(), index, cp, types, CHECK_VERIFY(this));
2794 
2795   // Get method name and signature
2796   Symbol* method_name = cp->name_ref_at(index);
2797   Symbol* method_sig = cp->signature_ref_at(index);
2798 
2799   // Method signature was checked in ClassFileParser.
2800   assert(SignatureVerifier::is_valid_method_signature(method_sig),
2801          "Invalid method signature");
2802 
2803   // Get referenced class type
2804   VerificationType ref_class_type;
2805   if (opcode == Bytecodes::_invokedynamic) {
2806     if (_klass->major_version() < Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {
2807       class_format_error(
2808         "invokedynamic instructions not supported by this class file version (%d), class %s",
2809         _klass->major_version(), _klass->external_name());
2810       return;
2811     }
2812   } else {
2813     ref_class_type = cp_ref_index_to_type(index, cp, CHECK_VERIFY(this));
2814   }
2815 
2816   assert(sizeof(VerificationType) == sizeof(uintptr_t),
2817         "buffer type must match VerificationType size");
2818 
2819   // Get the UTF8 index for this signature.
2820   int sig_index = cp->signature_ref_index_at(cp->name_and_type_ref_index_at(index));
2821 
2822   // Get the signature's verification types.
2823   sig_as_verification_types* mth_sig_verif_types;
2824   sig_as_verification_types** mth_sig_verif_types_ptr = method_signatures_table()->get(sig_index);
2825   if (mth_sig_verif_types_ptr != NULL) {
2826     // Found the entry for the signature's verification types in the hash table.
2827     mth_sig_verif_types = *mth_sig_verif_types_ptr;
2828     assert(mth_sig_verif_types != NULL, "Unexpected NULL sig_as_verification_types value");
2829   } else {
2830     // Not found, add the entry to the table.
2831     GrowableArray<VerificationType>* verif_types = new GrowableArray<VerificationType>(10);
2832     mth_sig_verif_types = new sig_as_verification_types(verif_types);
2833     create_method_sig_entry(mth_sig_verif_types, sig_index, CHECK_VERIFY(this));
2834   }
2835 
2836   // Get the number of arguments for this signature.
2837   int nargs = mth_sig_verif_types->num_args();
2838 
2839   // Check instruction operands
2840   u2 bci = bcs->bci();
2841   if (opcode == Bytecodes::_invokeinterface) {
2842     address bcp = bcs->bcp();
2843     // 4905268: count operand in invokeinterface should be nargs+1, not nargs.
2844     // JSR202 spec: The count operand of an invokeinterface instruction is valid if it is
2845     // the difference between the size of the operand stack before and after the instruction
2846     // executes.
2847     if (*(bcp+3) != (nargs+1)) {
2848       verify_error(ErrorContext::bad_code(bci),
2849           "Inconsistent args count operand in invokeinterface");
2850       return;
2851     }
2852     if (*(bcp+4) != 0) {
2853       verify_error(ErrorContext::bad_code(bci),
2854           "Fourth operand byte of invokeinterface must be zero");
2855       return;
2856     }
2857   }
2858 
2859   if (opcode == Bytecodes::_invokedynamic) {
2860     address bcp = bcs->bcp();
2861     if (*(bcp+3) != 0 || *(bcp+4) != 0) {
2862       verify_error(ErrorContext::bad_code(bci),
2863           "Third and fourth operand bytes of invokedynamic must be zero");
2864       return;
2865     }
2866   }
2867 
2868   if (method_name->char_at(0) == '<') {
2869     // Make sure <init> can only be invoked by invokespecial
2870     if (opcode != Bytecodes::_invokespecial ||
2871         method_name != vmSymbols::object_initializer_name()) {
2872       verify_error(ErrorContext::bad_code(bci),
2873           "Illegal call to internal method");
2874       return;
2875     }
2876   } else if (opcode == Bytecodes::_invokespecial
2877              && !is_same_or_direct_interface(current_class(), current_type(), ref_class_type)
2878              && !ref_class_type.equals(VerificationType::reference_type(
2879                   current_class()->super()->name()))) {
2880     bool subtype = false;
2881     bool have_imr_indirect = cp->tag_at(index).value() == JVM_CONSTANT_InterfaceMethodref;
2882     if (!current_class()->is_unsafe_anonymous()) {
2883       subtype = ref_class_type.is_assignable_from(
2884                  current_type(), this, false, CHECK_VERIFY(this));
2885     } else {
2886       VerificationType unsafe_anonymous_host_type =
2887                         VerificationType::reference_type(current_class()->unsafe_anonymous_host()->name());
2888       subtype = ref_class_type.is_assignable_from(unsafe_anonymous_host_type, this, false, CHECK_VERIFY(this));
2889 
2890       // If invokespecial of IMR, need to recheck for same or
2891       // direct interface relative to the host class
2892       have_imr_indirect = (have_imr_indirect &&
2893                            !is_same_or_direct_interface(
2894                              current_class()->unsafe_anonymous_host(),
2895                              unsafe_anonymous_host_type, ref_class_type));
2896     }
2897     if (!subtype) {
2898       verify_error(ErrorContext::bad_code(bci),
2899           "Bad invokespecial instruction: "
2900           "current class isn't assignable to reference class.");
2901        return;
2902     } else if (have_imr_indirect) {
2903       verify_error(ErrorContext::bad_code(bci),
2904           "Bad invokespecial instruction: "
2905           "interface method reference is in an indirect superinterface.");
2906       return;
2907     }
2908 
2909   }
2910 
2911   // Get the verification types for the method's arguments.
2912   GrowableArray<VerificationType>* sig_verif_types = mth_sig_verif_types->sig_verif_types();
2913   assert(sig_verif_types != NULL, "Missing signature's array of verification types");
2914   // Match method descriptor with operand stack
2915   // The arguments are on the stack in descending order.
2916   for (int i = nargs - 1; i >= 0; i--) { // Run backwards
2917     current_frame->pop_stack(sig_verif_types->at(i), CHECK_VERIFY(this));
2918   }
2919 
2920   // Check objectref on operand stack
2921   if (opcode != Bytecodes::_invokestatic &&
2922       opcode != Bytecodes::_invokedynamic) {
2923     if (method_name == vmSymbols::object_initializer_name()) {  // <init> method
2924       verify_invoke_init(bcs, index, ref_class_type, current_frame,
2925         code_length, in_try_block, this_uninit, cp, stackmap_table,
2926         CHECK_VERIFY(this));
2927       if (was_recursively_verified()) return;
2928     } else {   // other methods
2929       // Ensures that target class is assignable to method class.
2930       if (opcode == Bytecodes::_invokespecial) {
2931         if (!current_class()->is_unsafe_anonymous()) {
2932           current_frame->pop_stack(current_type(), CHECK_VERIFY(this));
2933         } else {
2934           // anonymous class invokespecial calls: check if the
2935           // objectref is a subtype of the unsafe_anonymous_host of the current class
2936           // to allow an anonymous class to reference methods in the unsafe_anonymous_host
2937           VerificationType top = current_frame->pop_stack(CHECK_VERIFY(this));
2938           VerificationType hosttype =
2939             VerificationType::reference_type(current_class()->unsafe_anonymous_host()->name());
2940           bool subtype = hosttype.is_assignable_from(top, this, false, CHECK_VERIFY(this));
2941           if (!subtype) {
2942             verify_error( ErrorContext::bad_type(current_frame->offset(),
2943               current_frame->stack_top_ctx(),
2944               TypeOrigin::implicit(top)),
2945               "Bad type on operand stack");
2946             return;
2947           }
2948         }
2949       } else if (opcode == Bytecodes::_invokevirtual) {
2950         VerificationType stack_object_type =
2951           current_frame->pop_stack(ref_class_type, CHECK_VERIFY(this));
2952         if (current_type() != stack_object_type) {
2953           if (was_recursively_verified()) return;
2954           assert(cp->cache() == NULL, "not rewritten yet");
2955           Symbol* ref_class_name =
2956             cp->klass_name_at(cp->klass_ref_index_at(index));
2957           // See the comments in verify_field_instructions() for
2958           // the rationale behind this.
2959           if (name_in_supers(ref_class_name, current_class())) {
2960             Klass* ref_class = load_class(ref_class_name, CHECK);
2961             if (is_protected_access(
2962                   _klass, ref_class, method_name, method_sig, true)) {
2963               // It's protected access, check if stack object is
2964               // assignable to current class.
2965               bool is_assignable = current_type().is_assignable_from(
2966                 stack_object_type, this, true, CHECK_VERIFY(this));
2967               if (!is_assignable) {
2968                 if (ref_class_type.name() == vmSymbols::java_lang_Object()
2969                     && stack_object_type.is_array()
2970                     && method_name == vmSymbols::clone_name()) {
2971                   // Special case: arrays pretend to implement public Object
2972                   // clone().
2973                 } else {
2974                   verify_error(ErrorContext::bad_type(bci,
2975                       current_frame->stack_top_ctx(),
2976                       TypeOrigin::implicit(current_type())),
2977                       "Bad access to protected data in invokevirtual");
2978                   return;
2979                 }
2980               }
2981             }
2982           }
2983         }
2984       } else {
2985         assert(opcode == Bytecodes::_invokeinterface, "Unexpected opcode encountered");
2986         current_frame->pop_stack(ref_class_type, CHECK_VERIFY(this));
2987       }
2988     }
2989   }
2990   // Push the result type.
2991   int sig_verif_types_len = sig_verif_types->length();
2992   if (sig_verif_types_len > nargs) {  // There's a return type
2993     if (method_name == vmSymbols::object_initializer_name()) {
2994       // <init> method must have a void return type
2995       /* Unreachable?  Class file parser verifies that methods with '<' have
2996        * void return */
2997       verify_error(ErrorContext::bad_code(bci),
2998           "Return type must be void in <init> method");
2999       return;
3000     }
3001 
3002     assert(sig_verif_types_len <= nargs + 2,
3003            "Signature verification types array return type is bogus");
3004     for (int i = nargs; i < sig_verif_types_len; i++) {
3005       assert(i == nargs || sig_verif_types->at(i).is_long2() ||
3006              sig_verif_types->at(i).is_double2(), "Unexpected return verificationType");
3007       current_frame->push_stack(sig_verif_types->at(i), CHECK_VERIFY(this));
3008     }
3009   }
3010 }
3011 
get_newarray_type(u2 index,u2 bci,TRAPS)3012 VerificationType ClassVerifier::get_newarray_type(
3013     u2 index, u2 bci, TRAPS) {
3014   const char* from_bt[] = {
3015     NULL, NULL, NULL, NULL, "[Z", "[C", "[F", "[D", "[B", "[S", "[I", "[J",
3016   };
3017   if (index < T_BOOLEAN || index > T_LONG) {
3018     verify_error(ErrorContext::bad_code(bci), "Illegal newarray instruction");
3019     return VerificationType::bogus_type();
3020   }
3021 
3022   // from_bt[index] contains the array signature which has a length of 2
3023   Symbol* sig = create_temporary_symbol(from_bt[index], 2);
3024   return VerificationType::reference_type(sig);
3025 }
3026 
verify_anewarray(u2 bci,u2 index,const constantPoolHandle & cp,StackMapFrame * current_frame,TRAPS)3027 void ClassVerifier::verify_anewarray(
3028     u2 bci, u2 index, const constantPoolHandle& cp,
3029     StackMapFrame* current_frame, TRAPS) {
3030   verify_cp_class_type(bci, index, cp, CHECK_VERIFY(this));
3031   current_frame->pop_stack(
3032     VerificationType::integer_type(), CHECK_VERIFY(this));
3033 
3034   if (was_recursively_verified()) return;
3035   VerificationType component_type =
3036     cp_index_to_type(index, cp, CHECK_VERIFY(this));
3037   int length;
3038   char* arr_sig_str;
3039   if (component_type.is_array()) {     // it's an array
3040     const char* component_name = component_type.name()->as_utf8();
3041     // Check for more than MAX_ARRAY_DIMENSIONS
3042     length = (int)strlen(component_name);
3043     if (length > MAX_ARRAY_DIMENSIONS &&
3044         component_name[MAX_ARRAY_DIMENSIONS - 1] == '[') {
3045       verify_error(ErrorContext::bad_code(bci),
3046         "Illegal anewarray instruction, array has more than 255 dimensions");
3047     }
3048     // add one dimension to component
3049     length++;
3050     arr_sig_str = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, length + 1);
3051     int n = os::snprintf(arr_sig_str, length + 1, "[%s", component_name);
3052     assert(n == length, "Unexpected number of characters in string");
3053   } else {         // it's an object or interface
3054     const char* component_name = component_type.name()->as_utf8();
3055     // add one dimension to component with 'L' prepended and ';' postpended.
3056     length = (int)strlen(component_name) + 3;
3057     arr_sig_str = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, length + 1);
3058     int n = os::snprintf(arr_sig_str, length + 1, "[L%s;", component_name);
3059     assert(n == length, "Unexpected number of characters in string");
3060   }
3061   Symbol* arr_sig = create_temporary_symbol(arr_sig_str, length);
3062   VerificationType new_array_type = VerificationType::reference_type(arr_sig);
3063   current_frame->push_stack(new_array_type, CHECK_VERIFY(this));
3064 }
3065 
verify_iload(u2 index,StackMapFrame * current_frame,TRAPS)3066 void ClassVerifier::verify_iload(u2 index, StackMapFrame* current_frame, TRAPS) {
3067   current_frame->get_local(
3068     index, VerificationType::integer_type(), CHECK_VERIFY(this));
3069   current_frame->push_stack(
3070     VerificationType::integer_type(), CHECK_VERIFY(this));
3071 }
3072 
verify_lload(u2 index,StackMapFrame * current_frame,TRAPS)3073 void ClassVerifier::verify_lload(u2 index, StackMapFrame* current_frame, TRAPS) {
3074   current_frame->get_local_2(
3075     index, VerificationType::long_type(),
3076     VerificationType::long2_type(), CHECK_VERIFY(this));
3077   current_frame->push_stack_2(
3078     VerificationType::long_type(),
3079     VerificationType::long2_type(), CHECK_VERIFY(this));
3080 }
3081 
verify_fload(u2 index,StackMapFrame * current_frame,TRAPS)3082 void ClassVerifier::verify_fload(u2 index, StackMapFrame* current_frame, TRAPS) {
3083   current_frame->get_local(
3084     index, VerificationType::float_type(), CHECK_VERIFY(this));
3085   current_frame->push_stack(
3086     VerificationType::float_type(), CHECK_VERIFY(this));
3087 }
3088 
verify_dload(u2 index,StackMapFrame * current_frame,TRAPS)3089 void ClassVerifier::verify_dload(u2 index, StackMapFrame* current_frame, TRAPS) {
3090   current_frame->get_local_2(
3091     index, VerificationType::double_type(),
3092     VerificationType::double2_type(), CHECK_VERIFY(this));
3093   current_frame->push_stack_2(
3094     VerificationType::double_type(),
3095     VerificationType::double2_type(), CHECK_VERIFY(this));
3096 }
3097 
verify_aload(u2 index,StackMapFrame * current_frame,TRAPS)3098 void ClassVerifier::verify_aload(u2 index, StackMapFrame* current_frame, TRAPS) {
3099   VerificationType type = current_frame->get_local(
3100     index, VerificationType::reference_check(), CHECK_VERIFY(this));
3101   current_frame->push_stack(type, CHECK_VERIFY(this));
3102 }
3103 
verify_istore(u2 index,StackMapFrame * current_frame,TRAPS)3104 void ClassVerifier::verify_istore(u2 index, StackMapFrame* current_frame, TRAPS) {
3105   current_frame->pop_stack(
3106     VerificationType::integer_type(), CHECK_VERIFY(this));
3107   current_frame->set_local(
3108     index, VerificationType::integer_type(), CHECK_VERIFY(this));
3109 }
3110 
verify_lstore(u2 index,StackMapFrame * current_frame,TRAPS)3111 void ClassVerifier::verify_lstore(u2 index, StackMapFrame* current_frame, TRAPS) {
3112   current_frame->pop_stack_2(
3113     VerificationType::long2_type(),
3114     VerificationType::long_type(), CHECK_VERIFY(this));
3115   current_frame->set_local_2(
3116     index, VerificationType::long_type(),
3117     VerificationType::long2_type(), CHECK_VERIFY(this));
3118 }
3119 
verify_fstore(u2 index,StackMapFrame * current_frame,TRAPS)3120 void ClassVerifier::verify_fstore(u2 index, StackMapFrame* current_frame, TRAPS) {
3121   current_frame->pop_stack(VerificationType::float_type(), CHECK_VERIFY(this));
3122   current_frame->set_local(
3123     index, VerificationType::float_type(), CHECK_VERIFY(this));
3124 }
3125 
verify_dstore(u2 index,StackMapFrame * current_frame,TRAPS)3126 void ClassVerifier::verify_dstore(u2 index, StackMapFrame* current_frame, TRAPS) {
3127   current_frame->pop_stack_2(
3128     VerificationType::double2_type(),
3129     VerificationType::double_type(), CHECK_VERIFY(this));
3130   current_frame->set_local_2(
3131     index, VerificationType::double_type(),
3132     VerificationType::double2_type(), CHECK_VERIFY(this));
3133 }
3134 
verify_astore(u2 index,StackMapFrame * current_frame,TRAPS)3135 void ClassVerifier::verify_astore(u2 index, StackMapFrame* current_frame, TRAPS) {
3136   VerificationType type = current_frame->pop_stack(
3137     VerificationType::reference_check(), CHECK_VERIFY(this));
3138   current_frame->set_local(index, type, CHECK_VERIFY(this));
3139 }
3140 
verify_iinc(u2 index,StackMapFrame * current_frame,TRAPS)3141 void ClassVerifier::verify_iinc(u2 index, StackMapFrame* current_frame, TRAPS) {
3142   VerificationType type = current_frame->get_local(
3143     index, VerificationType::integer_type(), CHECK_VERIFY(this));
3144   current_frame->set_local(index, type, CHECK_VERIFY(this));
3145 }
3146 
verify_return_value(VerificationType return_type,VerificationType type,u2 bci,StackMapFrame * current_frame,TRAPS)3147 void ClassVerifier::verify_return_value(
3148     VerificationType return_type, VerificationType type, u2 bci,
3149     StackMapFrame* current_frame, TRAPS) {
3150   if (return_type == VerificationType::bogus_type()) {
3151     verify_error(ErrorContext::bad_type(bci,
3152         current_frame->stack_top_ctx(), TypeOrigin::signature(return_type)),
3153         "Method expects a return value");
3154     return;
3155   }
3156   bool match = return_type.is_assignable_from(type, this, false, CHECK_VERIFY(this));
3157   if (!match) {
3158     verify_error(ErrorContext::bad_type(bci,
3159         current_frame->stack_top_ctx(), TypeOrigin::signature(return_type)),
3160         "Bad return type");
3161     return;
3162   }
3163 }
3164 
3165 // The verifier creates symbols which are substrings of Symbols.
3166 // These are stored in the verifier until the end of verification so that
3167 // they can be reference counted.
create_temporary_symbol(const Symbol * s,int begin,int end)3168 Symbol* ClassVerifier::create_temporary_symbol(const Symbol *s, int begin,
3169                                                int end) {
3170   const char* name = (const char*)s->base() + begin;
3171   int length = end - begin;
3172   return create_temporary_symbol(name, length);
3173 }
3174 
create_temporary_symbol(const char * name,int length)3175 Symbol* ClassVerifier::create_temporary_symbol(const char *name, int length) {
3176   // Quick deduplication check
3177   if (_previous_symbol != NULL && _previous_symbol->equals(name, length)) {
3178     return _previous_symbol;
3179   }
3180   Symbol* sym = SymbolTable::new_symbol(name, length);
3181   if (!sym->is_permanent()) {
3182     if (_symbols == NULL) {
3183       _symbols = new GrowableArray<Symbol*>(50, 0, NULL);
3184     }
3185     _symbols->push(sym);
3186   }
3187   _previous_symbol = sym;
3188   return sym;
3189 }
3190