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