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