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