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