method_verifier.cc revision 073ed9ba97df41862403f64d7a2e824d09ab50ed
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 const RegType& lo_half = descriptor[0] == 'J' ? reg_types_.LongLo() : reg_types_.DoubleLo(); 1223 const RegType& hi_half = descriptor[0] == 'J' ? reg_types_.LongHi() : reg_types_.DoubleHi(); 1224 reg_line->SetRegisterTypeWide(arg_start + cur_arg, lo_half, hi_half); 1225 cur_arg++; 1226 break; 1227 } 1228 default: 1229 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected signature type char '" 1230 << descriptor << "'"; 1231 return false; 1232 } 1233 cur_arg++; 1234 } 1235 if (cur_arg != expected_args) { 1236 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected " << expected_args 1237 << " arguments, found " << cur_arg; 1238 return false; 1239 } 1240 const char* descriptor = dex_file_->GetReturnTypeDescriptor(proto_id); 1241 // Validate return type. We don't do the type lookup; just want to make sure that it has the right 1242 // format. Only major difference from the method argument format is that 'V' is supported. 1243 bool result; 1244 if (IsPrimitiveDescriptor(descriptor[0]) || descriptor[0] == 'V') { 1245 result = descriptor[1] == '\0'; 1246 } else if (descriptor[0] == '[') { // single/multi-dimensional array of object/primitive 1247 size_t i = 0; 1248 do { 1249 i++; 1250 } while (descriptor[i] == '['); // process leading [ 1251 if (descriptor[i] == 'L') { // object array 1252 do { 1253 i++; // find closing ; 1254 } while (descriptor[i] != ';' && descriptor[i] != '\0'); 1255 result = descriptor[i] == ';'; 1256 } else { // primitive array 1257 result = IsPrimitiveDescriptor(descriptor[i]) && descriptor[i + 1] == '\0'; 1258 } 1259 } else if (descriptor[0] == 'L') { 1260 // could be more thorough here, but shouldn't be required 1261 size_t i = 0; 1262 do { 1263 i++; 1264 } while (descriptor[i] != ';' && descriptor[i] != '\0'); 1265 result = descriptor[i] == ';'; 1266 } else { 1267 result = false; 1268 } 1269 if (!result) { 1270 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected char in return type descriptor '" 1271 << descriptor << "'"; 1272 } 1273 return result; 1274} 1275 1276bool MethodVerifier::CodeFlowVerifyMethod() { 1277 const uint16_t* insns = code_item_->insns_; 1278 const uint32_t insns_size = code_item_->insns_size_in_code_units_; 1279 1280 /* Begin by marking the first instruction as "changed". */ 1281 insn_flags_[0].SetChanged(); 1282 uint32_t start_guess = 0; 1283 1284 /* Continue until no instructions are marked "changed". */ 1285 while (true) { 1286 // Find the first marked one. Use "start_guess" as a way to find one quickly. 1287 uint32_t insn_idx = start_guess; 1288 for (; insn_idx < insns_size; insn_idx++) { 1289 if (insn_flags_[insn_idx].IsChanged()) 1290 break; 1291 } 1292 if (insn_idx == insns_size) { 1293 if (start_guess != 0) { 1294 /* try again, starting from the top */ 1295 start_guess = 0; 1296 continue; 1297 } else { 1298 /* all flags are clear */ 1299 break; 1300 } 1301 } 1302 // We carry the working set of registers from instruction to instruction. If this address can 1303 // be the target of a branch (or throw) instruction, or if we're skipping around chasing 1304 // "changed" flags, we need to load the set of registers from the table. 1305 // Because we always prefer to continue on to the next instruction, we should never have a 1306 // situation where we have a stray "changed" flag set on an instruction that isn't a branch 1307 // target. 1308 work_insn_idx_ = insn_idx; 1309 if (insn_flags_[insn_idx].IsBranchTarget()) { 1310 work_line_->CopyFromLine(reg_table_.GetLine(insn_idx)); 1311 } else { 1312#ifndef NDEBUG 1313 /* 1314 * Sanity check: retrieve the stored register line (assuming 1315 * a full table) and make sure it actually matches. 1316 */ 1317 RegisterLine* register_line = reg_table_.GetLine(insn_idx); 1318 if (register_line != NULL) { 1319 if (work_line_->CompareLine(register_line) != 0) { 1320 Dump(std::cout); 1321 std::cout << info_messages_.str(); 1322 LOG(FATAL) << "work_line diverged in " << PrettyMethod(dex_method_idx_, *dex_file_) 1323 << "@" << reinterpret_cast<void*>(work_insn_idx_) << "\n" 1324 << " work_line=" << *work_line_ << "\n" 1325 << " expected=" << *register_line; 1326 } 1327 } 1328#endif 1329 } 1330 if (!CodeFlowVerifyInstruction(&start_guess)) { 1331 std::string prepend(PrettyMethod(dex_method_idx_, *dex_file_)); 1332 prepend += " failed to verify: "; 1333 PrependToLastFailMessage(prepend); 1334 return false; 1335 } 1336 /* Clear "changed" and mark as visited. */ 1337 insn_flags_[insn_idx].SetVisited(); 1338 insn_flags_[insn_idx].ClearChanged(); 1339 } 1340 1341 if (gDebugVerify) { 1342 /* 1343 * Scan for dead code. There's nothing "evil" about dead code 1344 * (besides the wasted space), but it indicates a flaw somewhere 1345 * down the line, possibly in the verifier. 1346 * 1347 * If we've substituted "always throw" instructions into the stream, 1348 * we are almost certainly going to have some dead code. 1349 */ 1350 int dead_start = -1; 1351 uint32_t insn_idx = 0; 1352 for (; insn_idx < insns_size; insn_idx += insn_flags_[insn_idx].GetLengthInCodeUnits()) { 1353 /* 1354 * Switch-statement data doesn't get "visited" by scanner. It 1355 * may or may not be preceded by a padding NOP (for alignment). 1356 */ 1357 if (insns[insn_idx] == Instruction::kPackedSwitchSignature || 1358 insns[insn_idx] == Instruction::kSparseSwitchSignature || 1359 insns[insn_idx] == Instruction::kArrayDataSignature || 1360 (insns[insn_idx] == Instruction::NOP && (insn_idx + 1 < insns_size) && 1361 (insns[insn_idx + 1] == Instruction::kPackedSwitchSignature || 1362 insns[insn_idx + 1] == Instruction::kSparseSwitchSignature || 1363 insns[insn_idx + 1] == Instruction::kArrayDataSignature))) { 1364 insn_flags_[insn_idx].SetVisited(); 1365 } 1366 1367 if (!insn_flags_[insn_idx].IsVisited()) { 1368 if (dead_start < 0) 1369 dead_start = insn_idx; 1370 } else if (dead_start >= 0) { 1371 LogVerifyInfo() << "dead code " << reinterpret_cast<void*>(dead_start) 1372 << "-" << reinterpret_cast<void*>(insn_idx - 1); 1373 dead_start = -1; 1374 } 1375 } 1376 if (dead_start >= 0) { 1377 LogVerifyInfo() << "dead code " << reinterpret_cast<void*>(dead_start) 1378 << "-" << reinterpret_cast<void*>(insn_idx - 1); 1379 } 1380 // To dump the state of the verify after a method, do something like: 1381 // if (PrettyMethod(dex_method_idx_, *dex_file_) == 1382 // "boolean java.lang.String.equals(java.lang.Object)") { 1383 // LOG(INFO) << info_messages_.str(); 1384 // } 1385 } 1386 return true; 1387} 1388 1389bool MethodVerifier::CodeFlowVerifyInstruction(uint32_t* start_guess) { 1390 // If we're doing FindLocksAtDexPc, check whether we're at the dex pc we care about. 1391 // We want the state _before_ the instruction, for the case where the dex pc we're 1392 // interested in is itself a monitor-enter instruction (which is a likely place 1393 // for a thread to be suspended). 1394 if (monitor_enter_dex_pcs_ != NULL && work_insn_idx_ == interesting_dex_pc_) { 1395 monitor_enter_dex_pcs_->clear(); // The new work line is more accurate than the previous one. 1396 for (size_t i = 0; i < work_line_->GetMonitorEnterCount(); ++i) { 1397 monitor_enter_dex_pcs_->push_back(work_line_->GetMonitorEnterDexPc(i)); 1398 } 1399 } 1400 1401 /* 1402 * Once we finish decoding the instruction, we need to figure out where 1403 * we can go from here. There are three possible ways to transfer 1404 * control to another statement: 1405 * 1406 * (1) Continue to the next instruction. Applies to all but 1407 * unconditional branches, method returns, and exception throws. 1408 * (2) Branch to one or more possible locations. Applies to branches 1409 * and switch statements. 1410 * (3) Exception handlers. Applies to any instruction that can 1411 * throw an exception that is handled by an encompassing "try" 1412 * block. 1413 * 1414 * We can also return, in which case there is no successor instruction 1415 * from this point. 1416 * 1417 * The behavior can be determined from the opcode flags. 1418 */ 1419 const uint16_t* insns = code_item_->insns_ + work_insn_idx_; 1420 const Instruction* inst = Instruction::At(insns); 1421 int opcode_flags = Instruction::FlagsOf(inst->Opcode()); 1422 1423 int32_t branch_target = 0; 1424 bool just_set_result = false; 1425 if (gDebugVerify) { 1426 // Generate processing back trace to debug verifier 1427 LogVerifyInfo() << "Processing " << inst->DumpString(dex_file_) << "\n" 1428 << *work_line_.get() << "\n"; 1429 } 1430 1431 /* 1432 * Make a copy of the previous register state. If the instruction 1433 * can throw an exception, we will copy/merge this into the "catch" 1434 * address rather than work_line, because we don't want the result 1435 * from the "successful" code path (e.g. a check-cast that "improves" 1436 * a type) to be visible to the exception handler. 1437 */ 1438 if ((opcode_flags & Instruction::kThrow) != 0 && CurrentInsnFlags()->IsInTry()) { 1439 saved_line_->CopyFromLine(work_line_.get()); 1440 } else { 1441#ifndef NDEBUG 1442 saved_line_->FillWithGarbage(); 1443#endif 1444 } 1445 1446 1447 // We need to ensure the work line is consistent while performing validation. When we spot a 1448 // peephole pattern we compute a new line for either the fallthrough instruction or the 1449 // branch target. 1450 std::unique_ptr<RegisterLine> branch_line; 1451 std::unique_ptr<RegisterLine> fallthrough_line; 1452 1453 switch (inst->Opcode()) { 1454 case Instruction::NOP: 1455 /* 1456 * A "pure" NOP has no effect on anything. Data tables start with 1457 * a signature that looks like a NOP; if we see one of these in 1458 * the course of executing code then we have a problem. 1459 */ 1460 if (inst->VRegA_10x() != 0) { 1461 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "encountered data table in instruction stream"; 1462 } 1463 break; 1464 1465 case Instruction::MOVE: 1466 work_line_->CopyRegister1(inst->VRegA_12x(), inst->VRegB_12x(), kTypeCategory1nr); 1467 break; 1468 case Instruction::MOVE_FROM16: 1469 work_line_->CopyRegister1(inst->VRegA_22x(), inst->VRegB_22x(), kTypeCategory1nr); 1470 break; 1471 case Instruction::MOVE_16: 1472 work_line_->CopyRegister1(inst->VRegA_32x(), inst->VRegB_32x(), kTypeCategory1nr); 1473 break; 1474 case Instruction::MOVE_WIDE: 1475 work_line_->CopyRegister2(inst->VRegA_12x(), inst->VRegB_12x()); 1476 break; 1477 case Instruction::MOVE_WIDE_FROM16: 1478 work_line_->CopyRegister2(inst->VRegA_22x(), inst->VRegB_22x()); 1479 break; 1480 case Instruction::MOVE_WIDE_16: 1481 work_line_->CopyRegister2(inst->VRegA_32x(), inst->VRegB_32x()); 1482 break; 1483 case Instruction::MOVE_OBJECT: 1484 work_line_->CopyRegister1(inst->VRegA_12x(), inst->VRegB_12x(), kTypeCategoryRef); 1485 break; 1486 case Instruction::MOVE_OBJECT_FROM16: 1487 work_line_->CopyRegister1(inst->VRegA_22x(), inst->VRegB_22x(), kTypeCategoryRef); 1488 break; 1489 case Instruction::MOVE_OBJECT_16: 1490 work_line_->CopyRegister1(inst->VRegA_32x(), inst->VRegB_32x(), kTypeCategoryRef); 1491 break; 1492 1493 /* 1494 * The move-result instructions copy data out of a "pseudo-register" 1495 * with the results from the last method invocation. In practice we 1496 * might want to hold the result in an actual CPU register, so the 1497 * Dalvik spec requires that these only appear immediately after an 1498 * invoke or filled-new-array. 1499 * 1500 * These calls invalidate the "result" register. (This is now 1501 * redundant with the reset done below, but it can make the debug info 1502 * easier to read in some cases.) 1503 */ 1504 case Instruction::MOVE_RESULT: 1505 work_line_->CopyResultRegister1(inst->VRegA_11x(), false); 1506 break; 1507 case Instruction::MOVE_RESULT_WIDE: 1508 work_line_->CopyResultRegister2(inst->VRegA_11x()); 1509 break; 1510 case Instruction::MOVE_RESULT_OBJECT: 1511 work_line_->CopyResultRegister1(inst->VRegA_11x(), true); 1512 break; 1513 1514 case Instruction::MOVE_EXCEPTION: { 1515 /* 1516 * This statement can only appear as the first instruction in an exception handler. We verify 1517 * that as part of extracting the exception type from the catch block list. 1518 */ 1519 const RegType& res_type = GetCaughtExceptionType(); 1520 work_line_->SetRegisterType(inst->VRegA_11x(), res_type); 1521 break; 1522 } 1523 case Instruction::RETURN_VOID: 1524 if (!IsConstructor() || work_line_->CheckConstructorReturn()) { 1525 if (!GetMethodReturnType().IsConflict()) { 1526 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-void not expected"; 1527 } 1528 } 1529 break; 1530 case Instruction::RETURN: 1531 if (!IsConstructor() || work_line_->CheckConstructorReturn()) { 1532 /* check the method signature */ 1533 const RegType& return_type = GetMethodReturnType(); 1534 if (!return_type.IsCategory1Types()) { 1535 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected non-category 1 return type " 1536 << return_type; 1537 } else { 1538 // Compilers may generate synthetic functions that write byte values into boolean fields. 1539 // Also, it may use integer values for boolean, byte, short, and character return types. 1540 const uint32_t vregA = inst->VRegA_11x(); 1541 const RegType& src_type = work_line_->GetRegisterType(vregA); 1542 bool use_src = ((return_type.IsBoolean() && src_type.IsByte()) || 1543 ((return_type.IsBoolean() || return_type.IsByte() || 1544 return_type.IsShort() || return_type.IsChar()) && 1545 src_type.IsInteger())); 1546 /* check the register contents */ 1547 bool success = 1548 work_line_->VerifyRegisterType(vregA, use_src ? src_type : return_type); 1549 if (!success) { 1550 AppendToLastFailMessage(StringPrintf(" return-1nr on invalid register v%d", vregA)); 1551 } 1552 } 1553 } 1554 break; 1555 case Instruction::RETURN_WIDE: 1556 if (!IsConstructor() || work_line_->CheckConstructorReturn()) { 1557 /* check the method signature */ 1558 const RegType& return_type = GetMethodReturnType(); 1559 if (!return_type.IsCategory2Types()) { 1560 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-wide not expected"; 1561 } else { 1562 /* check the register contents */ 1563 const uint32_t vregA = inst->VRegA_11x(); 1564 bool success = work_line_->VerifyRegisterType(vregA, return_type); 1565 if (!success) { 1566 AppendToLastFailMessage(StringPrintf(" return-wide on invalid register v%d", vregA)); 1567 } 1568 } 1569 } 1570 break; 1571 case Instruction::RETURN_OBJECT: 1572 if (!IsConstructor() || work_line_->CheckConstructorReturn()) { 1573 const RegType& return_type = GetMethodReturnType(); 1574 if (!return_type.IsReferenceTypes()) { 1575 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-object not expected"; 1576 } else { 1577 /* return_type is the *expected* return type, not register value */ 1578 DCHECK(!return_type.IsZero()); 1579 DCHECK(!return_type.IsUninitializedReference()); 1580 const uint32_t vregA = inst->VRegA_11x(); 1581 const RegType& reg_type = work_line_->GetRegisterType(vregA); 1582 // Disallow returning uninitialized values and verify that the reference in vAA is an 1583 // instance of the "return_type" 1584 if (reg_type.IsUninitializedTypes()) { 1585 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "returning uninitialized object '" 1586 << reg_type << "'"; 1587 } else if (!return_type.IsAssignableFrom(reg_type)) { 1588 if (reg_type.IsUnresolvedTypes() || return_type.IsUnresolvedTypes()) { 1589 Fail(VERIFY_ERROR_NO_CLASS) << " can't resolve returned type '" << return_type 1590 << "' or '" << reg_type << "'"; 1591 } else { 1592 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "returning '" << reg_type 1593 << "', but expected from declaration '" << return_type << "'"; 1594 } 1595 } 1596 } 1597 } 1598 break; 1599 1600 /* could be boolean, int, float, or a null reference */ 1601 case Instruction::CONST_4: { 1602 int32_t val = static_cast<int32_t>(inst->VRegB_11n() << 28) >> 28; 1603 work_line_->SetRegisterType(inst->VRegA_11n(), 1604 DetermineCat1Constant(val, need_precise_constants_)); 1605 break; 1606 } 1607 case Instruction::CONST_16: { 1608 int16_t val = static_cast<int16_t>(inst->VRegB_21s()); 1609 work_line_->SetRegisterType(inst->VRegA_21s(), 1610 DetermineCat1Constant(val, need_precise_constants_)); 1611 break; 1612 } 1613 case Instruction::CONST: { 1614 int32_t val = inst->VRegB_31i(); 1615 work_line_->SetRegisterType(inst->VRegA_31i(), 1616 DetermineCat1Constant(val, need_precise_constants_)); 1617 break; 1618 } 1619 case Instruction::CONST_HIGH16: { 1620 int32_t val = static_cast<int32_t>(inst->VRegB_21h() << 16); 1621 work_line_->SetRegisterType(inst->VRegA_21h(), 1622 DetermineCat1Constant(val, need_precise_constants_)); 1623 break; 1624 } 1625 /* could be long or double; resolved upon use */ 1626 case Instruction::CONST_WIDE_16: { 1627 int64_t val = static_cast<int16_t>(inst->VRegB_21s()); 1628 const RegType& lo = reg_types_.FromCat2ConstLo(static_cast<int32_t>(val), true); 1629 const RegType& hi = reg_types_.FromCat2ConstHi(static_cast<int32_t>(val >> 32), true); 1630 work_line_->SetRegisterTypeWide(inst->VRegA_21s(), lo, hi); 1631 break; 1632 } 1633 case Instruction::CONST_WIDE_32: { 1634 int64_t val = static_cast<int32_t>(inst->VRegB_31i()); 1635 const RegType& lo = reg_types_.FromCat2ConstLo(static_cast<int32_t>(val), true); 1636 const RegType& hi = reg_types_.FromCat2ConstHi(static_cast<int32_t>(val >> 32), true); 1637 work_line_->SetRegisterTypeWide(inst->VRegA_31i(), lo, hi); 1638 break; 1639 } 1640 case Instruction::CONST_WIDE: { 1641 int64_t val = inst->VRegB_51l(); 1642 const RegType& lo = reg_types_.FromCat2ConstLo(static_cast<int32_t>(val), true); 1643 const RegType& hi = reg_types_.FromCat2ConstHi(static_cast<int32_t>(val >> 32), true); 1644 work_line_->SetRegisterTypeWide(inst->VRegA_51l(), lo, hi); 1645 break; 1646 } 1647 case Instruction::CONST_WIDE_HIGH16: { 1648 int64_t val = static_cast<uint64_t>(inst->VRegB_21h()) << 48; 1649 const RegType& lo = reg_types_.FromCat2ConstLo(static_cast<int32_t>(val), true); 1650 const RegType& hi = reg_types_.FromCat2ConstHi(static_cast<int32_t>(val >> 32), true); 1651 work_line_->SetRegisterTypeWide(inst->VRegA_21h(), lo, hi); 1652 break; 1653 } 1654 case Instruction::CONST_STRING: 1655 work_line_->SetRegisterType(inst->VRegA_21c(), reg_types_.JavaLangString()); 1656 break; 1657 case Instruction::CONST_STRING_JUMBO: 1658 work_line_->SetRegisterType(inst->VRegA_31c(), reg_types_.JavaLangString()); 1659 break; 1660 case Instruction::CONST_CLASS: { 1661 // Get type from instruction if unresolved then we need an access check 1662 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved 1663 const RegType& res_type = ResolveClassAndCheckAccess(inst->VRegB_21c()); 1664 // Register holds class, ie its type is class, on error it will hold Conflict. 1665 work_line_->SetRegisterType(inst->VRegA_21c(), 1666 res_type.IsConflict() ? res_type 1667 : reg_types_.JavaLangClass(true)); 1668 break; 1669 } 1670 case Instruction::MONITOR_ENTER: 1671 work_line_->PushMonitor(inst->VRegA_11x(), work_insn_idx_); 1672 break; 1673 case Instruction::MONITOR_EXIT: 1674 /* 1675 * monitor-exit instructions are odd. They can throw exceptions, 1676 * but when they do they act as if they succeeded and the PC is 1677 * pointing to the following instruction. (This behavior goes back 1678 * to the need to handle asynchronous exceptions, a now-deprecated 1679 * feature that Dalvik doesn't support.) 1680 * 1681 * In practice we don't need to worry about this. The only 1682 * exceptions that can be thrown from monitor-exit are for a 1683 * null reference and -exit without a matching -enter. If the 1684 * structured locking checks are working, the former would have 1685 * failed on the -enter instruction, and the latter is impossible. 1686 * 1687 * This is fortunate, because issue 3221411 prevents us from 1688 * chasing the "can throw" path when monitor verification is 1689 * enabled. If we can fully verify the locking we can ignore 1690 * some catch blocks (which will show up as "dead" code when 1691 * we skip them here); if we can't, then the code path could be 1692 * "live" so we still need to check it. 1693 */ 1694 opcode_flags &= ~Instruction::kThrow; 1695 work_line_->PopMonitor(inst->VRegA_11x()); 1696 break; 1697 1698 case Instruction::CHECK_CAST: 1699 case Instruction::INSTANCE_OF: { 1700 /* 1701 * If this instruction succeeds, we will "downcast" register vA to the type in vB. (This 1702 * could be a "upcast" -- not expected, so we don't try to address it.) 1703 * 1704 * If it fails, an exception is thrown, which we deal with later by ignoring the update to 1705 * dec_insn.vA when branching to a handler. 1706 */ 1707 const bool is_checkcast = (inst->Opcode() == Instruction::CHECK_CAST); 1708 const uint32_t type_idx = (is_checkcast) ? inst->VRegB_21c() : inst->VRegC_22c(); 1709 const RegType& res_type = ResolveClassAndCheckAccess(type_idx); 1710 if (res_type.IsConflict()) { 1711 DCHECK_NE(failures_.size(), 0U); 1712 if (!is_checkcast) { 1713 work_line_->SetRegisterType(inst->VRegA_22c(), reg_types_.Boolean()); 1714 } 1715 break; // bad class 1716 } 1717 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved 1718 uint32_t orig_type_reg = (is_checkcast) ? inst->VRegA_21c() : inst->VRegB_22c(); 1719 const RegType& orig_type = work_line_->GetRegisterType(orig_type_reg); 1720 if (!res_type.IsNonZeroReferenceTypes()) { 1721 if (is_checkcast) { 1722 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "check-cast on unexpected class " << res_type; 1723 } else { 1724 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "instance-of on unexpected class " << res_type; 1725 } 1726 } else if (!orig_type.IsReferenceTypes()) { 1727 if (is_checkcast) { 1728 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "check-cast on non-reference in v" << orig_type_reg; 1729 } else { 1730 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "instance-of on non-reference in v" << orig_type_reg; 1731 } 1732 } else { 1733 if (is_checkcast) { 1734 work_line_->SetRegisterType(inst->VRegA_21c(), res_type); 1735 } else { 1736 work_line_->SetRegisterType(inst->VRegA_22c(), reg_types_.Boolean()); 1737 } 1738 } 1739 break; 1740 } 1741 case Instruction::ARRAY_LENGTH: { 1742 const RegType& res_type = work_line_->GetRegisterType(inst->VRegB_12x()); 1743 if (res_type.IsReferenceTypes()) { 1744 if (!res_type.IsArrayTypes() && !res_type.IsZero()) { // ie not an array or null 1745 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array-length on non-array " << res_type; 1746 } else { 1747 work_line_->SetRegisterType(inst->VRegA_12x(), reg_types_.Integer()); 1748 } 1749 } 1750 break; 1751 } 1752 case Instruction::NEW_INSTANCE: { 1753 const RegType& res_type = ResolveClassAndCheckAccess(inst->VRegB_21c()); 1754 if (res_type.IsConflict()) { 1755 DCHECK_NE(failures_.size(), 0U); 1756 break; // bad class 1757 } 1758 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved 1759 // can't create an instance of an interface or abstract class */ 1760 if (!res_type.IsInstantiableTypes()) { 1761 Fail(VERIFY_ERROR_INSTANTIATION) 1762 << "new-instance on primitive, interface or abstract class" << res_type; 1763 // Soft failure so carry on to set register type. 1764 } 1765 const RegType& uninit_type = reg_types_.Uninitialized(res_type, work_insn_idx_); 1766 // Any registers holding previous allocations from this address that have not yet been 1767 // initialized must be marked invalid. 1768 work_line_->MarkUninitRefsAsInvalid(uninit_type); 1769 // add the new uninitialized reference to the register state 1770 work_line_->SetRegisterType(inst->VRegA_21c(), uninit_type); 1771 break; 1772 } 1773 case Instruction::NEW_ARRAY: 1774 VerifyNewArray(inst, false, false); 1775 break; 1776 case Instruction::FILLED_NEW_ARRAY: 1777 VerifyNewArray(inst, true, false); 1778 just_set_result = true; // Filled new array sets result register 1779 break; 1780 case Instruction::FILLED_NEW_ARRAY_RANGE: 1781 VerifyNewArray(inst, true, true); 1782 just_set_result = true; // Filled new array range sets result register 1783 break; 1784 case Instruction::CMPL_FLOAT: 1785 case Instruction::CMPG_FLOAT: 1786 if (!work_line_->VerifyRegisterType(inst->VRegB_23x(), reg_types_.Float())) { 1787 break; 1788 } 1789 if (!work_line_->VerifyRegisterType(inst->VRegC_23x(), reg_types_.Float())) { 1790 break; 1791 } 1792 work_line_->SetRegisterType(inst->VRegA_23x(), reg_types_.Integer()); 1793 break; 1794 case Instruction::CMPL_DOUBLE: 1795 case Instruction::CMPG_DOUBLE: 1796 if (!work_line_->VerifyRegisterTypeWide(inst->VRegB_23x(), reg_types_.DoubleLo(), 1797 reg_types_.DoubleHi())) { 1798 break; 1799 } 1800 if (!work_line_->VerifyRegisterTypeWide(inst->VRegC_23x(), reg_types_.DoubleLo(), 1801 reg_types_.DoubleHi())) { 1802 break; 1803 } 1804 work_line_->SetRegisterType(inst->VRegA_23x(), reg_types_.Integer()); 1805 break; 1806 case Instruction::CMP_LONG: 1807 if (!work_line_->VerifyRegisterTypeWide(inst->VRegB_23x(), reg_types_.LongLo(), 1808 reg_types_.LongHi())) { 1809 break; 1810 } 1811 if (!work_line_->VerifyRegisterTypeWide(inst->VRegC_23x(), reg_types_.LongLo(), 1812 reg_types_.LongHi())) { 1813 break; 1814 } 1815 work_line_->SetRegisterType(inst->VRegA_23x(), reg_types_.Integer()); 1816 break; 1817 case Instruction::THROW: { 1818 const RegType& res_type = work_line_->GetRegisterType(inst->VRegA_11x()); 1819 if (!reg_types_.JavaLangThrowable(false).IsAssignableFrom(res_type)) { 1820 Fail(res_type.IsUnresolvedTypes() ? VERIFY_ERROR_NO_CLASS : VERIFY_ERROR_BAD_CLASS_SOFT) 1821 << "thrown class " << res_type << " not instanceof Throwable"; 1822 } 1823 break; 1824 } 1825 case Instruction::GOTO: 1826 case Instruction::GOTO_16: 1827 case Instruction::GOTO_32: 1828 /* no effect on or use of registers */ 1829 break; 1830 1831 case Instruction::PACKED_SWITCH: 1832 case Instruction::SPARSE_SWITCH: 1833 /* verify that vAA is an integer, or can be converted to one */ 1834 work_line_->VerifyRegisterType(inst->VRegA_31t(), reg_types_.Integer()); 1835 break; 1836 1837 case Instruction::FILL_ARRAY_DATA: { 1838 /* Similar to the verification done for APUT */ 1839 const RegType& array_type = work_line_->GetRegisterType(inst->VRegA_31t()); 1840 /* array_type can be null if the reg type is Zero */ 1841 if (!array_type.IsZero()) { 1842 if (!array_type.IsArrayTypes()) { 1843 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid fill-array-data with array type " 1844 << array_type; 1845 } else { 1846 const RegType& component_type = reg_types_.GetComponentType(array_type, 1847 class_loader_->Get()); 1848 DCHECK(!component_type.IsConflict()); 1849 if (component_type.IsNonZeroReferenceTypes()) { 1850 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid fill-array-data with component type " 1851 << component_type; 1852 } else { 1853 // Now verify if the element width in the table matches the element width declared in 1854 // the array 1855 const uint16_t* array_data = insns + (insns[1] | (((int32_t) insns[2]) << 16)); 1856 if (array_data[0] != Instruction::kArrayDataSignature) { 1857 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid magic for array-data"; 1858 } else { 1859 size_t elem_width = Primitive::ComponentSize(component_type.GetPrimitiveType()); 1860 // Since we don't compress the data in Dex, expect to see equal width of data stored 1861 // in the table and expected from the array class. 1862 if (array_data[1] != elem_width) { 1863 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array-data size mismatch (" << array_data[1] 1864 << " vs " << elem_width << ")"; 1865 } 1866 } 1867 } 1868 } 1869 } 1870 break; 1871 } 1872 case Instruction::IF_EQ: 1873 case Instruction::IF_NE: { 1874 const RegType& reg_type1 = work_line_->GetRegisterType(inst->VRegA_22t()); 1875 const RegType& reg_type2 = work_line_->GetRegisterType(inst->VRegB_22t()); 1876 bool mismatch = false; 1877 if (reg_type1.IsZero()) { // zero then integral or reference expected 1878 mismatch = !reg_type2.IsReferenceTypes() && !reg_type2.IsIntegralTypes(); 1879 } else if (reg_type1.IsReferenceTypes()) { // both references? 1880 mismatch = !reg_type2.IsReferenceTypes(); 1881 } else { // both integral? 1882 mismatch = !reg_type1.IsIntegralTypes() || !reg_type2.IsIntegralTypes(); 1883 } 1884 if (mismatch) { 1885 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "args to if-eq/if-ne (" << reg_type1 << "," 1886 << reg_type2 << ") must both be references or integral"; 1887 } 1888 break; 1889 } 1890 case Instruction::IF_LT: 1891 case Instruction::IF_GE: 1892 case Instruction::IF_GT: 1893 case Instruction::IF_LE: { 1894 const RegType& reg_type1 = work_line_->GetRegisterType(inst->VRegA_22t()); 1895 const RegType& reg_type2 = work_line_->GetRegisterType(inst->VRegB_22t()); 1896 if (!reg_type1.IsIntegralTypes() || !reg_type2.IsIntegralTypes()) { 1897 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "args to 'if' (" << reg_type1 << "," 1898 << reg_type2 << ") must be integral"; 1899 } 1900 break; 1901 } 1902 case Instruction::IF_EQZ: 1903 case Instruction::IF_NEZ: { 1904 const RegType& reg_type = work_line_->GetRegisterType(inst->VRegA_21t()); 1905 if (!reg_type.IsReferenceTypes() && !reg_type.IsIntegralTypes()) { 1906 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "type " << reg_type 1907 << " unexpected as arg to if-eqz/if-nez"; 1908 } 1909 1910 // Find previous instruction - its existence is a precondition to peephole optimization. 1911 uint32_t instance_of_idx = 0; 1912 if (0 != work_insn_idx_) { 1913 instance_of_idx = work_insn_idx_ - 1; 1914 while (0 != instance_of_idx && !insn_flags_[instance_of_idx].IsOpcode()) { 1915 instance_of_idx--; 1916 } 1917 CHECK(insn_flags_[instance_of_idx].IsOpcode()); 1918 } else { 1919 break; 1920 } 1921 1922 const Instruction* instance_of_inst = Instruction::At(code_item_->insns_ + instance_of_idx); 1923 1924 /* Check for peep-hole pattern of: 1925 * ...; 1926 * instance-of vX, vY, T; 1927 * ifXXX vX, label ; 1928 * ...; 1929 * label: 1930 * ...; 1931 * and sharpen the type of vY to be type T. 1932 * Note, this pattern can't be if: 1933 * - if there are other branches to this branch, 1934 * - when vX == vY. 1935 */ 1936 if (!CurrentInsnFlags()->IsBranchTarget() && 1937 (Instruction::INSTANCE_OF == instance_of_inst->Opcode()) && 1938 (inst->VRegA_21t() == instance_of_inst->VRegA_22c()) && 1939 (instance_of_inst->VRegA_22c() != instance_of_inst->VRegB_22c())) { 1940 // Check that the we are not attempting conversion to interface types, 1941 // which is not done because of the multiple inheritance implications. 1942 // Also don't change the type if it would result in an upcast. 1943 const RegType& orig_type = work_line_->GetRegisterType(instance_of_inst->VRegB_22c()); 1944 const RegType& cast_type = ResolveClassAndCheckAccess(instance_of_inst->VRegC_22c()); 1945 1946 if (!cast_type.IsUnresolvedTypes() && !orig_type.IsUnresolvedTypes() && 1947 !cast_type.GetClass()->IsInterface() && !cast_type.IsAssignableFrom(orig_type)) { 1948 RegisterLine* update_line = RegisterLine::Create(code_item_->registers_size_, this); 1949 if (inst->Opcode() == Instruction::IF_EQZ) { 1950 fallthrough_line.reset(update_line); 1951 } else { 1952 branch_line.reset(update_line); 1953 } 1954 update_line->CopyFromLine(work_line_.get()); 1955 update_line->SetRegisterType(instance_of_inst->VRegB_22c(), cast_type); 1956 if (!insn_flags_[instance_of_idx].IsBranchTarget() && 0 != instance_of_idx) { 1957 // See if instance-of was preceded by a move-object operation, common due to the small 1958 // register encoding space of instance-of, and propagate type information to the source 1959 // of the move-object. 1960 uint32_t move_idx = instance_of_idx - 1; 1961 while (0 != move_idx && !insn_flags_[move_idx].IsOpcode()) { 1962 move_idx--; 1963 } 1964 CHECK(insn_flags_[move_idx].IsOpcode()); 1965 const Instruction* move_inst = Instruction::At(code_item_->insns_ + move_idx); 1966 switch (move_inst->Opcode()) { 1967 case Instruction::MOVE_OBJECT: 1968 if (move_inst->VRegA_12x() == instance_of_inst->VRegB_22c()) { 1969 update_line->SetRegisterType(move_inst->VRegB_12x(), cast_type); 1970 } 1971 break; 1972 case Instruction::MOVE_OBJECT_FROM16: 1973 if (move_inst->VRegA_22x() == instance_of_inst->VRegB_22c()) { 1974 update_line->SetRegisterType(move_inst->VRegB_22x(), cast_type); 1975 } 1976 break; 1977 case Instruction::MOVE_OBJECT_16: 1978 if (move_inst->VRegA_32x() == instance_of_inst->VRegB_22c()) { 1979 update_line->SetRegisterType(move_inst->VRegB_32x(), cast_type); 1980 } 1981 break; 1982 default: 1983 break; 1984 } 1985 } 1986 } 1987 } 1988 1989 break; 1990 } 1991 case Instruction::IF_LTZ: 1992 case Instruction::IF_GEZ: 1993 case Instruction::IF_GTZ: 1994 case Instruction::IF_LEZ: { 1995 const RegType& reg_type = work_line_->GetRegisterType(inst->VRegA_21t()); 1996 if (!reg_type.IsIntegralTypes()) { 1997 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "type " << reg_type 1998 << " unexpected as arg to if-ltz/if-gez/if-gtz/if-lez"; 1999 } 2000 break; 2001 } 2002 case Instruction::AGET_BOOLEAN: 2003 VerifyAGet(inst, reg_types_.Boolean(), true); 2004 break; 2005 case Instruction::AGET_BYTE: 2006 VerifyAGet(inst, reg_types_.Byte(), true); 2007 break; 2008 case Instruction::AGET_CHAR: 2009 VerifyAGet(inst, reg_types_.Char(), true); 2010 break; 2011 case Instruction::AGET_SHORT: 2012 VerifyAGet(inst, reg_types_.Short(), true); 2013 break; 2014 case Instruction::AGET: 2015 VerifyAGet(inst, reg_types_.Integer(), true); 2016 break; 2017 case Instruction::AGET_WIDE: 2018 VerifyAGet(inst, reg_types_.LongLo(), true); 2019 break; 2020 case Instruction::AGET_OBJECT: 2021 VerifyAGet(inst, reg_types_.JavaLangObject(false), false); 2022 break; 2023 2024 case Instruction::APUT_BOOLEAN: 2025 VerifyAPut(inst, reg_types_.Boolean(), true); 2026 break; 2027 case Instruction::APUT_BYTE: 2028 VerifyAPut(inst, reg_types_.Byte(), true); 2029 break; 2030 case Instruction::APUT_CHAR: 2031 VerifyAPut(inst, reg_types_.Char(), true); 2032 break; 2033 case Instruction::APUT_SHORT: 2034 VerifyAPut(inst, reg_types_.Short(), true); 2035 break; 2036 case Instruction::APUT: 2037 VerifyAPut(inst, reg_types_.Integer(), true); 2038 break; 2039 case Instruction::APUT_WIDE: 2040 VerifyAPut(inst, reg_types_.LongLo(), true); 2041 break; 2042 case Instruction::APUT_OBJECT: 2043 VerifyAPut(inst, reg_types_.JavaLangObject(false), false); 2044 break; 2045 2046 case Instruction::IGET_BOOLEAN: 2047 VerifyISGet(inst, reg_types_.Boolean(), true, false); 2048 break; 2049 case Instruction::IGET_BYTE: 2050 VerifyISGet(inst, reg_types_.Byte(), true, false); 2051 break; 2052 case Instruction::IGET_CHAR: 2053 VerifyISGet(inst, reg_types_.Char(), true, false); 2054 break; 2055 case Instruction::IGET_SHORT: 2056 VerifyISGet(inst, reg_types_.Short(), true, false); 2057 break; 2058 case Instruction::IGET: 2059 VerifyISGet(inst, reg_types_.Integer(), true, false); 2060 break; 2061 case Instruction::IGET_WIDE: 2062 VerifyISGet(inst, reg_types_.LongLo(), true, false); 2063 break; 2064 case Instruction::IGET_OBJECT: 2065 VerifyISGet(inst, reg_types_.JavaLangObject(false), false, false); 2066 break; 2067 2068 case Instruction::IPUT_BOOLEAN: 2069 VerifyISPut(inst, reg_types_.Boolean(), true, false); 2070 break; 2071 case Instruction::IPUT_BYTE: 2072 VerifyISPut(inst, reg_types_.Byte(), true, false); 2073 break; 2074 case Instruction::IPUT_CHAR: 2075 VerifyISPut(inst, reg_types_.Char(), true, false); 2076 break; 2077 case Instruction::IPUT_SHORT: 2078 VerifyISPut(inst, reg_types_.Short(), true, false); 2079 break; 2080 case Instruction::IPUT: 2081 VerifyISPut(inst, reg_types_.Integer(), true, false); 2082 break; 2083 case Instruction::IPUT_WIDE: 2084 VerifyISPut(inst, reg_types_.LongLo(), true, false); 2085 break; 2086 case Instruction::IPUT_OBJECT: 2087 VerifyISPut(inst, reg_types_.JavaLangObject(false), false, false); 2088 break; 2089 2090 case Instruction::SGET_BOOLEAN: 2091 VerifyISGet(inst, reg_types_.Boolean(), true, true); 2092 break; 2093 case Instruction::SGET_BYTE: 2094 VerifyISGet(inst, reg_types_.Byte(), true, true); 2095 break; 2096 case Instruction::SGET_CHAR: 2097 VerifyISGet(inst, reg_types_.Char(), true, true); 2098 break; 2099 case Instruction::SGET_SHORT: 2100 VerifyISGet(inst, reg_types_.Short(), true, true); 2101 break; 2102 case Instruction::SGET: 2103 VerifyISGet(inst, reg_types_.Integer(), true, true); 2104 break; 2105 case Instruction::SGET_WIDE: 2106 VerifyISGet(inst, reg_types_.LongLo(), true, true); 2107 break; 2108 case Instruction::SGET_OBJECT: 2109 VerifyISGet(inst, reg_types_.JavaLangObject(false), false, true); 2110 break; 2111 2112 case Instruction::SPUT_BOOLEAN: 2113 VerifyISPut(inst, reg_types_.Boolean(), true, true); 2114 break; 2115 case Instruction::SPUT_BYTE: 2116 VerifyISPut(inst, reg_types_.Byte(), true, true); 2117 break; 2118 case Instruction::SPUT_CHAR: 2119 VerifyISPut(inst, reg_types_.Char(), true, true); 2120 break; 2121 case Instruction::SPUT_SHORT: 2122 VerifyISPut(inst, reg_types_.Short(), true, true); 2123 break; 2124 case Instruction::SPUT: 2125 VerifyISPut(inst, reg_types_.Integer(), true, true); 2126 break; 2127 case Instruction::SPUT_WIDE: 2128 VerifyISPut(inst, reg_types_.LongLo(), true, true); 2129 break; 2130 case Instruction::SPUT_OBJECT: 2131 VerifyISPut(inst, reg_types_.JavaLangObject(false), false, true); 2132 break; 2133 2134 case Instruction::INVOKE_VIRTUAL: 2135 case Instruction::INVOKE_VIRTUAL_RANGE: 2136 case Instruction::INVOKE_SUPER: 2137 case Instruction::INVOKE_SUPER_RANGE: { 2138 bool is_range = (inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE || 2139 inst->Opcode() == Instruction::INVOKE_SUPER_RANGE); 2140 bool is_super = (inst->Opcode() == Instruction::INVOKE_SUPER || 2141 inst->Opcode() == Instruction::INVOKE_SUPER_RANGE); 2142 mirror::ArtMethod* called_method = VerifyInvocationArgs(inst, METHOD_VIRTUAL, is_range, 2143 is_super); 2144 const RegType* return_type = nullptr; 2145 if (called_method != nullptr) { 2146 Thread* self = Thread::Current(); 2147 StackHandleScope<1> hs(self); 2148 Handle<mirror::ArtMethod> h_called_method(hs.NewHandle(called_method)); 2149 MethodHelper mh(h_called_method); 2150 mirror::Class* return_type_class = mh.GetReturnType(can_load_classes_); 2151 if (return_type_class != nullptr) { 2152 return_type = ®_types_.FromClass(h_called_method->GetReturnTypeDescriptor(), 2153 return_type_class, 2154 return_type_class->CannotBeAssignedFromOtherTypes()); 2155 } else { 2156 DCHECK(!can_load_classes_ || self->IsExceptionPending()); 2157 self->ClearException(); 2158 } 2159 } 2160 if (return_type == nullptr) { 2161 uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); 2162 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx); 2163 uint32_t return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_; 2164 const char* descriptor = dex_file_->StringByTypeIdx(return_type_idx); 2165 return_type = ®_types_.FromDescriptor(class_loader_->Get(), descriptor, false); 2166 } 2167 if (!return_type->IsLowHalf()) { 2168 work_line_->SetResultRegisterType(*return_type); 2169 } else { 2170 work_line_->SetResultRegisterTypeWide(*return_type, return_type->HighHalf(®_types_)); 2171 } 2172 just_set_result = true; 2173 break; 2174 } 2175 case Instruction::INVOKE_DIRECT: 2176 case Instruction::INVOKE_DIRECT_RANGE: { 2177 bool is_range = (inst->Opcode() == Instruction::INVOKE_DIRECT_RANGE); 2178 mirror::ArtMethod* called_method = VerifyInvocationArgs(inst, METHOD_DIRECT, 2179 is_range, false); 2180 const char* return_type_descriptor; 2181 bool is_constructor; 2182 if (called_method == NULL) { 2183 uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); 2184 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx); 2185 is_constructor = strcmp("<init>", dex_file_->StringDataByIdx(method_id.name_idx_)) == 0; 2186 uint32_t return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_; 2187 return_type_descriptor = dex_file_->StringByTypeIdx(return_type_idx); 2188 } else { 2189 is_constructor = called_method->IsConstructor(); 2190 return_type_descriptor = called_method->GetReturnTypeDescriptor(); 2191 } 2192 if (is_constructor) { 2193 /* 2194 * Some additional checks when calling a constructor. We know from the invocation arg check 2195 * that the "this" argument is an instance of called_method->klass. Now we further restrict 2196 * that to require that called_method->klass is the same as this->klass or this->super, 2197 * allowing the latter only if the "this" argument is the same as the "this" argument to 2198 * this method (which implies that we're in a constructor ourselves). 2199 */ 2200 const RegType& this_type = work_line_->GetInvocationThis(inst, is_range); 2201 if (this_type.IsConflict()) // failure. 2202 break; 2203 2204 /* no null refs allowed (?) */ 2205 if (this_type.IsZero()) { 2206 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unable to initialize null ref"; 2207 break; 2208 } 2209 2210 /* must be in same class or in superclass */ 2211 // const RegType& this_super_klass = this_type.GetSuperClass(®_types_); 2212 // TODO: re-enable constructor type verification 2213 // if (this_super_klass.IsConflict()) { 2214 // Unknown super class, fail so we re-check at runtime. 2215 // Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "super class unknown for '" << this_type << "'"; 2216 // break; 2217 // } 2218 2219 /* arg must be an uninitialized reference */ 2220 if (!this_type.IsUninitializedTypes()) { 2221 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Expected initialization on uninitialized reference " 2222 << this_type; 2223 break; 2224 } 2225 2226 /* 2227 * Replace the uninitialized reference with an initialized one. We need to do this for all 2228 * registers that have the same object instance in them, not just the "this" register. 2229 */ 2230 work_line_->MarkRefsAsInitialized(this_type); 2231 } 2232 const RegType& return_type = reg_types_.FromDescriptor(class_loader_->Get(), 2233 return_type_descriptor, false); 2234 if (!return_type.IsLowHalf()) { 2235 work_line_->SetResultRegisterType(return_type); 2236 } else { 2237 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(®_types_)); 2238 } 2239 just_set_result = true; 2240 break; 2241 } 2242 case Instruction::INVOKE_STATIC: 2243 case Instruction::INVOKE_STATIC_RANGE: { 2244 bool is_range = (inst->Opcode() == Instruction::INVOKE_STATIC_RANGE); 2245 mirror::ArtMethod* called_method = VerifyInvocationArgs(inst, 2246 METHOD_STATIC, 2247 is_range, 2248 false); 2249 const char* descriptor; 2250 if (called_method == NULL) { 2251 uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); 2252 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx); 2253 uint32_t return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_; 2254 descriptor = dex_file_->StringByTypeIdx(return_type_idx); 2255 } else { 2256 descriptor = called_method->GetReturnTypeDescriptor(); 2257 } 2258 const RegType& return_type = reg_types_.FromDescriptor(class_loader_->Get(), descriptor, 2259 false); 2260 if (!return_type.IsLowHalf()) { 2261 work_line_->SetResultRegisterType(return_type); 2262 } else { 2263 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(®_types_)); 2264 } 2265 just_set_result = true; 2266 } 2267 break; 2268 case Instruction::INVOKE_INTERFACE: 2269 case Instruction::INVOKE_INTERFACE_RANGE: { 2270 bool is_range = (inst->Opcode() == Instruction::INVOKE_INTERFACE_RANGE); 2271 mirror::ArtMethod* abs_method = VerifyInvocationArgs(inst, 2272 METHOD_INTERFACE, 2273 is_range, 2274 false); 2275 if (abs_method != NULL) { 2276 mirror::Class* called_interface = abs_method->GetDeclaringClass(); 2277 if (!called_interface->IsInterface() && !called_interface->IsObjectClass()) { 2278 Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected interface class in invoke-interface '" 2279 << PrettyMethod(abs_method) << "'"; 2280 break; 2281 } 2282 } 2283 /* Get the type of the "this" arg, which should either be a sub-interface of called 2284 * interface or Object (see comments in RegType::JoinClass). 2285 */ 2286 const RegType& this_type = work_line_->GetInvocationThis(inst, is_range); 2287 if (this_type.IsZero()) { 2288 /* null pointer always passes (and always fails at runtime) */ 2289 } else { 2290 if (this_type.IsUninitializedTypes()) { 2291 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "interface call on uninitialized object " 2292 << this_type; 2293 break; 2294 } 2295 // In the past we have tried to assert that "called_interface" is assignable 2296 // from "this_type.GetClass()", however, as we do an imprecise Join 2297 // (RegType::JoinClass) we don't have full information on what interfaces are 2298 // implemented by "this_type". For example, two classes may implement the same 2299 // interfaces and have a common parent that doesn't implement the interface. The 2300 // join will set "this_type" to the parent class and a test that this implements 2301 // the interface will incorrectly fail. 2302 } 2303 /* 2304 * We don't have an object instance, so we can't find the concrete method. However, all of 2305 * the type information is in the abstract method, so we're good. 2306 */ 2307 const char* descriptor; 2308 if (abs_method == NULL) { 2309 uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); 2310 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx); 2311 uint32_t return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_; 2312 descriptor = dex_file_->StringByTypeIdx(return_type_idx); 2313 } else { 2314 descriptor = abs_method->GetReturnTypeDescriptor(); 2315 } 2316 const RegType& return_type = reg_types_.FromDescriptor(class_loader_->Get(), descriptor, 2317 false); 2318 if (!return_type.IsLowHalf()) { 2319 work_line_->SetResultRegisterType(return_type); 2320 } else { 2321 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(®_types_)); 2322 } 2323 just_set_result = true; 2324 break; 2325 } 2326 case Instruction::NEG_INT: 2327 case Instruction::NOT_INT: 2328 work_line_->CheckUnaryOp(inst, reg_types_.Integer(), reg_types_.Integer()); 2329 break; 2330 case Instruction::NEG_LONG: 2331 case Instruction::NOT_LONG: 2332 work_line_->CheckUnaryOpWide(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2333 reg_types_.LongLo(), reg_types_.LongHi()); 2334 break; 2335 case Instruction::NEG_FLOAT: 2336 work_line_->CheckUnaryOp(inst, reg_types_.Float(), reg_types_.Float()); 2337 break; 2338 case Instruction::NEG_DOUBLE: 2339 work_line_->CheckUnaryOpWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2340 reg_types_.DoubleLo(), reg_types_.DoubleHi()); 2341 break; 2342 case Instruction::INT_TO_LONG: 2343 work_line_->CheckUnaryOpToWide(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2344 reg_types_.Integer()); 2345 break; 2346 case Instruction::INT_TO_FLOAT: 2347 work_line_->CheckUnaryOp(inst, reg_types_.Float(), reg_types_.Integer()); 2348 break; 2349 case Instruction::INT_TO_DOUBLE: 2350 work_line_->CheckUnaryOpToWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2351 reg_types_.Integer()); 2352 break; 2353 case Instruction::LONG_TO_INT: 2354 work_line_->CheckUnaryOpFromWide(inst, reg_types_.Integer(), 2355 reg_types_.LongLo(), reg_types_.LongHi()); 2356 break; 2357 case Instruction::LONG_TO_FLOAT: 2358 work_line_->CheckUnaryOpFromWide(inst, reg_types_.Float(), 2359 reg_types_.LongLo(), reg_types_.LongHi()); 2360 break; 2361 case Instruction::LONG_TO_DOUBLE: 2362 work_line_->CheckUnaryOpWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2363 reg_types_.LongLo(), reg_types_.LongHi()); 2364 break; 2365 case Instruction::FLOAT_TO_INT: 2366 work_line_->CheckUnaryOp(inst, reg_types_.Integer(), reg_types_.Float()); 2367 break; 2368 case Instruction::FLOAT_TO_LONG: 2369 work_line_->CheckUnaryOpToWide(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2370 reg_types_.Float()); 2371 break; 2372 case Instruction::FLOAT_TO_DOUBLE: 2373 work_line_->CheckUnaryOpToWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2374 reg_types_.Float()); 2375 break; 2376 case Instruction::DOUBLE_TO_INT: 2377 work_line_->CheckUnaryOpFromWide(inst, reg_types_.Integer(), 2378 reg_types_.DoubleLo(), reg_types_.DoubleHi()); 2379 break; 2380 case Instruction::DOUBLE_TO_LONG: 2381 work_line_->CheckUnaryOpWide(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2382 reg_types_.DoubleLo(), reg_types_.DoubleHi()); 2383 break; 2384 case Instruction::DOUBLE_TO_FLOAT: 2385 work_line_->CheckUnaryOpFromWide(inst, reg_types_.Float(), 2386 reg_types_.DoubleLo(), reg_types_.DoubleHi()); 2387 break; 2388 case Instruction::INT_TO_BYTE: 2389 work_line_->CheckUnaryOp(inst, reg_types_.Byte(), reg_types_.Integer()); 2390 break; 2391 case Instruction::INT_TO_CHAR: 2392 work_line_->CheckUnaryOp(inst, reg_types_.Char(), reg_types_.Integer()); 2393 break; 2394 case Instruction::INT_TO_SHORT: 2395 work_line_->CheckUnaryOp(inst, reg_types_.Short(), reg_types_.Integer()); 2396 break; 2397 2398 case Instruction::ADD_INT: 2399 case Instruction::SUB_INT: 2400 case Instruction::MUL_INT: 2401 case Instruction::REM_INT: 2402 case Instruction::DIV_INT: 2403 case Instruction::SHL_INT: 2404 case Instruction::SHR_INT: 2405 case Instruction::USHR_INT: 2406 work_line_->CheckBinaryOp(inst, reg_types_.Integer(), reg_types_.Integer(), 2407 reg_types_.Integer(), false); 2408 break; 2409 case Instruction::AND_INT: 2410 case Instruction::OR_INT: 2411 case Instruction::XOR_INT: 2412 work_line_->CheckBinaryOp(inst, reg_types_.Integer(), reg_types_.Integer(), 2413 reg_types_.Integer(), true); 2414 break; 2415 case Instruction::ADD_LONG: 2416 case Instruction::SUB_LONG: 2417 case Instruction::MUL_LONG: 2418 case Instruction::DIV_LONG: 2419 case Instruction::REM_LONG: 2420 case Instruction::AND_LONG: 2421 case Instruction::OR_LONG: 2422 case Instruction::XOR_LONG: 2423 work_line_->CheckBinaryOpWide(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2424 reg_types_.LongLo(), reg_types_.LongHi(), 2425 reg_types_.LongLo(), reg_types_.LongHi()); 2426 break; 2427 case Instruction::SHL_LONG: 2428 case Instruction::SHR_LONG: 2429 case Instruction::USHR_LONG: 2430 /* shift distance is Int, making these different from other binary operations */ 2431 work_line_->CheckBinaryOpWideShift(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2432 reg_types_.Integer()); 2433 break; 2434 case Instruction::ADD_FLOAT: 2435 case Instruction::SUB_FLOAT: 2436 case Instruction::MUL_FLOAT: 2437 case Instruction::DIV_FLOAT: 2438 case Instruction::REM_FLOAT: 2439 work_line_->CheckBinaryOp(inst, 2440 reg_types_.Float(), 2441 reg_types_.Float(), 2442 reg_types_.Float(), 2443 false); 2444 break; 2445 case Instruction::ADD_DOUBLE: 2446 case Instruction::SUB_DOUBLE: 2447 case Instruction::MUL_DOUBLE: 2448 case Instruction::DIV_DOUBLE: 2449 case Instruction::REM_DOUBLE: 2450 work_line_->CheckBinaryOpWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2451 reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2452 reg_types_.DoubleLo(), reg_types_.DoubleHi()); 2453 break; 2454 case Instruction::ADD_INT_2ADDR: 2455 case Instruction::SUB_INT_2ADDR: 2456 case Instruction::MUL_INT_2ADDR: 2457 case Instruction::REM_INT_2ADDR: 2458 case Instruction::SHL_INT_2ADDR: 2459 case Instruction::SHR_INT_2ADDR: 2460 case Instruction::USHR_INT_2ADDR: 2461 work_line_->CheckBinaryOp2addr(inst, 2462 reg_types_.Integer(), 2463 reg_types_.Integer(), 2464 reg_types_.Integer(), 2465 false); 2466 break; 2467 case Instruction::AND_INT_2ADDR: 2468 case Instruction::OR_INT_2ADDR: 2469 case Instruction::XOR_INT_2ADDR: 2470 work_line_->CheckBinaryOp2addr(inst, 2471 reg_types_.Integer(), 2472 reg_types_.Integer(), 2473 reg_types_.Integer(), 2474 true); 2475 break; 2476 case Instruction::DIV_INT_2ADDR: 2477 work_line_->CheckBinaryOp2addr(inst, 2478 reg_types_.Integer(), 2479 reg_types_.Integer(), 2480 reg_types_.Integer(), 2481 false); 2482 break; 2483 case Instruction::ADD_LONG_2ADDR: 2484 case Instruction::SUB_LONG_2ADDR: 2485 case Instruction::MUL_LONG_2ADDR: 2486 case Instruction::DIV_LONG_2ADDR: 2487 case Instruction::REM_LONG_2ADDR: 2488 case Instruction::AND_LONG_2ADDR: 2489 case Instruction::OR_LONG_2ADDR: 2490 case Instruction::XOR_LONG_2ADDR: 2491 work_line_->CheckBinaryOp2addrWide(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2492 reg_types_.LongLo(), reg_types_.LongHi(), 2493 reg_types_.LongLo(), reg_types_.LongHi()); 2494 break; 2495 case Instruction::SHL_LONG_2ADDR: 2496 case Instruction::SHR_LONG_2ADDR: 2497 case Instruction::USHR_LONG_2ADDR: 2498 work_line_->CheckBinaryOp2addrWideShift(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2499 reg_types_.Integer()); 2500 break; 2501 case Instruction::ADD_FLOAT_2ADDR: 2502 case Instruction::SUB_FLOAT_2ADDR: 2503 case Instruction::MUL_FLOAT_2ADDR: 2504 case Instruction::DIV_FLOAT_2ADDR: 2505 case Instruction::REM_FLOAT_2ADDR: 2506 work_line_->CheckBinaryOp2addr(inst, 2507 reg_types_.Float(), 2508 reg_types_.Float(), 2509 reg_types_.Float(), 2510 false); 2511 break; 2512 case Instruction::ADD_DOUBLE_2ADDR: 2513 case Instruction::SUB_DOUBLE_2ADDR: 2514 case Instruction::MUL_DOUBLE_2ADDR: 2515 case Instruction::DIV_DOUBLE_2ADDR: 2516 case Instruction::REM_DOUBLE_2ADDR: 2517 work_line_->CheckBinaryOp2addrWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2518 reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2519 reg_types_.DoubleLo(), reg_types_.DoubleHi()); 2520 break; 2521 case Instruction::ADD_INT_LIT16: 2522 case Instruction::RSUB_INT: 2523 case Instruction::MUL_INT_LIT16: 2524 case Instruction::DIV_INT_LIT16: 2525 case Instruction::REM_INT_LIT16: 2526 work_line_->CheckLiteralOp(inst, reg_types_.Integer(), reg_types_.Integer(), false, true); 2527 break; 2528 case Instruction::AND_INT_LIT16: 2529 case Instruction::OR_INT_LIT16: 2530 case Instruction::XOR_INT_LIT16: 2531 work_line_->CheckLiteralOp(inst, reg_types_.Integer(), reg_types_.Integer(), true, true); 2532 break; 2533 case Instruction::ADD_INT_LIT8: 2534 case Instruction::RSUB_INT_LIT8: 2535 case Instruction::MUL_INT_LIT8: 2536 case Instruction::DIV_INT_LIT8: 2537 case Instruction::REM_INT_LIT8: 2538 case Instruction::SHL_INT_LIT8: 2539 case Instruction::SHR_INT_LIT8: 2540 case Instruction::USHR_INT_LIT8: 2541 work_line_->CheckLiteralOp(inst, reg_types_.Integer(), reg_types_.Integer(), false, false); 2542 break; 2543 case Instruction::AND_INT_LIT8: 2544 case Instruction::OR_INT_LIT8: 2545 case Instruction::XOR_INT_LIT8: 2546 work_line_->CheckLiteralOp(inst, reg_types_.Integer(), reg_types_.Integer(), true, false); 2547 break; 2548 2549 // Special instructions. 2550 case Instruction::RETURN_VOID_BARRIER: 2551 if (!IsConstructor() || IsStatic()) { 2552 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-void-barrier not expected"; 2553 } 2554 break; 2555 // Note: the following instructions encode offsets derived from class linking. 2556 // As such they use Class*/Field*/AbstractMethod* as these offsets only have 2557 // meaning if the class linking and resolution were successful. 2558 case Instruction::IGET_QUICK: 2559 VerifyIGetQuick(inst, reg_types_.Integer(), true); 2560 break; 2561 case Instruction::IGET_WIDE_QUICK: 2562 VerifyIGetQuick(inst, reg_types_.LongLo(), true); 2563 break; 2564 case Instruction::IGET_OBJECT_QUICK: 2565 VerifyIGetQuick(inst, reg_types_.JavaLangObject(false), false); 2566 break; 2567 case Instruction::IPUT_QUICK: 2568 VerifyIPutQuick(inst, reg_types_.Integer(), true); 2569 break; 2570 case Instruction::IPUT_WIDE_QUICK: 2571 VerifyIPutQuick(inst, reg_types_.LongLo(), true); 2572 break; 2573 case Instruction::IPUT_OBJECT_QUICK: 2574 VerifyIPutQuick(inst, reg_types_.JavaLangObject(false), false); 2575 break; 2576 case Instruction::INVOKE_VIRTUAL_QUICK: 2577 case Instruction::INVOKE_VIRTUAL_RANGE_QUICK: { 2578 bool is_range = (inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE_QUICK); 2579 mirror::ArtMethod* called_method = VerifyInvokeVirtualQuickArgs(inst, is_range); 2580 if (called_method != NULL) { 2581 const char* descriptor = called_method->GetReturnTypeDescriptor(); 2582 const RegType& return_type = reg_types_.FromDescriptor(class_loader_->Get(), descriptor, 2583 false); 2584 if (!return_type.IsLowHalf()) { 2585 work_line_->SetResultRegisterType(return_type); 2586 } else { 2587 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(®_types_)); 2588 } 2589 just_set_result = true; 2590 } 2591 break; 2592 } 2593 2594 /* These should never appear during verification. */ 2595 case Instruction::UNUSED_3E: 2596 case Instruction::UNUSED_3F: 2597 case Instruction::UNUSED_40: 2598 case Instruction::UNUSED_41: 2599 case Instruction::UNUSED_42: 2600 case Instruction::UNUSED_43: 2601 case Instruction::UNUSED_79: 2602 case Instruction::UNUSED_7A: 2603 case Instruction::UNUSED_EB: 2604 case Instruction::UNUSED_EC: 2605 case Instruction::UNUSED_ED: 2606 case Instruction::UNUSED_EE: 2607 case Instruction::UNUSED_EF: 2608 case Instruction::UNUSED_F0: 2609 case Instruction::UNUSED_F1: 2610 case Instruction::UNUSED_F2: 2611 case Instruction::UNUSED_F3: 2612 case Instruction::UNUSED_F4: 2613 case Instruction::UNUSED_F5: 2614 case Instruction::UNUSED_F6: 2615 case Instruction::UNUSED_F7: 2616 case Instruction::UNUSED_F8: 2617 case Instruction::UNUSED_F9: 2618 case Instruction::UNUSED_FA: 2619 case Instruction::UNUSED_FB: 2620 case Instruction::UNUSED_FC: 2621 case Instruction::UNUSED_FD: 2622 case Instruction::UNUSED_FE: 2623 case Instruction::UNUSED_FF: 2624 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Unexpected opcode " << inst->DumpString(dex_file_); 2625 break; 2626 2627 /* 2628 * DO NOT add a "default" clause here. Without it the compiler will 2629 * complain if an instruction is missing (which is desirable). 2630 */ 2631 } // end - switch (dec_insn.opcode) 2632 2633 if (have_pending_hard_failure_) { 2634 if (Runtime::Current()->IsCompiler()) { 2635 /* When compiling, check that the last failure is a hard failure */ 2636 CHECK_EQ(failures_[failures_.size() - 1], VERIFY_ERROR_BAD_CLASS_HARD); 2637 } 2638 /* immediate failure, reject class */ 2639 info_messages_ << "Rejecting opcode " << inst->DumpString(dex_file_); 2640 return false; 2641 } else if (have_pending_runtime_throw_failure_) { 2642 /* checking interpreter will throw, mark following code as unreachable */ 2643 opcode_flags = Instruction::kThrow; 2644 } 2645 /* 2646 * If we didn't just set the result register, clear it out. This ensures that you can only use 2647 * "move-result" immediately after the result is set. (We could check this statically, but it's 2648 * not expensive and it makes our debugging output cleaner.) 2649 */ 2650 if (!just_set_result) { 2651 work_line_->SetResultTypeToUnknown(); 2652 } 2653 2654 2655 2656 /* 2657 * Handle "branch". Tag the branch target. 2658 * 2659 * NOTE: instructions like Instruction::EQZ provide information about the 2660 * state of the register when the branch is taken or not taken. For example, 2661 * somebody could get a reference field, check it for zero, and if the 2662 * branch is taken immediately store that register in a boolean field 2663 * since the value is known to be zero. We do not currently account for 2664 * that, and will reject the code. 2665 * 2666 * TODO: avoid re-fetching the branch target 2667 */ 2668 if ((opcode_flags & Instruction::kBranch) != 0) { 2669 bool isConditional, selfOkay; 2670 if (!GetBranchOffset(work_insn_idx_, &branch_target, &isConditional, &selfOkay)) { 2671 /* should never happen after static verification */ 2672 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad branch"; 2673 return false; 2674 } 2675 DCHECK_EQ(isConditional, (opcode_flags & Instruction::kContinue) != 0); 2676 if (!CheckNotMoveException(code_item_->insns_, work_insn_idx_ + branch_target)) { 2677 return false; 2678 } 2679 /* update branch target, set "changed" if appropriate */ 2680 if (NULL != branch_line.get()) { 2681 if (!UpdateRegisters(work_insn_idx_ + branch_target, branch_line.get())) { 2682 return false; 2683 } 2684 } else { 2685 if (!UpdateRegisters(work_insn_idx_ + branch_target, work_line_.get())) { 2686 return false; 2687 } 2688 } 2689 } 2690 2691 /* 2692 * Handle "switch". Tag all possible branch targets. 2693 * 2694 * We've already verified that the table is structurally sound, so we 2695 * just need to walk through and tag the targets. 2696 */ 2697 if ((opcode_flags & Instruction::kSwitch) != 0) { 2698 int offset_to_switch = insns[1] | (((int32_t) insns[2]) << 16); 2699 const uint16_t* switch_insns = insns + offset_to_switch; 2700 int switch_count = switch_insns[1]; 2701 int offset_to_targets, targ; 2702 2703 if ((*insns & 0xff) == Instruction::PACKED_SWITCH) { 2704 /* 0 = sig, 1 = count, 2/3 = first key */ 2705 offset_to_targets = 4; 2706 } else { 2707 /* 0 = sig, 1 = count, 2..count * 2 = keys */ 2708 DCHECK((*insns & 0xff) == Instruction::SPARSE_SWITCH); 2709 offset_to_targets = 2 + 2 * switch_count; 2710 } 2711 2712 /* verify each switch target */ 2713 for (targ = 0; targ < switch_count; targ++) { 2714 int offset; 2715 uint32_t abs_offset; 2716 2717 /* offsets are 32-bit, and only partly endian-swapped */ 2718 offset = switch_insns[offset_to_targets + targ * 2] | 2719 (((int32_t) switch_insns[offset_to_targets + targ * 2 + 1]) << 16); 2720 abs_offset = work_insn_idx_ + offset; 2721 DCHECK_LT(abs_offset, code_item_->insns_size_in_code_units_); 2722 if (!CheckNotMoveException(code_item_->insns_, abs_offset)) { 2723 return false; 2724 } 2725 if (!UpdateRegisters(abs_offset, work_line_.get())) 2726 return false; 2727 } 2728 } 2729 2730 /* 2731 * Handle instructions that can throw and that are sitting in a "try" block. (If they're not in a 2732 * "try" block when they throw, control transfers out of the method.) 2733 */ 2734 if ((opcode_flags & Instruction::kThrow) != 0 && insn_flags_[work_insn_idx_].IsInTry()) { 2735 bool within_catch_all = false; 2736 CatchHandlerIterator iterator(*code_item_, work_insn_idx_); 2737 2738 for (; iterator.HasNext(); iterator.Next()) { 2739 if (iterator.GetHandlerTypeIndex() == DexFile::kDexNoIndex16) { 2740 within_catch_all = true; 2741 } 2742 /* 2743 * Merge registers into the "catch" block. We want to use the "savedRegs" rather than 2744 * "work_regs", because at runtime the exception will be thrown before the instruction 2745 * modifies any registers. 2746 */ 2747 if (!UpdateRegisters(iterator.GetHandlerAddress(), saved_line_.get())) { 2748 return false; 2749 } 2750 } 2751 2752 /* 2753 * If the monitor stack depth is nonzero, there must be a "catch all" handler for this 2754 * instruction. This does apply to monitor-exit because of async exception handling. 2755 */ 2756 if (work_line_->MonitorStackDepth() > 0 && !within_catch_all) { 2757 /* 2758 * The state in work_line reflects the post-execution state. If the current instruction is a 2759 * monitor-enter and the monitor stack was empty, we don't need a catch-all (if it throws, 2760 * it will do so before grabbing the lock). 2761 */ 2762 if (inst->Opcode() != Instruction::MONITOR_ENTER || work_line_->MonitorStackDepth() != 1) { 2763 Fail(VERIFY_ERROR_BAD_CLASS_HARD) 2764 << "expected to be within a catch-all for an instruction where a monitor is held"; 2765 return false; 2766 } 2767 } 2768 } 2769 2770 /* Handle "continue". Tag the next consecutive instruction. 2771 * Note: Keep the code handling "continue" case below the "branch" and "switch" cases, 2772 * because it changes work_line_ when performing peephole optimization 2773 * and this change should not be used in those cases. 2774 */ 2775 if ((opcode_flags & Instruction::kContinue) != 0) { 2776 uint32_t next_insn_idx = work_insn_idx_ + CurrentInsnFlags()->GetLengthInCodeUnits(); 2777 if (next_insn_idx >= code_item_->insns_size_in_code_units_) { 2778 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Execution can walk off end of code area"; 2779 return false; 2780 } 2781 // The only way to get to a move-exception instruction is to get thrown there. Make sure the 2782 // next instruction isn't one. 2783 if (!CheckNotMoveException(code_item_->insns_, next_insn_idx)) { 2784 return false; 2785 } 2786 if (NULL != fallthrough_line.get()) { 2787 // Make workline consistent with fallthrough computed from peephole optimization. 2788 work_line_->CopyFromLine(fallthrough_line.get()); 2789 } 2790 if (insn_flags_[next_insn_idx].IsReturn()) { 2791 // For returns we only care about the operand to the return, all other registers are dead. 2792 const Instruction* ret_inst = Instruction::At(code_item_->insns_ + next_insn_idx); 2793 Instruction::Code opcode = ret_inst->Opcode(); 2794 if ((opcode == Instruction::RETURN_VOID) || (opcode == Instruction::RETURN_VOID_BARRIER)) { 2795 work_line_->MarkAllRegistersAsConflicts(); 2796 } else { 2797 if (opcode == Instruction::RETURN_WIDE) { 2798 work_line_->MarkAllRegistersAsConflictsExceptWide(ret_inst->VRegA_11x()); 2799 } else { 2800 work_line_->MarkAllRegistersAsConflictsExcept(ret_inst->VRegA_11x()); 2801 } 2802 } 2803 } 2804 RegisterLine* next_line = reg_table_.GetLine(next_insn_idx); 2805 if (next_line != NULL) { 2806 // Merge registers into what we have for the next instruction, 2807 // and set the "changed" flag if needed. 2808 if (!UpdateRegisters(next_insn_idx, work_line_.get())) { 2809 return false; 2810 } 2811 } else { 2812 /* 2813 * We're not recording register data for the next instruction, so we don't know what the 2814 * prior state was. We have to assume that something has changed and re-evaluate it. 2815 */ 2816 insn_flags_[next_insn_idx].SetChanged(); 2817 } 2818 } 2819 2820 /* If we're returning from the method, make sure monitor stack is empty. */ 2821 if ((opcode_flags & Instruction::kReturn) != 0) { 2822 if (!work_line_->VerifyMonitorStackEmpty()) { 2823 return false; 2824 } 2825 } 2826 2827 /* 2828 * Update start_guess. Advance to the next instruction of that's 2829 * possible, otherwise use the branch target if one was found. If 2830 * neither of those exists we're in a return or throw; leave start_guess 2831 * alone and let the caller sort it out. 2832 */ 2833 if ((opcode_flags & Instruction::kContinue) != 0) { 2834 *start_guess = work_insn_idx_ + insn_flags_[work_insn_idx_].GetLengthInCodeUnits(); 2835 } else if ((opcode_flags & Instruction::kBranch) != 0) { 2836 /* we're still okay if branch_target is zero */ 2837 *start_guess = work_insn_idx_ + branch_target; 2838 } 2839 2840 DCHECK_LT(*start_guess, code_item_->insns_size_in_code_units_); 2841 DCHECK(insn_flags_[*start_guess].IsOpcode()); 2842 2843 return true; 2844} // NOLINT(readability/fn_size) 2845 2846const RegType& MethodVerifier::ResolveClassAndCheckAccess(uint32_t class_idx) { 2847 const char* descriptor = dex_file_->StringByTypeIdx(class_idx); 2848 const RegType& referrer = GetDeclaringClass(); 2849 mirror::Class* klass = (*dex_cache_)->GetResolvedType(class_idx); 2850 const RegType& result = 2851 klass != NULL ? reg_types_.FromClass(descriptor, klass, 2852 klass->CannotBeAssignedFromOtherTypes()) 2853 : reg_types_.FromDescriptor(class_loader_->Get(), descriptor, false); 2854 if (result.IsConflict()) { 2855 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "accessing broken descriptor '" << descriptor 2856 << "' in " << referrer; 2857 return result; 2858 } 2859 if (klass == NULL && !result.IsUnresolvedTypes()) { 2860 (*dex_cache_)->SetResolvedType(class_idx, result.GetClass()); 2861 } 2862 // Check if access is allowed. Unresolved types use xxxWithAccessCheck to 2863 // check at runtime if access is allowed and so pass here. If result is 2864 // primitive, skip the access check. 2865 if (result.IsNonZeroReferenceTypes() && !result.IsUnresolvedTypes() && 2866 !referrer.IsUnresolvedTypes() && !referrer.CanAccess(result)) { 2867 Fail(VERIFY_ERROR_ACCESS_CLASS) << "illegal class access: '" 2868 << referrer << "' -> '" << result << "'"; 2869 } 2870 return result; 2871} 2872 2873const RegType& MethodVerifier::GetCaughtExceptionType() { 2874 const RegType* common_super = NULL; 2875 if (code_item_->tries_size_ != 0) { 2876 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item_, 0); 2877 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr); 2878 for (uint32_t i = 0; i < handlers_size; i++) { 2879 CatchHandlerIterator iterator(handlers_ptr); 2880 for (; iterator.HasNext(); iterator.Next()) { 2881 if (iterator.GetHandlerAddress() == (uint32_t) work_insn_idx_) { 2882 if (iterator.GetHandlerTypeIndex() == DexFile::kDexNoIndex16) { 2883 common_super = ®_types_.JavaLangThrowable(false); 2884 } else { 2885 const RegType& exception = ResolveClassAndCheckAccess(iterator.GetHandlerTypeIndex()); 2886 if (!reg_types_.JavaLangThrowable(false).IsAssignableFrom(exception)) { 2887 if (exception.IsUnresolvedTypes()) { 2888 // We don't know enough about the type. Fail here and let runtime handle it. 2889 Fail(VERIFY_ERROR_NO_CLASS) << "unresolved exception class " << exception; 2890 return exception; 2891 } else { 2892 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "unexpected non-exception class " << exception; 2893 return reg_types_.Conflict(); 2894 } 2895 } else if (common_super == nullptr) { 2896 common_super = &exception; 2897 } else if (common_super->Equals(exception)) { 2898 // odd case, but nothing to do 2899 } else { 2900 common_super = &common_super->Merge(exception, ®_types_); 2901 CHECK(reg_types_.JavaLangThrowable(false).IsAssignableFrom(*common_super)); 2902 } 2903 } 2904 } 2905 } 2906 handlers_ptr = iterator.EndDataPointer(); 2907 } 2908 } 2909 if (common_super == NULL) { 2910 /* no catch blocks, or no catches with classes we can find */ 2911 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "unable to find exception handler"; 2912 return reg_types_.Conflict(); 2913 } 2914 return *common_super; 2915} 2916 2917mirror::ArtMethod* MethodVerifier::ResolveMethodAndCheckAccess(uint32_t dex_method_idx, 2918 MethodType method_type) { 2919 const DexFile::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx); 2920 const RegType& klass_type = ResolveClassAndCheckAccess(method_id.class_idx_); 2921 if (klass_type.IsConflict()) { 2922 std::string append(" in attempt to access method "); 2923 append += dex_file_->GetMethodName(method_id); 2924 AppendToLastFailMessage(append); 2925 return NULL; 2926 } 2927 if (klass_type.IsUnresolvedTypes()) { 2928 return NULL; // Can't resolve Class so no more to do here 2929 } 2930 mirror::Class* klass = klass_type.GetClass(); 2931 const RegType& referrer = GetDeclaringClass(); 2932 mirror::ArtMethod* res_method = (*dex_cache_)->GetResolvedMethod(dex_method_idx); 2933 if (res_method == NULL) { 2934 const char* name = dex_file_->GetMethodName(method_id); 2935 const Signature signature = dex_file_->GetMethodSignature(method_id); 2936 2937 if (method_type == METHOD_DIRECT || method_type == METHOD_STATIC) { 2938 res_method = klass->FindDirectMethod(name, signature); 2939 } else if (method_type == METHOD_INTERFACE) { 2940 res_method = klass->FindInterfaceMethod(name, signature); 2941 } else { 2942 res_method = klass->FindVirtualMethod(name, signature); 2943 } 2944 if (res_method != NULL) { 2945 (*dex_cache_)->SetResolvedMethod(dex_method_idx, res_method); 2946 } else { 2947 // If a virtual or interface method wasn't found with the expected type, look in 2948 // the direct methods. This can happen when the wrong invoke type is used or when 2949 // a class has changed, and will be flagged as an error in later checks. 2950 if (method_type == METHOD_INTERFACE || method_type == METHOD_VIRTUAL) { 2951 res_method = klass->FindDirectMethod(name, signature); 2952 } 2953 if (res_method == NULL) { 2954 Fail(VERIFY_ERROR_NO_METHOD) << "couldn't find method " 2955 << PrettyDescriptor(klass) << "." << name 2956 << " " << signature; 2957 return NULL; 2958 } 2959 } 2960 } 2961 // Make sure calls to constructors are "direct". There are additional restrictions but we don't 2962 // enforce them here. 2963 if (res_method->IsConstructor() && method_type != METHOD_DIRECT) { 2964 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "rejecting non-direct call to constructor " 2965 << PrettyMethod(res_method); 2966 return NULL; 2967 } 2968 // Disallow any calls to class initializers. 2969 if (res_method->IsClassInitializer()) { 2970 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "rejecting call to class initializer " 2971 << PrettyMethod(res_method); 2972 return NULL; 2973 } 2974 // Check if access is allowed. 2975 if (!referrer.CanAccessMember(res_method->GetDeclaringClass(), res_method->GetAccessFlags())) { 2976 Fail(VERIFY_ERROR_ACCESS_METHOD) << "illegal method access (call " << PrettyMethod(res_method) 2977 << " from " << referrer << ")"; 2978 return res_method; 2979 } 2980 // Check that invoke-virtual and invoke-super are not used on private methods of the same class. 2981 if (res_method->IsPrivate() && method_type == METHOD_VIRTUAL) { 2982 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invoke-super/virtual can't be used on private method " 2983 << PrettyMethod(res_method); 2984 return NULL; 2985 } 2986 // Check that interface methods match interface classes. 2987 if (klass->IsInterface() && method_type != METHOD_INTERFACE) { 2988 Fail(VERIFY_ERROR_CLASS_CHANGE) << "non-interface method " << PrettyMethod(res_method) 2989 << " is in an interface class " << PrettyClass(klass); 2990 return NULL; 2991 } else if (!klass->IsInterface() && method_type == METHOD_INTERFACE) { 2992 Fail(VERIFY_ERROR_CLASS_CHANGE) << "interface method " << PrettyMethod(res_method) 2993 << " is in a non-interface class " << PrettyClass(klass); 2994 return NULL; 2995 } 2996 // See if the method type implied by the invoke instruction matches the access flags for the 2997 // target method. 2998 if ((method_type == METHOD_DIRECT && !res_method->IsDirect()) || 2999 (method_type == METHOD_STATIC && !res_method->IsStatic()) || 3000 ((method_type == METHOD_VIRTUAL || method_type == METHOD_INTERFACE) && res_method->IsDirect()) 3001 ) { 3002 Fail(VERIFY_ERROR_CLASS_CHANGE) << "invoke type (" << method_type << ") does not match method " 3003 " type of " << PrettyMethod(res_method); 3004 return NULL; 3005 } 3006 return res_method; 3007} 3008 3009mirror::ArtMethod* MethodVerifier::VerifyInvocationArgs(const Instruction* inst, 3010 MethodType method_type, 3011 bool is_range, 3012 bool is_super) { 3013 // Resolve the method. This could be an abstract or concrete method depending on what sort of call 3014 // we're making. 3015 const uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); 3016 3017 // As the method may not have been resolved, make this static check against what we expect. 3018 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx); 3019 uint32_t shorty_idx = dex_file_->GetProtoId(method_id.proto_idx_).shorty_idx_; 3020 uint32_t shorty_len; 3021 const char* descriptor = dex_file_->StringDataAndUtf16LengthByIdx(shorty_idx, &shorty_len); 3022 int32_t sig_registers = method_type == METHOD_STATIC ? 0 : 1; 3023 for (size_t i = 1; i < shorty_len; i++) { 3024 if (descriptor[i] == 'J' || descriptor[i] == 'D') { 3025 sig_registers += 2; 3026 } else { 3027 sig_registers++; 3028 } 3029 } 3030 if (inst->VRegA() != sig_registers) { 3031 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation, expected " << inst->VRegA() << 3032 " arguments, found " << sig_registers; 3033 return nullptr; 3034 } 3035 3036 mirror::ArtMethod* res_method = ResolveMethodAndCheckAccess(method_idx, method_type); 3037 if (res_method == NULL) { // error or class is unresolved 3038 return NULL; 3039 } 3040 3041 // If we're using invoke-super(method), make sure that the executing method's class' superclass 3042 // has a vtable entry for the target method. 3043 if (is_super) { 3044 DCHECK(method_type == METHOD_VIRTUAL); 3045 const RegType& super = GetDeclaringClass().GetSuperClass(®_types_); 3046 if (super.IsUnresolvedTypes()) { 3047 Fail(VERIFY_ERROR_NO_METHOD) << "unknown super class in invoke-super from " 3048 << PrettyMethod(dex_method_idx_, *dex_file_) 3049 << " to super " << PrettyMethod(res_method); 3050 return NULL; 3051 } 3052 mirror::Class* super_klass = super.GetClass(); 3053 if (res_method->GetMethodIndex() >= super_klass->GetVTable()->GetLength()) { 3054 Fail(VERIFY_ERROR_NO_METHOD) << "invalid invoke-super from " 3055 << PrettyMethod(dex_method_idx_, *dex_file_) 3056 << " to super " << super 3057 << "." << res_method->GetName() 3058 << res_method->GetSignature(); 3059 return NULL; 3060 } 3061 } 3062 // We use vAA as our expected arg count, rather than res_method->insSize, because we need to 3063 // match the call to the signature. Also, we might be calling through an abstract method 3064 // definition (which doesn't have register count values). 3065 const size_t expected_args = (is_range) ? inst->VRegA_3rc() : inst->VRegA_35c(); 3066 /* caught by static verifier */ 3067 DCHECK(is_range || expected_args <= 5); 3068 if (expected_args > code_item_->outs_size_) { 3069 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid argument count (" << expected_args 3070 << ") exceeds outsSize (" << code_item_->outs_size_ << ")"; 3071 return NULL; 3072 } 3073 3074 /* 3075 * Check the "this" argument, which must be an instance of the class that declared the method. 3076 * For an interface class, we don't do the full interface merge (see JoinClass), so we can't do a 3077 * rigorous check here (which is okay since we have to do it at runtime). 3078 */ 3079 size_t actual_args = 0; 3080 if (!res_method->IsStatic()) { 3081 const RegType& actual_arg_type = work_line_->GetInvocationThis(inst, is_range); 3082 if (actual_arg_type.IsConflict()) { // GetInvocationThis failed. 3083 return NULL; 3084 } 3085 if (actual_arg_type.IsUninitializedReference() && !res_method->IsConstructor()) { 3086 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "'this' arg must be initialized"; 3087 return NULL; 3088 } 3089 if (method_type != METHOD_INTERFACE && !actual_arg_type.IsZero()) { 3090 mirror::Class* klass = res_method->GetDeclaringClass(); 3091 const RegType& res_method_class = 3092 reg_types_.FromClass(klass->GetDescriptor().c_str(), klass, 3093 klass->CannotBeAssignedFromOtherTypes()); 3094 if (!res_method_class.IsAssignableFrom(actual_arg_type)) { 3095 Fail(actual_arg_type.IsUnresolvedTypes() ? VERIFY_ERROR_NO_CLASS: 3096 VERIFY_ERROR_BAD_CLASS_SOFT) << "'this' argument '" << actual_arg_type 3097 << "' not instance of '" << res_method_class << "'"; 3098 return NULL; 3099 } 3100 } 3101 actual_args++; 3102 } 3103 /* 3104 * Process the target method's signature. This signature may or may not 3105 * have been verified, so we can't assume it's properly formed. 3106 */ 3107 const DexFile::TypeList* params = res_method->GetParameterTypeList(); 3108 size_t params_size = params == NULL ? 0 : params->Size(); 3109 uint32_t arg[5]; 3110 if (!is_range) { 3111 inst->GetVarArgs(arg); 3112 } 3113 for (size_t param_index = 0; param_index < params_size; param_index++) { 3114 if (actual_args >= expected_args) { 3115 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invalid call to '" << PrettyMethod(res_method) 3116 << "'. Expected " << expected_args << " arguments, processing argument " << actual_args 3117 << " (where longs/doubles count twice)."; 3118 return NULL; 3119 } 3120 const char* descriptor = 3121 res_method->GetTypeDescriptorFromTypeIdx(params->GetTypeItem(param_index).type_idx_); 3122 if (descriptor == NULL) { 3123 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation of " << PrettyMethod(res_method) 3124 << " missing signature component"; 3125 return NULL; 3126 } 3127 const RegType& reg_type = reg_types_.FromDescriptor(class_loader_->Get(), descriptor, false); 3128 uint32_t get_reg = is_range ? inst->VRegC_3rc() + actual_args : arg[actual_args]; 3129 if (reg_type.IsIntegralTypes()) { 3130 const RegType& src_type = work_line_->GetRegisterType(get_reg); 3131 if (!src_type.IsIntegralTypes()) { 3132 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "register v" << get_reg << " has type " << src_type 3133 << " but expected " << reg_type; 3134 return res_method; 3135 } 3136 } else if (!work_line_->VerifyRegisterType(get_reg, reg_type)) { 3137 return res_method; 3138 } 3139 actual_args = reg_type.IsLongOrDoubleTypes() ? actual_args + 2 : actual_args + 1; 3140 } 3141 if (actual_args != expected_args) { 3142 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation of " << PrettyMethod(res_method) 3143 << " expected " << expected_args << " arguments, found " << actual_args; 3144 return NULL; 3145 } else { 3146 return res_method; 3147 } 3148} 3149 3150mirror::ArtMethod* MethodVerifier::GetQuickInvokedMethod(const Instruction* inst, 3151 RegisterLine* reg_line, bool is_range) { 3152 DCHECK(inst->Opcode() == Instruction::INVOKE_VIRTUAL_QUICK || 3153 inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE_QUICK); 3154 const RegType& actual_arg_type = reg_line->GetInvocationThis(inst, is_range); 3155 if (!actual_arg_type.HasClass()) { 3156 VLOG(verifier) << "Failed to get mirror::Class* from '" << actual_arg_type << "'"; 3157 return nullptr; 3158 } 3159 mirror::ObjectArray<mirror::ArtMethod>* vtable = nullptr; 3160 mirror::Class* klass = actual_arg_type.GetClass(); 3161 if (klass->IsInterface()) { 3162 // Derive Object.class from Class.class.getSuperclass(). 3163 mirror::Class* object_klass = klass->GetClass()->GetSuperClass(); 3164 CHECK(object_klass->IsObjectClass()); 3165 vtable = object_klass->GetVTable(); 3166 } else { 3167 vtable = klass->GetVTable(); 3168 } 3169 CHECK(vtable != nullptr) << PrettyDescriptor(klass); 3170 uint16_t vtable_index = is_range ? inst->VRegB_3rc() : inst->VRegB_35c(); 3171 CHECK_LT(static_cast<int32_t>(vtable_index), vtable->GetLength()) << PrettyDescriptor(klass); 3172 mirror::ArtMethod* res_method = vtable->Get(vtable_index); 3173 CHECK(!Thread::Current()->IsExceptionPending()); 3174 return res_method; 3175} 3176 3177mirror::ArtMethod* MethodVerifier::VerifyInvokeVirtualQuickArgs(const Instruction* inst, 3178 bool is_range) { 3179 DCHECK(Runtime::Current()->IsStarted()); 3180 mirror::ArtMethod* res_method = GetQuickInvokedMethod(inst, work_line_.get(), 3181 is_range); 3182 if (res_method == NULL) { 3183 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Cannot infer method from " << inst->Name(); 3184 return NULL; 3185 } 3186 CHECK(!res_method->IsDirect() && !res_method->IsStatic()); 3187 3188 // We use vAA as our expected arg count, rather than res_method->insSize, because we need to 3189 // match the call to the signature. Also, we might be calling through an abstract method 3190 // definition (which doesn't have register count values). 3191 const RegType& actual_arg_type = work_line_->GetInvocationThis(inst, is_range); 3192 if (actual_arg_type.IsConflict()) { // GetInvocationThis failed. 3193 return NULL; 3194 } 3195 const size_t expected_args = (is_range) ? inst->VRegA_3rc() : inst->VRegA_35c(); 3196 /* caught by static verifier */ 3197 DCHECK(is_range || expected_args <= 5); 3198 if (expected_args > code_item_->outs_size_) { 3199 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid argument count (" << expected_args 3200 << ") exceeds outsSize (" << code_item_->outs_size_ << ")"; 3201 return NULL; 3202 } 3203 3204 /* 3205 * Check the "this" argument, which must be an instance of the class that declared the method. 3206 * For an interface class, we don't do the full interface merge (see JoinClass), so we can't do a 3207 * rigorous check here (which is okay since we have to do it at runtime). 3208 */ 3209 if (actual_arg_type.IsUninitializedReference() && !res_method->IsConstructor()) { 3210 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "'this' arg must be initialized"; 3211 return NULL; 3212 } 3213 if (!actual_arg_type.IsZero()) { 3214 mirror::Class* klass = res_method->GetDeclaringClass(); 3215 const RegType& res_method_class = 3216 reg_types_.FromClass(klass->GetDescriptor().c_str(), klass, 3217 klass->CannotBeAssignedFromOtherTypes()); 3218 if (!res_method_class.IsAssignableFrom(actual_arg_type)) { 3219 Fail(actual_arg_type.IsUnresolvedTypes() ? VERIFY_ERROR_NO_CLASS : 3220 VERIFY_ERROR_BAD_CLASS_SOFT) << "'this' argument '" << actual_arg_type 3221 << "' not instance of '" << res_method_class << "'"; 3222 return NULL; 3223 } 3224 } 3225 /* 3226 * Process the target method's signature. This signature may or may not 3227 * have been verified, so we can't assume it's properly formed. 3228 */ 3229 const DexFile::TypeList* params = res_method->GetParameterTypeList(); 3230 size_t params_size = params == NULL ? 0 : params->Size(); 3231 uint32_t arg[5]; 3232 if (!is_range) { 3233 inst->GetVarArgs(arg); 3234 } 3235 size_t actual_args = 1; 3236 for (size_t param_index = 0; param_index < params_size; param_index++) { 3237 if (actual_args >= expected_args) { 3238 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invalid call to '" << PrettyMethod(res_method) 3239 << "'. Expected " << expected_args 3240 << " arguments, processing argument " << actual_args 3241 << " (where longs/doubles count twice)."; 3242 return NULL; 3243 } 3244 const char* descriptor = 3245 res_method->GetTypeDescriptorFromTypeIdx(params->GetTypeItem(param_index).type_idx_); 3246 if (descriptor == NULL) { 3247 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation of " << PrettyMethod(res_method) 3248 << " missing signature component"; 3249 return NULL; 3250 } 3251 const RegType& reg_type = reg_types_.FromDescriptor(class_loader_->Get(), descriptor, false); 3252 uint32_t get_reg = is_range ? inst->VRegC_3rc() + actual_args : arg[actual_args]; 3253 if (!work_line_->VerifyRegisterType(get_reg, reg_type)) { 3254 return res_method; 3255 } 3256 actual_args = reg_type.IsLongOrDoubleTypes() ? actual_args + 2 : actual_args + 1; 3257 } 3258 if (actual_args != expected_args) { 3259 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation of " << PrettyMethod(res_method) 3260 << " expected " << expected_args << " arguments, found " << actual_args; 3261 return NULL; 3262 } else { 3263 return res_method; 3264 } 3265} 3266 3267void MethodVerifier::VerifyNewArray(const Instruction* inst, bool is_filled, bool is_range) { 3268 uint32_t type_idx; 3269 if (!is_filled) { 3270 DCHECK_EQ(inst->Opcode(), Instruction::NEW_ARRAY); 3271 type_idx = inst->VRegC_22c(); 3272 } else if (!is_range) { 3273 DCHECK_EQ(inst->Opcode(), Instruction::FILLED_NEW_ARRAY); 3274 type_idx = inst->VRegB_35c(); 3275 } else { 3276 DCHECK_EQ(inst->Opcode(), Instruction::FILLED_NEW_ARRAY_RANGE); 3277 type_idx = inst->VRegB_3rc(); 3278 } 3279 const RegType& res_type = ResolveClassAndCheckAccess(type_idx); 3280 if (res_type.IsConflict()) { // bad class 3281 DCHECK_NE(failures_.size(), 0U); 3282 } else { 3283 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved 3284 if (!res_type.IsArrayTypes()) { 3285 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "new-array on non-array class " << res_type; 3286 } else if (!is_filled) { 3287 /* make sure "size" register is valid type */ 3288 work_line_->VerifyRegisterType(inst->VRegB_22c(), reg_types_.Integer()); 3289 /* set register type to array class */ 3290 const RegType& precise_type = reg_types_.FromUninitialized(res_type); 3291 work_line_->SetRegisterType(inst->VRegA_22c(), precise_type); 3292 } else { 3293 // Verify each register. If "arg_count" is bad, VerifyRegisterType() will run off the end of 3294 // the list and fail. It's legal, if silly, for arg_count to be zero. 3295 const RegType& expected_type = reg_types_.GetComponentType(res_type, class_loader_->Get()); 3296 uint32_t arg_count = (is_range) ? inst->VRegA_3rc() : inst->VRegA_35c(); 3297 uint32_t arg[5]; 3298 if (!is_range) { 3299 inst->GetVarArgs(arg); 3300 } 3301 for (size_t ui = 0; ui < arg_count; ui++) { 3302 uint32_t get_reg = is_range ? inst->VRegC_3rc() + ui : arg[ui]; 3303 if (!work_line_->VerifyRegisterType(get_reg, expected_type)) { 3304 work_line_->SetResultRegisterType(reg_types_.Conflict()); 3305 return; 3306 } 3307 } 3308 // filled-array result goes into "result" register 3309 const RegType& precise_type = reg_types_.FromUninitialized(res_type); 3310 work_line_->SetResultRegisterType(precise_type); 3311 } 3312 } 3313} 3314 3315void MethodVerifier::VerifyAGet(const Instruction* inst, 3316 const RegType& insn_type, bool is_primitive) { 3317 const RegType& index_type = work_line_->GetRegisterType(inst->VRegC_23x()); 3318 if (!index_type.IsArrayIndexTypes()) { 3319 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Invalid reg type for array index (" << index_type << ")"; 3320 } else { 3321 const RegType& array_type = work_line_->GetRegisterType(inst->VRegB_23x()); 3322 if (array_type.IsZero()) { 3323 // Null array class; this code path will fail at runtime. Infer a merge-able type from the 3324 // instruction type. TODO: have a proper notion of bottom here. 3325 if (!is_primitive || insn_type.IsCategory1Types()) { 3326 // Reference or category 1 3327 work_line_->SetRegisterType(inst->VRegA_23x(), reg_types_.Zero()); 3328 } else { 3329 // Category 2 3330 work_line_->SetRegisterTypeWide(inst->VRegA_23x(), reg_types_.FromCat2ConstLo(0, false), 3331 reg_types_.FromCat2ConstHi(0, false)); 3332 } 3333 } else if (!array_type.IsArrayTypes()) { 3334 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "not array type " << array_type << " with aget"; 3335 } else { 3336 /* verify the class */ 3337 const RegType& component_type = reg_types_.GetComponentType(array_type, class_loader_->Get()); 3338 if (!component_type.IsReferenceTypes() && !is_primitive) { 3339 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "primitive array type " << array_type 3340 << " source for aget-object"; 3341 } else if (component_type.IsNonZeroReferenceTypes() && is_primitive) { 3342 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "reference array type " << array_type 3343 << " source for category 1 aget"; 3344 } else if (is_primitive && !insn_type.Equals(component_type) && 3345 !((insn_type.IsInteger() && component_type.IsFloat()) || 3346 (insn_type.IsLong() && component_type.IsDouble()))) { 3347 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array type " << array_type 3348 << " incompatible with aget of type " << insn_type; 3349 } else { 3350 // Use knowledge of the field type which is stronger than the type inferred from the 3351 // instruction, which can't differentiate object types and ints from floats, longs from 3352 // doubles. 3353 if (!component_type.IsLowHalf()) { 3354 work_line_->SetRegisterType(inst->VRegA_23x(), component_type); 3355 } else { 3356 work_line_->SetRegisterTypeWide(inst->VRegA_23x(), component_type, 3357 component_type.HighHalf(®_types_)); 3358 } 3359 } 3360 } 3361 } 3362} 3363 3364void MethodVerifier::VerifyPrimitivePut(const RegType& target_type, const RegType& insn_type, 3365 const uint32_t vregA) { 3366 // Primitive assignability rules are weaker than regular assignability rules. 3367 bool instruction_compatible; 3368 bool value_compatible; 3369 const RegType& value_type = work_line_->GetRegisterType(vregA); 3370 if (target_type.IsIntegralTypes()) { 3371 instruction_compatible = target_type.Equals(insn_type); 3372 value_compatible = value_type.IsIntegralTypes(); 3373 } else if (target_type.IsFloat()) { 3374 instruction_compatible = insn_type.IsInteger(); // no put-float, so expect put-int 3375 value_compatible = value_type.IsFloatTypes(); 3376 } else if (target_type.IsLong()) { 3377 instruction_compatible = insn_type.IsLong(); 3378 value_compatible = value_type.IsLongTypes(); 3379 } else if (target_type.IsDouble()) { 3380 instruction_compatible = insn_type.IsLong(); // no put-double, so expect put-long 3381 value_compatible = value_type.IsDoubleTypes(); 3382 } else { 3383 instruction_compatible = false; // reference with primitive store 3384 value_compatible = false; // unused 3385 } 3386 if (!instruction_compatible) { 3387 // This is a global failure rather than a class change failure as the instructions and 3388 // the descriptors for the type should have been consistent within the same file at 3389 // compile time. 3390 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "put insn has type '" << insn_type 3391 << "' but expected type '" << target_type << "'"; 3392 return; 3393 } 3394 if (!value_compatible) { 3395 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected value in v" << vregA 3396 << " of type " << value_type << " but expected " << target_type << " for put"; 3397 return; 3398 } 3399} 3400 3401void MethodVerifier::VerifyAPut(const Instruction* inst, 3402 const RegType& insn_type, bool is_primitive) { 3403 const RegType& index_type = work_line_->GetRegisterType(inst->VRegC_23x()); 3404 if (!index_type.IsArrayIndexTypes()) { 3405 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Invalid reg type for array index (" << index_type << ")"; 3406 } else { 3407 const RegType& array_type = work_line_->GetRegisterType(inst->VRegB_23x()); 3408 if (array_type.IsZero()) { 3409 // Null array type; this code path will fail at runtime. Infer a merge-able type from the 3410 // instruction type. 3411 } else if (!array_type.IsArrayTypes()) { 3412 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "not array type " << array_type << " with aput"; 3413 } else { 3414 const RegType& component_type = reg_types_.GetComponentType(array_type, class_loader_->Get()); 3415 const uint32_t vregA = inst->VRegA_23x(); 3416 if (is_primitive) { 3417 VerifyPrimitivePut(component_type, insn_type, vregA); 3418 } else { 3419 if (!component_type.IsReferenceTypes()) { 3420 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "primitive array type " << array_type 3421 << " source for aput-object"; 3422 } else { 3423 // The instruction agrees with the type of array, confirm the value to be stored does too 3424 // Note: we use the instruction type (rather than the component type) for aput-object as 3425 // incompatible classes will be caught at runtime as an array store exception 3426 work_line_->VerifyRegisterType(vregA, insn_type); 3427 } 3428 } 3429 } 3430 } 3431} 3432 3433mirror::ArtField* MethodVerifier::GetStaticField(int field_idx) { 3434 const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx); 3435 // Check access to class 3436 const RegType& klass_type = ResolveClassAndCheckAccess(field_id.class_idx_); 3437 if (klass_type.IsConflict()) { // bad class 3438 AppendToLastFailMessage(StringPrintf(" in attempt to access static field %d (%s) in %s", 3439 field_idx, dex_file_->GetFieldName(field_id), 3440 dex_file_->GetFieldDeclaringClassDescriptor(field_id))); 3441 return NULL; 3442 } 3443 if (klass_type.IsUnresolvedTypes()) { 3444 return NULL; // Can't resolve Class so no more to do here, will do checking at runtime. 3445 } 3446 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 3447 mirror::ArtField* field = class_linker->ResolveFieldJLS(*dex_file_, field_idx, *dex_cache_, 3448 *class_loader_); 3449 if (field == NULL) { 3450 VLOG(verifier) << "Unable to resolve static field " << field_idx << " (" 3451 << dex_file_->GetFieldName(field_id) << ") in " 3452 << dex_file_->GetFieldDeclaringClassDescriptor(field_id); 3453 DCHECK(Thread::Current()->IsExceptionPending()); 3454 Thread::Current()->ClearException(); 3455 return NULL; 3456 } else if (!GetDeclaringClass().CanAccessMember(field->GetDeclaringClass(), 3457 field->GetAccessFlags())) { 3458 Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot access static field " << PrettyField(field) 3459 << " from " << GetDeclaringClass(); 3460 return NULL; 3461 } else if (!field->IsStatic()) { 3462 Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected field " << PrettyField(field) << " to be static"; 3463 return NULL; 3464 } 3465 return field; 3466} 3467 3468mirror::ArtField* MethodVerifier::GetInstanceField(const RegType& obj_type, int field_idx) { 3469 const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx); 3470 // Check access to class 3471 const RegType& klass_type = ResolveClassAndCheckAccess(field_id.class_idx_); 3472 if (klass_type.IsConflict()) { 3473 AppendToLastFailMessage(StringPrintf(" in attempt to access instance field %d (%s) in %s", 3474 field_idx, dex_file_->GetFieldName(field_id), 3475 dex_file_->GetFieldDeclaringClassDescriptor(field_id))); 3476 return NULL; 3477 } 3478 if (klass_type.IsUnresolvedTypes()) { 3479 return NULL; // Can't resolve Class so no more to do here 3480 } 3481 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 3482 mirror::ArtField* field = class_linker->ResolveFieldJLS(*dex_file_, field_idx, *dex_cache_, 3483 *class_loader_); 3484 if (field == NULL) { 3485 VLOG(verifier) << "Unable to resolve instance field " << field_idx << " (" 3486 << dex_file_->GetFieldName(field_id) << ") in " 3487 << dex_file_->GetFieldDeclaringClassDescriptor(field_id); 3488 DCHECK(Thread::Current()->IsExceptionPending()); 3489 Thread::Current()->ClearException(); 3490 return NULL; 3491 } else if (!GetDeclaringClass().CanAccessMember(field->GetDeclaringClass(), 3492 field->GetAccessFlags())) { 3493 Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot access instance field " << PrettyField(field) 3494 << " from " << GetDeclaringClass(); 3495 return NULL; 3496 } else if (field->IsStatic()) { 3497 Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected field " << PrettyField(field) 3498 << " to not be static"; 3499 return NULL; 3500 } else if (obj_type.IsZero()) { 3501 // Cannot infer and check type, however, access will cause null pointer exception 3502 return field; 3503 } else { 3504 mirror::Class* klass = field->GetDeclaringClass(); 3505 const RegType& field_klass = 3506 reg_types_.FromClass(dex_file_->GetFieldDeclaringClassDescriptor(field_id), 3507 klass, klass->CannotBeAssignedFromOtherTypes()); 3508 if (obj_type.IsUninitializedTypes() && 3509 (!IsConstructor() || GetDeclaringClass().Equals(obj_type) || 3510 !field_klass.Equals(GetDeclaringClass()))) { 3511 // Field accesses through uninitialized references are only allowable for constructors where 3512 // the field is declared in this class 3513 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "cannot access instance field " << PrettyField(field) 3514 << " of a not fully initialized object within the context" 3515 << " of " << PrettyMethod(dex_method_idx_, *dex_file_); 3516 return NULL; 3517 } else if (!field_klass.IsAssignableFrom(obj_type)) { 3518 // Trying to access C1.field1 using reference of type C2, which is neither C1 or a sub-class 3519 // of C1. For resolution to occur the declared class of the field must be compatible with 3520 // obj_type, we've discovered this wasn't so, so report the field didn't exist. 3521 Fail(VERIFY_ERROR_NO_FIELD) << "cannot access instance field " << PrettyField(field) 3522 << " from object of type " << obj_type; 3523 return NULL; 3524 } else { 3525 return field; 3526 } 3527 } 3528} 3529 3530void MethodVerifier::VerifyISGet(const Instruction* inst, const RegType& insn_type, 3531 bool is_primitive, bool is_static) { 3532 uint32_t field_idx = is_static ? inst->VRegB_21c() : inst->VRegC_22c(); 3533 mirror::ArtField* field; 3534 if (is_static) { 3535 field = GetStaticField(field_idx); 3536 } else { 3537 const RegType& object_type = work_line_->GetRegisterType(inst->VRegB_22c()); 3538 field = GetInstanceField(object_type, field_idx); 3539 } 3540 const RegType* field_type = nullptr; 3541 if (field != NULL) { 3542 Thread* self = Thread::Current(); 3543 mirror::Class* field_type_class; 3544 { 3545 StackHandleScope<1> hs(self); 3546 HandleWrapper<mirror::ArtField> h_field(hs.NewHandleWrapper(&field)); 3547 field_type_class = FieldHelper(h_field).GetType(can_load_classes_); 3548 } 3549 if (field_type_class != nullptr) { 3550 field_type = ®_types_.FromClass(field->GetTypeDescriptor(), field_type_class, 3551 field_type_class->CannotBeAssignedFromOtherTypes()); 3552 } else { 3553 DCHECK(!can_load_classes_ || self->IsExceptionPending()); 3554 self->ClearException(); 3555 } 3556 } 3557 if (field_type == nullptr) { 3558 const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx); 3559 const char* descriptor = dex_file_->GetFieldTypeDescriptor(field_id); 3560 field_type = ®_types_.FromDescriptor(class_loader_->Get(), descriptor, false); 3561 } 3562 DCHECK(field_type != nullptr); 3563 const uint32_t vregA = (is_static) ? inst->VRegA_21c() : inst->VRegA_22c(); 3564 if (is_primitive) { 3565 if (field_type->Equals(insn_type) || 3566 (field_type->IsFloat() && insn_type.IsInteger()) || 3567 (field_type->IsDouble() && insn_type.IsLong())) { 3568 // expected that read is of the correct primitive type or that int reads are reading 3569 // floats or long reads are reading doubles 3570 } else { 3571 // This is a global failure rather than a class change failure as the instructions and 3572 // the descriptors for the type should have been consistent within the same file at 3573 // compile time 3574 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected field " << PrettyField(field) 3575 << " to be of type '" << insn_type 3576 << "' but found type '" << *field_type << "' in get"; 3577 return; 3578 } 3579 } else { 3580 if (!insn_type.IsAssignableFrom(*field_type)) { 3581 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "expected field " << PrettyField(field) 3582 << " to be compatible with type '" << insn_type 3583 << "' but found type '" << *field_type 3584 << "' in Get-object"; 3585 work_line_->SetRegisterType(vregA, reg_types_.Conflict()); 3586 return; 3587 } 3588 } 3589 if (!field_type->IsLowHalf()) { 3590 work_line_->SetRegisterType(vregA, *field_type); 3591 } else { 3592 work_line_->SetRegisterTypeWide(vregA, *field_type, field_type->HighHalf(®_types_)); 3593 } 3594} 3595 3596void MethodVerifier::VerifyISPut(const Instruction* inst, const RegType& insn_type, 3597 bool is_primitive, bool is_static) { 3598 uint32_t field_idx = is_static ? inst->VRegB_21c() : inst->VRegC_22c(); 3599 mirror::ArtField* field; 3600 if (is_static) { 3601 field = GetStaticField(field_idx); 3602 } else { 3603 const RegType& object_type = work_line_->GetRegisterType(inst->VRegB_22c()); 3604 field = GetInstanceField(object_type, field_idx); 3605 } 3606 const RegType* field_type = nullptr; 3607 if (field != NULL) { 3608 if (field->IsFinal() && field->GetDeclaringClass() != GetDeclaringClass().GetClass()) { 3609 Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot modify final field " << PrettyField(field) 3610 << " from other class " << GetDeclaringClass(); 3611 return; 3612 } 3613 mirror::Class* field_type_class; 3614 { 3615 StackHandleScope<1> hs(Thread::Current()); 3616 HandleWrapper<mirror::ArtField> h_field(hs.NewHandleWrapper(&field)); 3617 FieldHelper fh(h_field); 3618 field_type_class = fh.GetType(can_load_classes_); 3619 } 3620 if (field_type_class != nullptr) { 3621 field_type = ®_types_.FromClass(field->GetTypeDescriptor(), field_type_class, 3622 field_type_class->CannotBeAssignedFromOtherTypes()); 3623 } else { 3624 Thread* self = Thread::Current(); 3625 DCHECK(!can_load_classes_ || self->IsExceptionPending()); 3626 self->ClearException(); 3627 } 3628 } 3629 if (field_type == nullptr) { 3630 const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx); 3631 const char* descriptor = dex_file_->GetFieldTypeDescriptor(field_id); 3632 field_type = ®_types_.FromDescriptor(class_loader_->Get(), descriptor, false); 3633 } 3634 DCHECK(field_type != nullptr); 3635 const uint32_t vregA = (is_static) ? inst->VRegA_21c() : inst->VRegA_22c(); 3636 if (is_primitive) { 3637 VerifyPrimitivePut(*field_type, insn_type, vregA); 3638 } else { 3639 if (!insn_type.IsAssignableFrom(*field_type)) { 3640 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "expected field " << PrettyField(field) 3641 << " to be compatible with type '" << insn_type 3642 << "' but found type '" << *field_type 3643 << "' in put-object"; 3644 return; 3645 } 3646 work_line_->VerifyRegisterType(vregA, *field_type); 3647 } 3648} 3649 3650mirror::ArtField* MethodVerifier::GetQuickFieldAccess(const Instruction* inst, 3651 RegisterLine* reg_line) { 3652 DCHECK(inst->Opcode() == Instruction::IGET_QUICK || 3653 inst->Opcode() == Instruction::IGET_WIDE_QUICK || 3654 inst->Opcode() == Instruction::IGET_OBJECT_QUICK || 3655 inst->Opcode() == Instruction::IPUT_QUICK || 3656 inst->Opcode() == Instruction::IPUT_WIDE_QUICK || 3657 inst->Opcode() == Instruction::IPUT_OBJECT_QUICK); 3658 const RegType& object_type = reg_line->GetRegisterType(inst->VRegB_22c()); 3659 if (!object_type.HasClass()) { 3660 VLOG(verifier) << "Failed to get mirror::Class* from '" << object_type << "'"; 3661 return nullptr; 3662 } 3663 uint32_t field_offset = static_cast<uint32_t>(inst->VRegC_22c()); 3664 mirror::ArtField* f = mirror::ArtField::FindInstanceFieldWithOffset(object_type.GetClass(), 3665 field_offset); 3666 if (f == nullptr) { 3667 VLOG(verifier) << "Failed to find instance field at offset '" << field_offset 3668 << "' from '" << PrettyDescriptor(object_type.GetClass()) << "'"; 3669 } 3670 return f; 3671} 3672 3673void MethodVerifier::VerifyIGetQuick(const Instruction* inst, const RegType& insn_type, 3674 bool is_primitive) { 3675 DCHECK(Runtime::Current()->IsStarted()); 3676 mirror::ArtField* field = GetQuickFieldAccess(inst, work_line_.get()); 3677 if (field == NULL) { 3678 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Cannot infer field from " << inst->Name(); 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 const RegType* field_type; 3689 if (field_type_class != nullptr) { 3690 field_type = ®_types_.FromClass(field->GetTypeDescriptor(), field_type_class, 3691 field_type_class->CannotBeAssignedFromOtherTypes()); 3692 } else { 3693 Thread* self = Thread::Current(); 3694 DCHECK(!can_load_classes_ || self->IsExceptionPending()); 3695 self->ClearException(); 3696 field_type = ®_types_.FromDescriptor(field->GetDeclaringClass()->GetClassLoader(), 3697 field->GetTypeDescriptor(), false); 3698 } 3699 DCHECK(field_type != nullptr); 3700 const uint32_t vregA = inst->VRegA_22c(); 3701 if (is_primitive) { 3702 if (field_type->Equals(insn_type) || 3703 (field_type->IsFloat() && insn_type.IsIntegralTypes()) || 3704 (field_type->IsDouble() && insn_type.IsLongTypes())) { 3705 // expected that read is of the correct primitive type or that int reads are reading 3706 // floats or long reads are reading doubles 3707 } else { 3708 // This is a global failure rather than a class change failure as the instructions and 3709 // the descriptors for the type should have been consistent within the same file at 3710 // compile time 3711 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected field " << PrettyField(field) 3712 << " to be of type '" << insn_type 3713 << "' but found type '" << *field_type << "' in Get"; 3714 return; 3715 } 3716 } else { 3717 if (!insn_type.IsAssignableFrom(*field_type)) { 3718 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "expected field " << PrettyField(field) 3719 << " to be compatible with type '" << insn_type 3720 << "' but found type '" << *field_type 3721 << "' in get-object"; 3722 work_line_->SetRegisterType(vregA, reg_types_.Conflict()); 3723 return; 3724 } 3725 } 3726 if (!field_type->IsLowHalf()) { 3727 work_line_->SetRegisterType(vregA, *field_type); 3728 } else { 3729 work_line_->SetRegisterTypeWide(vregA, *field_type, field_type->HighHalf(®_types_)); 3730 } 3731} 3732 3733void MethodVerifier::VerifyIPutQuick(const Instruction* inst, const RegType& insn_type, 3734 bool is_primitive) { 3735 DCHECK(Runtime::Current()->IsStarted()); 3736 mirror::ArtField* field = GetQuickFieldAccess(inst, work_line_.get()); 3737 if (field == NULL) { 3738 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Cannot infer field from " << inst->Name(); 3739 return; 3740 } 3741 const char* descriptor = field->GetTypeDescriptor(); 3742 mirror::ClassLoader* loader = field->GetDeclaringClass()->GetClassLoader(); 3743 const RegType& field_type = reg_types_.FromDescriptor(loader, descriptor, false); 3744 if (field != NULL) { 3745 if (field->IsFinal() && field->GetDeclaringClass() != GetDeclaringClass().GetClass()) { 3746 Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot modify final field " << PrettyField(field) 3747 << " from other class " << GetDeclaringClass(); 3748 return; 3749 } 3750 } 3751 const uint32_t vregA = inst->VRegA_22c(); 3752 if (is_primitive) { 3753 // Primitive field assignability rules are weaker than regular assignability rules 3754 bool instruction_compatible; 3755 bool value_compatible; 3756 const RegType& value_type = work_line_->GetRegisterType(vregA); 3757 if (field_type.IsIntegralTypes()) { 3758 instruction_compatible = insn_type.IsIntegralTypes(); 3759 value_compatible = value_type.IsIntegralTypes(); 3760 } else if (field_type.IsFloat()) { 3761 instruction_compatible = insn_type.IsInteger(); // no [is]put-float, so expect [is]put-int 3762 value_compatible = value_type.IsFloatTypes(); 3763 } else if (field_type.IsLong()) { 3764 instruction_compatible = insn_type.IsLong(); 3765 value_compatible = value_type.IsLongTypes(); 3766 } else if (field_type.IsDouble()) { 3767 instruction_compatible = insn_type.IsLong(); // no [is]put-double, so expect [is]put-long 3768 value_compatible = value_type.IsDoubleTypes(); 3769 } else { 3770 instruction_compatible = false; // reference field with primitive store 3771 value_compatible = false; // unused 3772 } 3773 if (!instruction_compatible) { 3774 // This is a global failure rather than a class change failure as the instructions and 3775 // the descriptors for the type should have been consistent within the same file at 3776 // compile time 3777 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected field " << PrettyField(field) 3778 << " to be of type '" << insn_type 3779 << "' but found type '" << field_type 3780 << "' in put"; 3781 return; 3782 } 3783 if (!value_compatible) { 3784 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected value in v" << vregA 3785 << " of type " << value_type 3786 << " but expected " << field_type 3787 << " for store to " << PrettyField(field) << " in put"; 3788 return; 3789 } 3790 } else { 3791 if (!insn_type.IsAssignableFrom(field_type)) { 3792 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "expected field " << PrettyField(field) 3793 << " to be compatible with type '" << insn_type 3794 << "' but found type '" << field_type 3795 << "' in put-object"; 3796 return; 3797 } 3798 work_line_->VerifyRegisterType(vregA, field_type); 3799 } 3800} 3801 3802bool MethodVerifier::CheckNotMoveException(const uint16_t* insns, int insn_idx) { 3803 if ((insns[insn_idx] & 0xff) == Instruction::MOVE_EXCEPTION) { 3804 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid use of move-exception"; 3805 return false; 3806 } 3807 return true; 3808} 3809 3810bool MethodVerifier::UpdateRegisters(uint32_t next_insn, const RegisterLine* merge_line) { 3811 bool changed = true; 3812 RegisterLine* target_line = reg_table_.GetLine(next_insn); 3813 if (!insn_flags_[next_insn].IsVisitedOrChanged()) { 3814 /* 3815 * We haven't processed this instruction before, and we haven't touched the registers here, so 3816 * there's nothing to "merge". Copy the registers over and mark it as changed. (This is the 3817 * only way a register can transition out of "unknown", so this is not just an optimization.) 3818 */ 3819 if (!insn_flags_[next_insn].IsReturn()) { 3820 target_line->CopyFromLine(merge_line); 3821 } else { 3822 // Verify that the monitor stack is empty on return. 3823 if (!merge_line->VerifyMonitorStackEmpty()) { 3824 return false; 3825 } 3826 // For returns we only care about the operand to the return, all other registers are dead. 3827 // Initialize them as conflicts so they don't add to GC and deoptimization information. 3828 const Instruction* ret_inst = Instruction::At(code_item_->insns_ + next_insn); 3829 Instruction::Code opcode = ret_inst->Opcode(); 3830 if ((opcode == Instruction::RETURN_VOID) || (opcode == Instruction::RETURN_VOID_BARRIER)) { 3831 target_line->MarkAllRegistersAsConflicts(); 3832 } else { 3833 target_line->CopyFromLine(merge_line); 3834 if (opcode == Instruction::RETURN_WIDE) { 3835 target_line->MarkAllRegistersAsConflictsExceptWide(ret_inst->VRegA_11x()); 3836 } else { 3837 target_line->MarkAllRegistersAsConflictsExcept(ret_inst->VRegA_11x()); 3838 } 3839 } 3840 } 3841 } else { 3842 std::unique_ptr<RegisterLine> copy(gDebugVerify ? 3843 RegisterLine::Create(target_line->NumRegs(), this) : 3844 NULL); 3845 if (gDebugVerify) { 3846 copy->CopyFromLine(target_line); 3847 } 3848 changed = target_line->MergeRegisters(merge_line); 3849 if (have_pending_hard_failure_) { 3850 return false; 3851 } 3852 if (gDebugVerify && changed) { 3853 LogVerifyInfo() << "Merging at [" << reinterpret_cast<void*>(work_insn_idx_) << "]" 3854 << " to [" << reinterpret_cast<void*>(next_insn) << "]: " << "\n" 3855 << *copy.get() << " MERGE\n" 3856 << *merge_line << " ==\n" 3857 << *target_line << "\n"; 3858 } 3859 } 3860 if (changed) { 3861 insn_flags_[next_insn].SetChanged(); 3862 } 3863 return true; 3864} 3865 3866InstructionFlags* MethodVerifier::CurrentInsnFlags() { 3867 return &insn_flags_[work_insn_idx_]; 3868} 3869 3870const RegType& MethodVerifier::GetMethodReturnType() { 3871 if (return_type_ == nullptr) { 3872 if (mirror_method_ != NULL) { 3873 Thread* self = Thread::Current(); 3874 StackHandleScope<1> hs(self); 3875 mirror::Class* return_type_class; 3876 { 3877 HandleWrapper<mirror::ArtMethod> h_mirror_method(hs.NewHandleWrapper(&mirror_method_)); 3878 return_type_class = MethodHelper(h_mirror_method).GetReturnType(can_load_classes_); 3879 } 3880 if (return_type_class != nullptr) { 3881 return_type_ = ®_types_.FromClass(mirror_method_->GetReturnTypeDescriptor(), 3882 return_type_class, 3883 return_type_class->CannotBeAssignedFromOtherTypes()); 3884 } else { 3885 DCHECK(!can_load_classes_ || self->IsExceptionPending()); 3886 self->ClearException(); 3887 } 3888 } 3889 if (return_type_ == nullptr) { 3890 const DexFile::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx_); 3891 const DexFile::ProtoId& proto_id = dex_file_->GetMethodPrototype(method_id); 3892 uint16_t return_type_idx = proto_id.return_type_idx_; 3893 const char* descriptor = dex_file_->GetTypeDescriptor(dex_file_->GetTypeId(return_type_idx)); 3894 return_type_ = ®_types_.FromDescriptor(class_loader_->Get(), descriptor, false); 3895 } 3896 } 3897 return *return_type_; 3898} 3899 3900const RegType& MethodVerifier::GetDeclaringClass() { 3901 if (declaring_class_ == NULL) { 3902 const DexFile::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx_); 3903 const char* descriptor 3904 = dex_file_->GetTypeDescriptor(dex_file_->GetTypeId(method_id.class_idx_)); 3905 if (mirror_method_ != NULL) { 3906 mirror::Class* klass = mirror_method_->GetDeclaringClass(); 3907 declaring_class_ = ®_types_.FromClass(descriptor, klass, 3908 klass->CannotBeAssignedFromOtherTypes()); 3909 } else { 3910 declaring_class_ = ®_types_.FromDescriptor(class_loader_->Get(), descriptor, false); 3911 } 3912 } 3913 return *declaring_class_; 3914} 3915 3916std::vector<int32_t> MethodVerifier::DescribeVRegs(uint32_t dex_pc) { 3917 RegisterLine* line = reg_table_.GetLine(dex_pc); 3918 DCHECK(line != nullptr) << "No register line at DEX pc " << StringPrintf("0x%x", dex_pc); 3919 std::vector<int32_t> result; 3920 for (size_t i = 0; i < line->NumRegs(); ++i) { 3921 const RegType& type = line->GetRegisterType(i); 3922 if (type.IsConstant()) { 3923 result.push_back(type.IsPreciseConstant() ? kConstant : kImpreciseConstant); 3924 result.push_back(type.ConstantValue()); 3925 } else if (type.IsConstantLo()) { 3926 result.push_back(type.IsPreciseConstantLo() ? kConstant : kImpreciseConstant); 3927 result.push_back(type.ConstantValueLo()); 3928 } else if (type.IsConstantHi()) { 3929 result.push_back(type.IsPreciseConstantHi() ? kConstant : kImpreciseConstant); 3930 result.push_back(type.ConstantValueHi()); 3931 } else if (type.IsIntegralTypes()) { 3932 result.push_back(kIntVReg); 3933 result.push_back(0); 3934 } else if (type.IsFloat()) { 3935 result.push_back(kFloatVReg); 3936 result.push_back(0); 3937 } else if (type.IsLong()) { 3938 result.push_back(kLongLoVReg); 3939 result.push_back(0); 3940 result.push_back(kLongHiVReg); 3941 result.push_back(0); 3942 ++i; 3943 } else if (type.IsDouble()) { 3944 result.push_back(kDoubleLoVReg); 3945 result.push_back(0); 3946 result.push_back(kDoubleHiVReg); 3947 result.push_back(0); 3948 ++i; 3949 } else if (type.IsUndefined() || type.IsConflict() || type.IsHighHalf()) { 3950 result.push_back(kUndefined); 3951 result.push_back(0); 3952 } else { 3953 CHECK(type.IsNonZeroReferenceTypes()); 3954 result.push_back(kReferenceVReg); 3955 result.push_back(0); 3956 } 3957 } 3958 return result; 3959} 3960 3961const RegType& MethodVerifier::DetermineCat1Constant(int32_t value, bool precise) { 3962 if (precise) { 3963 // Precise constant type. 3964 return reg_types_.FromCat1Const(value, true); 3965 } else { 3966 // Imprecise constant type. 3967 if (value < -32768) { 3968 return reg_types_.IntConstant(); 3969 } else if (value < -128) { 3970 return reg_types_.ShortConstant(); 3971 } else if (value < 0) { 3972 return reg_types_.ByteConstant(); 3973 } else if (value == 0) { 3974 return reg_types_.Zero(); 3975 } else if (value == 1) { 3976 return reg_types_.One(); 3977 } else if (value < 128) { 3978 return reg_types_.PosByteConstant(); 3979 } else if (value < 32768) { 3980 return reg_types_.PosShortConstant(); 3981 } else if (value < 65536) { 3982 return reg_types_.CharConstant(); 3983 } else { 3984 return reg_types_.IntConstant(); 3985 } 3986 } 3987} 3988 3989void MethodVerifier::Init() { 3990 art::verifier::RegTypeCache::Init(); 3991} 3992 3993void MethodVerifier::Shutdown() { 3994 verifier::RegTypeCache::ShutDown(); 3995} 3996 3997void MethodVerifier::VisitRoots(RootCallback* callback, void* arg) { 3998 reg_types_.VisitRoots(callback, arg); 3999} 4000 4001} // namespace verifier 4002} // namespace art 4003