method_verifier.cc revision 77cd4d677c682c194b8325b209cb76720be4046a
1/* 2 * Copyright (C) 2011 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#include "method_verifier-inl.h" 18 19#include <iostream> 20 21#include "base/logging.h" 22#include "base/mutex-inl.h" 23#include "class_linker.h" 24#include "compiler_callbacks.h" 25#include "dex_file-inl.h" 26#include "dex_instruction-inl.h" 27#include "dex_instruction_visitor.h" 28#include "gc/accounting/card_table-inl.h" 29#include "indenter.h" 30#include "intern_table.h" 31#include "leb128.h" 32#include "mirror/art_field-inl.h" 33#include "mirror/art_method-inl.h" 34#include "mirror/class.h" 35#include "mirror/class-inl.h" 36#include "mirror/dex_cache-inl.h" 37#include "mirror/object-inl.h" 38#include "mirror/object_array-inl.h" 39#include "object_utils.h" 40#include "register_line-inl.h" 41#include "runtime.h" 42#include "scoped_thread_state_change.h" 43#include "handle_scope-inl.h" 44#include "verifier/dex_gc_map.h" 45 46namespace art { 47namespace verifier { 48 49static const bool gDebugVerify = false; 50// TODO: Add a constant to method_verifier to turn on verbose logging? 51 52void PcToRegisterLineTable::Init(RegisterTrackingMode mode, InstructionFlags* flags, 53 uint32_t insns_size, uint16_t registers_size, 54 MethodVerifier* verifier) { 55 DCHECK_GT(insns_size, 0U); 56 register_lines_.reset(new RegisterLine*[insns_size]()); 57 size_ = insns_size; 58 for (uint32_t i = 0; i < insns_size; i++) { 59 bool interesting = false; 60 switch (mode) { 61 case kTrackRegsAll: 62 interesting = flags[i].IsOpcode(); 63 break; 64 case kTrackCompilerInterestPoints: 65 interesting = flags[i].IsCompileTimeInfoPoint() || flags[i].IsBranchTarget(); 66 break; 67 case kTrackRegsBranches: 68 interesting = flags[i].IsBranchTarget(); 69 break; 70 default: 71 break; 72 } 73 if (interesting) { 74 register_lines_[i] = RegisterLine::Create(registers_size, verifier); 75 } 76 } 77} 78 79PcToRegisterLineTable::~PcToRegisterLineTable() { 80 for (size_t i = 0; i < size_; i++) { 81 delete register_lines_[i]; 82 if (kIsDebugBuild) { 83 register_lines_[i] = nullptr; 84 } 85 } 86} 87 88MethodVerifier::FailureKind MethodVerifier::VerifyClass(mirror::Class* klass, 89 bool allow_soft_failures, 90 std::string* error) { 91 if (klass->IsVerified()) { 92 return kNoFailure; 93 } 94 bool early_failure = false; 95 std::string failure_message; 96 const DexFile& dex_file = klass->GetDexFile(); 97 const DexFile::ClassDef* class_def = klass->GetClassDef(); 98 mirror::Class* super = klass->GetSuperClass(); 99 if (super == NULL && "Ljava/lang/Object;" != klass->GetDescriptor()) { 100 early_failure = true; 101 failure_message = " that has no super class"; 102 } else if (super != NULL && super->IsFinal()) { 103 early_failure = true; 104 failure_message = " that attempts to sub-class final class " + PrettyDescriptor(super); 105 } else if (class_def == NULL) { 106 early_failure = true; 107 failure_message = " that isn't present in dex file " + dex_file.GetLocation(); 108 } 109 if (early_failure) { 110 *error = "Verifier rejected class " + PrettyDescriptor(klass) + failure_message; 111 if (Runtime::Current()->IsCompiler()) { 112 ClassReference ref(&dex_file, klass->GetDexClassDefIndex()); 113 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref); 114 } 115 return kHardFailure; 116 } 117 StackHandleScope<2> hs(Thread::Current()); 118 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache())); 119 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader())); 120 return VerifyClass(&dex_file, dex_cache, class_loader, class_def, allow_soft_failures, error); 121} 122 123MethodVerifier::FailureKind MethodVerifier::VerifyClass(const DexFile* dex_file, 124 Handle<mirror::DexCache> dex_cache, 125 Handle<mirror::ClassLoader> class_loader, 126 const DexFile::ClassDef* class_def, 127 bool allow_soft_failures, 128 std::string* error) { 129 DCHECK(class_def != nullptr); 130 const byte* class_data = dex_file->GetClassData(*class_def); 131 if (class_data == NULL) { 132 // empty class, probably a marker interface 133 return kNoFailure; 134 } 135 ClassDataItemIterator it(*dex_file, class_data); 136 while (it.HasNextStaticField() || it.HasNextInstanceField()) { 137 it.Next(); 138 } 139 size_t error_count = 0; 140 bool hard_fail = false; 141 ClassLinker* linker = Runtime::Current()->GetClassLinker(); 142 int64_t previous_direct_method_idx = -1; 143 while (it.HasNextDirectMethod()) { 144 uint32_t method_idx = it.GetMemberIndex(); 145 if (method_idx == previous_direct_method_idx) { 146 // smali can create dex files with two encoded_methods sharing the same method_idx 147 // http://code.google.com/p/smali/issues/detail?id=119 148 it.Next(); 149 continue; 150 } 151 previous_direct_method_idx = method_idx; 152 InvokeType type = it.GetMethodInvokeType(*class_def); 153 mirror::ArtMethod* method = 154 linker->ResolveMethod(*dex_file, method_idx, dex_cache, class_loader, 155 NullHandle<mirror::ArtMethod>(), type); 156 if (method == NULL) { 157 DCHECK(Thread::Current()->IsExceptionPending()); 158 // We couldn't resolve the method, but continue regardless. 159 Thread::Current()->ClearException(); 160 } 161 MethodVerifier::FailureKind result = VerifyMethod(method_idx, 162 dex_file, 163 dex_cache, 164 class_loader, 165 class_def, 166 it.GetMethodCodeItem(), 167 method, 168 it.GetMemberAccessFlags(), 169 allow_soft_failures, 170 false); 171 if (result != kNoFailure) { 172 if (result == kHardFailure) { 173 hard_fail = true; 174 if (error_count > 0) { 175 *error += "\n"; 176 } 177 *error = "Verifier rejected class "; 178 *error += PrettyDescriptor(dex_file->GetClassDescriptor(*class_def)); 179 *error += " due to bad method "; 180 *error += PrettyMethod(method_idx, *dex_file); 181 } 182 ++error_count; 183 } 184 it.Next(); 185 } 186 int64_t previous_virtual_method_idx = -1; 187 while (it.HasNextVirtualMethod()) { 188 uint32_t method_idx = it.GetMemberIndex(); 189 if (method_idx == previous_virtual_method_idx) { 190 // smali can create dex files with two encoded_methods sharing the same method_idx 191 // http://code.google.com/p/smali/issues/detail?id=119 192 it.Next(); 193 continue; 194 } 195 previous_virtual_method_idx = method_idx; 196 InvokeType type = it.GetMethodInvokeType(*class_def); 197 mirror::ArtMethod* method = 198 linker->ResolveMethod(*dex_file, method_idx, dex_cache, class_loader, 199 NullHandle<mirror::ArtMethod>(), type); 200 if (method == NULL) { 201 DCHECK(Thread::Current()->IsExceptionPending()); 202 // We couldn't resolve the method, but continue regardless. 203 Thread::Current()->ClearException(); 204 } 205 MethodVerifier::FailureKind result = VerifyMethod(method_idx, 206 dex_file, 207 dex_cache, 208 class_loader, 209 class_def, 210 it.GetMethodCodeItem(), 211 method, 212 it.GetMemberAccessFlags(), 213 allow_soft_failures, 214 false); 215 if (result != kNoFailure) { 216 if (result == kHardFailure) { 217 hard_fail = true; 218 if (error_count > 0) { 219 *error += "\n"; 220 } 221 *error = "Verifier rejected class "; 222 *error += PrettyDescriptor(dex_file->GetClassDescriptor(*class_def)); 223 *error += " due to bad method "; 224 *error += PrettyMethod(method_idx, *dex_file); 225 } 226 ++error_count; 227 } 228 it.Next(); 229 } 230 if (error_count == 0) { 231 return kNoFailure; 232 } else { 233 return hard_fail ? kHardFailure : kSoftFailure; 234 } 235} 236 237MethodVerifier::FailureKind MethodVerifier::VerifyMethod(uint32_t method_idx, 238 const DexFile* dex_file, 239 Handle<mirror::DexCache> dex_cache, 240 Handle<mirror::ClassLoader> class_loader, 241 const DexFile::ClassDef* class_def, 242 const DexFile::CodeItem* code_item, 243 mirror::ArtMethod* method, 244 uint32_t method_access_flags, 245 bool allow_soft_failures, 246 bool need_precise_constants) { 247 MethodVerifier::FailureKind result = kNoFailure; 248 uint64_t start_ns = NanoTime(); 249 250 MethodVerifier verifier(dex_file, &dex_cache, &class_loader, class_def, code_item, 251 method_idx, method, method_access_flags, true, allow_soft_failures, 252 need_precise_constants); 253 if (verifier.Verify()) { 254 // Verification completed, however failures may be pending that didn't cause the verification 255 // to hard fail. 256 CHECK(!verifier.have_pending_hard_failure_); 257 if (verifier.failures_.size() != 0) { 258 if (VLOG_IS_ON(verifier)) { 259 verifier.DumpFailures(VLOG_STREAM(verifier) << "Soft verification failures in " 260 << PrettyMethod(method_idx, *dex_file) << "\n"); 261 } 262 result = kSoftFailure; 263 } 264 } else { 265 // Bad method data. 266 CHECK_NE(verifier.failures_.size(), 0U); 267 CHECK(verifier.have_pending_hard_failure_); 268 verifier.DumpFailures(LOG(INFO) << "Verification error in " 269 << PrettyMethod(method_idx, *dex_file) << "\n"); 270 if (gDebugVerify) { 271 std::cout << "\n" << verifier.info_messages_.str(); 272 verifier.Dump(std::cout); 273 } 274 result = kHardFailure; 275 } 276 uint64_t duration_ns = NanoTime() - start_ns; 277 if (duration_ns > MsToNs(100) && !kIsDebugBuild) { 278 LOG(WARNING) << "Verification of " << PrettyMethod(method_idx, *dex_file) 279 << " took " << PrettyDuration(duration_ns); 280 } 281 return result; 282} 283 284void MethodVerifier::VerifyMethodAndDump(std::ostream& os, uint32_t dex_method_idx, 285 const DexFile* dex_file, 286 Handle<mirror::DexCache> dex_cache, 287 Handle<mirror::ClassLoader> class_loader, 288 const DexFile::ClassDef* class_def, 289 const DexFile::CodeItem* code_item, 290 mirror::ArtMethod* method, 291 uint32_t method_access_flags) { 292 MethodVerifier verifier(dex_file, &dex_cache, &class_loader, class_def, code_item, 293 dex_method_idx, method, method_access_flags, true, true, true); 294 verifier.Verify(); 295 verifier.DumpFailures(os); 296 os << verifier.info_messages_.str(); 297 verifier.Dump(os); 298} 299 300MethodVerifier::MethodVerifier(const DexFile* dex_file, Handle<mirror::DexCache>* dex_cache, 301 Handle<mirror::ClassLoader>* class_loader, 302 const DexFile::ClassDef* class_def, 303 const DexFile::CodeItem* code_item, uint32_t dex_method_idx, 304 mirror::ArtMethod* method, uint32_t method_access_flags, 305 bool can_load_classes, bool allow_soft_failures, 306 bool need_precise_constants) 307 : reg_types_(can_load_classes), 308 work_insn_idx_(-1), 309 dex_method_idx_(dex_method_idx), 310 mirror_method_(method), 311 method_access_flags_(method_access_flags), 312 return_type_(nullptr), 313 dex_file_(dex_file), 314 dex_cache_(dex_cache), 315 class_loader_(class_loader), 316 class_def_(class_def), 317 code_item_(code_item), 318 declaring_class_(NULL), 319 interesting_dex_pc_(-1), 320 monitor_enter_dex_pcs_(nullptr), 321 have_pending_hard_failure_(false), 322 have_pending_runtime_throw_failure_(false), 323 new_instance_count_(0), 324 monitor_enter_count_(0), 325 can_load_classes_(can_load_classes), 326 allow_soft_failures_(allow_soft_failures), 327 need_precise_constants_(need_precise_constants), 328 has_check_casts_(false), 329 has_virtual_or_interface_invokes_(false) { 330 Runtime::Current()->AddMethodVerifier(this); 331 DCHECK(class_def != nullptr); 332} 333 334MethodVerifier::~MethodVerifier() { 335 Runtime::Current()->RemoveMethodVerifier(this); 336 STLDeleteElements(&failure_messages_); 337} 338 339void MethodVerifier::FindLocksAtDexPc(mirror::ArtMethod* m, uint32_t dex_pc, 340 std::vector<uint32_t>* monitor_enter_dex_pcs) { 341 StackHandleScope<2> hs(Thread::Current()); 342 Handle<mirror::DexCache> dex_cache(hs.NewHandle(m->GetDexCache())); 343 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(m->GetClassLoader())); 344 MethodVerifier verifier(m->GetDexFile(), &dex_cache, &class_loader, &m->GetClassDef(), 345 m->GetCodeItem(), m->GetDexMethodIndex(), m, m->GetAccessFlags(), false, 346 true, false); 347 verifier.interesting_dex_pc_ = dex_pc; 348 verifier.monitor_enter_dex_pcs_ = monitor_enter_dex_pcs; 349 verifier.FindLocksAtDexPc(); 350} 351 352void MethodVerifier::FindLocksAtDexPc() { 353 CHECK(monitor_enter_dex_pcs_ != NULL); 354 CHECK(code_item_ != NULL); // This only makes sense for methods with code. 355 356 // Strictly speaking, we ought to be able to get away with doing a subset of the full method 357 // verification. In practice, the phase we want relies on data structures set up by all the 358 // earlier passes, so we just run the full method verification and bail out early when we've 359 // got what we wanted. 360 Verify(); 361} 362 363mirror::ArtField* MethodVerifier::FindAccessedFieldAtDexPc(mirror::ArtMethod* m, 364 uint32_t dex_pc) { 365 StackHandleScope<2> hs(Thread::Current()); 366 Handle<mirror::DexCache> dex_cache(hs.NewHandle(m->GetDexCache())); 367 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(m->GetClassLoader())); 368 MethodVerifier verifier(m->GetDexFile(), &dex_cache, &class_loader, &m->GetClassDef(), 369 m->GetCodeItem(), m->GetDexMethodIndex(), m, m->GetAccessFlags(), true, 370 true, false); 371 return verifier.FindAccessedFieldAtDexPc(dex_pc); 372} 373 374mirror::ArtField* MethodVerifier::FindAccessedFieldAtDexPc(uint32_t dex_pc) { 375 CHECK(code_item_ != NULL); // This only makes sense for methods with code. 376 377 // Strictly speaking, we ought to be able to get away with doing a subset of the full method 378 // verification. In practice, the phase we want relies on data structures set up by all the 379 // earlier passes, so we just run the full method verification and bail out early when we've 380 // got what we wanted. 381 bool success = Verify(); 382 if (!success) { 383 return nullptr; 384 } 385 RegisterLine* register_line = reg_table_.GetLine(dex_pc); 386 if (register_line == NULL) { 387 return nullptr; 388 } 389 const Instruction* inst = Instruction::At(code_item_->insns_ + dex_pc); 390 return GetQuickFieldAccess(inst, register_line); 391} 392 393mirror::ArtMethod* MethodVerifier::FindInvokedMethodAtDexPc(mirror::ArtMethod* m, 394 uint32_t dex_pc) { 395 StackHandleScope<2> hs(Thread::Current()); 396 Handle<mirror::DexCache> dex_cache(hs.NewHandle(m->GetDexCache())); 397 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(m->GetClassLoader())); 398 MethodVerifier verifier(m->GetDexFile(), &dex_cache, &class_loader, &m->GetClassDef(), 399 m->GetCodeItem(), m->GetDexMethodIndex(), m, m->GetAccessFlags(), true, 400 true, false); 401 return verifier.FindInvokedMethodAtDexPc(dex_pc); 402} 403 404mirror::ArtMethod* MethodVerifier::FindInvokedMethodAtDexPc(uint32_t dex_pc) { 405 CHECK(code_item_ != NULL); // This only makes sense for methods with code. 406 407 // Strictly speaking, we ought to be able to get away with doing a subset of the full method 408 // verification. In practice, the phase we want relies on data structures set up by all the 409 // earlier passes, so we just run the full method verification and bail out early when we've 410 // got what we wanted. 411 bool success = Verify(); 412 if (!success) { 413 return NULL; 414 } 415 RegisterLine* register_line = reg_table_.GetLine(dex_pc); 416 if (register_line == NULL) { 417 return NULL; 418 } 419 const Instruction* inst = Instruction::At(code_item_->insns_ + dex_pc); 420 const bool is_range = (inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE_QUICK); 421 return GetQuickInvokedMethod(inst, register_line, is_range); 422} 423 424bool MethodVerifier::Verify() { 425 // If there aren't any instructions, make sure that's expected, then exit successfully. 426 if (code_item_ == NULL) { 427 if ((method_access_flags_ & (kAccNative | kAccAbstract)) == 0) { 428 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "zero-length code in concrete non-native method"; 429 return false; 430 } else { 431 return true; 432 } 433 } 434 // Sanity-check the register counts. ins + locals = registers, so make sure that ins <= registers. 435 if (code_item_->ins_size_ > code_item_->registers_size_) { 436 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad register counts (ins=" << code_item_->ins_size_ 437 << " regs=" << code_item_->registers_size_; 438 return false; 439 } 440 // Allocate and initialize an array to hold instruction data. 441 insn_flags_.reset(new InstructionFlags[code_item_->insns_size_in_code_units_]()); 442 // Run through the instructions and see if the width checks out. 443 bool result = ComputeWidthsAndCountOps(); 444 // Flag instructions guarded by a "try" block and check exception handlers. 445 result = result && ScanTryCatchBlocks(); 446 // Perform static instruction verification. 447 result = result && VerifyInstructions(); 448 // Perform code-flow analysis and return. 449 result = result && VerifyCodeFlow(); 450 // Compute information for compiler. 451 if (result && Runtime::Current()->IsCompiler()) { 452 result = Runtime::Current()->GetCompilerCallbacks()->MethodVerified(this); 453 } 454 return result; 455} 456 457std::ostream& MethodVerifier::Fail(VerifyError error) { 458 switch (error) { 459 case VERIFY_ERROR_NO_CLASS: 460 case VERIFY_ERROR_NO_FIELD: 461 case VERIFY_ERROR_NO_METHOD: 462 case VERIFY_ERROR_ACCESS_CLASS: 463 case VERIFY_ERROR_ACCESS_FIELD: 464 case VERIFY_ERROR_ACCESS_METHOD: 465 case VERIFY_ERROR_INSTANTIATION: 466 case VERIFY_ERROR_CLASS_CHANGE: 467 if (Runtime::Current()->IsCompiler() || !can_load_classes_) { 468 // If we're optimistically running verification at compile time, turn NO_xxx, ACCESS_xxx, 469 // class change and instantiation errors into soft verification errors so that we re-verify 470 // at runtime. We may fail to find or to agree on access because of not yet available class 471 // loaders, or class loaders that will differ at runtime. In these cases, we don't want to 472 // affect the soundness of the code being compiled. Instead, the generated code runs "slow 473 // paths" that dynamically perform the verification and cause the behavior to be that akin 474 // to an interpreter. 475 error = VERIFY_ERROR_BAD_CLASS_SOFT; 476 } else { 477 // If we fail again at runtime, mark that this instruction would throw and force this 478 // method to be executed using the interpreter with checks. 479 have_pending_runtime_throw_failure_ = true; 480 } 481 break; 482 // Indication that verification should be retried at runtime. 483 case VERIFY_ERROR_BAD_CLASS_SOFT: 484 if (!allow_soft_failures_) { 485 have_pending_hard_failure_ = true; 486 } 487 break; 488 // Hard verification failures at compile time will still fail at runtime, so the class is 489 // marked as rejected to prevent it from being compiled. 490 case VERIFY_ERROR_BAD_CLASS_HARD: { 491 if (Runtime::Current()->IsCompiler()) { 492 ClassReference ref(dex_file_, dex_file_->GetIndexForClassDef(*class_def_)); 493 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref); 494 } 495 have_pending_hard_failure_ = true; 496 break; 497 } 498 } 499 failures_.push_back(error); 500 std::string location(StringPrintf("%s: [0x%X]", PrettyMethod(dex_method_idx_, *dex_file_).c_str(), 501 work_insn_idx_)); 502 std::ostringstream* failure_message = new std::ostringstream(location); 503 failure_messages_.push_back(failure_message); 504 return *failure_message; 505} 506 507std::ostream& MethodVerifier::LogVerifyInfo() { 508 return info_messages_ << "VFY: " << PrettyMethod(dex_method_idx_, *dex_file_) 509 << '[' << reinterpret_cast<void*>(work_insn_idx_) << "] : "; 510} 511 512void MethodVerifier::PrependToLastFailMessage(std::string prepend) { 513 size_t failure_num = failure_messages_.size(); 514 DCHECK_NE(failure_num, 0U); 515 std::ostringstream* last_fail_message = failure_messages_[failure_num - 1]; 516 prepend += last_fail_message->str(); 517 failure_messages_[failure_num - 1] = new std::ostringstream(prepend); 518 delete last_fail_message; 519} 520 521void MethodVerifier::AppendToLastFailMessage(std::string append) { 522 size_t failure_num = failure_messages_.size(); 523 DCHECK_NE(failure_num, 0U); 524 std::ostringstream* last_fail_message = failure_messages_[failure_num - 1]; 525 (*last_fail_message) << append; 526} 527 528bool MethodVerifier::ComputeWidthsAndCountOps() { 529 const uint16_t* insns = code_item_->insns_; 530 size_t insns_size = code_item_->insns_size_in_code_units_; 531 const Instruction* inst = Instruction::At(insns); 532 size_t new_instance_count = 0; 533 size_t monitor_enter_count = 0; 534 size_t dex_pc = 0; 535 536 while (dex_pc < insns_size) { 537 Instruction::Code opcode = inst->Opcode(); 538 switch (opcode) { 539 case Instruction::APUT_OBJECT: 540 case Instruction::CHECK_CAST: 541 has_check_casts_ = true; 542 break; 543 case Instruction::INVOKE_VIRTUAL: 544 case Instruction::INVOKE_VIRTUAL_RANGE: 545 case Instruction::INVOKE_INTERFACE: 546 case Instruction::INVOKE_INTERFACE_RANGE: 547 has_virtual_or_interface_invokes_ = true; 548 break; 549 case Instruction::MONITOR_ENTER: 550 monitor_enter_count++; 551 break; 552 case Instruction::NEW_INSTANCE: 553 new_instance_count++; 554 break; 555 default: 556 break; 557 } 558 size_t inst_size = inst->SizeInCodeUnits(); 559 insn_flags_[dex_pc].SetLengthInCodeUnits(inst_size); 560 dex_pc += inst_size; 561 inst = inst->Next(); 562 } 563 564 if (dex_pc != insns_size) { 565 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "code did not end where expected (" 566 << dex_pc << " vs. " << insns_size << ")"; 567 return false; 568 } 569 570 new_instance_count_ = new_instance_count; 571 monitor_enter_count_ = monitor_enter_count; 572 return true; 573} 574 575bool MethodVerifier::ScanTryCatchBlocks() { 576 uint32_t tries_size = code_item_->tries_size_; 577 if (tries_size == 0) { 578 return true; 579 } 580 uint32_t insns_size = code_item_->insns_size_in_code_units_; 581 const DexFile::TryItem* tries = DexFile::GetTryItems(*code_item_, 0); 582 583 for (uint32_t idx = 0; idx < tries_size; idx++) { 584 const DexFile::TryItem* try_item = &tries[idx]; 585 uint32_t start = try_item->start_addr_; 586 uint32_t end = start + try_item->insn_count_; 587 if ((start >= end) || (start >= insns_size) || (end > insns_size)) { 588 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad exception entry: startAddr=" << start 589 << " endAddr=" << end << " (size=" << insns_size << ")"; 590 return false; 591 } 592 if (!insn_flags_[start].IsOpcode()) { 593 Fail(VERIFY_ERROR_BAD_CLASS_HARD) 594 << "'try' block starts inside an instruction (" << start << ")"; 595 return false; 596 } 597 for (uint32_t dex_pc = start; dex_pc < end; 598 dex_pc += insn_flags_[dex_pc].GetLengthInCodeUnits()) { 599 insn_flags_[dex_pc].SetInTry(); 600 } 601 } 602 // Iterate over each of the handlers to verify target addresses. 603 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item_, 0); 604 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr); 605 ClassLinker* linker = Runtime::Current()->GetClassLinker(); 606 for (uint32_t idx = 0; idx < handlers_size; idx++) { 607 CatchHandlerIterator iterator(handlers_ptr); 608 for (; iterator.HasNext(); iterator.Next()) { 609 uint32_t dex_pc= iterator.GetHandlerAddress(); 610 if (!insn_flags_[dex_pc].IsOpcode()) { 611 Fail(VERIFY_ERROR_BAD_CLASS_HARD) 612 << "exception handler starts at bad address (" << dex_pc << ")"; 613 return false; 614 } 615 insn_flags_[dex_pc].SetBranchTarget(); 616 // Ensure exception types are resolved so that they don't need resolution to be delivered, 617 // unresolved exception types will be ignored by exception delivery 618 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) { 619 mirror::Class* exception_type = linker->ResolveType(*dex_file_, 620 iterator.GetHandlerTypeIndex(), 621 *dex_cache_, *class_loader_); 622 if (exception_type == NULL) { 623 DCHECK(Thread::Current()->IsExceptionPending()); 624 Thread::Current()->ClearException(); 625 } 626 } 627 } 628 handlers_ptr = iterator.EndDataPointer(); 629 } 630 return true; 631} 632 633bool MethodVerifier::VerifyInstructions() { 634 const Instruction* inst = Instruction::At(code_item_->insns_); 635 636 /* Flag the start of the method as a branch target, and a GC point due to stack overflow errors */ 637 insn_flags_[0].SetBranchTarget(); 638 insn_flags_[0].SetCompileTimeInfoPoint(); 639 640 uint32_t insns_size = code_item_->insns_size_in_code_units_; 641 for (uint32_t dex_pc = 0; dex_pc < insns_size;) { 642 if (!VerifyInstruction(inst, dex_pc)) { 643 DCHECK_NE(failures_.size(), 0U); 644 return false; 645 } 646 /* Flag instructions that are garbage collection points */ 647 // All invoke points are marked as "Throw" points already. 648 // We are relying on this to also count all the invokes as interesting. 649 if (inst->IsBranch() || inst->IsSwitch() || inst->IsThrow()) { 650 insn_flags_[dex_pc].SetCompileTimeInfoPoint(); 651 } else if (inst->IsReturn()) { 652 insn_flags_[dex_pc].SetCompileTimeInfoPointAndReturn(); 653 } 654 dex_pc += inst->SizeInCodeUnits(); 655 inst = inst->Next(); 656 } 657 return true; 658} 659 660bool MethodVerifier::VerifyInstruction(const Instruction* inst, uint32_t code_offset) { 661 bool result = true; 662 switch (inst->GetVerifyTypeArgumentA()) { 663 case Instruction::kVerifyRegA: 664 result = result && CheckRegisterIndex(inst->VRegA()); 665 break; 666 case Instruction::kVerifyRegAWide: 667 result = result && CheckWideRegisterIndex(inst->VRegA()); 668 break; 669 } 670 switch (inst->GetVerifyTypeArgumentB()) { 671 case Instruction::kVerifyRegB: 672 result = result && CheckRegisterIndex(inst->VRegB()); 673 break; 674 case Instruction::kVerifyRegBField: 675 result = result && CheckFieldIndex(inst->VRegB()); 676 break; 677 case Instruction::kVerifyRegBMethod: 678 result = result && CheckMethodIndex(inst->VRegB()); 679 break; 680 case Instruction::kVerifyRegBNewInstance: 681 result = result && CheckNewInstance(inst->VRegB()); 682 break; 683 case Instruction::kVerifyRegBString: 684 result = result && CheckStringIndex(inst->VRegB()); 685 break; 686 case Instruction::kVerifyRegBType: 687 result = result && CheckTypeIndex(inst->VRegB()); 688 break; 689 case Instruction::kVerifyRegBWide: 690 result = result && CheckWideRegisterIndex(inst->VRegB()); 691 break; 692 } 693 switch (inst->GetVerifyTypeArgumentC()) { 694 case Instruction::kVerifyRegC: 695 result = result && CheckRegisterIndex(inst->VRegC()); 696 break; 697 case Instruction::kVerifyRegCField: 698 result = result && CheckFieldIndex(inst->VRegC()); 699 break; 700 case Instruction::kVerifyRegCNewArray: 701 result = result && CheckNewArray(inst->VRegC()); 702 break; 703 case Instruction::kVerifyRegCType: 704 result = result && CheckTypeIndex(inst->VRegC()); 705 break; 706 case Instruction::kVerifyRegCWide: 707 result = result && CheckWideRegisterIndex(inst->VRegC()); 708 break; 709 } 710 switch (inst->GetVerifyExtraFlags()) { 711 case Instruction::kVerifyArrayData: 712 result = result && CheckArrayData(code_offset); 713 break; 714 case Instruction::kVerifyBranchTarget: 715 result = result && CheckBranchTarget(code_offset); 716 break; 717 case Instruction::kVerifySwitchTargets: 718 result = result && CheckSwitchTargets(code_offset); 719 break; 720 case Instruction::kVerifyVarArg: { 721 uint32_t args[Instruction::kMaxVarArgRegs]; 722 inst->GetVarArgs(args); 723 result = result && CheckVarArgRegs(inst->VRegA(), args); 724 break; 725 } 726 case Instruction::kVerifyVarArgRange: 727 result = result && CheckVarArgRangeRegs(inst->VRegA(), inst->VRegC()); 728 break; 729 case Instruction::kVerifyError: 730 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected opcode " << inst->Name(); 731 result = false; 732 break; 733 } 734 if (inst->GetVerifyIsRuntimeOnly() && Runtime::Current()->IsCompiler()) { 735 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "opcode only expected at runtime " << inst->Name(); 736 result = false; 737 } 738 return result; 739} 740 741bool MethodVerifier::CheckRegisterIndex(uint32_t idx) { 742 if (idx >= code_item_->registers_size_) { 743 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "register index out of range (" << idx << " >= " 744 << code_item_->registers_size_ << ")"; 745 return false; 746 } 747 return true; 748} 749 750bool MethodVerifier::CheckWideRegisterIndex(uint32_t idx) { 751 if (idx + 1 >= code_item_->registers_size_) { 752 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "wide register index out of range (" << idx 753 << "+1 >= " << code_item_->registers_size_ << ")"; 754 return false; 755 } 756 return true; 757} 758 759bool MethodVerifier::CheckFieldIndex(uint32_t idx) { 760 if (idx >= dex_file_->GetHeader().field_ids_size_) { 761 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad field index " << idx << " (max " 762 << dex_file_->GetHeader().field_ids_size_ << ")"; 763 return false; 764 } 765 return true; 766} 767 768bool MethodVerifier::CheckMethodIndex(uint32_t idx) { 769 if (idx >= dex_file_->GetHeader().method_ids_size_) { 770 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad method index " << idx << " (max " 771 << dex_file_->GetHeader().method_ids_size_ << ")"; 772 return false; 773 } 774 return true; 775} 776 777bool MethodVerifier::CheckNewInstance(uint32_t idx) { 778 if (idx >= dex_file_->GetHeader().type_ids_size_) { 779 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad type index " << idx << " (max " 780 << dex_file_->GetHeader().type_ids_size_ << ")"; 781 return false; 782 } 783 // We don't need the actual class, just a pointer to the class name. 784 const char* descriptor = dex_file_->StringByTypeIdx(idx); 785 if (descriptor[0] != 'L') { 786 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "can't call new-instance on type '" << descriptor << "'"; 787 return false; 788 } 789 return true; 790} 791 792bool MethodVerifier::CheckStringIndex(uint32_t idx) { 793 if (idx >= dex_file_->GetHeader().string_ids_size_) { 794 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad string index " << idx << " (max " 795 << dex_file_->GetHeader().string_ids_size_ << ")"; 796 return false; 797 } 798 return true; 799} 800 801bool MethodVerifier::CheckTypeIndex(uint32_t idx) { 802 if (idx >= dex_file_->GetHeader().type_ids_size_) { 803 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad type index " << idx << " (max " 804 << dex_file_->GetHeader().type_ids_size_ << ")"; 805 return false; 806 } 807 return true; 808} 809 810bool MethodVerifier::CheckNewArray(uint32_t idx) { 811 if (idx >= dex_file_->GetHeader().type_ids_size_) { 812 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad type index " << idx << " (max " 813 << dex_file_->GetHeader().type_ids_size_ << ")"; 814 return false; 815 } 816 int bracket_count = 0; 817 const char* descriptor = dex_file_->StringByTypeIdx(idx); 818 const char* cp = descriptor; 819 while (*cp++ == '[') { 820 bracket_count++; 821 } 822 if (bracket_count == 0) { 823 /* The given class must be an array type. */ 824 Fail(VERIFY_ERROR_BAD_CLASS_HARD) 825 << "can't new-array class '" << descriptor << "' (not an array)"; 826 return false; 827 } else if (bracket_count > 255) { 828 /* It is illegal to create an array of more than 255 dimensions. */ 829 Fail(VERIFY_ERROR_BAD_CLASS_HARD) 830 << "can't new-array class '" << descriptor << "' (exceeds limit)"; 831 return false; 832 } 833 return true; 834} 835 836bool MethodVerifier::CheckArrayData(uint32_t cur_offset) { 837 const uint32_t insn_count = code_item_->insns_size_in_code_units_; 838 const uint16_t* insns = code_item_->insns_ + cur_offset; 839 const uint16_t* array_data; 840 int32_t array_data_offset; 841 842 DCHECK_LT(cur_offset, insn_count); 843 /* make sure the start of the array data table is in range */ 844 array_data_offset = insns[1] | (((int32_t) insns[2]) << 16); 845 if ((int32_t) cur_offset + array_data_offset < 0 || 846 cur_offset + array_data_offset + 2 >= insn_count) { 847 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid array data start: at " << cur_offset 848 << ", data offset " << array_data_offset 849 << ", count " << insn_count; 850 return false; 851 } 852 /* offset to array data table is a relative branch-style offset */ 853 array_data = insns + array_data_offset; 854 /* make sure the table is 32-bit aligned */ 855 if ((reinterpret_cast<uintptr_t>(array_data) & 0x03) != 0) { 856 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unaligned array data table: at " << cur_offset 857 << ", data offset " << array_data_offset; 858 return false; 859 } 860 uint32_t value_width = array_data[1]; 861 uint32_t value_count = *reinterpret_cast<const uint32_t*>(&array_data[2]); 862 uint32_t table_size = 4 + (value_width * value_count + 1) / 2; 863 /* make sure the end of the switch is in range */ 864 if (cur_offset + array_data_offset + table_size > insn_count) { 865 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid array data end: at " << cur_offset 866 << ", data offset " << array_data_offset << ", end " 867 << cur_offset + array_data_offset + table_size 868 << ", count " << insn_count; 869 return false; 870 } 871 return true; 872} 873 874bool MethodVerifier::CheckBranchTarget(uint32_t cur_offset) { 875 int32_t offset; 876 bool isConditional, selfOkay; 877 if (!GetBranchOffset(cur_offset, &offset, &isConditional, &selfOkay)) { 878 return false; 879 } 880 if (!selfOkay && offset == 0) { 881 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "branch offset of zero not allowed at" 882 << reinterpret_cast<void*>(cur_offset); 883 return false; 884 } 885 // Check for 32-bit overflow. This isn't strictly necessary if we can depend on the runtime 886 // to have identical "wrap-around" behavior, but it's unwise to depend on that. 887 if (((int64_t) cur_offset + (int64_t) offset) != (int64_t) (cur_offset + offset)) { 888 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "branch target overflow " 889 << reinterpret_cast<void*>(cur_offset) << " +" << offset; 890 return false; 891 } 892 const uint32_t insn_count = code_item_->insns_size_in_code_units_; 893 int32_t abs_offset = cur_offset + offset; 894 if (abs_offset < 0 || 895 (uint32_t) abs_offset >= insn_count || 896 !insn_flags_[abs_offset].IsOpcode()) { 897 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid branch target " << offset << " (-> " 898 << reinterpret_cast<void*>(abs_offset) << ") at " 899 << reinterpret_cast<void*>(cur_offset); 900 return false; 901 } 902 insn_flags_[abs_offset].SetBranchTarget(); 903 return true; 904} 905 906bool MethodVerifier::GetBranchOffset(uint32_t cur_offset, int32_t* pOffset, bool* pConditional, 907 bool* selfOkay) { 908 const uint16_t* insns = code_item_->insns_ + cur_offset; 909 *pConditional = false; 910 *selfOkay = false; 911 switch (*insns & 0xff) { 912 case Instruction::GOTO: 913 *pOffset = ((int16_t) *insns) >> 8; 914 break; 915 case Instruction::GOTO_32: 916 *pOffset = insns[1] | (((uint32_t) insns[2]) << 16); 917 *selfOkay = true; 918 break; 919 case Instruction::GOTO_16: 920 *pOffset = (int16_t) insns[1]; 921 break; 922 case Instruction::IF_EQ: 923 case Instruction::IF_NE: 924 case Instruction::IF_LT: 925 case Instruction::IF_GE: 926 case Instruction::IF_GT: 927 case Instruction::IF_LE: 928 case Instruction::IF_EQZ: 929 case Instruction::IF_NEZ: 930 case Instruction::IF_LTZ: 931 case Instruction::IF_GEZ: 932 case Instruction::IF_GTZ: 933 case Instruction::IF_LEZ: 934 *pOffset = (int16_t) insns[1]; 935 *pConditional = true; 936 break; 937 default: 938 return false; 939 break; 940 } 941 return true; 942} 943 944bool MethodVerifier::CheckSwitchTargets(uint32_t cur_offset) { 945 const uint32_t insn_count = code_item_->insns_size_in_code_units_; 946 DCHECK_LT(cur_offset, insn_count); 947 const uint16_t* insns = code_item_->insns_ + cur_offset; 948 /* make sure the start of the switch is in range */ 949 int32_t switch_offset = insns[1] | ((int32_t) insns[2]) << 16; 950 if ((int32_t) cur_offset + switch_offset < 0 || cur_offset + switch_offset + 2 >= insn_count) { 951 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid switch start: at " << cur_offset 952 << ", switch offset " << switch_offset 953 << ", count " << insn_count; 954 return false; 955 } 956 /* offset to switch table is a relative branch-style offset */ 957 const uint16_t* switch_insns = insns + switch_offset; 958 /* make sure the table is 32-bit aligned */ 959 if ((reinterpret_cast<uintptr_t>(switch_insns) & 0x03) != 0) { 960 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unaligned switch table: at " << cur_offset 961 << ", switch offset " << switch_offset; 962 return false; 963 } 964 uint32_t switch_count = switch_insns[1]; 965 int32_t keys_offset, targets_offset; 966 uint16_t expected_signature; 967 if ((*insns & 0xff) == Instruction::PACKED_SWITCH) { 968 /* 0=sig, 1=count, 2/3=firstKey */ 969 targets_offset = 4; 970 keys_offset = -1; 971 expected_signature = Instruction::kPackedSwitchSignature; 972 } else { 973 /* 0=sig, 1=count, 2..count*2 = keys */ 974 keys_offset = 2; 975 targets_offset = 2 + 2 * switch_count; 976 expected_signature = Instruction::kSparseSwitchSignature; 977 } 978 uint32_t table_size = targets_offset + switch_count * 2; 979 if (switch_insns[0] != expected_signature) { 980 Fail(VERIFY_ERROR_BAD_CLASS_HARD) 981 << StringPrintf("wrong signature for switch table (%x, wanted %x)", 982 switch_insns[0], expected_signature); 983 return false; 984 } 985 /* make sure the end of the switch is in range */ 986 if (cur_offset + switch_offset + table_size > (uint32_t) insn_count) { 987 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid switch end: at " << cur_offset 988 << ", switch offset " << switch_offset 989 << ", end " << (cur_offset + switch_offset + table_size) 990 << ", count " << insn_count; 991 return false; 992 } 993 /* for a sparse switch, verify the keys are in ascending order */ 994 if (keys_offset > 0 && switch_count > 1) { 995 int32_t last_key = switch_insns[keys_offset] | (switch_insns[keys_offset + 1] << 16); 996 for (uint32_t targ = 1; targ < switch_count; targ++) { 997 int32_t key = (int32_t) switch_insns[keys_offset + targ * 2] | 998 (int32_t) (switch_insns[keys_offset + targ * 2 + 1] << 16); 999 if (key <= last_key) { 1000 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid packed switch: last key=" << last_key 1001 << ", this=" << key; 1002 return false; 1003 } 1004 last_key = key; 1005 } 1006 } 1007 /* verify each switch target */ 1008 for (uint32_t targ = 0; targ < switch_count; targ++) { 1009 int32_t offset = (int32_t) switch_insns[targets_offset + targ * 2] | 1010 (int32_t) (switch_insns[targets_offset + targ * 2 + 1] << 16); 1011 int32_t abs_offset = cur_offset + offset; 1012 if (abs_offset < 0 || 1013 abs_offset >= (int32_t) insn_count || 1014 !insn_flags_[abs_offset].IsOpcode()) { 1015 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid switch target " << offset 1016 << " (-> " << reinterpret_cast<void*>(abs_offset) << ") at " 1017 << reinterpret_cast<void*>(cur_offset) 1018 << "[" << targ << "]"; 1019 return false; 1020 } 1021 insn_flags_[abs_offset].SetBranchTarget(); 1022 } 1023 return true; 1024} 1025 1026bool MethodVerifier::CheckVarArgRegs(uint32_t vA, uint32_t arg[]) { 1027 if (vA > Instruction::kMaxVarArgRegs) { 1028 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid arg count (" << vA << ") in non-range invoke)"; 1029 return false; 1030 } 1031 uint16_t registers_size = code_item_->registers_size_; 1032 for (uint32_t idx = 0; idx < vA; idx++) { 1033 if (arg[idx] >= registers_size) { 1034 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid reg index (" << arg[idx] 1035 << ") in non-range invoke (>= " << registers_size << ")"; 1036 return false; 1037 } 1038 } 1039 1040 return true; 1041} 1042 1043bool MethodVerifier::CheckVarArgRangeRegs(uint32_t vA, uint32_t vC) { 1044 uint16_t registers_size = code_item_->registers_size_; 1045 // vA/vC are unsigned 8-bit/16-bit quantities for /range instructions, so there's no risk of 1046 // integer overflow when adding them here. 1047 if (vA + vC > registers_size) { 1048 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid reg index " << vA << "+" << vC 1049 << " in range invoke (> " << registers_size << ")"; 1050 return false; 1051 } 1052 return true; 1053} 1054 1055bool MethodVerifier::VerifyCodeFlow() { 1056 uint16_t registers_size = code_item_->registers_size_; 1057 uint32_t insns_size = code_item_->insns_size_in_code_units_; 1058 1059 if (registers_size * insns_size > 4*1024*1024) { 1060 LOG(WARNING) << "warning: method is huge (regs=" << registers_size 1061 << " insns_size=" << insns_size << ")"; 1062 } 1063 /* Create and initialize table holding register status */ 1064 reg_table_.Init(kTrackCompilerInterestPoints, 1065 insn_flags_.get(), 1066 insns_size, 1067 registers_size, 1068 this); 1069 1070 1071 work_line_.reset(RegisterLine::Create(registers_size, this)); 1072 saved_line_.reset(RegisterLine::Create(registers_size, this)); 1073 1074 /* Initialize register types of method arguments. */ 1075 if (!SetTypesFromSignature()) { 1076 DCHECK_NE(failures_.size(), 0U); 1077 std::string prepend("Bad signature in "); 1078 prepend += PrettyMethod(dex_method_idx_, *dex_file_); 1079 PrependToLastFailMessage(prepend); 1080 return false; 1081 } 1082 /* Perform code flow verification. */ 1083 if (!CodeFlowVerifyMethod()) { 1084 DCHECK_NE(failures_.size(), 0U); 1085 return false; 1086 } 1087 return true; 1088} 1089 1090std::ostream& MethodVerifier::DumpFailures(std::ostream& os) { 1091 DCHECK_EQ(failures_.size(), failure_messages_.size()); 1092 for (size_t i = 0; i < failures_.size(); ++i) { 1093 os << failure_messages_[i]->str() << "\n"; 1094 } 1095 return os; 1096} 1097 1098extern "C" void MethodVerifierGdbDump(MethodVerifier* v) 1099 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 1100 v->Dump(std::cerr); 1101} 1102 1103void MethodVerifier::Dump(std::ostream& os) { 1104 if (code_item_ == NULL) { 1105 os << "Native method\n"; 1106 return; 1107 } 1108 { 1109 os << "Register Types:\n"; 1110 Indenter indent_filter(os.rdbuf(), kIndentChar, kIndentBy1Count); 1111 std::ostream indent_os(&indent_filter); 1112 reg_types_.Dump(indent_os); 1113 } 1114 os << "Dumping instructions and register lines:\n"; 1115 Indenter indent_filter(os.rdbuf(), kIndentChar, kIndentBy1Count); 1116 std::ostream indent_os(&indent_filter); 1117 const Instruction* inst = Instruction::At(code_item_->insns_); 1118 for (size_t dex_pc = 0; dex_pc < code_item_->insns_size_in_code_units_; 1119 dex_pc += insn_flags_[dex_pc].GetLengthInCodeUnits()) { 1120 RegisterLine* reg_line = reg_table_.GetLine(dex_pc); 1121 if (reg_line != NULL) { 1122 indent_os << reg_line->Dump() << "\n"; 1123 } 1124 indent_os << StringPrintf("0x%04zx", dex_pc) << ": " << insn_flags_[dex_pc].ToString() << " "; 1125 const bool kDumpHexOfInstruction = false; 1126 if (kDumpHexOfInstruction) { 1127 indent_os << inst->DumpHex(5) << " "; 1128 } 1129 indent_os << inst->DumpString(dex_file_) << "\n"; 1130 inst = inst->Next(); 1131 } 1132} 1133 1134static bool IsPrimitiveDescriptor(char descriptor) { 1135 switch (descriptor) { 1136 case 'I': 1137 case 'C': 1138 case 'S': 1139 case 'B': 1140 case 'Z': 1141 case 'F': 1142 case 'D': 1143 case 'J': 1144 return true; 1145 default: 1146 return false; 1147 } 1148} 1149 1150bool MethodVerifier::SetTypesFromSignature() { 1151 RegisterLine* reg_line = reg_table_.GetLine(0); 1152 int arg_start = code_item_->registers_size_ - code_item_->ins_size_; 1153 size_t expected_args = code_item_->ins_size_; /* long/double count as two */ 1154 1155 DCHECK_GE(arg_start, 0); /* should have been verified earlier */ 1156 // Include the "this" pointer. 1157 size_t cur_arg = 0; 1158 if (!IsStatic()) { 1159 // If this is a constructor for a class other than java.lang.Object, mark the first ("this") 1160 // argument as uninitialized. This restricts field access until the superclass constructor is 1161 // called. 1162 const RegType& declaring_class = GetDeclaringClass(); 1163 if (IsConstructor() && !declaring_class.IsJavaLangObject()) { 1164 reg_line->SetRegisterType(arg_start + cur_arg, 1165 reg_types_.UninitializedThisArgument(declaring_class)); 1166 } else { 1167 reg_line->SetRegisterType(arg_start + cur_arg, declaring_class); 1168 } 1169 cur_arg++; 1170 } 1171 1172 const DexFile::ProtoId& proto_id = 1173 dex_file_->GetMethodPrototype(dex_file_->GetMethodId(dex_method_idx_)); 1174 DexFileParameterIterator iterator(*dex_file_, proto_id); 1175 1176 for (; iterator.HasNext(); iterator.Next()) { 1177 const char* descriptor = iterator.GetDescriptor(); 1178 if (descriptor == NULL) { 1179 LOG(FATAL) << "Null descriptor"; 1180 } 1181 if (cur_arg >= expected_args) { 1182 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected " << expected_args 1183 << " args, found more (" << descriptor << ")"; 1184 return false; 1185 } 1186 switch (descriptor[0]) { 1187 case 'L': 1188 case '[': 1189 // We assume that reference arguments are initialized. The only way it could be otherwise 1190 // (assuming the caller was verified) is if the current method is <init>, but in that case 1191 // it's effectively considered initialized the instant we reach here (in the sense that we 1192 // can return without doing anything or call virtual methods). 1193 { 1194 const RegType& reg_type = ResolveClassAndCheckAccess(iterator.GetTypeIdx()); 1195 if (!reg_type.IsNonZeroReferenceTypes()) { 1196 DCHECK(HasFailures()); 1197 return false; 1198 } 1199 reg_line->SetRegisterType(arg_start + cur_arg, reg_type); 1200 } 1201 break; 1202 case 'Z': 1203 reg_line->SetRegisterType(arg_start + cur_arg, reg_types_.Boolean()); 1204 break; 1205 case 'C': 1206 reg_line->SetRegisterType(arg_start + cur_arg, reg_types_.Char()); 1207 break; 1208 case 'B': 1209 reg_line->SetRegisterType(arg_start + cur_arg, reg_types_.Byte()); 1210 break; 1211 case 'I': 1212 reg_line->SetRegisterType(arg_start + cur_arg, reg_types_.Integer()); 1213 break; 1214 case 'S': 1215 reg_line->SetRegisterType(arg_start + cur_arg, reg_types_.Short()); 1216 break; 1217 case 'F': 1218 reg_line->SetRegisterType(arg_start + cur_arg, reg_types_.Float()); 1219 break; 1220 case 'J': 1221 case 'D': { 1222 if (cur_arg + 1 >= expected_args) { 1223 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected " << expected_args 1224 << " args, found more (" << descriptor << ")"; 1225 return false; 1226 } 1227 1228 const RegType& lo_half = descriptor[0] == 'J' ? reg_types_.LongLo() : reg_types_.DoubleLo(); 1229 const RegType& hi_half = descriptor[0] == 'J' ? reg_types_.LongHi() : reg_types_.DoubleHi(); 1230 reg_line->SetRegisterTypeWide(arg_start + cur_arg, lo_half, hi_half); 1231 cur_arg++; 1232 break; 1233 } 1234 default: 1235 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected signature type char '" 1236 << descriptor << "'"; 1237 return false; 1238 } 1239 cur_arg++; 1240 } 1241 if (cur_arg != expected_args) { 1242 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected " << expected_args 1243 << " arguments, found " << cur_arg; 1244 return false; 1245 } 1246 const char* descriptor = dex_file_->GetReturnTypeDescriptor(proto_id); 1247 // Validate return type. We don't do the type lookup; just want to make sure that it has the right 1248 // format. Only major difference from the method argument format is that 'V' is supported. 1249 bool result; 1250 if (IsPrimitiveDescriptor(descriptor[0]) || descriptor[0] == 'V') { 1251 result = descriptor[1] == '\0'; 1252 } else if (descriptor[0] == '[') { // single/multi-dimensional array of object/primitive 1253 size_t i = 0; 1254 do { 1255 i++; 1256 } while (descriptor[i] == '['); // process leading [ 1257 if (descriptor[i] == 'L') { // object array 1258 do { 1259 i++; // find closing ; 1260 } while (descriptor[i] != ';' && descriptor[i] != '\0'); 1261 result = descriptor[i] == ';'; 1262 } else { // primitive array 1263 result = IsPrimitiveDescriptor(descriptor[i]) && descriptor[i + 1] == '\0'; 1264 } 1265 } else if (descriptor[0] == 'L') { 1266 // could be more thorough here, but shouldn't be required 1267 size_t i = 0; 1268 do { 1269 i++; 1270 } while (descriptor[i] != ';' && descriptor[i] != '\0'); 1271 result = descriptor[i] == ';'; 1272 } else { 1273 result = false; 1274 } 1275 if (!result) { 1276 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected char in return type descriptor '" 1277 << descriptor << "'"; 1278 } 1279 return result; 1280} 1281 1282bool MethodVerifier::CodeFlowVerifyMethod() { 1283 const uint16_t* insns = code_item_->insns_; 1284 const uint32_t insns_size = code_item_->insns_size_in_code_units_; 1285 1286 /* Begin by marking the first instruction as "changed". */ 1287 insn_flags_[0].SetChanged(); 1288 uint32_t start_guess = 0; 1289 1290 /* Continue until no instructions are marked "changed". */ 1291 while (true) { 1292 // Find the first marked one. Use "start_guess" as a way to find one quickly. 1293 uint32_t insn_idx = start_guess; 1294 for (; insn_idx < insns_size; insn_idx++) { 1295 if (insn_flags_[insn_idx].IsChanged()) 1296 break; 1297 } 1298 if (insn_idx == insns_size) { 1299 if (start_guess != 0) { 1300 /* try again, starting from the top */ 1301 start_guess = 0; 1302 continue; 1303 } else { 1304 /* all flags are clear */ 1305 break; 1306 } 1307 } 1308 // We carry the working set of registers from instruction to instruction. If this address can 1309 // be the target of a branch (or throw) instruction, or if we're skipping around chasing 1310 // "changed" flags, we need to load the set of registers from the table. 1311 // Because we always prefer to continue on to the next instruction, we should never have a 1312 // situation where we have a stray "changed" flag set on an instruction that isn't a branch 1313 // target. 1314 work_insn_idx_ = insn_idx; 1315 if (insn_flags_[insn_idx].IsBranchTarget()) { 1316 work_line_->CopyFromLine(reg_table_.GetLine(insn_idx)); 1317 } else { 1318#ifndef NDEBUG 1319 /* 1320 * Sanity check: retrieve the stored register line (assuming 1321 * a full table) and make sure it actually matches. 1322 */ 1323 RegisterLine* register_line = reg_table_.GetLine(insn_idx); 1324 if (register_line != NULL) { 1325 if (work_line_->CompareLine(register_line) != 0) { 1326 Dump(std::cout); 1327 std::cout << info_messages_.str(); 1328 LOG(FATAL) << "work_line diverged in " << PrettyMethod(dex_method_idx_, *dex_file_) 1329 << "@" << reinterpret_cast<void*>(work_insn_idx_) << "\n" 1330 << " work_line=" << *work_line_ << "\n" 1331 << " expected=" << *register_line; 1332 } 1333 } 1334#endif 1335 } 1336 if (!CodeFlowVerifyInstruction(&start_guess)) { 1337 std::string prepend(PrettyMethod(dex_method_idx_, *dex_file_)); 1338 prepend += " failed to verify: "; 1339 PrependToLastFailMessage(prepend); 1340 return false; 1341 } 1342 /* Clear "changed" and mark as visited. */ 1343 insn_flags_[insn_idx].SetVisited(); 1344 insn_flags_[insn_idx].ClearChanged(); 1345 } 1346 1347 if (gDebugVerify) { 1348 /* 1349 * Scan for dead code. There's nothing "evil" about dead code 1350 * (besides the wasted space), but it indicates a flaw somewhere 1351 * down the line, possibly in the verifier. 1352 * 1353 * If we've substituted "always throw" instructions into the stream, 1354 * we are almost certainly going to have some dead code. 1355 */ 1356 int dead_start = -1; 1357 uint32_t insn_idx = 0; 1358 for (; insn_idx < insns_size; insn_idx += insn_flags_[insn_idx].GetLengthInCodeUnits()) { 1359 /* 1360 * Switch-statement data doesn't get "visited" by scanner. It 1361 * may or may not be preceded by a padding NOP (for alignment). 1362 */ 1363 if (insns[insn_idx] == Instruction::kPackedSwitchSignature || 1364 insns[insn_idx] == Instruction::kSparseSwitchSignature || 1365 insns[insn_idx] == Instruction::kArrayDataSignature || 1366 (insns[insn_idx] == Instruction::NOP && (insn_idx + 1 < insns_size) && 1367 (insns[insn_idx + 1] == Instruction::kPackedSwitchSignature || 1368 insns[insn_idx + 1] == Instruction::kSparseSwitchSignature || 1369 insns[insn_idx + 1] == Instruction::kArrayDataSignature))) { 1370 insn_flags_[insn_idx].SetVisited(); 1371 } 1372 1373 if (!insn_flags_[insn_idx].IsVisited()) { 1374 if (dead_start < 0) 1375 dead_start = insn_idx; 1376 } else if (dead_start >= 0) { 1377 LogVerifyInfo() << "dead code " << reinterpret_cast<void*>(dead_start) 1378 << "-" << reinterpret_cast<void*>(insn_idx - 1); 1379 dead_start = -1; 1380 } 1381 } 1382 if (dead_start >= 0) { 1383 LogVerifyInfo() << "dead code " << reinterpret_cast<void*>(dead_start) 1384 << "-" << reinterpret_cast<void*>(insn_idx - 1); 1385 } 1386 // To dump the state of the verify after a method, do something like: 1387 // if (PrettyMethod(dex_method_idx_, *dex_file_) == 1388 // "boolean java.lang.String.equals(java.lang.Object)") { 1389 // LOG(INFO) << info_messages_.str(); 1390 // } 1391 } 1392 return true; 1393} 1394 1395bool MethodVerifier::CodeFlowVerifyInstruction(uint32_t* start_guess) { 1396 // If we're doing FindLocksAtDexPc, check whether we're at the dex pc we care about. 1397 // We want the state _before_ the instruction, for the case where the dex pc we're 1398 // interested in is itself a monitor-enter instruction (which is a likely place 1399 // for a thread to be suspended). 1400 if (monitor_enter_dex_pcs_ != NULL && work_insn_idx_ == interesting_dex_pc_) { 1401 monitor_enter_dex_pcs_->clear(); // The new work line is more accurate than the previous one. 1402 for (size_t i = 0; i < work_line_->GetMonitorEnterCount(); ++i) { 1403 monitor_enter_dex_pcs_->push_back(work_line_->GetMonitorEnterDexPc(i)); 1404 } 1405 } 1406 1407 /* 1408 * Once we finish decoding the instruction, we need to figure out where 1409 * we can go from here. There are three possible ways to transfer 1410 * control to another statement: 1411 * 1412 * (1) Continue to the next instruction. Applies to all but 1413 * unconditional branches, method returns, and exception throws. 1414 * (2) Branch to one or more possible locations. Applies to branches 1415 * and switch statements. 1416 * (3) Exception handlers. Applies to any instruction that can 1417 * throw an exception that is handled by an encompassing "try" 1418 * block. 1419 * 1420 * We can also return, in which case there is no successor instruction 1421 * from this point. 1422 * 1423 * The behavior can be determined from the opcode flags. 1424 */ 1425 const uint16_t* insns = code_item_->insns_ + work_insn_idx_; 1426 const Instruction* inst = Instruction::At(insns); 1427 int opcode_flags = Instruction::FlagsOf(inst->Opcode()); 1428 1429 int32_t branch_target = 0; 1430 bool just_set_result = false; 1431 if (gDebugVerify) { 1432 // Generate processing back trace to debug verifier 1433 LogVerifyInfo() << "Processing " << inst->DumpString(dex_file_) << "\n" 1434 << *work_line_.get() << "\n"; 1435 } 1436 1437 /* 1438 * Make a copy of the previous register state. If the instruction 1439 * can throw an exception, we will copy/merge this into the "catch" 1440 * address rather than work_line, because we don't want the result 1441 * from the "successful" code path (e.g. a check-cast that "improves" 1442 * a type) to be visible to the exception handler. 1443 */ 1444 if ((opcode_flags & Instruction::kThrow) != 0 && CurrentInsnFlags()->IsInTry()) { 1445 saved_line_->CopyFromLine(work_line_.get()); 1446 } else { 1447#ifndef NDEBUG 1448 saved_line_->FillWithGarbage(); 1449#endif 1450 } 1451 1452 1453 // We need to ensure the work line is consistent while performing validation. When we spot a 1454 // peephole pattern we compute a new line for either the fallthrough instruction or the 1455 // branch target. 1456 std::unique_ptr<RegisterLine> branch_line; 1457 std::unique_ptr<RegisterLine> fallthrough_line; 1458 1459 switch (inst->Opcode()) { 1460 case Instruction::NOP: 1461 /* 1462 * A "pure" NOP has no effect on anything. Data tables start with 1463 * a signature that looks like a NOP; if we see one of these in 1464 * the course of executing code then we have a problem. 1465 */ 1466 if (inst->VRegA_10x() != 0) { 1467 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "encountered data table in instruction stream"; 1468 } 1469 break; 1470 1471 case Instruction::MOVE: 1472 work_line_->CopyRegister1(inst->VRegA_12x(), inst->VRegB_12x(), kTypeCategory1nr); 1473 break; 1474 case Instruction::MOVE_FROM16: 1475 work_line_->CopyRegister1(inst->VRegA_22x(), inst->VRegB_22x(), kTypeCategory1nr); 1476 break; 1477 case Instruction::MOVE_16: 1478 work_line_->CopyRegister1(inst->VRegA_32x(), inst->VRegB_32x(), kTypeCategory1nr); 1479 break; 1480 case Instruction::MOVE_WIDE: 1481 work_line_->CopyRegister2(inst->VRegA_12x(), inst->VRegB_12x()); 1482 break; 1483 case Instruction::MOVE_WIDE_FROM16: 1484 work_line_->CopyRegister2(inst->VRegA_22x(), inst->VRegB_22x()); 1485 break; 1486 case Instruction::MOVE_WIDE_16: 1487 work_line_->CopyRegister2(inst->VRegA_32x(), inst->VRegB_32x()); 1488 break; 1489 case Instruction::MOVE_OBJECT: 1490 work_line_->CopyRegister1(inst->VRegA_12x(), inst->VRegB_12x(), kTypeCategoryRef); 1491 break; 1492 case Instruction::MOVE_OBJECT_FROM16: 1493 work_line_->CopyRegister1(inst->VRegA_22x(), inst->VRegB_22x(), kTypeCategoryRef); 1494 break; 1495 case Instruction::MOVE_OBJECT_16: 1496 work_line_->CopyRegister1(inst->VRegA_32x(), inst->VRegB_32x(), kTypeCategoryRef); 1497 break; 1498 1499 /* 1500 * The move-result instructions copy data out of a "pseudo-register" 1501 * with the results from the last method invocation. In practice we 1502 * might want to hold the result in an actual CPU register, so the 1503 * Dalvik spec requires that these only appear immediately after an 1504 * invoke or filled-new-array. 1505 * 1506 * These calls invalidate the "result" register. (This is now 1507 * redundant with the reset done below, but it can make the debug info 1508 * easier to read in some cases.) 1509 */ 1510 case Instruction::MOVE_RESULT: 1511 work_line_->CopyResultRegister1(inst->VRegA_11x(), false); 1512 break; 1513 case Instruction::MOVE_RESULT_WIDE: 1514 work_line_->CopyResultRegister2(inst->VRegA_11x()); 1515 break; 1516 case Instruction::MOVE_RESULT_OBJECT: 1517 work_line_->CopyResultRegister1(inst->VRegA_11x(), true); 1518 break; 1519 1520 case Instruction::MOVE_EXCEPTION: { 1521 /* 1522 * This statement can only appear as the first instruction in an exception handler. We verify 1523 * that as part of extracting the exception type from the catch block list. 1524 */ 1525 const RegType& res_type = GetCaughtExceptionType(); 1526 work_line_->SetRegisterType(inst->VRegA_11x(), res_type); 1527 break; 1528 } 1529 case Instruction::RETURN_VOID: 1530 if (!IsConstructor() || work_line_->CheckConstructorReturn()) { 1531 if (!GetMethodReturnType().IsConflict()) { 1532 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-void not expected"; 1533 } 1534 } 1535 break; 1536 case Instruction::RETURN: 1537 if (!IsConstructor() || work_line_->CheckConstructorReturn()) { 1538 /* check the method signature */ 1539 const RegType& return_type = GetMethodReturnType(); 1540 if (!return_type.IsCategory1Types()) { 1541 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected non-category 1 return type " 1542 << return_type; 1543 } else { 1544 // Compilers may generate synthetic functions that write byte values into boolean fields. 1545 // Also, it may use integer values for boolean, byte, short, and character return types. 1546 const uint32_t vregA = inst->VRegA_11x(); 1547 const RegType& src_type = work_line_->GetRegisterType(vregA); 1548 bool use_src = ((return_type.IsBoolean() && src_type.IsByte()) || 1549 ((return_type.IsBoolean() || return_type.IsByte() || 1550 return_type.IsShort() || return_type.IsChar()) && 1551 src_type.IsInteger())); 1552 /* check the register contents */ 1553 bool success = 1554 work_line_->VerifyRegisterType(vregA, use_src ? src_type : return_type); 1555 if (!success) { 1556 AppendToLastFailMessage(StringPrintf(" return-1nr on invalid register v%d", vregA)); 1557 } 1558 } 1559 } 1560 break; 1561 case Instruction::RETURN_WIDE: 1562 if (!IsConstructor() || work_line_->CheckConstructorReturn()) { 1563 /* check the method signature */ 1564 const RegType& return_type = GetMethodReturnType(); 1565 if (!return_type.IsCategory2Types()) { 1566 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-wide not expected"; 1567 } else { 1568 /* check the register contents */ 1569 const uint32_t vregA = inst->VRegA_11x(); 1570 bool success = work_line_->VerifyRegisterType(vregA, return_type); 1571 if (!success) { 1572 AppendToLastFailMessage(StringPrintf(" return-wide on invalid register v%d", vregA)); 1573 } 1574 } 1575 } 1576 break; 1577 case Instruction::RETURN_OBJECT: 1578 if (!IsConstructor() || work_line_->CheckConstructorReturn()) { 1579 const RegType& return_type = GetMethodReturnType(); 1580 if (!return_type.IsReferenceTypes()) { 1581 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-object not expected"; 1582 } else { 1583 /* return_type is the *expected* return type, not register value */ 1584 DCHECK(!return_type.IsZero()); 1585 DCHECK(!return_type.IsUninitializedReference()); 1586 const uint32_t vregA = inst->VRegA_11x(); 1587 const RegType& reg_type = work_line_->GetRegisterType(vregA); 1588 // Disallow returning uninitialized values and verify that the reference in vAA is an 1589 // instance of the "return_type" 1590 if (reg_type.IsUninitializedTypes()) { 1591 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "returning uninitialized object '" 1592 << reg_type << "'"; 1593 } else if (!return_type.IsAssignableFrom(reg_type)) { 1594 if (reg_type.IsUnresolvedTypes() || return_type.IsUnresolvedTypes()) { 1595 Fail(VERIFY_ERROR_NO_CLASS) << " can't resolve returned type '" << return_type 1596 << "' or '" << reg_type << "'"; 1597 } else { 1598 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "returning '" << reg_type 1599 << "', but expected from declaration '" << return_type << "'"; 1600 } 1601 } 1602 } 1603 } 1604 break; 1605 1606 /* could be boolean, int, float, or a null reference */ 1607 case Instruction::CONST_4: { 1608 int32_t val = static_cast<int32_t>(inst->VRegB_11n() << 28) >> 28; 1609 work_line_->SetRegisterType(inst->VRegA_11n(), 1610 DetermineCat1Constant(val, need_precise_constants_)); 1611 break; 1612 } 1613 case Instruction::CONST_16: { 1614 int16_t val = static_cast<int16_t>(inst->VRegB_21s()); 1615 work_line_->SetRegisterType(inst->VRegA_21s(), 1616 DetermineCat1Constant(val, need_precise_constants_)); 1617 break; 1618 } 1619 case Instruction::CONST: { 1620 int32_t val = inst->VRegB_31i(); 1621 work_line_->SetRegisterType(inst->VRegA_31i(), 1622 DetermineCat1Constant(val, need_precise_constants_)); 1623 break; 1624 } 1625 case Instruction::CONST_HIGH16: { 1626 int32_t val = static_cast<int32_t>(inst->VRegB_21h() << 16); 1627 work_line_->SetRegisterType(inst->VRegA_21h(), 1628 DetermineCat1Constant(val, need_precise_constants_)); 1629 break; 1630 } 1631 /* could be long or double; resolved upon use */ 1632 case Instruction::CONST_WIDE_16: { 1633 int64_t val = static_cast<int16_t>(inst->VRegB_21s()); 1634 const RegType& lo = reg_types_.FromCat2ConstLo(static_cast<int32_t>(val), true); 1635 const RegType& hi = reg_types_.FromCat2ConstHi(static_cast<int32_t>(val >> 32), true); 1636 work_line_->SetRegisterTypeWide(inst->VRegA_21s(), lo, hi); 1637 break; 1638 } 1639 case Instruction::CONST_WIDE_32: { 1640 int64_t val = static_cast<int32_t>(inst->VRegB_31i()); 1641 const RegType& lo = reg_types_.FromCat2ConstLo(static_cast<int32_t>(val), true); 1642 const RegType& hi = reg_types_.FromCat2ConstHi(static_cast<int32_t>(val >> 32), true); 1643 work_line_->SetRegisterTypeWide(inst->VRegA_31i(), lo, hi); 1644 break; 1645 } 1646 case Instruction::CONST_WIDE: { 1647 int64_t val = inst->VRegB_51l(); 1648 const RegType& lo = reg_types_.FromCat2ConstLo(static_cast<int32_t>(val), true); 1649 const RegType& hi = reg_types_.FromCat2ConstHi(static_cast<int32_t>(val >> 32), true); 1650 work_line_->SetRegisterTypeWide(inst->VRegA_51l(), lo, hi); 1651 break; 1652 } 1653 case Instruction::CONST_WIDE_HIGH16: { 1654 int64_t val = static_cast<uint64_t>(inst->VRegB_21h()) << 48; 1655 const RegType& lo = reg_types_.FromCat2ConstLo(static_cast<int32_t>(val), true); 1656 const RegType& hi = reg_types_.FromCat2ConstHi(static_cast<int32_t>(val >> 32), true); 1657 work_line_->SetRegisterTypeWide(inst->VRegA_21h(), lo, hi); 1658 break; 1659 } 1660 case Instruction::CONST_STRING: 1661 work_line_->SetRegisterType(inst->VRegA_21c(), reg_types_.JavaLangString()); 1662 break; 1663 case Instruction::CONST_STRING_JUMBO: 1664 work_line_->SetRegisterType(inst->VRegA_31c(), reg_types_.JavaLangString()); 1665 break; 1666 case Instruction::CONST_CLASS: { 1667 // Get type from instruction if unresolved then we need an access check 1668 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved 1669 const RegType& res_type = ResolveClassAndCheckAccess(inst->VRegB_21c()); 1670 // Register holds class, ie its type is class, on error it will hold Conflict. 1671 work_line_->SetRegisterType(inst->VRegA_21c(), 1672 res_type.IsConflict() ? res_type 1673 : reg_types_.JavaLangClass(true)); 1674 break; 1675 } 1676 case Instruction::MONITOR_ENTER: 1677 work_line_->PushMonitor(inst->VRegA_11x(), work_insn_idx_); 1678 break; 1679 case Instruction::MONITOR_EXIT: 1680 /* 1681 * monitor-exit instructions are odd. They can throw exceptions, 1682 * but when they do they act as if they succeeded and the PC is 1683 * pointing to the following instruction. (This behavior goes back 1684 * to the need to handle asynchronous exceptions, a now-deprecated 1685 * feature that Dalvik doesn't support.) 1686 * 1687 * In practice we don't need to worry about this. The only 1688 * exceptions that can be thrown from monitor-exit are for a 1689 * null reference and -exit without a matching -enter. If the 1690 * structured locking checks are working, the former would have 1691 * failed on the -enter instruction, and the latter is impossible. 1692 * 1693 * This is fortunate, because issue 3221411 prevents us from 1694 * chasing the "can throw" path when monitor verification is 1695 * enabled. If we can fully verify the locking we can ignore 1696 * some catch blocks (which will show up as "dead" code when 1697 * we skip them here); if we can't, then the code path could be 1698 * "live" so we still need to check it. 1699 */ 1700 opcode_flags &= ~Instruction::kThrow; 1701 work_line_->PopMonitor(inst->VRegA_11x()); 1702 break; 1703 1704 case Instruction::CHECK_CAST: 1705 case Instruction::INSTANCE_OF: { 1706 /* 1707 * If this instruction succeeds, we will "downcast" register vA to the type in vB. (This 1708 * could be a "upcast" -- not expected, so we don't try to address it.) 1709 * 1710 * If it fails, an exception is thrown, which we deal with later by ignoring the update to 1711 * dec_insn.vA when branching to a handler. 1712 */ 1713 const bool is_checkcast = (inst->Opcode() == Instruction::CHECK_CAST); 1714 const uint32_t type_idx = (is_checkcast) ? inst->VRegB_21c() : inst->VRegC_22c(); 1715 const RegType& res_type = ResolveClassAndCheckAccess(type_idx); 1716 if (res_type.IsConflict()) { 1717 DCHECK_NE(failures_.size(), 0U); 1718 if (!is_checkcast) { 1719 work_line_->SetRegisterType(inst->VRegA_22c(), reg_types_.Boolean()); 1720 } 1721 break; // bad class 1722 } 1723 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved 1724 uint32_t orig_type_reg = (is_checkcast) ? inst->VRegA_21c() : inst->VRegB_22c(); 1725 const RegType& orig_type = work_line_->GetRegisterType(orig_type_reg); 1726 if (!res_type.IsNonZeroReferenceTypes()) { 1727 if (is_checkcast) { 1728 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "check-cast on unexpected class " << res_type; 1729 } else { 1730 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "instance-of on unexpected class " << res_type; 1731 } 1732 } else if (!orig_type.IsReferenceTypes()) { 1733 if (is_checkcast) { 1734 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "check-cast on non-reference in v" << orig_type_reg; 1735 } else { 1736 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "instance-of on non-reference in v" << orig_type_reg; 1737 } 1738 } else { 1739 if (is_checkcast) { 1740 work_line_->SetRegisterType(inst->VRegA_21c(), res_type); 1741 } else { 1742 work_line_->SetRegisterType(inst->VRegA_22c(), reg_types_.Boolean()); 1743 } 1744 } 1745 break; 1746 } 1747 case Instruction::ARRAY_LENGTH: { 1748 const RegType& res_type = work_line_->GetRegisterType(inst->VRegB_12x()); 1749 if (res_type.IsReferenceTypes()) { 1750 if (!res_type.IsArrayTypes() && !res_type.IsZero()) { // ie not an array or null 1751 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array-length on non-array " << res_type; 1752 } else { 1753 work_line_->SetRegisterType(inst->VRegA_12x(), reg_types_.Integer()); 1754 } 1755 } 1756 break; 1757 } 1758 case Instruction::NEW_INSTANCE: { 1759 const RegType& res_type = ResolveClassAndCheckAccess(inst->VRegB_21c()); 1760 if (res_type.IsConflict()) { 1761 DCHECK_NE(failures_.size(), 0U); 1762 break; // bad class 1763 } 1764 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved 1765 // can't create an instance of an interface or abstract class */ 1766 if (!res_type.IsInstantiableTypes()) { 1767 Fail(VERIFY_ERROR_INSTANTIATION) 1768 << "new-instance on primitive, interface or abstract class" << res_type; 1769 // Soft failure so carry on to set register type. 1770 } 1771 const RegType& uninit_type = reg_types_.Uninitialized(res_type, work_insn_idx_); 1772 // Any registers holding previous allocations from this address that have not yet been 1773 // initialized must be marked invalid. 1774 work_line_->MarkUninitRefsAsInvalid(uninit_type); 1775 // add the new uninitialized reference to the register state 1776 work_line_->SetRegisterType(inst->VRegA_21c(), uninit_type); 1777 break; 1778 } 1779 case Instruction::NEW_ARRAY: 1780 VerifyNewArray(inst, false, false); 1781 break; 1782 case Instruction::FILLED_NEW_ARRAY: 1783 VerifyNewArray(inst, true, false); 1784 just_set_result = true; // Filled new array sets result register 1785 break; 1786 case Instruction::FILLED_NEW_ARRAY_RANGE: 1787 VerifyNewArray(inst, true, true); 1788 just_set_result = true; // Filled new array range sets result register 1789 break; 1790 case Instruction::CMPL_FLOAT: 1791 case Instruction::CMPG_FLOAT: 1792 if (!work_line_->VerifyRegisterType(inst->VRegB_23x(), reg_types_.Float())) { 1793 break; 1794 } 1795 if (!work_line_->VerifyRegisterType(inst->VRegC_23x(), reg_types_.Float())) { 1796 break; 1797 } 1798 work_line_->SetRegisterType(inst->VRegA_23x(), reg_types_.Integer()); 1799 break; 1800 case Instruction::CMPL_DOUBLE: 1801 case Instruction::CMPG_DOUBLE: 1802 if (!work_line_->VerifyRegisterTypeWide(inst->VRegB_23x(), reg_types_.DoubleLo(), 1803 reg_types_.DoubleHi())) { 1804 break; 1805 } 1806 if (!work_line_->VerifyRegisterTypeWide(inst->VRegC_23x(), reg_types_.DoubleLo(), 1807 reg_types_.DoubleHi())) { 1808 break; 1809 } 1810 work_line_->SetRegisterType(inst->VRegA_23x(), reg_types_.Integer()); 1811 break; 1812 case Instruction::CMP_LONG: 1813 if (!work_line_->VerifyRegisterTypeWide(inst->VRegB_23x(), reg_types_.LongLo(), 1814 reg_types_.LongHi())) { 1815 break; 1816 } 1817 if (!work_line_->VerifyRegisterTypeWide(inst->VRegC_23x(), reg_types_.LongLo(), 1818 reg_types_.LongHi())) { 1819 break; 1820 } 1821 work_line_->SetRegisterType(inst->VRegA_23x(), reg_types_.Integer()); 1822 break; 1823 case Instruction::THROW: { 1824 const RegType& res_type = work_line_->GetRegisterType(inst->VRegA_11x()); 1825 if (!reg_types_.JavaLangThrowable(false).IsAssignableFrom(res_type)) { 1826 Fail(res_type.IsUnresolvedTypes() ? VERIFY_ERROR_NO_CLASS : VERIFY_ERROR_BAD_CLASS_SOFT) 1827 << "thrown class " << res_type << " not instanceof Throwable"; 1828 } 1829 break; 1830 } 1831 case Instruction::GOTO: 1832 case Instruction::GOTO_16: 1833 case Instruction::GOTO_32: 1834 /* no effect on or use of registers */ 1835 break; 1836 1837 case Instruction::PACKED_SWITCH: 1838 case Instruction::SPARSE_SWITCH: 1839 /* verify that vAA is an integer, or can be converted to one */ 1840 work_line_->VerifyRegisterType(inst->VRegA_31t(), reg_types_.Integer()); 1841 break; 1842 1843 case Instruction::FILL_ARRAY_DATA: { 1844 /* Similar to the verification done for APUT */ 1845 const RegType& array_type = work_line_->GetRegisterType(inst->VRegA_31t()); 1846 /* array_type can be null if the reg type is Zero */ 1847 if (!array_type.IsZero()) { 1848 if (!array_type.IsArrayTypes()) { 1849 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid fill-array-data with array type " 1850 << array_type; 1851 } else { 1852 const RegType& component_type = reg_types_.GetComponentType(array_type, 1853 class_loader_->Get()); 1854 DCHECK(!component_type.IsConflict()); 1855 if (component_type.IsNonZeroReferenceTypes()) { 1856 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid fill-array-data with component type " 1857 << component_type; 1858 } else { 1859 // Now verify if the element width in the table matches the element width declared in 1860 // the array 1861 const uint16_t* array_data = insns + (insns[1] | (((int32_t) insns[2]) << 16)); 1862 if (array_data[0] != Instruction::kArrayDataSignature) { 1863 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid magic for array-data"; 1864 } else { 1865 size_t elem_width = Primitive::ComponentSize(component_type.GetPrimitiveType()); 1866 // Since we don't compress the data in Dex, expect to see equal width of data stored 1867 // in the table and expected from the array class. 1868 if (array_data[1] != elem_width) { 1869 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array-data size mismatch (" << array_data[1] 1870 << " vs " << elem_width << ")"; 1871 } 1872 } 1873 } 1874 } 1875 } 1876 break; 1877 } 1878 case Instruction::IF_EQ: 1879 case Instruction::IF_NE: { 1880 const RegType& reg_type1 = work_line_->GetRegisterType(inst->VRegA_22t()); 1881 const RegType& reg_type2 = work_line_->GetRegisterType(inst->VRegB_22t()); 1882 bool mismatch = false; 1883 if (reg_type1.IsZero()) { // zero then integral or reference expected 1884 mismatch = !reg_type2.IsReferenceTypes() && !reg_type2.IsIntegralTypes(); 1885 } else if (reg_type1.IsReferenceTypes()) { // both references? 1886 mismatch = !reg_type2.IsReferenceTypes(); 1887 } else { // both integral? 1888 mismatch = !reg_type1.IsIntegralTypes() || !reg_type2.IsIntegralTypes(); 1889 } 1890 if (mismatch) { 1891 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "args to if-eq/if-ne (" << reg_type1 << "," 1892 << reg_type2 << ") must both be references or integral"; 1893 } 1894 break; 1895 } 1896 case Instruction::IF_LT: 1897 case Instruction::IF_GE: 1898 case Instruction::IF_GT: 1899 case Instruction::IF_LE: { 1900 const RegType& reg_type1 = work_line_->GetRegisterType(inst->VRegA_22t()); 1901 const RegType& reg_type2 = work_line_->GetRegisterType(inst->VRegB_22t()); 1902 if (!reg_type1.IsIntegralTypes() || !reg_type2.IsIntegralTypes()) { 1903 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "args to 'if' (" << reg_type1 << "," 1904 << reg_type2 << ") must be integral"; 1905 } 1906 break; 1907 } 1908 case Instruction::IF_EQZ: 1909 case Instruction::IF_NEZ: { 1910 const RegType& reg_type = work_line_->GetRegisterType(inst->VRegA_21t()); 1911 if (!reg_type.IsReferenceTypes() && !reg_type.IsIntegralTypes()) { 1912 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "type " << reg_type 1913 << " unexpected as arg to if-eqz/if-nez"; 1914 } 1915 1916 // Find previous instruction - its existence is a precondition to peephole optimization. 1917 uint32_t instance_of_idx = 0; 1918 if (0 != work_insn_idx_) { 1919 instance_of_idx = work_insn_idx_ - 1; 1920 while (0 != instance_of_idx && !insn_flags_[instance_of_idx].IsOpcode()) { 1921 instance_of_idx--; 1922 } 1923 CHECK(insn_flags_[instance_of_idx].IsOpcode()); 1924 } else { 1925 break; 1926 } 1927 1928 const Instruction* instance_of_inst = Instruction::At(code_item_->insns_ + instance_of_idx); 1929 1930 /* Check for peep-hole pattern of: 1931 * ...; 1932 * instance-of vX, vY, T; 1933 * ifXXX vX, label ; 1934 * ...; 1935 * label: 1936 * ...; 1937 * and sharpen the type of vY to be type T. 1938 * Note, this pattern can't be if: 1939 * - if there are other branches to this branch, 1940 * - when vX == vY. 1941 */ 1942 if (!CurrentInsnFlags()->IsBranchTarget() && 1943 (Instruction::INSTANCE_OF == instance_of_inst->Opcode()) && 1944 (inst->VRegA_21t() == instance_of_inst->VRegA_22c()) && 1945 (instance_of_inst->VRegA_22c() != instance_of_inst->VRegB_22c())) { 1946 // Check that the we are not attempting conversion to interface types, 1947 // which is not done because of the multiple inheritance implications. 1948 // Also don't change the type if it would result in an upcast. 1949 const RegType& orig_type = work_line_->GetRegisterType(instance_of_inst->VRegB_22c()); 1950 const RegType& cast_type = ResolveClassAndCheckAccess(instance_of_inst->VRegC_22c()); 1951 1952 if (!cast_type.IsUnresolvedTypes() && !orig_type.IsUnresolvedTypes() && 1953 !cast_type.GetClass()->IsInterface() && !cast_type.IsAssignableFrom(orig_type)) { 1954 RegisterLine* update_line = RegisterLine::Create(code_item_->registers_size_, this); 1955 if (inst->Opcode() == Instruction::IF_EQZ) { 1956 fallthrough_line.reset(update_line); 1957 } else { 1958 branch_line.reset(update_line); 1959 } 1960 update_line->CopyFromLine(work_line_.get()); 1961 update_line->SetRegisterType(instance_of_inst->VRegB_22c(), cast_type); 1962 if (!insn_flags_[instance_of_idx].IsBranchTarget() && 0 != instance_of_idx) { 1963 // See if instance-of was preceded by a move-object operation, common due to the small 1964 // register encoding space of instance-of, and propagate type information to the source 1965 // of the move-object. 1966 uint32_t move_idx = instance_of_idx - 1; 1967 while (0 != move_idx && !insn_flags_[move_idx].IsOpcode()) { 1968 move_idx--; 1969 } 1970 CHECK(insn_flags_[move_idx].IsOpcode()); 1971 const Instruction* move_inst = Instruction::At(code_item_->insns_ + move_idx); 1972 switch (move_inst->Opcode()) { 1973 case Instruction::MOVE_OBJECT: 1974 if (move_inst->VRegA_12x() == instance_of_inst->VRegB_22c()) { 1975 update_line->SetRegisterType(move_inst->VRegB_12x(), cast_type); 1976 } 1977 break; 1978 case Instruction::MOVE_OBJECT_FROM16: 1979 if (move_inst->VRegA_22x() == instance_of_inst->VRegB_22c()) { 1980 update_line->SetRegisterType(move_inst->VRegB_22x(), cast_type); 1981 } 1982 break; 1983 case Instruction::MOVE_OBJECT_16: 1984 if (move_inst->VRegA_32x() == instance_of_inst->VRegB_22c()) { 1985 update_line->SetRegisterType(move_inst->VRegB_32x(), cast_type); 1986 } 1987 break; 1988 default: 1989 break; 1990 } 1991 } 1992 } 1993 } 1994 1995 break; 1996 } 1997 case Instruction::IF_LTZ: 1998 case Instruction::IF_GEZ: 1999 case Instruction::IF_GTZ: 2000 case Instruction::IF_LEZ: { 2001 const RegType& reg_type = work_line_->GetRegisterType(inst->VRegA_21t()); 2002 if (!reg_type.IsIntegralTypes()) { 2003 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "type " << reg_type 2004 << " unexpected as arg to if-ltz/if-gez/if-gtz/if-lez"; 2005 } 2006 break; 2007 } 2008 case Instruction::AGET_BOOLEAN: 2009 VerifyAGet(inst, reg_types_.Boolean(), true); 2010 break; 2011 case Instruction::AGET_BYTE: 2012 VerifyAGet(inst, reg_types_.Byte(), true); 2013 break; 2014 case Instruction::AGET_CHAR: 2015 VerifyAGet(inst, reg_types_.Char(), true); 2016 break; 2017 case Instruction::AGET_SHORT: 2018 VerifyAGet(inst, reg_types_.Short(), true); 2019 break; 2020 case Instruction::AGET: 2021 VerifyAGet(inst, reg_types_.Integer(), true); 2022 break; 2023 case Instruction::AGET_WIDE: 2024 VerifyAGet(inst, reg_types_.LongLo(), true); 2025 break; 2026 case Instruction::AGET_OBJECT: 2027 VerifyAGet(inst, reg_types_.JavaLangObject(false), false); 2028 break; 2029 2030 case Instruction::APUT_BOOLEAN: 2031 VerifyAPut(inst, reg_types_.Boolean(), true); 2032 break; 2033 case Instruction::APUT_BYTE: 2034 VerifyAPut(inst, reg_types_.Byte(), true); 2035 break; 2036 case Instruction::APUT_CHAR: 2037 VerifyAPut(inst, reg_types_.Char(), true); 2038 break; 2039 case Instruction::APUT_SHORT: 2040 VerifyAPut(inst, reg_types_.Short(), true); 2041 break; 2042 case Instruction::APUT: 2043 VerifyAPut(inst, reg_types_.Integer(), true); 2044 break; 2045 case Instruction::APUT_WIDE: 2046 VerifyAPut(inst, reg_types_.LongLo(), true); 2047 break; 2048 case Instruction::APUT_OBJECT: 2049 VerifyAPut(inst, reg_types_.JavaLangObject(false), false); 2050 break; 2051 2052 case Instruction::IGET_BOOLEAN: 2053 VerifyISGet(inst, reg_types_.Boolean(), true, false); 2054 break; 2055 case Instruction::IGET_BYTE: 2056 VerifyISGet(inst, reg_types_.Byte(), true, false); 2057 break; 2058 case Instruction::IGET_CHAR: 2059 VerifyISGet(inst, reg_types_.Char(), true, false); 2060 break; 2061 case Instruction::IGET_SHORT: 2062 VerifyISGet(inst, reg_types_.Short(), true, false); 2063 break; 2064 case Instruction::IGET: 2065 VerifyISGet(inst, reg_types_.Integer(), true, false); 2066 break; 2067 case Instruction::IGET_WIDE: 2068 VerifyISGet(inst, reg_types_.LongLo(), true, false); 2069 break; 2070 case Instruction::IGET_OBJECT: 2071 VerifyISGet(inst, reg_types_.JavaLangObject(false), false, false); 2072 break; 2073 2074 case Instruction::IPUT_BOOLEAN: 2075 VerifyISPut(inst, reg_types_.Boolean(), true, false); 2076 break; 2077 case Instruction::IPUT_BYTE: 2078 VerifyISPut(inst, reg_types_.Byte(), true, false); 2079 break; 2080 case Instruction::IPUT_CHAR: 2081 VerifyISPut(inst, reg_types_.Char(), true, false); 2082 break; 2083 case Instruction::IPUT_SHORT: 2084 VerifyISPut(inst, reg_types_.Short(), true, false); 2085 break; 2086 case Instruction::IPUT: 2087 VerifyISPut(inst, reg_types_.Integer(), true, false); 2088 break; 2089 case Instruction::IPUT_WIDE: 2090 VerifyISPut(inst, reg_types_.LongLo(), true, false); 2091 break; 2092 case Instruction::IPUT_OBJECT: 2093 VerifyISPut(inst, reg_types_.JavaLangObject(false), false, false); 2094 break; 2095 2096 case Instruction::SGET_BOOLEAN: 2097 VerifyISGet(inst, reg_types_.Boolean(), true, true); 2098 break; 2099 case Instruction::SGET_BYTE: 2100 VerifyISGet(inst, reg_types_.Byte(), true, true); 2101 break; 2102 case Instruction::SGET_CHAR: 2103 VerifyISGet(inst, reg_types_.Char(), true, true); 2104 break; 2105 case Instruction::SGET_SHORT: 2106 VerifyISGet(inst, reg_types_.Short(), true, true); 2107 break; 2108 case Instruction::SGET: 2109 VerifyISGet(inst, reg_types_.Integer(), true, true); 2110 break; 2111 case Instruction::SGET_WIDE: 2112 VerifyISGet(inst, reg_types_.LongLo(), true, true); 2113 break; 2114 case Instruction::SGET_OBJECT: 2115 VerifyISGet(inst, reg_types_.JavaLangObject(false), false, true); 2116 break; 2117 2118 case Instruction::SPUT_BOOLEAN: 2119 VerifyISPut(inst, reg_types_.Boolean(), true, true); 2120 break; 2121 case Instruction::SPUT_BYTE: 2122 VerifyISPut(inst, reg_types_.Byte(), true, true); 2123 break; 2124 case Instruction::SPUT_CHAR: 2125 VerifyISPut(inst, reg_types_.Char(), true, true); 2126 break; 2127 case Instruction::SPUT_SHORT: 2128 VerifyISPut(inst, reg_types_.Short(), true, true); 2129 break; 2130 case Instruction::SPUT: 2131 VerifyISPut(inst, reg_types_.Integer(), true, true); 2132 break; 2133 case Instruction::SPUT_WIDE: 2134 VerifyISPut(inst, reg_types_.LongLo(), true, true); 2135 break; 2136 case Instruction::SPUT_OBJECT: 2137 VerifyISPut(inst, reg_types_.JavaLangObject(false), false, true); 2138 break; 2139 2140 case Instruction::INVOKE_VIRTUAL: 2141 case Instruction::INVOKE_VIRTUAL_RANGE: 2142 case Instruction::INVOKE_SUPER: 2143 case Instruction::INVOKE_SUPER_RANGE: { 2144 bool is_range = (inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE || 2145 inst->Opcode() == Instruction::INVOKE_SUPER_RANGE); 2146 bool is_super = (inst->Opcode() == Instruction::INVOKE_SUPER || 2147 inst->Opcode() == Instruction::INVOKE_SUPER_RANGE); 2148 mirror::ArtMethod* called_method = VerifyInvocationArgs(inst, METHOD_VIRTUAL, is_range, 2149 is_super); 2150 const RegType* return_type = nullptr; 2151 if (called_method != nullptr) { 2152 Thread* self = Thread::Current(); 2153 StackHandleScope<1> hs(self); 2154 Handle<mirror::ArtMethod> h_called_method(hs.NewHandle(called_method)); 2155 MethodHelper mh(h_called_method); 2156 mirror::Class* return_type_class = mh.GetReturnType(can_load_classes_); 2157 if (return_type_class != nullptr) { 2158 return_type = ®_types_.FromClass(h_called_method->GetReturnTypeDescriptor(), 2159 return_type_class, 2160 return_type_class->CannotBeAssignedFromOtherTypes()); 2161 } else { 2162 DCHECK(!can_load_classes_ || self->IsExceptionPending()); 2163 self->ClearException(); 2164 } 2165 } 2166 if (return_type == nullptr) { 2167 uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); 2168 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx); 2169 uint32_t return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_; 2170 const char* descriptor = dex_file_->StringByTypeIdx(return_type_idx); 2171 return_type = ®_types_.FromDescriptor(class_loader_->Get(), descriptor, false); 2172 } 2173 if (!return_type->IsLowHalf()) { 2174 work_line_->SetResultRegisterType(*return_type); 2175 } else { 2176 work_line_->SetResultRegisterTypeWide(*return_type, return_type->HighHalf(®_types_)); 2177 } 2178 just_set_result = true; 2179 break; 2180 } 2181 case Instruction::INVOKE_DIRECT: 2182 case Instruction::INVOKE_DIRECT_RANGE: { 2183 bool is_range = (inst->Opcode() == Instruction::INVOKE_DIRECT_RANGE); 2184 mirror::ArtMethod* called_method = VerifyInvocationArgs(inst, METHOD_DIRECT, 2185 is_range, false); 2186 const char* return_type_descriptor; 2187 bool is_constructor; 2188 if (called_method == NULL) { 2189 uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); 2190 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx); 2191 is_constructor = strcmp("<init>", dex_file_->StringDataByIdx(method_id.name_idx_)) == 0; 2192 uint32_t return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_; 2193 return_type_descriptor = dex_file_->StringByTypeIdx(return_type_idx); 2194 } else { 2195 is_constructor = called_method->IsConstructor(); 2196 return_type_descriptor = called_method->GetReturnTypeDescriptor(); 2197 } 2198 if (is_constructor) { 2199 /* 2200 * Some additional checks when calling a constructor. We know from the invocation arg check 2201 * that the "this" argument is an instance of called_method->klass. Now we further restrict 2202 * that to require that called_method->klass is the same as this->klass or this->super, 2203 * allowing the latter only if the "this" argument is the same as the "this" argument to 2204 * this method (which implies that we're in a constructor ourselves). 2205 */ 2206 const RegType& this_type = work_line_->GetInvocationThis(inst, is_range); 2207 if (this_type.IsConflict()) // failure. 2208 break; 2209 2210 /* no null refs allowed (?) */ 2211 if (this_type.IsZero()) { 2212 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unable to initialize null ref"; 2213 break; 2214 } 2215 2216 /* must be in same class or in superclass */ 2217 // const RegType& this_super_klass = this_type.GetSuperClass(®_types_); 2218 // TODO: re-enable constructor type verification 2219 // if (this_super_klass.IsConflict()) { 2220 // Unknown super class, fail so we re-check at runtime. 2221 // Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "super class unknown for '" << this_type << "'"; 2222 // break; 2223 // } 2224 2225 /* arg must be an uninitialized reference */ 2226 if (!this_type.IsUninitializedTypes()) { 2227 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Expected initialization on uninitialized reference " 2228 << this_type; 2229 break; 2230 } 2231 2232 /* 2233 * Replace the uninitialized reference with an initialized one. We need to do this for all 2234 * registers that have the same object instance in them, not just the "this" register. 2235 */ 2236 work_line_->MarkRefsAsInitialized(this_type); 2237 } 2238 const RegType& return_type = reg_types_.FromDescriptor(class_loader_->Get(), 2239 return_type_descriptor, false); 2240 if (!return_type.IsLowHalf()) { 2241 work_line_->SetResultRegisterType(return_type); 2242 } else { 2243 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(®_types_)); 2244 } 2245 just_set_result = true; 2246 break; 2247 } 2248 case Instruction::INVOKE_STATIC: 2249 case Instruction::INVOKE_STATIC_RANGE: { 2250 bool is_range = (inst->Opcode() == Instruction::INVOKE_STATIC_RANGE); 2251 mirror::ArtMethod* called_method = VerifyInvocationArgs(inst, 2252 METHOD_STATIC, 2253 is_range, 2254 false); 2255 const char* descriptor; 2256 if (called_method == NULL) { 2257 uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); 2258 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx); 2259 uint32_t return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_; 2260 descriptor = dex_file_->StringByTypeIdx(return_type_idx); 2261 } else { 2262 descriptor = called_method->GetReturnTypeDescriptor(); 2263 } 2264 const RegType& return_type = reg_types_.FromDescriptor(class_loader_->Get(), descriptor, 2265 false); 2266 if (!return_type.IsLowHalf()) { 2267 work_line_->SetResultRegisterType(return_type); 2268 } else { 2269 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(®_types_)); 2270 } 2271 just_set_result = true; 2272 } 2273 break; 2274 case Instruction::INVOKE_INTERFACE: 2275 case Instruction::INVOKE_INTERFACE_RANGE: { 2276 bool is_range = (inst->Opcode() == Instruction::INVOKE_INTERFACE_RANGE); 2277 mirror::ArtMethod* abs_method = VerifyInvocationArgs(inst, 2278 METHOD_INTERFACE, 2279 is_range, 2280 false); 2281 if (abs_method != NULL) { 2282 mirror::Class* called_interface = abs_method->GetDeclaringClass(); 2283 if (!called_interface->IsInterface() && !called_interface->IsObjectClass()) { 2284 Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected interface class in invoke-interface '" 2285 << PrettyMethod(abs_method) << "'"; 2286 break; 2287 } 2288 } 2289 /* Get the type of the "this" arg, which should either be a sub-interface of called 2290 * interface or Object (see comments in RegType::JoinClass). 2291 */ 2292 const RegType& this_type = work_line_->GetInvocationThis(inst, is_range); 2293 if (this_type.IsZero()) { 2294 /* null pointer always passes (and always fails at runtime) */ 2295 } else { 2296 if (this_type.IsUninitializedTypes()) { 2297 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "interface call on uninitialized object " 2298 << this_type; 2299 break; 2300 } 2301 // In the past we have tried to assert that "called_interface" is assignable 2302 // from "this_type.GetClass()", however, as we do an imprecise Join 2303 // (RegType::JoinClass) we don't have full information on what interfaces are 2304 // implemented by "this_type". For example, two classes may implement the same 2305 // interfaces and have a common parent that doesn't implement the interface. The 2306 // join will set "this_type" to the parent class and a test that this implements 2307 // the interface will incorrectly fail. 2308 } 2309 /* 2310 * We don't have an object instance, so we can't find the concrete method. However, all of 2311 * the type information is in the abstract method, so we're good. 2312 */ 2313 const char* descriptor; 2314 if (abs_method == NULL) { 2315 uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); 2316 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx); 2317 uint32_t return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_; 2318 descriptor = dex_file_->StringByTypeIdx(return_type_idx); 2319 } else { 2320 descriptor = abs_method->GetReturnTypeDescriptor(); 2321 } 2322 const RegType& return_type = reg_types_.FromDescriptor(class_loader_->Get(), descriptor, 2323 false); 2324 if (!return_type.IsLowHalf()) { 2325 work_line_->SetResultRegisterType(return_type); 2326 } else { 2327 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(®_types_)); 2328 } 2329 just_set_result = true; 2330 break; 2331 } 2332 case Instruction::NEG_INT: 2333 case Instruction::NOT_INT: 2334 work_line_->CheckUnaryOp(inst, reg_types_.Integer(), reg_types_.Integer()); 2335 break; 2336 case Instruction::NEG_LONG: 2337 case Instruction::NOT_LONG: 2338 work_line_->CheckUnaryOpWide(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2339 reg_types_.LongLo(), reg_types_.LongHi()); 2340 break; 2341 case Instruction::NEG_FLOAT: 2342 work_line_->CheckUnaryOp(inst, reg_types_.Float(), reg_types_.Float()); 2343 break; 2344 case Instruction::NEG_DOUBLE: 2345 work_line_->CheckUnaryOpWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2346 reg_types_.DoubleLo(), reg_types_.DoubleHi()); 2347 break; 2348 case Instruction::INT_TO_LONG: 2349 work_line_->CheckUnaryOpToWide(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2350 reg_types_.Integer()); 2351 break; 2352 case Instruction::INT_TO_FLOAT: 2353 work_line_->CheckUnaryOp(inst, reg_types_.Float(), reg_types_.Integer()); 2354 break; 2355 case Instruction::INT_TO_DOUBLE: 2356 work_line_->CheckUnaryOpToWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2357 reg_types_.Integer()); 2358 break; 2359 case Instruction::LONG_TO_INT: 2360 work_line_->CheckUnaryOpFromWide(inst, reg_types_.Integer(), 2361 reg_types_.LongLo(), reg_types_.LongHi()); 2362 break; 2363 case Instruction::LONG_TO_FLOAT: 2364 work_line_->CheckUnaryOpFromWide(inst, reg_types_.Float(), 2365 reg_types_.LongLo(), reg_types_.LongHi()); 2366 break; 2367 case Instruction::LONG_TO_DOUBLE: 2368 work_line_->CheckUnaryOpWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2369 reg_types_.LongLo(), reg_types_.LongHi()); 2370 break; 2371 case Instruction::FLOAT_TO_INT: 2372 work_line_->CheckUnaryOp(inst, reg_types_.Integer(), reg_types_.Float()); 2373 break; 2374 case Instruction::FLOAT_TO_LONG: 2375 work_line_->CheckUnaryOpToWide(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2376 reg_types_.Float()); 2377 break; 2378 case Instruction::FLOAT_TO_DOUBLE: 2379 work_line_->CheckUnaryOpToWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2380 reg_types_.Float()); 2381 break; 2382 case Instruction::DOUBLE_TO_INT: 2383 work_line_->CheckUnaryOpFromWide(inst, reg_types_.Integer(), 2384 reg_types_.DoubleLo(), reg_types_.DoubleHi()); 2385 break; 2386 case Instruction::DOUBLE_TO_LONG: 2387 work_line_->CheckUnaryOpWide(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2388 reg_types_.DoubleLo(), reg_types_.DoubleHi()); 2389 break; 2390 case Instruction::DOUBLE_TO_FLOAT: 2391 work_line_->CheckUnaryOpFromWide(inst, reg_types_.Float(), 2392 reg_types_.DoubleLo(), reg_types_.DoubleHi()); 2393 break; 2394 case Instruction::INT_TO_BYTE: 2395 work_line_->CheckUnaryOp(inst, reg_types_.Byte(), reg_types_.Integer()); 2396 break; 2397 case Instruction::INT_TO_CHAR: 2398 work_line_->CheckUnaryOp(inst, reg_types_.Char(), reg_types_.Integer()); 2399 break; 2400 case Instruction::INT_TO_SHORT: 2401 work_line_->CheckUnaryOp(inst, reg_types_.Short(), reg_types_.Integer()); 2402 break; 2403 2404 case Instruction::ADD_INT: 2405 case Instruction::SUB_INT: 2406 case Instruction::MUL_INT: 2407 case Instruction::REM_INT: 2408 case Instruction::DIV_INT: 2409 case Instruction::SHL_INT: 2410 case Instruction::SHR_INT: 2411 case Instruction::USHR_INT: 2412 work_line_->CheckBinaryOp(inst, reg_types_.Integer(), reg_types_.Integer(), 2413 reg_types_.Integer(), false); 2414 break; 2415 case Instruction::AND_INT: 2416 case Instruction::OR_INT: 2417 case Instruction::XOR_INT: 2418 work_line_->CheckBinaryOp(inst, reg_types_.Integer(), reg_types_.Integer(), 2419 reg_types_.Integer(), true); 2420 break; 2421 case Instruction::ADD_LONG: 2422 case Instruction::SUB_LONG: 2423 case Instruction::MUL_LONG: 2424 case Instruction::DIV_LONG: 2425 case Instruction::REM_LONG: 2426 case Instruction::AND_LONG: 2427 case Instruction::OR_LONG: 2428 case Instruction::XOR_LONG: 2429 work_line_->CheckBinaryOpWide(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2430 reg_types_.LongLo(), reg_types_.LongHi(), 2431 reg_types_.LongLo(), reg_types_.LongHi()); 2432 break; 2433 case Instruction::SHL_LONG: 2434 case Instruction::SHR_LONG: 2435 case Instruction::USHR_LONG: 2436 /* shift distance is Int, making these different from other binary operations */ 2437 work_line_->CheckBinaryOpWideShift(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2438 reg_types_.Integer()); 2439 break; 2440 case Instruction::ADD_FLOAT: 2441 case Instruction::SUB_FLOAT: 2442 case Instruction::MUL_FLOAT: 2443 case Instruction::DIV_FLOAT: 2444 case Instruction::REM_FLOAT: 2445 work_line_->CheckBinaryOp(inst, 2446 reg_types_.Float(), 2447 reg_types_.Float(), 2448 reg_types_.Float(), 2449 false); 2450 break; 2451 case Instruction::ADD_DOUBLE: 2452 case Instruction::SUB_DOUBLE: 2453 case Instruction::MUL_DOUBLE: 2454 case Instruction::DIV_DOUBLE: 2455 case Instruction::REM_DOUBLE: 2456 work_line_->CheckBinaryOpWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2457 reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2458 reg_types_.DoubleLo(), reg_types_.DoubleHi()); 2459 break; 2460 case Instruction::ADD_INT_2ADDR: 2461 case Instruction::SUB_INT_2ADDR: 2462 case Instruction::MUL_INT_2ADDR: 2463 case Instruction::REM_INT_2ADDR: 2464 case Instruction::SHL_INT_2ADDR: 2465 case Instruction::SHR_INT_2ADDR: 2466 case Instruction::USHR_INT_2ADDR: 2467 work_line_->CheckBinaryOp2addr(inst, 2468 reg_types_.Integer(), 2469 reg_types_.Integer(), 2470 reg_types_.Integer(), 2471 false); 2472 break; 2473 case Instruction::AND_INT_2ADDR: 2474 case Instruction::OR_INT_2ADDR: 2475 case Instruction::XOR_INT_2ADDR: 2476 work_line_->CheckBinaryOp2addr(inst, 2477 reg_types_.Integer(), 2478 reg_types_.Integer(), 2479 reg_types_.Integer(), 2480 true); 2481 break; 2482 case Instruction::DIV_INT_2ADDR: 2483 work_line_->CheckBinaryOp2addr(inst, 2484 reg_types_.Integer(), 2485 reg_types_.Integer(), 2486 reg_types_.Integer(), 2487 false); 2488 break; 2489 case Instruction::ADD_LONG_2ADDR: 2490 case Instruction::SUB_LONG_2ADDR: 2491 case Instruction::MUL_LONG_2ADDR: 2492 case Instruction::DIV_LONG_2ADDR: 2493 case Instruction::REM_LONG_2ADDR: 2494 case Instruction::AND_LONG_2ADDR: 2495 case Instruction::OR_LONG_2ADDR: 2496 case Instruction::XOR_LONG_2ADDR: 2497 work_line_->CheckBinaryOp2addrWide(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2498 reg_types_.LongLo(), reg_types_.LongHi(), 2499 reg_types_.LongLo(), reg_types_.LongHi()); 2500 break; 2501 case Instruction::SHL_LONG_2ADDR: 2502 case Instruction::SHR_LONG_2ADDR: 2503 case Instruction::USHR_LONG_2ADDR: 2504 work_line_->CheckBinaryOp2addrWideShift(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2505 reg_types_.Integer()); 2506 break; 2507 case Instruction::ADD_FLOAT_2ADDR: 2508 case Instruction::SUB_FLOAT_2ADDR: 2509 case Instruction::MUL_FLOAT_2ADDR: 2510 case Instruction::DIV_FLOAT_2ADDR: 2511 case Instruction::REM_FLOAT_2ADDR: 2512 work_line_->CheckBinaryOp2addr(inst, 2513 reg_types_.Float(), 2514 reg_types_.Float(), 2515 reg_types_.Float(), 2516 false); 2517 break; 2518 case Instruction::ADD_DOUBLE_2ADDR: 2519 case Instruction::SUB_DOUBLE_2ADDR: 2520 case Instruction::MUL_DOUBLE_2ADDR: 2521 case Instruction::DIV_DOUBLE_2ADDR: 2522 case Instruction::REM_DOUBLE_2ADDR: 2523 work_line_->CheckBinaryOp2addrWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2524 reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2525 reg_types_.DoubleLo(), reg_types_.DoubleHi()); 2526 break; 2527 case Instruction::ADD_INT_LIT16: 2528 case Instruction::RSUB_INT: 2529 case Instruction::MUL_INT_LIT16: 2530 case Instruction::DIV_INT_LIT16: 2531 case Instruction::REM_INT_LIT16: 2532 work_line_->CheckLiteralOp(inst, reg_types_.Integer(), reg_types_.Integer(), false, true); 2533 break; 2534 case Instruction::AND_INT_LIT16: 2535 case Instruction::OR_INT_LIT16: 2536 case Instruction::XOR_INT_LIT16: 2537 work_line_->CheckLiteralOp(inst, reg_types_.Integer(), reg_types_.Integer(), true, true); 2538 break; 2539 case Instruction::ADD_INT_LIT8: 2540 case Instruction::RSUB_INT_LIT8: 2541 case Instruction::MUL_INT_LIT8: 2542 case Instruction::DIV_INT_LIT8: 2543 case Instruction::REM_INT_LIT8: 2544 case Instruction::SHL_INT_LIT8: 2545 case Instruction::SHR_INT_LIT8: 2546 case Instruction::USHR_INT_LIT8: 2547 work_line_->CheckLiteralOp(inst, reg_types_.Integer(), reg_types_.Integer(), false, false); 2548 break; 2549 case Instruction::AND_INT_LIT8: 2550 case Instruction::OR_INT_LIT8: 2551 case Instruction::XOR_INT_LIT8: 2552 work_line_->CheckLiteralOp(inst, reg_types_.Integer(), reg_types_.Integer(), true, false); 2553 break; 2554 2555 // Special instructions. 2556 case Instruction::RETURN_VOID_BARRIER: 2557 if (!IsConstructor() || IsStatic()) { 2558 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-void-barrier not expected"; 2559 } 2560 break; 2561 // Note: the following instructions encode offsets derived from class linking. 2562 // As such they use Class*/Field*/AbstractMethod* as these offsets only have 2563 // meaning if the class linking and resolution were successful. 2564 case Instruction::IGET_QUICK: 2565 VerifyIGetQuick(inst, reg_types_.Integer(), true); 2566 break; 2567 case Instruction::IGET_WIDE_QUICK: 2568 VerifyIGetQuick(inst, reg_types_.LongLo(), true); 2569 break; 2570 case Instruction::IGET_OBJECT_QUICK: 2571 VerifyIGetQuick(inst, reg_types_.JavaLangObject(false), false); 2572 break; 2573 case Instruction::IPUT_QUICK: 2574 VerifyIPutQuick(inst, reg_types_.Integer(), true); 2575 break; 2576 case Instruction::IPUT_WIDE_QUICK: 2577 VerifyIPutQuick(inst, reg_types_.LongLo(), true); 2578 break; 2579 case Instruction::IPUT_OBJECT_QUICK: 2580 VerifyIPutQuick(inst, reg_types_.JavaLangObject(false), false); 2581 break; 2582 case Instruction::INVOKE_VIRTUAL_QUICK: 2583 case Instruction::INVOKE_VIRTUAL_RANGE_QUICK: { 2584 bool is_range = (inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE_QUICK); 2585 mirror::ArtMethod* called_method = VerifyInvokeVirtualQuickArgs(inst, is_range); 2586 if (called_method != NULL) { 2587 const char* descriptor = called_method->GetReturnTypeDescriptor(); 2588 const RegType& return_type = reg_types_.FromDescriptor(class_loader_->Get(), descriptor, 2589 false); 2590 if (!return_type.IsLowHalf()) { 2591 work_line_->SetResultRegisterType(return_type); 2592 } else { 2593 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(®_types_)); 2594 } 2595 just_set_result = true; 2596 } 2597 break; 2598 } 2599 2600 /* These should never appear during verification. */ 2601 case Instruction::UNUSED_3E: 2602 case Instruction::UNUSED_3F: 2603 case Instruction::UNUSED_40: 2604 case Instruction::UNUSED_41: 2605 case Instruction::UNUSED_42: 2606 case Instruction::UNUSED_43: 2607 case Instruction::UNUSED_79: 2608 case Instruction::UNUSED_7A: 2609 case Instruction::UNUSED_EB: 2610 case Instruction::UNUSED_EC: 2611 case Instruction::UNUSED_ED: 2612 case Instruction::UNUSED_EE: 2613 case Instruction::UNUSED_EF: 2614 case Instruction::UNUSED_F0: 2615 case Instruction::UNUSED_F1: 2616 case Instruction::UNUSED_F2: 2617 case Instruction::UNUSED_F3: 2618 case Instruction::UNUSED_F4: 2619 case Instruction::UNUSED_F5: 2620 case Instruction::UNUSED_F6: 2621 case Instruction::UNUSED_F7: 2622 case Instruction::UNUSED_F8: 2623 case Instruction::UNUSED_F9: 2624 case Instruction::UNUSED_FA: 2625 case Instruction::UNUSED_FB: 2626 case Instruction::UNUSED_FC: 2627 case Instruction::UNUSED_FD: 2628 case Instruction::UNUSED_FE: 2629 case Instruction::UNUSED_FF: 2630 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Unexpected opcode " << inst->DumpString(dex_file_); 2631 break; 2632 2633 /* 2634 * DO NOT add a "default" clause here. Without it the compiler will 2635 * complain if an instruction is missing (which is desirable). 2636 */ 2637 } // end - switch (dec_insn.opcode) 2638 2639 if (have_pending_hard_failure_) { 2640 if (Runtime::Current()->IsCompiler()) { 2641 /* When compiling, check that the last failure is a hard failure */ 2642 CHECK_EQ(failures_[failures_.size() - 1], VERIFY_ERROR_BAD_CLASS_HARD); 2643 } 2644 /* immediate failure, reject class */ 2645 info_messages_ << "Rejecting opcode " << inst->DumpString(dex_file_); 2646 return false; 2647 } else if (have_pending_runtime_throw_failure_) { 2648 /* checking interpreter will throw, mark following code as unreachable */ 2649 opcode_flags = Instruction::kThrow; 2650 } 2651 /* 2652 * If we didn't just set the result register, clear it out. This ensures that you can only use 2653 * "move-result" immediately after the result is set. (We could check this statically, but it's 2654 * not expensive and it makes our debugging output cleaner.) 2655 */ 2656 if (!just_set_result) { 2657 work_line_->SetResultTypeToUnknown(); 2658 } 2659 2660 2661 2662 /* 2663 * Handle "branch". Tag the branch target. 2664 * 2665 * NOTE: instructions like Instruction::EQZ provide information about the 2666 * state of the register when the branch is taken or not taken. For example, 2667 * somebody could get a reference field, check it for zero, and if the 2668 * branch is taken immediately store that register in a boolean field 2669 * since the value is known to be zero. We do not currently account for 2670 * that, and will reject the code. 2671 * 2672 * TODO: avoid re-fetching the branch target 2673 */ 2674 if ((opcode_flags & Instruction::kBranch) != 0) { 2675 bool isConditional, selfOkay; 2676 if (!GetBranchOffset(work_insn_idx_, &branch_target, &isConditional, &selfOkay)) { 2677 /* should never happen after static verification */ 2678 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad branch"; 2679 return false; 2680 } 2681 DCHECK_EQ(isConditional, (opcode_flags & Instruction::kContinue) != 0); 2682 if (!CheckNotMoveException(code_item_->insns_, work_insn_idx_ + branch_target)) { 2683 return false; 2684 } 2685 /* update branch target, set "changed" if appropriate */ 2686 if (NULL != branch_line.get()) { 2687 if (!UpdateRegisters(work_insn_idx_ + branch_target, branch_line.get())) { 2688 return false; 2689 } 2690 } else { 2691 if (!UpdateRegisters(work_insn_idx_ + branch_target, work_line_.get())) { 2692 return false; 2693 } 2694 } 2695 } 2696 2697 /* 2698 * Handle "switch". Tag all possible branch targets. 2699 * 2700 * We've already verified that the table is structurally sound, so we 2701 * just need to walk through and tag the targets. 2702 */ 2703 if ((opcode_flags & Instruction::kSwitch) != 0) { 2704 int offset_to_switch = insns[1] | (((int32_t) insns[2]) << 16); 2705 const uint16_t* switch_insns = insns + offset_to_switch; 2706 int switch_count = switch_insns[1]; 2707 int offset_to_targets, targ; 2708 2709 if ((*insns & 0xff) == Instruction::PACKED_SWITCH) { 2710 /* 0 = sig, 1 = count, 2/3 = first key */ 2711 offset_to_targets = 4; 2712 } else { 2713 /* 0 = sig, 1 = count, 2..count * 2 = keys */ 2714 DCHECK((*insns & 0xff) == Instruction::SPARSE_SWITCH); 2715 offset_to_targets = 2 + 2 * switch_count; 2716 } 2717 2718 /* verify each switch target */ 2719 for (targ = 0; targ < switch_count; targ++) { 2720 int offset; 2721 uint32_t abs_offset; 2722 2723 /* offsets are 32-bit, and only partly endian-swapped */ 2724 offset = switch_insns[offset_to_targets + targ * 2] | 2725 (((int32_t) switch_insns[offset_to_targets + targ * 2 + 1]) << 16); 2726 abs_offset = work_insn_idx_ + offset; 2727 DCHECK_LT(abs_offset, code_item_->insns_size_in_code_units_); 2728 if (!CheckNotMoveException(code_item_->insns_, abs_offset)) { 2729 return false; 2730 } 2731 if (!UpdateRegisters(abs_offset, work_line_.get())) 2732 return false; 2733 } 2734 } 2735 2736 /* 2737 * Handle instructions that can throw and that are sitting in a "try" block. (If they're not in a 2738 * "try" block when they throw, control transfers out of the method.) 2739 */ 2740 if ((opcode_flags & Instruction::kThrow) != 0 && insn_flags_[work_insn_idx_].IsInTry()) { 2741 bool within_catch_all = false; 2742 CatchHandlerIterator iterator(*code_item_, work_insn_idx_); 2743 2744 for (; iterator.HasNext(); iterator.Next()) { 2745 if (iterator.GetHandlerTypeIndex() == DexFile::kDexNoIndex16) { 2746 within_catch_all = true; 2747 } 2748 /* 2749 * Merge registers into the "catch" block. We want to use the "savedRegs" rather than 2750 * "work_regs", because at runtime the exception will be thrown before the instruction 2751 * modifies any registers. 2752 */ 2753 if (!UpdateRegisters(iterator.GetHandlerAddress(), saved_line_.get())) { 2754 return false; 2755 } 2756 } 2757 2758 /* 2759 * If the monitor stack depth is nonzero, there must be a "catch all" handler for this 2760 * instruction. This does apply to monitor-exit because of async exception handling. 2761 */ 2762 if (work_line_->MonitorStackDepth() > 0 && !within_catch_all) { 2763 /* 2764 * The state in work_line reflects the post-execution state. If the current instruction is a 2765 * monitor-enter and the monitor stack was empty, we don't need a catch-all (if it throws, 2766 * it will do so before grabbing the lock). 2767 */ 2768 if (inst->Opcode() != Instruction::MONITOR_ENTER || work_line_->MonitorStackDepth() != 1) { 2769 Fail(VERIFY_ERROR_BAD_CLASS_HARD) 2770 << "expected to be within a catch-all for an instruction where a monitor is held"; 2771 return false; 2772 } 2773 } 2774 } 2775 2776 /* Handle "continue". Tag the next consecutive instruction. 2777 * Note: Keep the code handling "continue" case below the "branch" and "switch" cases, 2778 * because it changes work_line_ when performing peephole optimization 2779 * and this change should not be used in those cases. 2780 */ 2781 if ((opcode_flags & Instruction::kContinue) != 0) { 2782 uint32_t next_insn_idx = work_insn_idx_ + CurrentInsnFlags()->GetLengthInCodeUnits(); 2783 if (next_insn_idx >= code_item_->insns_size_in_code_units_) { 2784 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Execution can walk off end of code area"; 2785 return false; 2786 } 2787 // The only way to get to a move-exception instruction is to get thrown there. Make sure the 2788 // next instruction isn't one. 2789 if (!CheckNotMoveException(code_item_->insns_, next_insn_idx)) { 2790 return false; 2791 } 2792 if (NULL != fallthrough_line.get()) { 2793 // Make workline consistent with fallthrough computed from peephole optimization. 2794 work_line_->CopyFromLine(fallthrough_line.get()); 2795 } 2796 if (insn_flags_[next_insn_idx].IsReturn()) { 2797 // For returns we only care about the operand to the return, all other registers are dead. 2798 const Instruction* ret_inst = Instruction::At(code_item_->insns_ + next_insn_idx); 2799 Instruction::Code opcode = ret_inst->Opcode(); 2800 if ((opcode == Instruction::RETURN_VOID) || (opcode == Instruction::RETURN_VOID_BARRIER)) { 2801 work_line_->MarkAllRegistersAsConflicts(); 2802 } else { 2803 if (opcode == Instruction::RETURN_WIDE) { 2804 work_line_->MarkAllRegistersAsConflictsExceptWide(ret_inst->VRegA_11x()); 2805 } else { 2806 work_line_->MarkAllRegistersAsConflictsExcept(ret_inst->VRegA_11x()); 2807 } 2808 } 2809 } 2810 RegisterLine* next_line = reg_table_.GetLine(next_insn_idx); 2811 if (next_line != NULL) { 2812 // Merge registers into what we have for the next instruction, 2813 // and set the "changed" flag if needed. 2814 if (!UpdateRegisters(next_insn_idx, work_line_.get())) { 2815 return false; 2816 } 2817 } else { 2818 /* 2819 * We're not recording register data for the next instruction, so we don't know what the 2820 * prior state was. We have to assume that something has changed and re-evaluate it. 2821 */ 2822 insn_flags_[next_insn_idx].SetChanged(); 2823 } 2824 } 2825 2826 /* If we're returning from the method, make sure monitor stack is empty. */ 2827 if ((opcode_flags & Instruction::kReturn) != 0) { 2828 if (!work_line_->VerifyMonitorStackEmpty()) { 2829 return false; 2830 } 2831 } 2832 2833 /* 2834 * Update start_guess. Advance to the next instruction of that's 2835 * possible, otherwise use the branch target if one was found. If 2836 * neither of those exists we're in a return or throw; leave start_guess 2837 * alone and let the caller sort it out. 2838 */ 2839 if ((opcode_flags & Instruction::kContinue) != 0) { 2840 *start_guess = work_insn_idx_ + insn_flags_[work_insn_idx_].GetLengthInCodeUnits(); 2841 } else if ((opcode_flags & Instruction::kBranch) != 0) { 2842 /* we're still okay if branch_target is zero */ 2843 *start_guess = work_insn_idx_ + branch_target; 2844 } 2845 2846 DCHECK_LT(*start_guess, code_item_->insns_size_in_code_units_); 2847 DCHECK(insn_flags_[*start_guess].IsOpcode()); 2848 2849 return true; 2850} // NOLINT(readability/fn_size) 2851 2852const RegType& MethodVerifier::ResolveClassAndCheckAccess(uint32_t class_idx) { 2853 const char* descriptor = dex_file_->StringByTypeIdx(class_idx); 2854 const RegType& referrer = GetDeclaringClass(); 2855 mirror::Class* klass = (*dex_cache_)->GetResolvedType(class_idx); 2856 const RegType& result = 2857 klass != NULL ? reg_types_.FromClass(descriptor, klass, 2858 klass->CannotBeAssignedFromOtherTypes()) 2859 : reg_types_.FromDescriptor(class_loader_->Get(), descriptor, false); 2860 if (result.IsConflict()) { 2861 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "accessing broken descriptor '" << descriptor 2862 << "' in " << referrer; 2863 return result; 2864 } 2865 if (klass == NULL && !result.IsUnresolvedTypes()) { 2866 (*dex_cache_)->SetResolvedType(class_idx, result.GetClass()); 2867 } 2868 // Check if access is allowed. Unresolved types use xxxWithAccessCheck to 2869 // check at runtime if access is allowed and so pass here. If result is 2870 // primitive, skip the access check. 2871 if (result.IsNonZeroReferenceTypes() && !result.IsUnresolvedTypes() && 2872 !referrer.IsUnresolvedTypes() && !referrer.CanAccess(result)) { 2873 Fail(VERIFY_ERROR_ACCESS_CLASS) << "illegal class access: '" 2874 << referrer << "' -> '" << result << "'"; 2875 } 2876 return result; 2877} 2878 2879const RegType& MethodVerifier::GetCaughtExceptionType() { 2880 const RegType* common_super = NULL; 2881 if (code_item_->tries_size_ != 0) { 2882 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item_, 0); 2883 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr); 2884 for (uint32_t i = 0; i < handlers_size; i++) { 2885 CatchHandlerIterator iterator(handlers_ptr); 2886 for (; iterator.HasNext(); iterator.Next()) { 2887 if (iterator.GetHandlerAddress() == (uint32_t) work_insn_idx_) { 2888 if (iterator.GetHandlerTypeIndex() == DexFile::kDexNoIndex16) { 2889 common_super = ®_types_.JavaLangThrowable(false); 2890 } else { 2891 const RegType& exception = ResolveClassAndCheckAccess(iterator.GetHandlerTypeIndex()); 2892 if (!reg_types_.JavaLangThrowable(false).IsAssignableFrom(exception)) { 2893 if (exception.IsUnresolvedTypes()) { 2894 // We don't know enough about the type. Fail here and let runtime handle it. 2895 Fail(VERIFY_ERROR_NO_CLASS) << "unresolved exception class " << exception; 2896 return exception; 2897 } else { 2898 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "unexpected non-exception class " << exception; 2899 return reg_types_.Conflict(); 2900 } 2901 } else if (common_super == nullptr) { 2902 common_super = &exception; 2903 } else if (common_super->Equals(exception)) { 2904 // odd case, but nothing to do 2905 } else { 2906 common_super = &common_super->Merge(exception, ®_types_); 2907 CHECK(reg_types_.JavaLangThrowable(false).IsAssignableFrom(*common_super)); 2908 } 2909 } 2910 } 2911 } 2912 handlers_ptr = iterator.EndDataPointer(); 2913 } 2914 } 2915 if (common_super == NULL) { 2916 /* no catch blocks, or no catches with classes we can find */ 2917 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "unable to find exception handler"; 2918 return reg_types_.Conflict(); 2919 } 2920 return *common_super; 2921} 2922 2923mirror::ArtMethod* MethodVerifier::ResolveMethodAndCheckAccess(uint32_t dex_method_idx, 2924 MethodType method_type) { 2925 const DexFile::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx); 2926 const RegType& klass_type = ResolveClassAndCheckAccess(method_id.class_idx_); 2927 if (klass_type.IsConflict()) { 2928 std::string append(" in attempt to access method "); 2929 append += dex_file_->GetMethodName(method_id); 2930 AppendToLastFailMessage(append); 2931 return NULL; 2932 } 2933 if (klass_type.IsUnresolvedTypes()) { 2934 return NULL; // Can't resolve Class so no more to do here 2935 } 2936 mirror::Class* klass = klass_type.GetClass(); 2937 const RegType& referrer = GetDeclaringClass(); 2938 mirror::ArtMethod* res_method = (*dex_cache_)->GetResolvedMethod(dex_method_idx); 2939 if (res_method == NULL) { 2940 const char* name = dex_file_->GetMethodName(method_id); 2941 const Signature signature = dex_file_->GetMethodSignature(method_id); 2942 2943 if (method_type == METHOD_DIRECT || method_type == METHOD_STATIC) { 2944 res_method = klass->FindDirectMethod(name, signature); 2945 } else if (method_type == METHOD_INTERFACE) { 2946 res_method = klass->FindInterfaceMethod(name, signature); 2947 } else { 2948 res_method = klass->FindVirtualMethod(name, signature); 2949 } 2950 if (res_method != NULL) { 2951 (*dex_cache_)->SetResolvedMethod(dex_method_idx, res_method); 2952 } else { 2953 // If a virtual or interface method wasn't found with the expected type, look in 2954 // the direct methods. This can happen when the wrong invoke type is used or when 2955 // a class has changed, and will be flagged as an error in later checks. 2956 if (method_type == METHOD_INTERFACE || method_type == METHOD_VIRTUAL) { 2957 res_method = klass->FindDirectMethod(name, signature); 2958 } 2959 if (res_method == NULL) { 2960 Fail(VERIFY_ERROR_NO_METHOD) << "couldn't find method " 2961 << PrettyDescriptor(klass) << "." << name 2962 << " " << signature; 2963 return NULL; 2964 } 2965 } 2966 } 2967 // Make sure calls to constructors are "direct". There are additional restrictions but we don't 2968 // enforce them here. 2969 if (res_method->IsConstructor() && method_type != METHOD_DIRECT) { 2970 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "rejecting non-direct call to constructor " 2971 << PrettyMethod(res_method); 2972 return NULL; 2973 } 2974 // Disallow any calls to class initializers. 2975 if (res_method->IsClassInitializer()) { 2976 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "rejecting call to class initializer " 2977 << PrettyMethod(res_method); 2978 return NULL; 2979 } 2980 // Check if access is allowed. 2981 if (!referrer.CanAccessMember(res_method->GetDeclaringClass(), res_method->GetAccessFlags())) { 2982 Fail(VERIFY_ERROR_ACCESS_METHOD) << "illegal method access (call " << PrettyMethod(res_method) 2983 << " from " << referrer << ")"; 2984 return res_method; 2985 } 2986 // Check that invoke-virtual and invoke-super are not used on private methods of the same class. 2987 if (res_method->IsPrivate() && method_type == METHOD_VIRTUAL) { 2988 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invoke-super/virtual can't be used on private method " 2989 << PrettyMethod(res_method); 2990 return NULL; 2991 } 2992 // Check that interface methods match interface classes. 2993 if (klass->IsInterface() && method_type != METHOD_INTERFACE) { 2994 Fail(VERIFY_ERROR_CLASS_CHANGE) << "non-interface method " << PrettyMethod(res_method) 2995 << " is in an interface class " << PrettyClass(klass); 2996 return NULL; 2997 } else if (!klass->IsInterface() && method_type == METHOD_INTERFACE) { 2998 Fail(VERIFY_ERROR_CLASS_CHANGE) << "interface method " << PrettyMethod(res_method) 2999 << " is in a non-interface class " << PrettyClass(klass); 3000 return NULL; 3001 } 3002 // See if the method type implied by the invoke instruction matches the access flags for the 3003 // target method. 3004 if ((method_type == METHOD_DIRECT && !res_method->IsDirect()) || 3005 (method_type == METHOD_STATIC && !res_method->IsStatic()) || 3006 ((method_type == METHOD_VIRTUAL || method_type == METHOD_INTERFACE) && res_method->IsDirect()) 3007 ) { 3008 Fail(VERIFY_ERROR_CLASS_CHANGE) << "invoke type (" << method_type << ") does not match method " 3009 " type of " << PrettyMethod(res_method); 3010 return NULL; 3011 } 3012 return res_method; 3013} 3014 3015template <class T> 3016mirror::ArtMethod* MethodVerifier::VerifyInvocationArgsFromIterator(T* it, const Instruction* inst, 3017 MethodType method_type, 3018 bool is_range, 3019 mirror::ArtMethod* res_method) { 3020 // We use vAA as our expected arg count, rather than res_method->insSize, because we need to 3021 // match the call to the signature. Also, we might be calling through an abstract method 3022 // definition (which doesn't have register count values). 3023 const size_t expected_args = (is_range) ? inst->VRegA_3rc() : inst->VRegA_35c(); 3024 /* caught by static verifier */ 3025 DCHECK(is_range || expected_args <= 5); 3026 if (expected_args > code_item_->outs_size_) { 3027 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid argument count (" << expected_args 3028 << ") exceeds outsSize (" << code_item_->outs_size_ << ")"; 3029 return nullptr; 3030 } 3031 3032 uint32_t arg[5]; 3033 if (!is_range) { 3034 inst->GetVarArgs(arg); 3035 } 3036 uint32_t sig_registers = 0; 3037 3038 /* 3039 * Check the "this" argument, which must be an instance of the class that declared the method. 3040 * For an interface class, we don't do the full interface merge (see JoinClass), so we can't do a 3041 * rigorous check here (which is okay since we have to do it at runtime). 3042 */ 3043 if (method_type != METHOD_STATIC) { 3044 const RegType& actual_arg_type = work_line_->GetInvocationThis(inst, is_range); 3045 if (actual_arg_type.IsConflict()) { // GetInvocationThis failed. 3046 CHECK(have_pending_hard_failure_); 3047 return nullptr; 3048 } 3049 if (actual_arg_type.IsUninitializedReference()) { 3050 if (res_method) { 3051 if (!res_method->IsConstructor()) { 3052 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "'this' arg must be initialized"; 3053 return nullptr; 3054 } 3055 } else { 3056 // Check whether the name of the called method is "<init>" 3057 const uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); 3058 if (strcmp(dex_file_->GetMethodName(dex_file_->GetMethodId(method_idx)), "init") != 0) { 3059 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "'this' arg must be initialized"; 3060 return nullptr; 3061 } 3062 } 3063 } 3064 if (method_type != METHOD_INTERFACE && !actual_arg_type.IsZero()) { 3065 const RegType* res_method_class; 3066 if (res_method != nullptr) { 3067 mirror::Class* klass = res_method->GetDeclaringClass(); 3068 res_method_class = ®_types_.FromClass(klass->GetDescriptor().c_str(), klass, 3069 klass->CannotBeAssignedFromOtherTypes()); 3070 } else { 3071 const uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); 3072 const uint16_t class_idx = dex_file_->GetMethodId(method_idx).class_idx_; 3073 res_method_class = ®_types_.FromDescriptor(class_loader_->Get(), 3074 dex_file_->StringByTypeIdx(class_idx), 3075 false); 3076 } 3077 if (!res_method_class->IsAssignableFrom(actual_arg_type)) { 3078 Fail(actual_arg_type.IsUnresolvedTypes() ? VERIFY_ERROR_NO_CLASS: 3079 VERIFY_ERROR_BAD_CLASS_SOFT) << "'this' argument '" << actual_arg_type 3080 << "' not instance of '" << *res_method_class << "'"; 3081 // Continue on soft failures. We need to find possible hard failures to avoid problems in 3082 // the compiler. 3083 if (have_pending_hard_failure_) { 3084 return nullptr; 3085 } 3086 } 3087 } 3088 sig_registers = 1; 3089 } 3090 3091 for ( ; it->HasNext(); it->Next()) { 3092 if (sig_registers >= expected_args) { 3093 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation, expected " << inst->VRegA() << 3094 " arguments, found " << sig_registers << " or more."; 3095 return nullptr; 3096 } 3097 3098 const char* param_descriptor = it->GetDescriptor(); 3099 3100 if (param_descriptor == nullptr) { 3101 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation because of missing signature " 3102 "component"; 3103 return nullptr; 3104 } 3105 3106 const RegType& reg_type = reg_types_.FromDescriptor(class_loader_->Get(), param_descriptor, 3107 false); 3108 uint32_t get_reg = is_range ? inst->VRegC_3rc() + static_cast<uint32_t>(sig_registers) : 3109 arg[sig_registers]; 3110 if (reg_type.IsIntegralTypes()) { 3111 const RegType& src_type = work_line_->GetRegisterType(get_reg); 3112 if (!src_type.IsIntegralTypes()) { 3113 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "register v" << get_reg << " has type " << src_type 3114 << " but expected " << reg_type; 3115 return res_method; 3116 } 3117 } else if (!work_line_->VerifyRegisterType(get_reg, reg_type)) { 3118 // Continue on soft failures. We need to find possible hard failures to avoid problems in the 3119 // compiler. 3120 if (have_pending_hard_failure_) { 3121 return res_method; 3122 } 3123 } 3124 sig_registers += reg_type.IsLongOrDoubleTypes() ? 2 : 1; 3125 } 3126 if (expected_args != sig_registers) { 3127 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation, expected " << expected_args << 3128 " arguments, found " << sig_registers; 3129 return nullptr; 3130 } 3131 return res_method; 3132} 3133 3134void MethodVerifier::VerifyInvocationArgsUnresolvedMethod(const Instruction* inst, 3135 MethodType method_type, 3136 bool is_range) { 3137 // As the method may not have been resolved, make this static check against what we expect. 3138 // The main reason for this code block is to fail hard when we find an illegal use, e.g., 3139 // wrong number of arguments or wrong primitive types, even if the method could not be resolved. 3140 const uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); 3141 DexFileParameterIterator it(*dex_file_, 3142 dex_file_->GetProtoId(dex_file_->GetMethodId(method_idx).proto_idx_)); 3143 VerifyInvocationArgsFromIterator<DexFileParameterIterator>(&it, inst, method_type, is_range, 3144 nullptr); 3145} 3146 3147class MethodParamListDescriptorIterator { 3148 public: 3149 explicit MethodParamListDescriptorIterator(mirror::ArtMethod* res_method) : 3150 res_method_(res_method), pos_(0), params_(res_method->GetParameterTypeList()), 3151 params_size_(params_ == nullptr ? 0 : params_->Size()) { 3152 } 3153 3154 bool HasNext() { 3155 return pos_ < params_size_; 3156 } 3157 3158 void Next() { 3159 ++pos_; 3160 } 3161 3162 const char* GetDescriptor() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 3163 return res_method_->GetTypeDescriptorFromTypeIdx(params_->GetTypeItem(pos_).type_idx_); 3164 } 3165 3166 private: 3167 mirror::ArtMethod* res_method_; 3168 size_t pos_; 3169 const DexFile::TypeList* params_; 3170 const size_t params_size_; 3171}; 3172 3173mirror::ArtMethod* MethodVerifier::VerifyInvocationArgs(const Instruction* inst, 3174 MethodType method_type, 3175 bool is_range, 3176 bool is_super) { 3177 // Resolve the method. This could be an abstract or concrete method depending on what sort of call 3178 // we're making. 3179 const uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); 3180 3181 mirror::ArtMethod* res_method = ResolveMethodAndCheckAccess(method_idx, method_type); 3182 if (res_method == NULL) { // error or class is unresolved 3183 // Check what we can statically. 3184 if (!have_pending_hard_failure_) { 3185 VerifyInvocationArgsUnresolvedMethod(inst, method_type, is_range); 3186 } 3187 return nullptr; 3188 } 3189 3190 // If we're using invoke-super(method), make sure that the executing method's class' superclass 3191 // has a vtable entry for the target method. 3192 if (is_super) { 3193 DCHECK(method_type == METHOD_VIRTUAL); 3194 const RegType& super = GetDeclaringClass().GetSuperClass(®_types_); 3195 if (super.IsUnresolvedTypes()) { 3196 Fail(VERIFY_ERROR_NO_METHOD) << "unknown super class in invoke-super from " 3197 << PrettyMethod(dex_method_idx_, *dex_file_) 3198 << " to super " << PrettyMethod(res_method); 3199 return nullptr; 3200 } 3201 mirror::Class* super_klass = super.GetClass(); 3202 if (res_method->GetMethodIndex() >= super_klass->GetVTable()->GetLength()) { 3203 Fail(VERIFY_ERROR_NO_METHOD) << "invalid invoke-super from " 3204 << PrettyMethod(dex_method_idx_, *dex_file_) 3205 << " to super " << super 3206 << "." << res_method->GetName() 3207 << res_method->GetSignature(); 3208 return nullptr; 3209 } 3210 } 3211 3212 // Process the target method's signature. This signature may or may not 3213 MethodParamListDescriptorIterator it(res_method); 3214 return VerifyInvocationArgsFromIterator<MethodParamListDescriptorIterator>(&it, inst, method_type, 3215 is_range, res_method); 3216} 3217 3218mirror::ArtMethod* MethodVerifier::GetQuickInvokedMethod(const Instruction* inst, 3219 RegisterLine* reg_line, bool is_range) { 3220 DCHECK(inst->Opcode() == Instruction::INVOKE_VIRTUAL_QUICK || 3221 inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE_QUICK); 3222 const RegType& actual_arg_type = reg_line->GetInvocationThis(inst, is_range); 3223 if (!actual_arg_type.HasClass()) { 3224 VLOG(verifier) << "Failed to get mirror::Class* from '" << actual_arg_type << "'"; 3225 return nullptr; 3226 } 3227 mirror::ObjectArray<mirror::ArtMethod>* vtable = nullptr; 3228 mirror::Class* klass = actual_arg_type.GetClass(); 3229 if (klass->IsInterface()) { 3230 // Derive Object.class from Class.class.getSuperclass(). 3231 mirror::Class* object_klass = klass->GetClass()->GetSuperClass(); 3232 CHECK(object_klass->IsObjectClass()); 3233 vtable = object_klass->GetVTable(); 3234 } else { 3235 vtable = klass->GetVTable(); 3236 } 3237 CHECK(vtable != nullptr) << PrettyDescriptor(klass); 3238 uint16_t vtable_index = is_range ? inst->VRegB_3rc() : inst->VRegB_35c(); 3239 CHECK_LT(static_cast<int32_t>(vtable_index), vtable->GetLength()) << PrettyDescriptor(klass); 3240 mirror::ArtMethod* res_method = vtable->Get(vtable_index); 3241 CHECK(!Thread::Current()->IsExceptionPending()); 3242 return res_method; 3243} 3244 3245mirror::ArtMethod* MethodVerifier::VerifyInvokeVirtualQuickArgs(const Instruction* inst, 3246 bool is_range) { 3247 DCHECK(Runtime::Current()->IsStarted()); 3248 mirror::ArtMethod* res_method = GetQuickInvokedMethod(inst, work_line_.get(), 3249 is_range); 3250 if (res_method == NULL) { 3251 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Cannot infer method from " << inst->Name(); 3252 return NULL; 3253 } 3254 CHECK(!res_method->IsDirect() && !res_method->IsStatic()); 3255 3256 // We use vAA as our expected arg count, rather than res_method->insSize, because we need to 3257 // match the call to the signature. Also, we might be calling through an abstract method 3258 // definition (which doesn't have register count values). 3259 const RegType& actual_arg_type = work_line_->GetInvocationThis(inst, is_range); 3260 if (actual_arg_type.IsConflict()) { // GetInvocationThis failed. 3261 return NULL; 3262 } 3263 const size_t expected_args = (is_range) ? inst->VRegA_3rc() : inst->VRegA_35c(); 3264 /* caught by static verifier */ 3265 DCHECK(is_range || expected_args <= 5); 3266 if (expected_args > code_item_->outs_size_) { 3267 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid argument count (" << expected_args 3268 << ") exceeds outsSize (" << code_item_->outs_size_ << ")"; 3269 return NULL; 3270 } 3271 3272 /* 3273 * Check the "this" argument, which must be an instance of the class that declared the method. 3274 * For an interface class, we don't do the full interface merge (see JoinClass), so we can't do a 3275 * rigorous check here (which is okay since we have to do it at runtime). 3276 */ 3277 if (actual_arg_type.IsUninitializedReference() && !res_method->IsConstructor()) { 3278 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "'this' arg must be initialized"; 3279 return NULL; 3280 } 3281 if (!actual_arg_type.IsZero()) { 3282 mirror::Class* klass = res_method->GetDeclaringClass(); 3283 const RegType& res_method_class = 3284 reg_types_.FromClass(klass->GetDescriptor().c_str(), klass, 3285 klass->CannotBeAssignedFromOtherTypes()); 3286 if (!res_method_class.IsAssignableFrom(actual_arg_type)) { 3287 Fail(actual_arg_type.IsUnresolvedTypes() ? VERIFY_ERROR_NO_CLASS : 3288 VERIFY_ERROR_BAD_CLASS_SOFT) << "'this' argument '" << actual_arg_type 3289 << "' not instance of '" << res_method_class << "'"; 3290 return NULL; 3291 } 3292 } 3293 /* 3294 * Process the target method's signature. This signature may or may not 3295 * have been verified, so we can't assume it's properly formed. 3296 */ 3297 const DexFile::TypeList* params = res_method->GetParameterTypeList(); 3298 size_t params_size = params == NULL ? 0 : params->Size(); 3299 uint32_t arg[5]; 3300 if (!is_range) { 3301 inst->GetVarArgs(arg); 3302 } 3303 size_t actual_args = 1; 3304 for (size_t param_index = 0; param_index < params_size; param_index++) { 3305 if (actual_args >= expected_args) { 3306 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invalid call to '" << PrettyMethod(res_method) 3307 << "'. Expected " << expected_args 3308 << " arguments, processing argument " << actual_args 3309 << " (where longs/doubles count twice)."; 3310 return NULL; 3311 } 3312 const char* descriptor = 3313 res_method->GetTypeDescriptorFromTypeIdx(params->GetTypeItem(param_index).type_idx_); 3314 if (descriptor == NULL) { 3315 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation of " << PrettyMethod(res_method) 3316 << " missing signature component"; 3317 return NULL; 3318 } 3319 const RegType& reg_type = reg_types_.FromDescriptor(class_loader_->Get(), descriptor, false); 3320 uint32_t get_reg = is_range ? inst->VRegC_3rc() + actual_args : arg[actual_args]; 3321 if (!work_line_->VerifyRegisterType(get_reg, reg_type)) { 3322 return res_method; 3323 } 3324 actual_args = reg_type.IsLongOrDoubleTypes() ? actual_args + 2 : actual_args + 1; 3325 } 3326 if (actual_args != expected_args) { 3327 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation of " << PrettyMethod(res_method) 3328 << " expected " << expected_args << " arguments, found " << actual_args; 3329 return NULL; 3330 } else { 3331 return res_method; 3332 } 3333} 3334 3335void MethodVerifier::VerifyNewArray(const Instruction* inst, bool is_filled, bool is_range) { 3336 uint32_t type_idx; 3337 if (!is_filled) { 3338 DCHECK_EQ(inst->Opcode(), Instruction::NEW_ARRAY); 3339 type_idx = inst->VRegC_22c(); 3340 } else if (!is_range) { 3341 DCHECK_EQ(inst->Opcode(), Instruction::FILLED_NEW_ARRAY); 3342 type_idx = inst->VRegB_35c(); 3343 } else { 3344 DCHECK_EQ(inst->Opcode(), Instruction::FILLED_NEW_ARRAY_RANGE); 3345 type_idx = inst->VRegB_3rc(); 3346 } 3347 const RegType& res_type = ResolveClassAndCheckAccess(type_idx); 3348 if (res_type.IsConflict()) { // bad class 3349 DCHECK_NE(failures_.size(), 0U); 3350 } else { 3351 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved 3352 if (!res_type.IsArrayTypes()) { 3353 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "new-array on non-array class " << res_type; 3354 } else if (!is_filled) { 3355 /* make sure "size" register is valid type */ 3356 work_line_->VerifyRegisterType(inst->VRegB_22c(), reg_types_.Integer()); 3357 /* set register type to array class */ 3358 const RegType& precise_type = reg_types_.FromUninitialized(res_type); 3359 work_line_->SetRegisterType(inst->VRegA_22c(), precise_type); 3360 } else { 3361 // Verify each register. If "arg_count" is bad, VerifyRegisterType() will run off the end of 3362 // the list and fail. It's legal, if silly, for arg_count to be zero. 3363 const RegType& expected_type = reg_types_.GetComponentType(res_type, class_loader_->Get()); 3364 uint32_t arg_count = (is_range) ? inst->VRegA_3rc() : inst->VRegA_35c(); 3365 uint32_t arg[5]; 3366 if (!is_range) { 3367 inst->GetVarArgs(arg); 3368 } 3369 for (size_t ui = 0; ui < arg_count; ui++) { 3370 uint32_t get_reg = is_range ? inst->VRegC_3rc() + ui : arg[ui]; 3371 if (!work_line_->VerifyRegisterType(get_reg, expected_type)) { 3372 work_line_->SetResultRegisterType(reg_types_.Conflict()); 3373 return; 3374 } 3375 } 3376 // filled-array result goes into "result" register 3377 const RegType& precise_type = reg_types_.FromUninitialized(res_type); 3378 work_line_->SetResultRegisterType(precise_type); 3379 } 3380 } 3381} 3382 3383void MethodVerifier::VerifyAGet(const Instruction* inst, 3384 const RegType& insn_type, bool is_primitive) { 3385 const RegType& index_type = work_line_->GetRegisterType(inst->VRegC_23x()); 3386 if (!index_type.IsArrayIndexTypes()) { 3387 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Invalid reg type for array index (" << index_type << ")"; 3388 } else { 3389 const RegType& array_type = work_line_->GetRegisterType(inst->VRegB_23x()); 3390 if (array_type.IsZero()) { 3391 // Null array class; this code path will fail at runtime. Infer a merge-able type from the 3392 // instruction type. TODO: have a proper notion of bottom here. 3393 if (!is_primitive || insn_type.IsCategory1Types()) { 3394 // Reference or category 1 3395 work_line_->SetRegisterType(inst->VRegA_23x(), reg_types_.Zero()); 3396 } else { 3397 // Category 2 3398 work_line_->SetRegisterTypeWide(inst->VRegA_23x(), reg_types_.FromCat2ConstLo(0, false), 3399 reg_types_.FromCat2ConstHi(0, false)); 3400 } 3401 } else if (!array_type.IsArrayTypes()) { 3402 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "not array type " << array_type << " with aget"; 3403 } else { 3404 /* verify the class */ 3405 const RegType& component_type = reg_types_.GetComponentType(array_type, class_loader_->Get()); 3406 if (!component_type.IsReferenceTypes() && !is_primitive) { 3407 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "primitive array type " << array_type 3408 << " source for aget-object"; 3409 } else if (component_type.IsNonZeroReferenceTypes() && is_primitive) { 3410 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "reference array type " << array_type 3411 << " source for category 1 aget"; 3412 } else if (is_primitive && !insn_type.Equals(component_type) && 3413 !((insn_type.IsInteger() && component_type.IsFloat()) || 3414 (insn_type.IsLong() && component_type.IsDouble()))) { 3415 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array type " << array_type 3416 << " incompatible with aget of type " << insn_type; 3417 } else { 3418 // Use knowledge of the field type which is stronger than the type inferred from the 3419 // instruction, which can't differentiate object types and ints from floats, longs from 3420 // doubles. 3421 if (!component_type.IsLowHalf()) { 3422 work_line_->SetRegisterType(inst->VRegA_23x(), component_type); 3423 } else { 3424 work_line_->SetRegisterTypeWide(inst->VRegA_23x(), component_type, 3425 component_type.HighHalf(®_types_)); 3426 } 3427 } 3428 } 3429 } 3430} 3431 3432void MethodVerifier::VerifyPrimitivePut(const RegType& target_type, const RegType& insn_type, 3433 const uint32_t vregA) { 3434 // Primitive assignability rules are weaker than regular assignability rules. 3435 bool instruction_compatible; 3436 bool value_compatible; 3437 const RegType& value_type = work_line_->GetRegisterType(vregA); 3438 if (target_type.IsIntegralTypes()) { 3439 instruction_compatible = target_type.Equals(insn_type); 3440 value_compatible = value_type.IsIntegralTypes(); 3441 } else if (target_type.IsFloat()) { 3442 instruction_compatible = insn_type.IsInteger(); // no put-float, so expect put-int 3443 value_compatible = value_type.IsFloatTypes(); 3444 } else if (target_type.IsLong()) { 3445 instruction_compatible = insn_type.IsLong(); 3446 value_compatible = value_type.IsLongTypes(); 3447 } else if (target_type.IsDouble()) { 3448 instruction_compatible = insn_type.IsLong(); // no put-double, so expect put-long 3449 value_compatible = value_type.IsDoubleTypes(); 3450 } else { 3451 instruction_compatible = false; // reference with primitive store 3452 value_compatible = false; // unused 3453 } 3454 if (!instruction_compatible) { 3455 // This is a global failure rather than a class change failure as the instructions and 3456 // the descriptors for the type should have been consistent within the same file at 3457 // compile time. 3458 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "put insn has type '" << insn_type 3459 << "' but expected type '" << target_type << "'"; 3460 return; 3461 } 3462 if (!value_compatible) { 3463 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected value in v" << vregA 3464 << " of type " << value_type << " but expected " << target_type << " for put"; 3465 return; 3466 } 3467} 3468 3469void MethodVerifier::VerifyAPut(const Instruction* inst, 3470 const RegType& insn_type, bool is_primitive) { 3471 const RegType& index_type = work_line_->GetRegisterType(inst->VRegC_23x()); 3472 if (!index_type.IsArrayIndexTypes()) { 3473 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Invalid reg type for array index (" << index_type << ")"; 3474 } else { 3475 const RegType& array_type = work_line_->GetRegisterType(inst->VRegB_23x()); 3476 if (array_type.IsZero()) { 3477 // Null array type; this code path will fail at runtime. Infer a merge-able type from the 3478 // instruction type. 3479 } else if (!array_type.IsArrayTypes()) { 3480 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "not array type " << array_type << " with aput"; 3481 } else { 3482 const RegType& component_type = reg_types_.GetComponentType(array_type, class_loader_->Get()); 3483 const uint32_t vregA = inst->VRegA_23x(); 3484 if (is_primitive) { 3485 VerifyPrimitivePut(component_type, insn_type, vregA); 3486 } else { 3487 if (!component_type.IsReferenceTypes()) { 3488 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "primitive array type " << array_type 3489 << " source for aput-object"; 3490 } else { 3491 // The instruction agrees with the type of array, confirm the value to be stored does too 3492 // Note: we use the instruction type (rather than the component type) for aput-object as 3493 // incompatible classes will be caught at runtime as an array store exception 3494 work_line_->VerifyRegisterType(vregA, insn_type); 3495 } 3496 } 3497 } 3498 } 3499} 3500 3501mirror::ArtField* MethodVerifier::GetStaticField(int field_idx) { 3502 const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx); 3503 // Check access to class 3504 const RegType& klass_type = ResolveClassAndCheckAccess(field_id.class_idx_); 3505 if (klass_type.IsConflict()) { // bad class 3506 AppendToLastFailMessage(StringPrintf(" in attempt to access static field %d (%s) in %s", 3507 field_idx, dex_file_->GetFieldName(field_id), 3508 dex_file_->GetFieldDeclaringClassDescriptor(field_id))); 3509 return NULL; 3510 } 3511 if (klass_type.IsUnresolvedTypes()) { 3512 return NULL; // Can't resolve Class so no more to do here, will do checking at runtime. 3513 } 3514 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 3515 mirror::ArtField* field = class_linker->ResolveFieldJLS(*dex_file_, field_idx, *dex_cache_, 3516 *class_loader_); 3517 if (field == NULL) { 3518 VLOG(verifier) << "Unable to resolve static field " << field_idx << " (" 3519 << dex_file_->GetFieldName(field_id) << ") in " 3520 << dex_file_->GetFieldDeclaringClassDescriptor(field_id); 3521 DCHECK(Thread::Current()->IsExceptionPending()); 3522 Thread::Current()->ClearException(); 3523 return NULL; 3524 } else if (!GetDeclaringClass().CanAccessMember(field->GetDeclaringClass(), 3525 field->GetAccessFlags())) { 3526 Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot access static field " << PrettyField(field) 3527 << " from " << GetDeclaringClass(); 3528 return NULL; 3529 } else if (!field->IsStatic()) { 3530 Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected field " << PrettyField(field) << " to be static"; 3531 return NULL; 3532 } 3533 return field; 3534} 3535 3536mirror::ArtField* MethodVerifier::GetInstanceField(const RegType& obj_type, int field_idx) { 3537 const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx); 3538 // Check access to class 3539 const RegType& klass_type = ResolveClassAndCheckAccess(field_id.class_idx_); 3540 if (klass_type.IsConflict()) { 3541 AppendToLastFailMessage(StringPrintf(" in attempt to access instance field %d (%s) in %s", 3542 field_idx, dex_file_->GetFieldName(field_id), 3543 dex_file_->GetFieldDeclaringClassDescriptor(field_id))); 3544 return NULL; 3545 } 3546 if (klass_type.IsUnresolvedTypes()) { 3547 return NULL; // Can't resolve Class so no more to do here 3548 } 3549 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 3550 mirror::ArtField* field = class_linker->ResolveFieldJLS(*dex_file_, field_idx, *dex_cache_, 3551 *class_loader_); 3552 if (field == NULL) { 3553 VLOG(verifier) << "Unable to resolve instance field " << field_idx << " (" 3554 << dex_file_->GetFieldName(field_id) << ") in " 3555 << dex_file_->GetFieldDeclaringClassDescriptor(field_id); 3556 DCHECK(Thread::Current()->IsExceptionPending()); 3557 Thread::Current()->ClearException(); 3558 return NULL; 3559 } else if (!GetDeclaringClass().CanAccessMember(field->GetDeclaringClass(), 3560 field->GetAccessFlags())) { 3561 Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot access instance field " << PrettyField(field) 3562 << " from " << GetDeclaringClass(); 3563 return NULL; 3564 } else if (field->IsStatic()) { 3565 Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected field " << PrettyField(field) 3566 << " to not be static"; 3567 return NULL; 3568 } else if (obj_type.IsZero()) { 3569 // Cannot infer and check type, however, access will cause null pointer exception 3570 return field; 3571 } else { 3572 mirror::Class* klass = field->GetDeclaringClass(); 3573 const RegType& field_klass = 3574 reg_types_.FromClass(dex_file_->GetFieldDeclaringClassDescriptor(field_id), 3575 klass, klass->CannotBeAssignedFromOtherTypes()); 3576 if (obj_type.IsUninitializedTypes() && 3577 (!IsConstructor() || GetDeclaringClass().Equals(obj_type) || 3578 !field_klass.Equals(GetDeclaringClass()))) { 3579 // Field accesses through uninitialized references are only allowable for constructors where 3580 // the field is declared in this class 3581 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "cannot access instance field " << PrettyField(field) 3582 << " of a not fully initialized object within the context" 3583 << " of " << PrettyMethod(dex_method_idx_, *dex_file_); 3584 return NULL; 3585 } else if (!field_klass.IsAssignableFrom(obj_type)) { 3586 // Trying to access C1.field1 using reference of type C2, which is neither C1 or a sub-class 3587 // of C1. For resolution to occur the declared class of the field must be compatible with 3588 // obj_type, we've discovered this wasn't so, so report the field didn't exist. 3589 Fail(VERIFY_ERROR_NO_FIELD) << "cannot access instance field " << PrettyField(field) 3590 << " from object of type " << obj_type; 3591 return NULL; 3592 } else { 3593 return field; 3594 } 3595 } 3596} 3597 3598void MethodVerifier::VerifyISGet(const Instruction* inst, const RegType& insn_type, 3599 bool is_primitive, bool is_static) { 3600 uint32_t field_idx = is_static ? inst->VRegB_21c() : inst->VRegC_22c(); 3601 mirror::ArtField* field; 3602 if (is_static) { 3603 field = GetStaticField(field_idx); 3604 } else { 3605 const RegType& object_type = work_line_->GetRegisterType(inst->VRegB_22c()); 3606 field = GetInstanceField(object_type, field_idx); 3607 } 3608 const RegType* field_type = nullptr; 3609 if (field != NULL) { 3610 Thread* self = Thread::Current(); 3611 mirror::Class* field_type_class; 3612 { 3613 StackHandleScope<1> hs(self); 3614 HandleWrapper<mirror::ArtField> h_field(hs.NewHandleWrapper(&field)); 3615 field_type_class = FieldHelper(h_field).GetType(can_load_classes_); 3616 } 3617 if (field_type_class != nullptr) { 3618 field_type = ®_types_.FromClass(field->GetTypeDescriptor(), field_type_class, 3619 field_type_class->CannotBeAssignedFromOtherTypes()); 3620 } else { 3621 DCHECK(!can_load_classes_ || self->IsExceptionPending()); 3622 self->ClearException(); 3623 } 3624 } 3625 if (field_type == nullptr) { 3626 const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx); 3627 const char* descriptor = dex_file_->GetFieldTypeDescriptor(field_id); 3628 field_type = ®_types_.FromDescriptor(class_loader_->Get(), descriptor, false); 3629 } 3630 DCHECK(field_type != nullptr); 3631 const uint32_t vregA = (is_static) ? inst->VRegA_21c() : inst->VRegA_22c(); 3632 if (is_primitive) { 3633 if (field_type->Equals(insn_type) || 3634 (field_type->IsFloat() && insn_type.IsInteger()) || 3635 (field_type->IsDouble() && insn_type.IsLong())) { 3636 // expected that read is of the correct primitive type or that int reads are reading 3637 // floats or long reads are reading doubles 3638 } else { 3639 // This is a global failure rather than a class change failure as the instructions and 3640 // the descriptors for the type should have been consistent within the same file at 3641 // compile time 3642 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected field " << PrettyField(field) 3643 << " to be of type '" << insn_type 3644 << "' but found type '" << *field_type << "' in get"; 3645 return; 3646 } 3647 } else { 3648 if (!insn_type.IsAssignableFrom(*field_type)) { 3649 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "expected field " << PrettyField(field) 3650 << " to be compatible with type '" << insn_type 3651 << "' but found type '" << *field_type 3652 << "' in Get-object"; 3653 work_line_->SetRegisterType(vregA, reg_types_.Conflict()); 3654 return; 3655 } 3656 } 3657 if (!field_type->IsLowHalf()) { 3658 work_line_->SetRegisterType(vregA, *field_type); 3659 } else { 3660 work_line_->SetRegisterTypeWide(vregA, *field_type, field_type->HighHalf(®_types_)); 3661 } 3662} 3663 3664void MethodVerifier::VerifyISPut(const Instruction* inst, const RegType& insn_type, 3665 bool is_primitive, bool is_static) { 3666 uint32_t field_idx = is_static ? inst->VRegB_21c() : inst->VRegC_22c(); 3667 mirror::ArtField* field; 3668 if (is_static) { 3669 field = GetStaticField(field_idx); 3670 } else { 3671 const RegType& object_type = work_line_->GetRegisterType(inst->VRegB_22c()); 3672 field = GetInstanceField(object_type, field_idx); 3673 } 3674 const RegType* field_type = nullptr; 3675 if (field != NULL) { 3676 if (field->IsFinal() && field->GetDeclaringClass() != GetDeclaringClass().GetClass()) { 3677 Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot modify final field " << PrettyField(field) 3678 << " from other class " << GetDeclaringClass(); 3679 return; 3680 } 3681 mirror::Class* field_type_class; 3682 { 3683 StackHandleScope<1> hs(Thread::Current()); 3684 HandleWrapper<mirror::ArtField> h_field(hs.NewHandleWrapper(&field)); 3685 FieldHelper fh(h_field); 3686 field_type_class = fh.GetType(can_load_classes_); 3687 } 3688 if (field_type_class != nullptr) { 3689 field_type = ®_types_.FromClass(field->GetTypeDescriptor(), field_type_class, 3690 field_type_class->CannotBeAssignedFromOtherTypes()); 3691 } else { 3692 Thread* self = Thread::Current(); 3693 DCHECK(!can_load_classes_ || self->IsExceptionPending()); 3694 self->ClearException(); 3695 } 3696 } 3697 if (field_type == nullptr) { 3698 const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx); 3699 const char* descriptor = dex_file_->GetFieldTypeDescriptor(field_id); 3700 field_type = ®_types_.FromDescriptor(class_loader_->Get(), descriptor, false); 3701 } 3702 DCHECK(field_type != nullptr); 3703 const uint32_t vregA = (is_static) ? inst->VRegA_21c() : inst->VRegA_22c(); 3704 if (is_primitive) { 3705 VerifyPrimitivePut(*field_type, insn_type, vregA); 3706 } else { 3707 if (!insn_type.IsAssignableFrom(*field_type)) { 3708 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "expected field " << PrettyField(field) 3709 << " to be compatible with type '" << insn_type 3710 << "' but found type '" << *field_type 3711 << "' in put-object"; 3712 return; 3713 } 3714 work_line_->VerifyRegisterType(vregA, *field_type); 3715 } 3716} 3717 3718mirror::ArtField* MethodVerifier::GetQuickFieldAccess(const Instruction* inst, 3719 RegisterLine* reg_line) { 3720 DCHECK(inst->Opcode() == Instruction::IGET_QUICK || 3721 inst->Opcode() == Instruction::IGET_WIDE_QUICK || 3722 inst->Opcode() == Instruction::IGET_OBJECT_QUICK || 3723 inst->Opcode() == Instruction::IPUT_QUICK || 3724 inst->Opcode() == Instruction::IPUT_WIDE_QUICK || 3725 inst->Opcode() == Instruction::IPUT_OBJECT_QUICK); 3726 const RegType& object_type = reg_line->GetRegisterType(inst->VRegB_22c()); 3727 if (!object_type.HasClass()) { 3728 VLOG(verifier) << "Failed to get mirror::Class* from '" << object_type << "'"; 3729 return nullptr; 3730 } 3731 uint32_t field_offset = static_cast<uint32_t>(inst->VRegC_22c()); 3732 mirror::ArtField* f = mirror::ArtField::FindInstanceFieldWithOffset(object_type.GetClass(), 3733 field_offset); 3734 if (f == nullptr) { 3735 VLOG(verifier) << "Failed to find instance field at offset '" << field_offset 3736 << "' from '" << PrettyDescriptor(object_type.GetClass()) << "'"; 3737 } 3738 return f; 3739} 3740 3741void MethodVerifier::VerifyIGetQuick(const Instruction* inst, const RegType& insn_type, 3742 bool is_primitive) { 3743 DCHECK(Runtime::Current()->IsStarted()); 3744 mirror::ArtField* field = GetQuickFieldAccess(inst, work_line_.get()); 3745 if (field == NULL) { 3746 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Cannot infer field from " << inst->Name(); 3747 return; 3748 } 3749 mirror::Class* field_type_class; 3750 { 3751 StackHandleScope<1> hs(Thread::Current()); 3752 HandleWrapper<mirror::ArtField> h_field(hs.NewHandleWrapper(&field)); 3753 FieldHelper fh(h_field); 3754 field_type_class = fh.GetType(can_load_classes_); 3755 } 3756 const RegType* field_type; 3757 if (field_type_class != nullptr) { 3758 field_type = ®_types_.FromClass(field->GetTypeDescriptor(), field_type_class, 3759 field_type_class->CannotBeAssignedFromOtherTypes()); 3760 } else { 3761 Thread* self = Thread::Current(); 3762 DCHECK(!can_load_classes_ || self->IsExceptionPending()); 3763 self->ClearException(); 3764 field_type = ®_types_.FromDescriptor(field->GetDeclaringClass()->GetClassLoader(), 3765 field->GetTypeDescriptor(), false); 3766 } 3767 DCHECK(field_type != nullptr); 3768 const uint32_t vregA = inst->VRegA_22c(); 3769 if (is_primitive) { 3770 if (field_type->Equals(insn_type) || 3771 (field_type->IsFloat() && insn_type.IsIntegralTypes()) || 3772 (field_type->IsDouble() && insn_type.IsLongTypes())) { 3773 // expected that read is of the correct primitive type or that int reads are reading 3774 // floats or long reads are reading doubles 3775 } else { 3776 // This is a global failure rather than a class change failure as the instructions and 3777 // the descriptors for the type should have been consistent within the same file at 3778 // compile time 3779 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected field " << PrettyField(field) 3780 << " to be of type '" << insn_type 3781 << "' but found type '" << *field_type << "' in Get"; 3782 return; 3783 } 3784 } else { 3785 if (!insn_type.IsAssignableFrom(*field_type)) { 3786 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "expected field " << PrettyField(field) 3787 << " to be compatible with type '" << insn_type 3788 << "' but found type '" << *field_type 3789 << "' in get-object"; 3790 work_line_->SetRegisterType(vregA, reg_types_.Conflict()); 3791 return; 3792 } 3793 } 3794 if (!field_type->IsLowHalf()) { 3795 work_line_->SetRegisterType(vregA, *field_type); 3796 } else { 3797 work_line_->SetRegisterTypeWide(vregA, *field_type, field_type->HighHalf(®_types_)); 3798 } 3799} 3800 3801void MethodVerifier::VerifyIPutQuick(const Instruction* inst, const RegType& insn_type, 3802 bool is_primitive) { 3803 DCHECK(Runtime::Current()->IsStarted()); 3804 mirror::ArtField* field = GetQuickFieldAccess(inst, work_line_.get()); 3805 if (field == NULL) { 3806 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Cannot infer field from " << inst->Name(); 3807 return; 3808 } 3809 const char* descriptor = field->GetTypeDescriptor(); 3810 mirror::ClassLoader* loader = field->GetDeclaringClass()->GetClassLoader(); 3811 const RegType& field_type = reg_types_.FromDescriptor(loader, descriptor, false); 3812 if (field != NULL) { 3813 if (field->IsFinal() && field->GetDeclaringClass() != GetDeclaringClass().GetClass()) { 3814 Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot modify final field " << PrettyField(field) 3815 << " from other class " << GetDeclaringClass(); 3816 return; 3817 } 3818 } 3819 const uint32_t vregA = inst->VRegA_22c(); 3820 if (is_primitive) { 3821 // Primitive field assignability rules are weaker than regular assignability rules 3822 bool instruction_compatible; 3823 bool value_compatible; 3824 const RegType& value_type = work_line_->GetRegisterType(vregA); 3825 if (field_type.IsIntegralTypes()) { 3826 instruction_compatible = insn_type.IsIntegralTypes(); 3827 value_compatible = value_type.IsIntegralTypes(); 3828 } else if (field_type.IsFloat()) { 3829 instruction_compatible = insn_type.IsInteger(); // no [is]put-float, so expect [is]put-int 3830 value_compatible = value_type.IsFloatTypes(); 3831 } else if (field_type.IsLong()) { 3832 instruction_compatible = insn_type.IsLong(); 3833 value_compatible = value_type.IsLongTypes(); 3834 } else if (field_type.IsDouble()) { 3835 instruction_compatible = insn_type.IsLong(); // no [is]put-double, so expect [is]put-long 3836 value_compatible = value_type.IsDoubleTypes(); 3837 } else { 3838 instruction_compatible = false; // reference field with primitive store 3839 value_compatible = false; // unused 3840 } 3841 if (!instruction_compatible) { 3842 // This is a global failure rather than a class change failure as the instructions and 3843 // the descriptors for the type should have been consistent within the same file at 3844 // compile time 3845 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected field " << PrettyField(field) 3846 << " to be of type '" << insn_type 3847 << "' but found type '" << field_type 3848 << "' in put"; 3849 return; 3850 } 3851 if (!value_compatible) { 3852 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected value in v" << vregA 3853 << " of type " << value_type 3854 << " but expected " << field_type 3855 << " for store to " << PrettyField(field) << " in put"; 3856 return; 3857 } 3858 } else { 3859 if (!insn_type.IsAssignableFrom(field_type)) { 3860 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "expected field " << PrettyField(field) 3861 << " to be compatible with type '" << insn_type 3862 << "' but found type '" << field_type 3863 << "' in put-object"; 3864 return; 3865 } 3866 work_line_->VerifyRegisterType(vregA, field_type); 3867 } 3868} 3869 3870bool MethodVerifier::CheckNotMoveException(const uint16_t* insns, int insn_idx) { 3871 if ((insns[insn_idx] & 0xff) == Instruction::MOVE_EXCEPTION) { 3872 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid use of move-exception"; 3873 return false; 3874 } 3875 return true; 3876} 3877 3878bool MethodVerifier::UpdateRegisters(uint32_t next_insn, const RegisterLine* merge_line) { 3879 bool changed = true; 3880 RegisterLine* target_line = reg_table_.GetLine(next_insn); 3881 if (!insn_flags_[next_insn].IsVisitedOrChanged()) { 3882 /* 3883 * We haven't processed this instruction before, and we haven't touched the registers here, so 3884 * there's nothing to "merge". Copy the registers over and mark it as changed. (This is the 3885 * only way a register can transition out of "unknown", so this is not just an optimization.) 3886 */ 3887 if (!insn_flags_[next_insn].IsReturn()) { 3888 target_line->CopyFromLine(merge_line); 3889 } else { 3890 // Verify that the monitor stack is empty on return. 3891 if (!merge_line->VerifyMonitorStackEmpty()) { 3892 return false; 3893 } 3894 // For returns we only care about the operand to the return, all other registers are dead. 3895 // Initialize them as conflicts so they don't add to GC and deoptimization information. 3896 const Instruction* ret_inst = Instruction::At(code_item_->insns_ + next_insn); 3897 Instruction::Code opcode = ret_inst->Opcode(); 3898 if ((opcode == Instruction::RETURN_VOID) || (opcode == Instruction::RETURN_VOID_BARRIER)) { 3899 target_line->MarkAllRegistersAsConflicts(); 3900 } else { 3901 target_line->CopyFromLine(merge_line); 3902 if (opcode == Instruction::RETURN_WIDE) { 3903 target_line->MarkAllRegistersAsConflictsExceptWide(ret_inst->VRegA_11x()); 3904 } else { 3905 target_line->MarkAllRegistersAsConflictsExcept(ret_inst->VRegA_11x()); 3906 } 3907 } 3908 } 3909 } else { 3910 std::unique_ptr<RegisterLine> copy(gDebugVerify ? 3911 RegisterLine::Create(target_line->NumRegs(), this) : 3912 NULL); 3913 if (gDebugVerify) { 3914 copy->CopyFromLine(target_line); 3915 } 3916 changed = target_line->MergeRegisters(merge_line); 3917 if (have_pending_hard_failure_) { 3918 return false; 3919 } 3920 if (gDebugVerify && changed) { 3921 LogVerifyInfo() << "Merging at [" << reinterpret_cast<void*>(work_insn_idx_) << "]" 3922 << " to [" << reinterpret_cast<void*>(next_insn) << "]: " << "\n" 3923 << *copy.get() << " MERGE\n" 3924 << *merge_line << " ==\n" 3925 << *target_line << "\n"; 3926 } 3927 } 3928 if (changed) { 3929 insn_flags_[next_insn].SetChanged(); 3930 } 3931 return true; 3932} 3933 3934InstructionFlags* MethodVerifier::CurrentInsnFlags() { 3935 return &insn_flags_[work_insn_idx_]; 3936} 3937 3938const RegType& MethodVerifier::GetMethodReturnType() { 3939 if (return_type_ == nullptr) { 3940 if (mirror_method_ != NULL) { 3941 Thread* self = Thread::Current(); 3942 StackHandleScope<1> hs(self); 3943 mirror::Class* return_type_class; 3944 { 3945 HandleWrapper<mirror::ArtMethod> h_mirror_method(hs.NewHandleWrapper(&mirror_method_)); 3946 return_type_class = MethodHelper(h_mirror_method).GetReturnType(can_load_classes_); 3947 } 3948 if (return_type_class != nullptr) { 3949 return_type_ = ®_types_.FromClass(mirror_method_->GetReturnTypeDescriptor(), 3950 return_type_class, 3951 return_type_class->CannotBeAssignedFromOtherTypes()); 3952 } else { 3953 DCHECK(!can_load_classes_ || self->IsExceptionPending()); 3954 self->ClearException(); 3955 } 3956 } 3957 if (return_type_ == nullptr) { 3958 const DexFile::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx_); 3959 const DexFile::ProtoId& proto_id = dex_file_->GetMethodPrototype(method_id); 3960 uint16_t return_type_idx = proto_id.return_type_idx_; 3961 const char* descriptor = dex_file_->GetTypeDescriptor(dex_file_->GetTypeId(return_type_idx)); 3962 return_type_ = ®_types_.FromDescriptor(class_loader_->Get(), descriptor, false); 3963 } 3964 } 3965 return *return_type_; 3966} 3967 3968const RegType& MethodVerifier::GetDeclaringClass() { 3969 if (declaring_class_ == NULL) { 3970 const DexFile::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx_); 3971 const char* descriptor 3972 = dex_file_->GetTypeDescriptor(dex_file_->GetTypeId(method_id.class_idx_)); 3973 if (mirror_method_ != NULL) { 3974 mirror::Class* klass = mirror_method_->GetDeclaringClass(); 3975 declaring_class_ = ®_types_.FromClass(descriptor, klass, 3976 klass->CannotBeAssignedFromOtherTypes()); 3977 } else { 3978 declaring_class_ = ®_types_.FromDescriptor(class_loader_->Get(), descriptor, false); 3979 } 3980 } 3981 return *declaring_class_; 3982} 3983 3984std::vector<int32_t> MethodVerifier::DescribeVRegs(uint32_t dex_pc) { 3985 RegisterLine* line = reg_table_.GetLine(dex_pc); 3986 DCHECK(line != nullptr) << "No register line at DEX pc " << StringPrintf("0x%x", dex_pc); 3987 std::vector<int32_t> result; 3988 for (size_t i = 0; i < line->NumRegs(); ++i) { 3989 const RegType& type = line->GetRegisterType(i); 3990 if (type.IsConstant()) { 3991 result.push_back(type.IsPreciseConstant() ? kConstant : kImpreciseConstant); 3992 result.push_back(type.ConstantValue()); 3993 } else if (type.IsConstantLo()) { 3994 result.push_back(type.IsPreciseConstantLo() ? kConstant : kImpreciseConstant); 3995 result.push_back(type.ConstantValueLo()); 3996 } else if (type.IsConstantHi()) { 3997 result.push_back(type.IsPreciseConstantHi() ? kConstant : kImpreciseConstant); 3998 result.push_back(type.ConstantValueHi()); 3999 } else if (type.IsIntegralTypes()) { 4000 result.push_back(kIntVReg); 4001 result.push_back(0); 4002 } else if (type.IsFloat()) { 4003 result.push_back(kFloatVReg); 4004 result.push_back(0); 4005 } else if (type.IsLong()) { 4006 result.push_back(kLongLoVReg); 4007 result.push_back(0); 4008 result.push_back(kLongHiVReg); 4009 result.push_back(0); 4010 ++i; 4011 } else if (type.IsDouble()) { 4012 result.push_back(kDoubleLoVReg); 4013 result.push_back(0); 4014 result.push_back(kDoubleHiVReg); 4015 result.push_back(0); 4016 ++i; 4017 } else if (type.IsUndefined() || type.IsConflict() || type.IsHighHalf()) { 4018 result.push_back(kUndefined); 4019 result.push_back(0); 4020 } else { 4021 CHECK(type.IsNonZeroReferenceTypes()); 4022 result.push_back(kReferenceVReg); 4023 result.push_back(0); 4024 } 4025 } 4026 return result; 4027} 4028 4029const RegType& MethodVerifier::DetermineCat1Constant(int32_t value, bool precise) { 4030 if (precise) { 4031 // Precise constant type. 4032 return reg_types_.FromCat1Const(value, true); 4033 } else { 4034 // Imprecise constant type. 4035 if (value < -32768) { 4036 return reg_types_.IntConstant(); 4037 } else if (value < -128) { 4038 return reg_types_.ShortConstant(); 4039 } else if (value < 0) { 4040 return reg_types_.ByteConstant(); 4041 } else if (value == 0) { 4042 return reg_types_.Zero(); 4043 } else if (value == 1) { 4044 return reg_types_.One(); 4045 } else if (value < 128) { 4046 return reg_types_.PosByteConstant(); 4047 } else if (value < 32768) { 4048 return reg_types_.PosShortConstant(); 4049 } else if (value < 65536) { 4050 return reg_types_.CharConstant(); 4051 } else { 4052 return reg_types_.IntConstant(); 4053 } 4054 } 4055} 4056 4057void MethodVerifier::Init() { 4058 art::verifier::RegTypeCache::Init(); 4059} 4060 4061void MethodVerifier::Shutdown() { 4062 verifier::RegTypeCache::ShutDown(); 4063} 4064 4065void MethodVerifier::VisitRoots(RootCallback* callback, void* arg) { 4066 reg_types_.VisitRoots(callback, arg); 4067} 4068 4069} // namespace verifier 4070} // namespace art 4071