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