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