method_verifier.cc revision ebbdd87cbb57e45da341fbf7325406e982810c10
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 DCHECK_NE(failures_.size(), 0U); 1731 if (!is_checkcast) { 1732 work_line_->SetRegisterType(inst->VRegA_22c(), reg_types_.Boolean()); 1733 } 1734 break; // bad class 1735 } 1736 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved 1737 uint32_t orig_type_reg = (is_checkcast) ? inst->VRegA_21c() : inst->VRegB_22c(); 1738 const RegType& orig_type = work_line_->GetRegisterType(orig_type_reg); 1739 if (!res_type.IsNonZeroReferenceTypes()) { 1740 if (is_checkcast) { 1741 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "check-cast on unexpected class " << res_type; 1742 } else { 1743 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "instance-of on unexpected class " << res_type; 1744 } 1745 } else if (!orig_type.IsReferenceTypes()) { 1746 if (is_checkcast) { 1747 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "check-cast on non-reference in v" << orig_type_reg; 1748 } else { 1749 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "instance-of on non-reference in v" << orig_type_reg; 1750 } 1751 } else { 1752 if (is_checkcast) { 1753 work_line_->SetRegisterType(inst->VRegA_21c(), res_type); 1754 } else { 1755 work_line_->SetRegisterType(inst->VRegA_22c(), reg_types_.Boolean()); 1756 } 1757 } 1758 break; 1759 } 1760 case Instruction::ARRAY_LENGTH: { 1761 const RegType& res_type = work_line_->GetRegisterType(inst->VRegB_12x()); 1762 if (res_type.IsReferenceTypes()) { 1763 if (!res_type.IsArrayTypes() && !res_type.IsZero()) { // ie not an array or null 1764 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array-length on non-array " << res_type; 1765 } else { 1766 work_line_->SetRegisterType(inst->VRegA_12x(), reg_types_.Integer()); 1767 } 1768 } 1769 break; 1770 } 1771 case Instruction::NEW_INSTANCE: { 1772 const RegType& res_type = ResolveClassAndCheckAccess(inst->VRegB_21c()); 1773 if (res_type.IsConflict()) { 1774 DCHECK_NE(failures_.size(), 0U); 1775 break; // bad class 1776 } 1777 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved 1778 // can't create an instance of an interface or abstract class */ 1779 if (!res_type.IsInstantiableTypes()) { 1780 Fail(VERIFY_ERROR_INSTANTIATION) 1781 << "new-instance on primitive, interface or abstract class" << res_type; 1782 // Soft failure so carry on to set register type. 1783 } 1784 const RegType& uninit_type = reg_types_.Uninitialized(res_type, work_insn_idx_); 1785 // Any registers holding previous allocations from this address that have not yet been 1786 // initialized must be marked invalid. 1787 work_line_->MarkUninitRefsAsInvalid(uninit_type); 1788 // add the new uninitialized reference to the register state 1789 work_line_->SetRegisterType(inst->VRegA_21c(), uninit_type); 1790 break; 1791 } 1792 case Instruction::NEW_ARRAY: 1793 VerifyNewArray(inst, false, false); 1794 break; 1795 case Instruction::FILLED_NEW_ARRAY: 1796 VerifyNewArray(inst, true, false); 1797 just_set_result = true; // Filled new array sets result register 1798 break; 1799 case Instruction::FILLED_NEW_ARRAY_RANGE: 1800 VerifyNewArray(inst, true, true); 1801 just_set_result = true; // Filled new array range sets result register 1802 break; 1803 case Instruction::CMPL_FLOAT: 1804 case Instruction::CMPG_FLOAT: 1805 if (!work_line_->VerifyRegisterType(inst->VRegB_23x(), reg_types_.Float())) { 1806 break; 1807 } 1808 if (!work_line_->VerifyRegisterType(inst->VRegC_23x(), reg_types_.Float())) { 1809 break; 1810 } 1811 work_line_->SetRegisterType(inst->VRegA_23x(), reg_types_.Integer()); 1812 break; 1813 case Instruction::CMPL_DOUBLE: 1814 case Instruction::CMPG_DOUBLE: 1815 if (!work_line_->VerifyRegisterTypeWide(inst->VRegB_23x(), reg_types_.DoubleLo(), 1816 reg_types_.DoubleHi())) { 1817 break; 1818 } 1819 if (!work_line_->VerifyRegisterTypeWide(inst->VRegC_23x(), reg_types_.DoubleLo(), 1820 reg_types_.DoubleHi())) { 1821 break; 1822 } 1823 work_line_->SetRegisterType(inst->VRegA_23x(), reg_types_.Integer()); 1824 break; 1825 case Instruction::CMP_LONG: 1826 if (!work_line_->VerifyRegisterTypeWide(inst->VRegB_23x(), reg_types_.LongLo(), 1827 reg_types_.LongHi())) { 1828 break; 1829 } 1830 if (!work_line_->VerifyRegisterTypeWide(inst->VRegC_23x(), reg_types_.LongLo(), 1831 reg_types_.LongHi())) { 1832 break; 1833 } 1834 work_line_->SetRegisterType(inst->VRegA_23x(), reg_types_.Integer()); 1835 break; 1836 case Instruction::THROW: { 1837 const RegType& res_type = work_line_->GetRegisterType(inst->VRegA_11x()); 1838 if (!reg_types_.JavaLangThrowable(false).IsAssignableFrom(res_type)) { 1839 Fail(res_type.IsUnresolvedTypes() ? VERIFY_ERROR_NO_CLASS : VERIFY_ERROR_BAD_CLASS_SOFT) 1840 << "thrown class " << res_type << " not instanceof Throwable"; 1841 } 1842 break; 1843 } 1844 case Instruction::GOTO: 1845 case Instruction::GOTO_16: 1846 case Instruction::GOTO_32: 1847 /* no effect on or use of registers */ 1848 break; 1849 1850 case Instruction::PACKED_SWITCH: 1851 case Instruction::SPARSE_SWITCH: 1852 /* verify that vAA is an integer, or can be converted to one */ 1853 work_line_->VerifyRegisterType(inst->VRegA_31t(), reg_types_.Integer()); 1854 break; 1855 1856 case Instruction::FILL_ARRAY_DATA: { 1857 /* Similar to the verification done for APUT */ 1858 const RegType& array_type = work_line_->GetRegisterType(inst->VRegA_31t()); 1859 /* array_type can be null if the reg type is Zero */ 1860 if (!array_type.IsZero()) { 1861 if (!array_type.IsArrayTypes()) { 1862 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid fill-array-data with array type " 1863 << array_type; 1864 } else { 1865 const RegType& component_type = reg_types_.GetComponentType(array_type, 1866 class_loader_->Get()); 1867 DCHECK(!component_type.IsConflict()); 1868 if (component_type.IsNonZeroReferenceTypes()) { 1869 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid fill-array-data with component type " 1870 << component_type; 1871 } else { 1872 // Now verify if the element width in the table matches the element width declared in 1873 // the array 1874 const uint16_t* array_data = insns + (insns[1] | (((int32_t) insns[2]) << 16)); 1875 if (array_data[0] != Instruction::kArrayDataSignature) { 1876 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid magic for array-data"; 1877 } else { 1878 size_t elem_width = Primitive::ComponentSize(component_type.GetPrimitiveType()); 1879 // Since we don't compress the data in Dex, expect to see equal width of data stored 1880 // in the table and expected from the array class. 1881 if (array_data[1] != elem_width) { 1882 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array-data size mismatch (" << array_data[1] 1883 << " vs " << elem_width << ")"; 1884 } 1885 } 1886 } 1887 } 1888 } 1889 break; 1890 } 1891 case Instruction::IF_EQ: 1892 case Instruction::IF_NE: { 1893 const RegType& reg_type1 = work_line_->GetRegisterType(inst->VRegA_22t()); 1894 const RegType& reg_type2 = work_line_->GetRegisterType(inst->VRegB_22t()); 1895 bool mismatch = false; 1896 if (reg_type1.IsZero()) { // zero then integral or reference expected 1897 mismatch = !reg_type2.IsReferenceTypes() && !reg_type2.IsIntegralTypes(); 1898 } else if (reg_type1.IsReferenceTypes()) { // both references? 1899 mismatch = !reg_type2.IsReferenceTypes(); 1900 } else { // both integral? 1901 mismatch = !reg_type1.IsIntegralTypes() || !reg_type2.IsIntegralTypes(); 1902 } 1903 if (mismatch) { 1904 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "args to if-eq/if-ne (" << reg_type1 << "," 1905 << reg_type2 << ") must both be references or integral"; 1906 } 1907 break; 1908 } 1909 case Instruction::IF_LT: 1910 case Instruction::IF_GE: 1911 case Instruction::IF_GT: 1912 case Instruction::IF_LE: { 1913 const RegType& reg_type1 = work_line_->GetRegisterType(inst->VRegA_22t()); 1914 const RegType& reg_type2 = work_line_->GetRegisterType(inst->VRegB_22t()); 1915 if (!reg_type1.IsIntegralTypes() || !reg_type2.IsIntegralTypes()) { 1916 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "args to 'if' (" << reg_type1 << "," 1917 << reg_type2 << ") must be integral"; 1918 } 1919 break; 1920 } 1921 case Instruction::IF_EQZ: 1922 case Instruction::IF_NEZ: { 1923 const RegType& reg_type = work_line_->GetRegisterType(inst->VRegA_21t()); 1924 if (!reg_type.IsReferenceTypes() && !reg_type.IsIntegralTypes()) { 1925 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "type " << reg_type 1926 << " unexpected as arg to if-eqz/if-nez"; 1927 } 1928 1929 // Find previous instruction - its existence is a precondition to peephole optimization. 1930 uint32_t instance_of_idx = 0; 1931 if (0 != work_insn_idx_) { 1932 instance_of_idx = work_insn_idx_ - 1; 1933 while (0 != instance_of_idx && !insn_flags_[instance_of_idx].IsOpcode()) { 1934 instance_of_idx--; 1935 } 1936 CHECK(insn_flags_[instance_of_idx].IsOpcode()); 1937 } else { 1938 break; 1939 } 1940 1941 const Instruction* instance_of_inst = Instruction::At(code_item_->insns_ + instance_of_idx); 1942 1943 /* Check for peep-hole pattern of: 1944 * ...; 1945 * instance-of vX, vY, T; 1946 * ifXXX vX, label ; 1947 * ...; 1948 * label: 1949 * ...; 1950 * and sharpen the type of vY to be type T. 1951 * Note, this pattern can't be if: 1952 * - if there are other branches to this branch, 1953 * - when vX == vY. 1954 */ 1955 if (!CurrentInsnFlags()->IsBranchTarget() && 1956 (Instruction::INSTANCE_OF == instance_of_inst->Opcode()) && 1957 (inst->VRegA_21t() == instance_of_inst->VRegA_22c()) && 1958 (instance_of_inst->VRegA_22c() != instance_of_inst->VRegB_22c())) { 1959 // Check the type of the instance-of is different than that of registers type, as if they 1960 // are the same there is no work to be done here. Check that the conversion is not to or 1961 // from an unresolved type as type information is imprecise. If the instance-of is to an 1962 // interface then ignore the type information as interfaces can only be treated as Objects 1963 // and we don't want to disallow field and other operations on the object. If the value 1964 // being instance-of checked against is known null (zero) then allow the optimization as 1965 // we didn't have type information. If the merge of the instance-of type with the original 1966 // type is assignable to the original then allow optimization. This check is performed to 1967 // ensure that subsequent merges don't lose type information - such as becoming an 1968 // interface from a class that would lose information relevant to field checks. 1969 const RegType& orig_type = work_line_->GetRegisterType(instance_of_inst->VRegB_22c()); 1970 const RegType& cast_type = ResolveClassAndCheckAccess(instance_of_inst->VRegC_22c()); 1971 1972 if (!orig_type.Equals(cast_type) && 1973 !cast_type.IsUnresolvedTypes() && !orig_type.IsUnresolvedTypes() && 1974 !cast_type.GetClass()->IsInterface() && 1975 (orig_type.IsZero() || 1976 orig_type.IsStrictlyAssignableFrom(cast_type.Merge(orig_type, ®_types_)))) { 1977 RegisterLine* update_line = RegisterLine::Create(code_item_->registers_size_, this); 1978 if (inst->Opcode() == Instruction::IF_EQZ) { 1979 fallthrough_line.reset(update_line); 1980 } else { 1981 branch_line.reset(update_line); 1982 } 1983 update_line->CopyFromLine(work_line_.get()); 1984 update_line->SetRegisterType(instance_of_inst->VRegB_22c(), cast_type); 1985 if (!insn_flags_[instance_of_idx].IsBranchTarget() && 0 != instance_of_idx) { 1986 // See if instance-of was preceded by a move-object operation, common due to the small 1987 // register encoding space of instance-of, and propagate type information to the source 1988 // of the move-object. 1989 uint32_t move_idx = instance_of_idx - 1; 1990 while (0 != move_idx && !insn_flags_[move_idx].IsOpcode()) { 1991 move_idx--; 1992 } 1993 CHECK(insn_flags_[move_idx].IsOpcode()); 1994 const Instruction* move_inst = Instruction::At(code_item_->insns_ + move_idx); 1995 switch (move_inst->Opcode()) { 1996 case Instruction::MOVE_OBJECT: 1997 if (move_inst->VRegA_12x() == instance_of_inst->VRegB_22c()) { 1998 update_line->SetRegisterType(move_inst->VRegB_12x(), cast_type); 1999 } 2000 break; 2001 case Instruction::MOVE_OBJECT_FROM16: 2002 if (move_inst->VRegA_22x() == instance_of_inst->VRegB_22c()) { 2003 update_line->SetRegisterType(move_inst->VRegB_22x(), cast_type); 2004 } 2005 break; 2006 case Instruction::MOVE_OBJECT_16: 2007 if (move_inst->VRegA_32x() == instance_of_inst->VRegB_22c()) { 2008 update_line->SetRegisterType(move_inst->VRegB_32x(), cast_type); 2009 } 2010 break; 2011 default: 2012 break; 2013 } 2014 } 2015 } 2016 } 2017 2018 break; 2019 } 2020 case Instruction::IF_LTZ: 2021 case Instruction::IF_GEZ: 2022 case Instruction::IF_GTZ: 2023 case Instruction::IF_LEZ: { 2024 const RegType& reg_type = work_line_->GetRegisterType(inst->VRegA_21t()); 2025 if (!reg_type.IsIntegralTypes()) { 2026 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "type " << reg_type 2027 << " unexpected as arg to if-ltz/if-gez/if-gtz/if-lez"; 2028 } 2029 break; 2030 } 2031 case Instruction::AGET_BOOLEAN: 2032 VerifyAGet(inst, reg_types_.Boolean(), true); 2033 break; 2034 case Instruction::AGET_BYTE: 2035 VerifyAGet(inst, reg_types_.Byte(), true); 2036 break; 2037 case Instruction::AGET_CHAR: 2038 VerifyAGet(inst, reg_types_.Char(), true); 2039 break; 2040 case Instruction::AGET_SHORT: 2041 VerifyAGet(inst, reg_types_.Short(), true); 2042 break; 2043 case Instruction::AGET: 2044 VerifyAGet(inst, reg_types_.Integer(), true); 2045 break; 2046 case Instruction::AGET_WIDE: 2047 VerifyAGet(inst, reg_types_.LongLo(), true); 2048 break; 2049 case Instruction::AGET_OBJECT: 2050 VerifyAGet(inst, reg_types_.JavaLangObject(false), false); 2051 break; 2052 2053 case Instruction::APUT_BOOLEAN: 2054 VerifyAPut(inst, reg_types_.Boolean(), true); 2055 break; 2056 case Instruction::APUT_BYTE: 2057 VerifyAPut(inst, reg_types_.Byte(), true); 2058 break; 2059 case Instruction::APUT_CHAR: 2060 VerifyAPut(inst, reg_types_.Char(), true); 2061 break; 2062 case Instruction::APUT_SHORT: 2063 VerifyAPut(inst, reg_types_.Short(), true); 2064 break; 2065 case Instruction::APUT: 2066 VerifyAPut(inst, reg_types_.Integer(), true); 2067 break; 2068 case Instruction::APUT_WIDE: 2069 VerifyAPut(inst, reg_types_.LongLo(), true); 2070 break; 2071 case Instruction::APUT_OBJECT: 2072 VerifyAPut(inst, reg_types_.JavaLangObject(false), false); 2073 break; 2074 2075 case Instruction::IGET_BOOLEAN: 2076 VerifyISGet(inst, reg_types_.Boolean(), true, false); 2077 break; 2078 case Instruction::IGET_BYTE: 2079 VerifyISGet(inst, reg_types_.Byte(), true, false); 2080 break; 2081 case Instruction::IGET_CHAR: 2082 VerifyISGet(inst, reg_types_.Char(), true, false); 2083 break; 2084 case Instruction::IGET_SHORT: 2085 VerifyISGet(inst, reg_types_.Short(), true, false); 2086 break; 2087 case Instruction::IGET: 2088 VerifyISGet(inst, reg_types_.Integer(), true, false); 2089 break; 2090 case Instruction::IGET_WIDE: 2091 VerifyISGet(inst, reg_types_.LongLo(), true, false); 2092 break; 2093 case Instruction::IGET_OBJECT: 2094 VerifyISGet(inst, reg_types_.JavaLangObject(false), false, false); 2095 break; 2096 2097 case Instruction::IPUT_BOOLEAN: 2098 VerifyISPut(inst, reg_types_.Boolean(), true, false); 2099 break; 2100 case Instruction::IPUT_BYTE: 2101 VerifyISPut(inst, reg_types_.Byte(), true, false); 2102 break; 2103 case Instruction::IPUT_CHAR: 2104 VerifyISPut(inst, reg_types_.Char(), true, false); 2105 break; 2106 case Instruction::IPUT_SHORT: 2107 VerifyISPut(inst, reg_types_.Short(), true, false); 2108 break; 2109 case Instruction::IPUT: 2110 VerifyISPut(inst, reg_types_.Integer(), true, false); 2111 break; 2112 case Instruction::IPUT_WIDE: 2113 VerifyISPut(inst, reg_types_.LongLo(), true, false); 2114 break; 2115 case Instruction::IPUT_OBJECT: 2116 VerifyISPut(inst, reg_types_.JavaLangObject(false), false, false); 2117 break; 2118 2119 case Instruction::SGET_BOOLEAN: 2120 VerifyISGet(inst, reg_types_.Boolean(), true, true); 2121 break; 2122 case Instruction::SGET_BYTE: 2123 VerifyISGet(inst, reg_types_.Byte(), true, true); 2124 break; 2125 case Instruction::SGET_CHAR: 2126 VerifyISGet(inst, reg_types_.Char(), true, true); 2127 break; 2128 case Instruction::SGET_SHORT: 2129 VerifyISGet(inst, reg_types_.Short(), true, true); 2130 break; 2131 case Instruction::SGET: 2132 VerifyISGet(inst, reg_types_.Integer(), true, true); 2133 break; 2134 case Instruction::SGET_WIDE: 2135 VerifyISGet(inst, reg_types_.LongLo(), true, true); 2136 break; 2137 case Instruction::SGET_OBJECT: 2138 VerifyISGet(inst, reg_types_.JavaLangObject(false), false, true); 2139 break; 2140 2141 case Instruction::SPUT_BOOLEAN: 2142 VerifyISPut(inst, reg_types_.Boolean(), true, true); 2143 break; 2144 case Instruction::SPUT_BYTE: 2145 VerifyISPut(inst, reg_types_.Byte(), true, true); 2146 break; 2147 case Instruction::SPUT_CHAR: 2148 VerifyISPut(inst, reg_types_.Char(), true, true); 2149 break; 2150 case Instruction::SPUT_SHORT: 2151 VerifyISPut(inst, reg_types_.Short(), true, true); 2152 break; 2153 case Instruction::SPUT: 2154 VerifyISPut(inst, reg_types_.Integer(), true, true); 2155 break; 2156 case Instruction::SPUT_WIDE: 2157 VerifyISPut(inst, reg_types_.LongLo(), true, true); 2158 break; 2159 case Instruction::SPUT_OBJECT: 2160 VerifyISPut(inst, reg_types_.JavaLangObject(false), false, true); 2161 break; 2162 2163 case Instruction::INVOKE_VIRTUAL: 2164 case Instruction::INVOKE_VIRTUAL_RANGE: 2165 case Instruction::INVOKE_SUPER: 2166 case Instruction::INVOKE_SUPER_RANGE: { 2167 bool is_range = (inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE || 2168 inst->Opcode() == Instruction::INVOKE_SUPER_RANGE); 2169 bool is_super = (inst->Opcode() == Instruction::INVOKE_SUPER || 2170 inst->Opcode() == Instruction::INVOKE_SUPER_RANGE); 2171 mirror::ArtMethod* called_method = VerifyInvocationArgs(inst, METHOD_VIRTUAL, is_range, 2172 is_super); 2173 const RegType* return_type = nullptr; 2174 if (called_method != nullptr) { 2175 Thread* self = Thread::Current(); 2176 StackHandleScope<1> hs(self); 2177 Handle<mirror::ArtMethod> h_called_method(hs.NewHandle(called_method)); 2178 MethodHelper mh(h_called_method); 2179 mirror::Class* return_type_class = mh.GetReturnType(can_load_classes_); 2180 if (return_type_class != nullptr) { 2181 return_type = ®_types_.FromClass(h_called_method->GetReturnTypeDescriptor(), 2182 return_type_class, 2183 return_type_class->CannotBeAssignedFromOtherTypes()); 2184 } else { 2185 DCHECK(!can_load_classes_ || self->IsExceptionPending()); 2186 self->ClearException(); 2187 } 2188 } 2189 if (return_type == nullptr) { 2190 uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); 2191 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx); 2192 uint32_t return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_; 2193 const char* descriptor = dex_file_->StringByTypeIdx(return_type_idx); 2194 return_type = ®_types_.FromDescriptor(class_loader_->Get(), descriptor, false); 2195 } 2196 if (!return_type->IsLowHalf()) { 2197 work_line_->SetResultRegisterType(*return_type); 2198 } else { 2199 work_line_->SetResultRegisterTypeWide(*return_type, return_type->HighHalf(®_types_)); 2200 } 2201 just_set_result = true; 2202 break; 2203 } 2204 case Instruction::INVOKE_DIRECT: 2205 case Instruction::INVOKE_DIRECT_RANGE: { 2206 bool is_range = (inst->Opcode() == Instruction::INVOKE_DIRECT_RANGE); 2207 mirror::ArtMethod* called_method = VerifyInvocationArgs(inst, METHOD_DIRECT, 2208 is_range, false); 2209 const char* return_type_descriptor; 2210 bool is_constructor; 2211 if (called_method == NULL) { 2212 uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); 2213 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx); 2214 is_constructor = strcmp("<init>", dex_file_->StringDataByIdx(method_id.name_idx_)) == 0; 2215 uint32_t return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_; 2216 return_type_descriptor = dex_file_->StringByTypeIdx(return_type_idx); 2217 } else { 2218 is_constructor = called_method->IsConstructor(); 2219 return_type_descriptor = called_method->GetReturnTypeDescriptor(); 2220 } 2221 if (is_constructor) { 2222 /* 2223 * Some additional checks when calling a constructor. We know from the invocation arg check 2224 * that the "this" argument is an instance of called_method->klass. Now we further restrict 2225 * that to require that called_method->klass is the same as this->klass or this->super, 2226 * allowing the latter only if the "this" argument is the same as the "this" argument to 2227 * this method (which implies that we're in a constructor ourselves). 2228 */ 2229 const RegType& this_type = work_line_->GetInvocationThis(inst, is_range); 2230 if (this_type.IsConflict()) // failure. 2231 break; 2232 2233 /* no null refs allowed (?) */ 2234 if (this_type.IsZero()) { 2235 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unable to initialize null ref"; 2236 break; 2237 } 2238 2239 /* must be in same class or in superclass */ 2240 // const RegType& this_super_klass = this_type.GetSuperClass(®_types_); 2241 // TODO: re-enable constructor type verification 2242 // if (this_super_klass.IsConflict()) { 2243 // Unknown super class, fail so we re-check at runtime. 2244 // Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "super class unknown for '" << this_type << "'"; 2245 // break; 2246 // } 2247 2248 /* arg must be an uninitialized reference */ 2249 if (!this_type.IsUninitializedTypes()) { 2250 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Expected initialization on uninitialized reference " 2251 << this_type; 2252 break; 2253 } 2254 2255 /* 2256 * Replace the uninitialized reference with an initialized one. We need to do this for all 2257 * registers that have the same object instance in them, not just the "this" register. 2258 */ 2259 work_line_->MarkRefsAsInitialized(this_type); 2260 } 2261 const RegType& return_type = reg_types_.FromDescriptor(class_loader_->Get(), 2262 return_type_descriptor, false); 2263 if (!return_type.IsLowHalf()) { 2264 work_line_->SetResultRegisterType(return_type); 2265 } else { 2266 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(®_types_)); 2267 } 2268 just_set_result = true; 2269 break; 2270 } 2271 case Instruction::INVOKE_STATIC: 2272 case Instruction::INVOKE_STATIC_RANGE: { 2273 bool is_range = (inst->Opcode() == Instruction::INVOKE_STATIC_RANGE); 2274 mirror::ArtMethod* called_method = VerifyInvocationArgs(inst, 2275 METHOD_STATIC, 2276 is_range, 2277 false); 2278 const char* descriptor; 2279 if (called_method == NULL) { 2280 uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); 2281 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx); 2282 uint32_t return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_; 2283 descriptor = dex_file_->StringByTypeIdx(return_type_idx); 2284 } else { 2285 descriptor = called_method->GetReturnTypeDescriptor(); 2286 } 2287 const RegType& return_type = reg_types_.FromDescriptor(class_loader_->Get(), descriptor, 2288 false); 2289 if (!return_type.IsLowHalf()) { 2290 work_line_->SetResultRegisterType(return_type); 2291 } else { 2292 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(®_types_)); 2293 } 2294 just_set_result = true; 2295 } 2296 break; 2297 case Instruction::INVOKE_INTERFACE: 2298 case Instruction::INVOKE_INTERFACE_RANGE: { 2299 bool is_range = (inst->Opcode() == Instruction::INVOKE_INTERFACE_RANGE); 2300 mirror::ArtMethod* abs_method = VerifyInvocationArgs(inst, 2301 METHOD_INTERFACE, 2302 is_range, 2303 false); 2304 if (abs_method != NULL) { 2305 mirror::Class* called_interface = abs_method->GetDeclaringClass(); 2306 if (!called_interface->IsInterface() && !called_interface->IsObjectClass()) { 2307 Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected interface class in invoke-interface '" 2308 << PrettyMethod(abs_method) << "'"; 2309 break; 2310 } 2311 } 2312 /* Get the type of the "this" arg, which should either be a sub-interface of called 2313 * interface or Object (see comments in RegType::JoinClass). 2314 */ 2315 const RegType& this_type = work_line_->GetInvocationThis(inst, is_range); 2316 if (this_type.IsZero()) { 2317 /* null pointer always passes (and always fails at runtime) */ 2318 } else { 2319 if (this_type.IsUninitializedTypes()) { 2320 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "interface call on uninitialized object " 2321 << this_type; 2322 break; 2323 } 2324 // In the past we have tried to assert that "called_interface" is assignable 2325 // from "this_type.GetClass()", however, as we do an imprecise Join 2326 // (RegType::JoinClass) we don't have full information on what interfaces are 2327 // implemented by "this_type". For example, two classes may implement the same 2328 // interfaces and have a common parent that doesn't implement the interface. The 2329 // join will set "this_type" to the parent class and a test that this implements 2330 // the interface will incorrectly fail. 2331 } 2332 /* 2333 * We don't have an object instance, so we can't find the concrete method. However, all of 2334 * the type information is in the abstract method, so we're good. 2335 */ 2336 const char* descriptor; 2337 if (abs_method == NULL) { 2338 uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); 2339 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx); 2340 uint32_t return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_; 2341 descriptor = dex_file_->StringByTypeIdx(return_type_idx); 2342 } else { 2343 descriptor = abs_method->GetReturnTypeDescriptor(); 2344 } 2345 const RegType& return_type = reg_types_.FromDescriptor(class_loader_->Get(), descriptor, 2346 false); 2347 if (!return_type.IsLowHalf()) { 2348 work_line_->SetResultRegisterType(return_type); 2349 } else { 2350 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(®_types_)); 2351 } 2352 just_set_result = true; 2353 break; 2354 } 2355 case Instruction::NEG_INT: 2356 case Instruction::NOT_INT: 2357 work_line_->CheckUnaryOp(inst, reg_types_.Integer(), reg_types_.Integer()); 2358 break; 2359 case Instruction::NEG_LONG: 2360 case Instruction::NOT_LONG: 2361 work_line_->CheckUnaryOpWide(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2362 reg_types_.LongLo(), reg_types_.LongHi()); 2363 break; 2364 case Instruction::NEG_FLOAT: 2365 work_line_->CheckUnaryOp(inst, reg_types_.Float(), reg_types_.Float()); 2366 break; 2367 case Instruction::NEG_DOUBLE: 2368 work_line_->CheckUnaryOpWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2369 reg_types_.DoubleLo(), reg_types_.DoubleHi()); 2370 break; 2371 case Instruction::INT_TO_LONG: 2372 work_line_->CheckUnaryOpToWide(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2373 reg_types_.Integer()); 2374 break; 2375 case Instruction::INT_TO_FLOAT: 2376 work_line_->CheckUnaryOp(inst, reg_types_.Float(), reg_types_.Integer()); 2377 break; 2378 case Instruction::INT_TO_DOUBLE: 2379 work_line_->CheckUnaryOpToWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2380 reg_types_.Integer()); 2381 break; 2382 case Instruction::LONG_TO_INT: 2383 work_line_->CheckUnaryOpFromWide(inst, reg_types_.Integer(), 2384 reg_types_.LongLo(), reg_types_.LongHi()); 2385 break; 2386 case Instruction::LONG_TO_FLOAT: 2387 work_line_->CheckUnaryOpFromWide(inst, reg_types_.Float(), 2388 reg_types_.LongLo(), reg_types_.LongHi()); 2389 break; 2390 case Instruction::LONG_TO_DOUBLE: 2391 work_line_->CheckUnaryOpWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2392 reg_types_.LongLo(), reg_types_.LongHi()); 2393 break; 2394 case Instruction::FLOAT_TO_INT: 2395 work_line_->CheckUnaryOp(inst, reg_types_.Integer(), reg_types_.Float()); 2396 break; 2397 case Instruction::FLOAT_TO_LONG: 2398 work_line_->CheckUnaryOpToWide(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2399 reg_types_.Float()); 2400 break; 2401 case Instruction::FLOAT_TO_DOUBLE: 2402 work_line_->CheckUnaryOpToWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2403 reg_types_.Float()); 2404 break; 2405 case Instruction::DOUBLE_TO_INT: 2406 work_line_->CheckUnaryOpFromWide(inst, reg_types_.Integer(), 2407 reg_types_.DoubleLo(), reg_types_.DoubleHi()); 2408 break; 2409 case Instruction::DOUBLE_TO_LONG: 2410 work_line_->CheckUnaryOpWide(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2411 reg_types_.DoubleLo(), reg_types_.DoubleHi()); 2412 break; 2413 case Instruction::DOUBLE_TO_FLOAT: 2414 work_line_->CheckUnaryOpFromWide(inst, reg_types_.Float(), 2415 reg_types_.DoubleLo(), reg_types_.DoubleHi()); 2416 break; 2417 case Instruction::INT_TO_BYTE: 2418 work_line_->CheckUnaryOp(inst, reg_types_.Byte(), reg_types_.Integer()); 2419 break; 2420 case Instruction::INT_TO_CHAR: 2421 work_line_->CheckUnaryOp(inst, reg_types_.Char(), reg_types_.Integer()); 2422 break; 2423 case Instruction::INT_TO_SHORT: 2424 work_line_->CheckUnaryOp(inst, reg_types_.Short(), reg_types_.Integer()); 2425 break; 2426 2427 case Instruction::ADD_INT: 2428 case Instruction::SUB_INT: 2429 case Instruction::MUL_INT: 2430 case Instruction::REM_INT: 2431 case Instruction::DIV_INT: 2432 case Instruction::SHL_INT: 2433 case Instruction::SHR_INT: 2434 case Instruction::USHR_INT: 2435 work_line_->CheckBinaryOp(inst, reg_types_.Integer(), reg_types_.Integer(), 2436 reg_types_.Integer(), false); 2437 break; 2438 case Instruction::AND_INT: 2439 case Instruction::OR_INT: 2440 case Instruction::XOR_INT: 2441 work_line_->CheckBinaryOp(inst, reg_types_.Integer(), reg_types_.Integer(), 2442 reg_types_.Integer(), true); 2443 break; 2444 case Instruction::ADD_LONG: 2445 case Instruction::SUB_LONG: 2446 case Instruction::MUL_LONG: 2447 case Instruction::DIV_LONG: 2448 case Instruction::REM_LONG: 2449 case Instruction::AND_LONG: 2450 case Instruction::OR_LONG: 2451 case Instruction::XOR_LONG: 2452 work_line_->CheckBinaryOpWide(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2453 reg_types_.LongLo(), reg_types_.LongHi(), 2454 reg_types_.LongLo(), reg_types_.LongHi()); 2455 break; 2456 case Instruction::SHL_LONG: 2457 case Instruction::SHR_LONG: 2458 case Instruction::USHR_LONG: 2459 /* shift distance is Int, making these different from other binary operations */ 2460 work_line_->CheckBinaryOpWideShift(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2461 reg_types_.Integer()); 2462 break; 2463 case Instruction::ADD_FLOAT: 2464 case Instruction::SUB_FLOAT: 2465 case Instruction::MUL_FLOAT: 2466 case Instruction::DIV_FLOAT: 2467 case Instruction::REM_FLOAT: 2468 work_line_->CheckBinaryOp(inst, 2469 reg_types_.Float(), 2470 reg_types_.Float(), 2471 reg_types_.Float(), 2472 false); 2473 break; 2474 case Instruction::ADD_DOUBLE: 2475 case Instruction::SUB_DOUBLE: 2476 case Instruction::MUL_DOUBLE: 2477 case Instruction::DIV_DOUBLE: 2478 case Instruction::REM_DOUBLE: 2479 work_line_->CheckBinaryOpWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2480 reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2481 reg_types_.DoubleLo(), reg_types_.DoubleHi()); 2482 break; 2483 case Instruction::ADD_INT_2ADDR: 2484 case Instruction::SUB_INT_2ADDR: 2485 case Instruction::MUL_INT_2ADDR: 2486 case Instruction::REM_INT_2ADDR: 2487 case Instruction::SHL_INT_2ADDR: 2488 case Instruction::SHR_INT_2ADDR: 2489 case Instruction::USHR_INT_2ADDR: 2490 work_line_->CheckBinaryOp2addr(inst, 2491 reg_types_.Integer(), 2492 reg_types_.Integer(), 2493 reg_types_.Integer(), 2494 false); 2495 break; 2496 case Instruction::AND_INT_2ADDR: 2497 case Instruction::OR_INT_2ADDR: 2498 case Instruction::XOR_INT_2ADDR: 2499 work_line_->CheckBinaryOp2addr(inst, 2500 reg_types_.Integer(), 2501 reg_types_.Integer(), 2502 reg_types_.Integer(), 2503 true); 2504 break; 2505 case Instruction::DIV_INT_2ADDR: 2506 work_line_->CheckBinaryOp2addr(inst, 2507 reg_types_.Integer(), 2508 reg_types_.Integer(), 2509 reg_types_.Integer(), 2510 false); 2511 break; 2512 case Instruction::ADD_LONG_2ADDR: 2513 case Instruction::SUB_LONG_2ADDR: 2514 case Instruction::MUL_LONG_2ADDR: 2515 case Instruction::DIV_LONG_2ADDR: 2516 case Instruction::REM_LONG_2ADDR: 2517 case Instruction::AND_LONG_2ADDR: 2518 case Instruction::OR_LONG_2ADDR: 2519 case Instruction::XOR_LONG_2ADDR: 2520 work_line_->CheckBinaryOp2addrWide(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2521 reg_types_.LongLo(), reg_types_.LongHi(), 2522 reg_types_.LongLo(), reg_types_.LongHi()); 2523 break; 2524 case Instruction::SHL_LONG_2ADDR: 2525 case Instruction::SHR_LONG_2ADDR: 2526 case Instruction::USHR_LONG_2ADDR: 2527 work_line_->CheckBinaryOp2addrWideShift(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2528 reg_types_.Integer()); 2529 break; 2530 case Instruction::ADD_FLOAT_2ADDR: 2531 case Instruction::SUB_FLOAT_2ADDR: 2532 case Instruction::MUL_FLOAT_2ADDR: 2533 case Instruction::DIV_FLOAT_2ADDR: 2534 case Instruction::REM_FLOAT_2ADDR: 2535 work_line_->CheckBinaryOp2addr(inst, 2536 reg_types_.Float(), 2537 reg_types_.Float(), 2538 reg_types_.Float(), 2539 false); 2540 break; 2541 case Instruction::ADD_DOUBLE_2ADDR: 2542 case Instruction::SUB_DOUBLE_2ADDR: 2543 case Instruction::MUL_DOUBLE_2ADDR: 2544 case Instruction::DIV_DOUBLE_2ADDR: 2545 case Instruction::REM_DOUBLE_2ADDR: 2546 work_line_->CheckBinaryOp2addrWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2547 reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2548 reg_types_.DoubleLo(), reg_types_.DoubleHi()); 2549 break; 2550 case Instruction::ADD_INT_LIT16: 2551 case Instruction::RSUB_INT: 2552 case Instruction::MUL_INT_LIT16: 2553 case Instruction::DIV_INT_LIT16: 2554 case Instruction::REM_INT_LIT16: 2555 work_line_->CheckLiteralOp(inst, reg_types_.Integer(), reg_types_.Integer(), false, true); 2556 break; 2557 case Instruction::AND_INT_LIT16: 2558 case Instruction::OR_INT_LIT16: 2559 case Instruction::XOR_INT_LIT16: 2560 work_line_->CheckLiteralOp(inst, reg_types_.Integer(), reg_types_.Integer(), true, true); 2561 break; 2562 case Instruction::ADD_INT_LIT8: 2563 case Instruction::RSUB_INT_LIT8: 2564 case Instruction::MUL_INT_LIT8: 2565 case Instruction::DIV_INT_LIT8: 2566 case Instruction::REM_INT_LIT8: 2567 case Instruction::SHL_INT_LIT8: 2568 case Instruction::SHR_INT_LIT8: 2569 case Instruction::USHR_INT_LIT8: 2570 work_line_->CheckLiteralOp(inst, reg_types_.Integer(), reg_types_.Integer(), false, false); 2571 break; 2572 case Instruction::AND_INT_LIT8: 2573 case Instruction::OR_INT_LIT8: 2574 case Instruction::XOR_INT_LIT8: 2575 work_line_->CheckLiteralOp(inst, reg_types_.Integer(), reg_types_.Integer(), true, false); 2576 break; 2577 2578 // Special instructions. 2579 case Instruction::RETURN_VOID_BARRIER: 2580 if (!IsConstructor() || IsStatic()) { 2581 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-void-barrier not expected"; 2582 } 2583 break; 2584 // Note: the following instructions encode offsets derived from class linking. 2585 // As such they use Class*/Field*/AbstractMethod* as these offsets only have 2586 // meaning if the class linking and resolution were successful. 2587 case Instruction::IGET_QUICK: 2588 VerifyIGetQuick(inst, reg_types_.Integer(), true); 2589 break; 2590 case Instruction::IGET_WIDE_QUICK: 2591 VerifyIGetQuick(inst, reg_types_.LongLo(), true); 2592 break; 2593 case Instruction::IGET_OBJECT_QUICK: 2594 VerifyIGetQuick(inst, reg_types_.JavaLangObject(false), false); 2595 break; 2596 case Instruction::IPUT_QUICK: 2597 VerifyIPutQuick(inst, reg_types_.Integer(), true); 2598 break; 2599 case Instruction::IPUT_WIDE_QUICK: 2600 VerifyIPutQuick(inst, reg_types_.LongLo(), true); 2601 break; 2602 case Instruction::IPUT_OBJECT_QUICK: 2603 VerifyIPutQuick(inst, reg_types_.JavaLangObject(false), false); 2604 break; 2605 case Instruction::INVOKE_VIRTUAL_QUICK: 2606 case Instruction::INVOKE_VIRTUAL_RANGE_QUICK: { 2607 bool is_range = (inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE_QUICK); 2608 mirror::ArtMethod* called_method = VerifyInvokeVirtualQuickArgs(inst, is_range); 2609 if (called_method != NULL) { 2610 const char* descriptor = called_method->GetReturnTypeDescriptor(); 2611 const RegType& return_type = reg_types_.FromDescriptor(class_loader_->Get(), descriptor, 2612 false); 2613 if (!return_type.IsLowHalf()) { 2614 work_line_->SetResultRegisterType(return_type); 2615 } else { 2616 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(®_types_)); 2617 } 2618 just_set_result = true; 2619 } 2620 break; 2621 } 2622 2623 /* These should never appear during verification. */ 2624 case Instruction::UNUSED_3E: 2625 case Instruction::UNUSED_3F: 2626 case Instruction::UNUSED_40: 2627 case Instruction::UNUSED_41: 2628 case Instruction::UNUSED_42: 2629 case Instruction::UNUSED_43: 2630 case Instruction::UNUSED_79: 2631 case Instruction::UNUSED_7A: 2632 case Instruction::UNUSED_EB: 2633 case Instruction::UNUSED_EC: 2634 case Instruction::UNUSED_ED: 2635 case Instruction::UNUSED_EE: 2636 case Instruction::UNUSED_EF: 2637 case Instruction::UNUSED_F0: 2638 case Instruction::UNUSED_F1: 2639 case Instruction::UNUSED_F2: 2640 case Instruction::UNUSED_F3: 2641 case Instruction::UNUSED_F4: 2642 case Instruction::UNUSED_F5: 2643 case Instruction::UNUSED_F6: 2644 case Instruction::UNUSED_F7: 2645 case Instruction::UNUSED_F8: 2646 case Instruction::UNUSED_F9: 2647 case Instruction::UNUSED_FA: 2648 case Instruction::UNUSED_FB: 2649 case Instruction::UNUSED_FC: 2650 case Instruction::UNUSED_FD: 2651 case Instruction::UNUSED_FE: 2652 case Instruction::UNUSED_FF: 2653 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Unexpected opcode " << inst->DumpString(dex_file_); 2654 break; 2655 2656 /* 2657 * DO NOT add a "default" clause here. Without it the compiler will 2658 * complain if an instruction is missing (which is desirable). 2659 */ 2660 } // end - switch (dec_insn.opcode) 2661 2662 if (have_pending_hard_failure_) { 2663 if (Runtime::Current()->IsCompiler()) { 2664 /* When compiling, check that the last failure is a hard failure */ 2665 CHECK_EQ(failures_[failures_.size() - 1], VERIFY_ERROR_BAD_CLASS_HARD); 2666 } 2667 /* immediate failure, reject class */ 2668 info_messages_ << "Rejecting opcode " << inst->DumpString(dex_file_); 2669 return false; 2670 } else if (have_pending_runtime_throw_failure_) { 2671 /* checking interpreter will throw, mark following code as unreachable */ 2672 opcode_flags = Instruction::kThrow; 2673 } 2674 /* 2675 * If we didn't just set the result register, clear it out. This ensures that you can only use 2676 * "move-result" immediately after the result is set. (We could check this statically, but it's 2677 * not expensive and it makes our debugging output cleaner.) 2678 */ 2679 if (!just_set_result) { 2680 work_line_->SetResultTypeToUnknown(); 2681 } 2682 2683 2684 2685 /* 2686 * Handle "branch". Tag the branch target. 2687 * 2688 * NOTE: instructions like Instruction::EQZ provide information about the 2689 * state of the register when the branch is taken or not taken. For example, 2690 * somebody could get a reference field, check it for zero, and if the 2691 * branch is taken immediately store that register in a boolean field 2692 * since the value is known to be zero. We do not currently account for 2693 * that, and will reject the code. 2694 * 2695 * TODO: avoid re-fetching the branch target 2696 */ 2697 if ((opcode_flags & Instruction::kBranch) != 0) { 2698 bool isConditional, selfOkay; 2699 if (!GetBranchOffset(work_insn_idx_, &branch_target, &isConditional, &selfOkay)) { 2700 /* should never happen after static verification */ 2701 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad branch"; 2702 return false; 2703 } 2704 DCHECK_EQ(isConditional, (opcode_flags & Instruction::kContinue) != 0); 2705 if (!CheckNotMoveException(code_item_->insns_, work_insn_idx_ + branch_target)) { 2706 return false; 2707 } 2708 /* update branch target, set "changed" if appropriate */ 2709 if (NULL != branch_line.get()) { 2710 if (!UpdateRegisters(work_insn_idx_ + branch_target, branch_line.get(), false)) { 2711 return false; 2712 } 2713 } else { 2714 if (!UpdateRegisters(work_insn_idx_ + branch_target, work_line_.get(), false)) { 2715 return false; 2716 } 2717 } 2718 } 2719 2720 /* 2721 * Handle "switch". Tag all possible branch targets. 2722 * 2723 * We've already verified that the table is structurally sound, so we 2724 * just need to walk through and tag the targets. 2725 */ 2726 if ((opcode_flags & Instruction::kSwitch) != 0) { 2727 int offset_to_switch = insns[1] | (((int32_t) insns[2]) << 16); 2728 const uint16_t* switch_insns = insns + offset_to_switch; 2729 int switch_count = switch_insns[1]; 2730 int offset_to_targets, targ; 2731 2732 if ((*insns & 0xff) == Instruction::PACKED_SWITCH) { 2733 /* 0 = sig, 1 = count, 2/3 = first key */ 2734 offset_to_targets = 4; 2735 } else { 2736 /* 0 = sig, 1 = count, 2..count * 2 = keys */ 2737 DCHECK((*insns & 0xff) == Instruction::SPARSE_SWITCH); 2738 offset_to_targets = 2 + 2 * switch_count; 2739 } 2740 2741 /* verify each switch target */ 2742 for (targ = 0; targ < switch_count; targ++) { 2743 int offset; 2744 uint32_t abs_offset; 2745 2746 /* offsets are 32-bit, and only partly endian-swapped */ 2747 offset = switch_insns[offset_to_targets + targ * 2] | 2748 (((int32_t) switch_insns[offset_to_targets + targ * 2 + 1]) << 16); 2749 abs_offset = work_insn_idx_ + offset; 2750 DCHECK_LT(abs_offset, code_item_->insns_size_in_code_units_); 2751 if (!CheckNotMoveException(code_item_->insns_, abs_offset)) { 2752 return false; 2753 } 2754 if (!UpdateRegisters(abs_offset, work_line_.get(), false)) { 2755 return false; 2756 } 2757 } 2758 } 2759 2760 /* 2761 * Handle instructions that can throw and that are sitting in a "try" block. (If they're not in a 2762 * "try" block when they throw, control transfers out of the method.) 2763 */ 2764 if ((opcode_flags & Instruction::kThrow) != 0 && insn_flags_[work_insn_idx_].IsInTry()) { 2765 bool within_catch_all = false; 2766 CatchHandlerIterator iterator(*code_item_, work_insn_idx_); 2767 2768 for (; iterator.HasNext(); iterator.Next()) { 2769 if (iterator.GetHandlerTypeIndex() == DexFile::kDexNoIndex16) { 2770 within_catch_all = true; 2771 } 2772 /* 2773 * Merge registers into the "catch" block. We want to use the "savedRegs" rather than 2774 * "work_regs", because at runtime the exception will be thrown before the instruction 2775 * modifies any registers. 2776 */ 2777 if (!UpdateRegisters(iterator.GetHandlerAddress(), saved_line_.get(), false)) { 2778 return false; 2779 } 2780 } 2781 2782 /* 2783 * If the monitor stack depth is nonzero, there must be a "catch all" handler for this 2784 * instruction. This does apply to monitor-exit because of async exception handling. 2785 */ 2786 if (work_line_->MonitorStackDepth() > 0 && !within_catch_all) { 2787 /* 2788 * The state in work_line reflects the post-execution state. If the current instruction is a 2789 * monitor-enter and the monitor stack was empty, we don't need a catch-all (if it throws, 2790 * it will do so before grabbing the lock). 2791 */ 2792 if (inst->Opcode() != Instruction::MONITOR_ENTER || work_line_->MonitorStackDepth() != 1) { 2793 Fail(VERIFY_ERROR_BAD_CLASS_HARD) 2794 << "expected to be within a catch-all for an instruction where a monitor is held"; 2795 return false; 2796 } 2797 } 2798 } 2799 2800 /* Handle "continue". Tag the next consecutive instruction. 2801 * Note: Keep the code handling "continue" case below the "branch" and "switch" cases, 2802 * because it changes work_line_ when performing peephole optimization 2803 * and this change should not be used in those cases. 2804 */ 2805 if ((opcode_flags & Instruction::kContinue) != 0) { 2806 uint32_t next_insn_idx = work_insn_idx_ + CurrentInsnFlags()->GetLengthInCodeUnits(); 2807 if (next_insn_idx >= code_item_->insns_size_in_code_units_) { 2808 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Execution can walk off end of code area"; 2809 return false; 2810 } 2811 // The only way to get to a move-exception instruction is to get thrown there. Make sure the 2812 // next instruction isn't one. 2813 if (!CheckNotMoveException(code_item_->insns_, next_insn_idx)) { 2814 return false; 2815 } 2816 if (NULL != fallthrough_line.get()) { 2817 // Make workline consistent with fallthrough computed from peephole optimization. 2818 work_line_->CopyFromLine(fallthrough_line.get()); 2819 } 2820 if (insn_flags_[next_insn_idx].IsReturn()) { 2821 // For returns we only care about the operand to the return, all other registers are dead. 2822 const Instruction* ret_inst = Instruction::At(code_item_->insns_ + next_insn_idx); 2823 Instruction::Code opcode = ret_inst->Opcode(); 2824 if ((opcode == Instruction::RETURN_VOID) || (opcode == Instruction::RETURN_VOID_BARRIER)) { 2825 work_line_->MarkAllRegistersAsConflicts(); 2826 } else { 2827 if (opcode == Instruction::RETURN_WIDE) { 2828 work_line_->MarkAllRegistersAsConflictsExceptWide(ret_inst->VRegA_11x()); 2829 } else { 2830 work_line_->MarkAllRegistersAsConflictsExcept(ret_inst->VRegA_11x()); 2831 } 2832 } 2833 } 2834 RegisterLine* next_line = reg_table_.GetLine(next_insn_idx); 2835 if (next_line != NULL) { 2836 // Merge registers into what we have for the next instruction, and set the "changed" flag if 2837 // needed. If the merge changes the state of the registers then the work line will be 2838 // updated. 2839 if (!UpdateRegisters(next_insn_idx, work_line_.get(), true)) { 2840 return false; 2841 } 2842 } else { 2843 /* 2844 * We're not recording register data for the next instruction, so we don't know what the 2845 * prior state was. We have to assume that something has changed and re-evaluate it. 2846 */ 2847 insn_flags_[next_insn_idx].SetChanged(); 2848 } 2849 } 2850 2851 /* If we're returning from the method, make sure monitor stack is empty. */ 2852 if ((opcode_flags & Instruction::kReturn) != 0) { 2853 if (!work_line_->VerifyMonitorStackEmpty()) { 2854 return false; 2855 } 2856 } 2857 2858 /* 2859 * Update start_guess. Advance to the next instruction of that's 2860 * possible, otherwise use the branch target if one was found. If 2861 * neither of those exists we're in a return or throw; leave start_guess 2862 * alone and let the caller sort it out. 2863 */ 2864 if ((opcode_flags & Instruction::kContinue) != 0) { 2865 *start_guess = work_insn_idx_ + insn_flags_[work_insn_idx_].GetLengthInCodeUnits(); 2866 } else if ((opcode_flags & Instruction::kBranch) != 0) { 2867 /* we're still okay if branch_target is zero */ 2868 *start_guess = work_insn_idx_ + branch_target; 2869 } 2870 2871 DCHECK_LT(*start_guess, code_item_->insns_size_in_code_units_); 2872 DCHECK(insn_flags_[*start_guess].IsOpcode()); 2873 2874 return true; 2875} // NOLINT(readability/fn_size) 2876 2877const RegType& MethodVerifier::ResolveClassAndCheckAccess(uint32_t class_idx) { 2878 const char* descriptor = dex_file_->StringByTypeIdx(class_idx); 2879 const RegType& referrer = GetDeclaringClass(); 2880 mirror::Class* klass = (*dex_cache_)->GetResolvedType(class_idx); 2881 const RegType& result = 2882 klass != NULL ? reg_types_.FromClass(descriptor, klass, 2883 klass->CannotBeAssignedFromOtherTypes()) 2884 : reg_types_.FromDescriptor(class_loader_->Get(), descriptor, false); 2885 if (result.IsConflict()) { 2886 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "accessing broken descriptor '" << descriptor 2887 << "' in " << referrer; 2888 return result; 2889 } 2890 if (klass == NULL && !result.IsUnresolvedTypes()) { 2891 (*dex_cache_)->SetResolvedType(class_idx, result.GetClass()); 2892 } 2893 // Check if access is allowed. Unresolved types use xxxWithAccessCheck to 2894 // check at runtime if access is allowed and so pass here. If result is 2895 // primitive, skip the access check. 2896 if (result.IsNonZeroReferenceTypes() && !result.IsUnresolvedTypes() && 2897 !referrer.IsUnresolvedTypes() && !referrer.CanAccess(result)) { 2898 Fail(VERIFY_ERROR_ACCESS_CLASS) << "illegal class access: '" 2899 << referrer << "' -> '" << result << "'"; 2900 } 2901 return result; 2902} 2903 2904const RegType& MethodVerifier::GetCaughtExceptionType() { 2905 const RegType* common_super = NULL; 2906 if (code_item_->tries_size_ != 0) { 2907 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item_, 0); 2908 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr); 2909 for (uint32_t i = 0; i < handlers_size; i++) { 2910 CatchHandlerIterator iterator(handlers_ptr); 2911 for (; iterator.HasNext(); iterator.Next()) { 2912 if (iterator.GetHandlerAddress() == (uint32_t) work_insn_idx_) { 2913 if (iterator.GetHandlerTypeIndex() == DexFile::kDexNoIndex16) { 2914 common_super = ®_types_.JavaLangThrowable(false); 2915 } else { 2916 const RegType& exception = ResolveClassAndCheckAccess(iterator.GetHandlerTypeIndex()); 2917 if (!reg_types_.JavaLangThrowable(false).IsAssignableFrom(exception)) { 2918 if (exception.IsUnresolvedTypes()) { 2919 // We don't know enough about the type. Fail here and let runtime handle it. 2920 Fail(VERIFY_ERROR_NO_CLASS) << "unresolved exception class " << exception; 2921 return exception; 2922 } else { 2923 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "unexpected non-exception class " << exception; 2924 return reg_types_.Conflict(); 2925 } 2926 } else if (common_super == nullptr) { 2927 common_super = &exception; 2928 } else if (common_super->Equals(exception)) { 2929 // odd case, but nothing to do 2930 } else { 2931 common_super = &common_super->Merge(exception, ®_types_); 2932 CHECK(reg_types_.JavaLangThrowable(false).IsAssignableFrom(*common_super)); 2933 } 2934 } 2935 } 2936 } 2937 handlers_ptr = iterator.EndDataPointer(); 2938 } 2939 } 2940 if (common_super == NULL) { 2941 /* no catch blocks, or no catches with classes we can find */ 2942 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "unable to find exception handler"; 2943 return reg_types_.Conflict(); 2944 } 2945 return *common_super; 2946} 2947 2948mirror::ArtMethod* MethodVerifier::ResolveMethodAndCheckAccess(uint32_t dex_method_idx, 2949 MethodType method_type) { 2950 const DexFile::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx); 2951 const RegType& klass_type = ResolveClassAndCheckAccess(method_id.class_idx_); 2952 if (klass_type.IsConflict()) { 2953 std::string append(" in attempt to access method "); 2954 append += dex_file_->GetMethodName(method_id); 2955 AppendToLastFailMessage(append); 2956 return NULL; 2957 } 2958 if (klass_type.IsUnresolvedTypes()) { 2959 return NULL; // Can't resolve Class so no more to do here 2960 } 2961 mirror::Class* klass = klass_type.GetClass(); 2962 const RegType& referrer = GetDeclaringClass(); 2963 mirror::ArtMethod* res_method = (*dex_cache_)->GetResolvedMethod(dex_method_idx); 2964 if (res_method == NULL) { 2965 const char* name = dex_file_->GetMethodName(method_id); 2966 const Signature signature = dex_file_->GetMethodSignature(method_id); 2967 2968 if (method_type == METHOD_DIRECT || method_type == METHOD_STATIC) { 2969 res_method = klass->FindDirectMethod(name, signature); 2970 } else if (method_type == METHOD_INTERFACE) { 2971 res_method = klass->FindInterfaceMethod(name, signature); 2972 } else { 2973 res_method = klass->FindVirtualMethod(name, signature); 2974 } 2975 if (res_method != NULL) { 2976 (*dex_cache_)->SetResolvedMethod(dex_method_idx, res_method); 2977 } else { 2978 // If a virtual or interface method wasn't found with the expected type, look in 2979 // the direct methods. This can happen when the wrong invoke type is used or when 2980 // a class has changed, and will be flagged as an error in later checks. 2981 if (method_type == METHOD_INTERFACE || method_type == METHOD_VIRTUAL) { 2982 res_method = klass->FindDirectMethod(name, signature); 2983 } 2984 if (res_method == NULL) { 2985 Fail(VERIFY_ERROR_NO_METHOD) << "couldn't find method " 2986 << PrettyDescriptor(klass) << "." << name 2987 << " " << signature; 2988 return NULL; 2989 } 2990 } 2991 } 2992 // Make sure calls to constructors are "direct". There are additional restrictions but we don't 2993 // enforce them here. 2994 if (res_method->IsConstructor() && method_type != METHOD_DIRECT) { 2995 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "rejecting non-direct call to constructor " 2996 << PrettyMethod(res_method); 2997 return NULL; 2998 } 2999 // Disallow any calls to class initializers. 3000 if (res_method->IsClassInitializer()) { 3001 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "rejecting call to class initializer " 3002 << PrettyMethod(res_method); 3003 return NULL; 3004 } 3005 // Check if access is allowed. 3006 if (!referrer.CanAccessMember(res_method->GetDeclaringClass(), res_method->GetAccessFlags())) { 3007 Fail(VERIFY_ERROR_ACCESS_METHOD) << "illegal method access (call " << PrettyMethod(res_method) 3008 << " from " << referrer << ")"; 3009 return res_method; 3010 } 3011 // Check that invoke-virtual and invoke-super are not used on private methods of the same class. 3012 if (res_method->IsPrivate() && method_type == METHOD_VIRTUAL) { 3013 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invoke-super/virtual can't be used on private method " 3014 << PrettyMethod(res_method); 3015 return NULL; 3016 } 3017 // Check that interface methods match interface classes. 3018 if (klass->IsInterface() && method_type != METHOD_INTERFACE) { 3019 Fail(VERIFY_ERROR_CLASS_CHANGE) << "non-interface method " << PrettyMethod(res_method) 3020 << " is in an interface class " << PrettyClass(klass); 3021 return NULL; 3022 } else if (!klass->IsInterface() && method_type == METHOD_INTERFACE) { 3023 Fail(VERIFY_ERROR_CLASS_CHANGE) << "interface method " << PrettyMethod(res_method) 3024 << " is in a non-interface class " << PrettyClass(klass); 3025 return NULL; 3026 } 3027 // See if the method type implied by the invoke instruction matches the access flags for the 3028 // target method. 3029 if ((method_type == METHOD_DIRECT && !res_method->IsDirect()) || 3030 (method_type == METHOD_STATIC && !res_method->IsStatic()) || 3031 ((method_type == METHOD_VIRTUAL || method_type == METHOD_INTERFACE) && res_method->IsDirect()) 3032 ) { 3033 Fail(VERIFY_ERROR_CLASS_CHANGE) << "invoke type (" << method_type << ") does not match method " 3034 " type of " << PrettyMethod(res_method); 3035 return NULL; 3036 } 3037 return res_method; 3038} 3039 3040template <class T> 3041mirror::ArtMethod* MethodVerifier::VerifyInvocationArgsFromIterator(T* it, const Instruction* inst, 3042 MethodType method_type, 3043 bool is_range, 3044 mirror::ArtMethod* res_method) { 3045 // We use vAA as our expected arg count, rather than res_method->insSize, because we need to 3046 // match the call to the signature. Also, we might be calling through an abstract method 3047 // definition (which doesn't have register count values). 3048 const size_t expected_args = (is_range) ? inst->VRegA_3rc() : inst->VRegA_35c(); 3049 /* caught by static verifier */ 3050 DCHECK(is_range || expected_args <= 5); 3051 if (expected_args > code_item_->outs_size_) { 3052 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid argument count (" << expected_args 3053 << ") exceeds outsSize (" << code_item_->outs_size_ << ")"; 3054 return nullptr; 3055 } 3056 3057 uint32_t arg[5]; 3058 if (!is_range) { 3059 inst->GetVarArgs(arg); 3060 } 3061 uint32_t sig_registers = 0; 3062 3063 /* 3064 * Check the "this" argument, which must be an instance of the class that declared the method. 3065 * For an interface class, we don't do the full interface merge (see JoinClass), so we can't do a 3066 * rigorous check here (which is okay since we have to do it at runtime). 3067 */ 3068 if (method_type != METHOD_STATIC) { 3069 const RegType& actual_arg_type = work_line_->GetInvocationThis(inst, is_range); 3070 if (actual_arg_type.IsConflict()) { // GetInvocationThis failed. 3071 CHECK(have_pending_hard_failure_); 3072 return nullptr; 3073 } 3074 if (actual_arg_type.IsUninitializedReference()) { 3075 if (res_method) { 3076 if (!res_method->IsConstructor()) { 3077 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "'this' arg must be initialized"; 3078 return nullptr; 3079 } 3080 } else { 3081 // Check whether the name of the called method is "<init>" 3082 const uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); 3083 if (strcmp(dex_file_->GetMethodName(dex_file_->GetMethodId(method_idx)), "init") != 0) { 3084 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "'this' arg must be initialized"; 3085 return nullptr; 3086 } 3087 } 3088 } 3089 if (method_type != METHOD_INTERFACE && !actual_arg_type.IsZero()) { 3090 const RegType* res_method_class; 3091 if (res_method != nullptr) { 3092 mirror::Class* klass = res_method->GetDeclaringClass(); 3093 res_method_class = ®_types_.FromClass(klass->GetDescriptor().c_str(), klass, 3094 klass->CannotBeAssignedFromOtherTypes()); 3095 } else { 3096 const uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); 3097 const uint16_t class_idx = dex_file_->GetMethodId(method_idx).class_idx_; 3098 res_method_class = ®_types_.FromDescriptor(class_loader_->Get(), 3099 dex_file_->StringByTypeIdx(class_idx), 3100 false); 3101 } 3102 if (!res_method_class->IsAssignableFrom(actual_arg_type)) { 3103 Fail(actual_arg_type.IsUnresolvedTypes() ? VERIFY_ERROR_NO_CLASS: 3104 VERIFY_ERROR_BAD_CLASS_SOFT) << "'this' argument '" << actual_arg_type 3105 << "' not instance of '" << *res_method_class << "'"; 3106 // Continue on soft failures. We need to find possible hard failures to avoid problems in 3107 // the compiler. 3108 if (have_pending_hard_failure_) { 3109 return nullptr; 3110 } 3111 } 3112 } 3113 sig_registers = 1; 3114 } 3115 3116 for ( ; it->HasNext(); it->Next()) { 3117 if (sig_registers >= expected_args) { 3118 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation, expected " << inst->VRegA() << 3119 " arguments, found " << sig_registers << " or more."; 3120 return nullptr; 3121 } 3122 3123 const char* param_descriptor = it->GetDescriptor(); 3124 3125 if (param_descriptor == nullptr) { 3126 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation because of missing signature " 3127 "component"; 3128 return nullptr; 3129 } 3130 3131 const RegType& reg_type = reg_types_.FromDescriptor(class_loader_->Get(), param_descriptor, 3132 false); 3133 uint32_t get_reg = is_range ? inst->VRegC_3rc() + static_cast<uint32_t>(sig_registers) : 3134 arg[sig_registers]; 3135 if (reg_type.IsIntegralTypes()) { 3136 const RegType& src_type = work_line_->GetRegisterType(get_reg); 3137 if (!src_type.IsIntegralTypes()) { 3138 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "register v" << get_reg << " has type " << src_type 3139 << " but expected " << reg_type; 3140 return res_method; 3141 } 3142 } else if (!work_line_->VerifyRegisterType(get_reg, reg_type)) { 3143 // Continue on soft failures. We need to find possible hard failures to avoid problems in the 3144 // compiler. 3145 if (have_pending_hard_failure_) { 3146 return res_method; 3147 } 3148 } 3149 sig_registers += reg_type.IsLongOrDoubleTypes() ? 2 : 1; 3150 } 3151 if (expected_args != sig_registers) { 3152 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation, expected " << expected_args << 3153 " arguments, found " << sig_registers; 3154 return nullptr; 3155 } 3156 return res_method; 3157} 3158 3159void MethodVerifier::VerifyInvocationArgsUnresolvedMethod(const Instruction* inst, 3160 MethodType method_type, 3161 bool is_range) { 3162 // As the method may not have been resolved, make this static check against what we expect. 3163 // The main reason for this code block is to fail hard when we find an illegal use, e.g., 3164 // wrong number of arguments or wrong primitive types, even if the method could not be resolved. 3165 const uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); 3166 DexFileParameterIterator it(*dex_file_, 3167 dex_file_->GetProtoId(dex_file_->GetMethodId(method_idx).proto_idx_)); 3168 VerifyInvocationArgsFromIterator<DexFileParameterIterator>(&it, inst, method_type, is_range, 3169 nullptr); 3170} 3171 3172class MethodParamListDescriptorIterator { 3173 public: 3174 explicit MethodParamListDescriptorIterator(mirror::ArtMethod* res_method) : 3175 res_method_(res_method), pos_(0), params_(res_method->GetParameterTypeList()), 3176 params_size_(params_ == nullptr ? 0 : params_->Size()) { 3177 } 3178 3179 bool HasNext() { 3180 return pos_ < params_size_; 3181 } 3182 3183 void Next() { 3184 ++pos_; 3185 } 3186 3187 const char* GetDescriptor() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 3188 return res_method_->GetTypeDescriptorFromTypeIdx(params_->GetTypeItem(pos_).type_idx_); 3189 } 3190 3191 private: 3192 mirror::ArtMethod* res_method_; 3193 size_t pos_; 3194 const DexFile::TypeList* params_; 3195 const size_t params_size_; 3196}; 3197 3198mirror::ArtMethod* MethodVerifier::VerifyInvocationArgs(const Instruction* inst, 3199 MethodType method_type, 3200 bool is_range, 3201 bool is_super) { 3202 // Resolve the method. This could be an abstract or concrete method depending on what sort of call 3203 // we're making. 3204 const uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); 3205 3206 mirror::ArtMethod* res_method = ResolveMethodAndCheckAccess(method_idx, method_type); 3207 if (res_method == NULL) { // error or class is unresolved 3208 // Check what we can statically. 3209 if (!have_pending_hard_failure_) { 3210 VerifyInvocationArgsUnresolvedMethod(inst, method_type, is_range); 3211 } 3212 return nullptr; 3213 } 3214 3215 // If we're using invoke-super(method), make sure that the executing method's class' superclass 3216 // has a vtable entry for the target method. 3217 if (is_super) { 3218 DCHECK(method_type == METHOD_VIRTUAL); 3219 const RegType& super = GetDeclaringClass().GetSuperClass(®_types_); 3220 if (super.IsUnresolvedTypes()) { 3221 Fail(VERIFY_ERROR_NO_METHOD) << "unknown super class in invoke-super from " 3222 << PrettyMethod(dex_method_idx_, *dex_file_) 3223 << " to super " << PrettyMethod(res_method); 3224 return nullptr; 3225 } 3226 mirror::Class* super_klass = super.GetClass(); 3227 if (res_method->GetMethodIndex() >= super_klass->GetVTable()->GetLength()) { 3228 Fail(VERIFY_ERROR_NO_METHOD) << "invalid invoke-super from " 3229 << PrettyMethod(dex_method_idx_, *dex_file_) 3230 << " to super " << super 3231 << "." << res_method->GetName() 3232 << res_method->GetSignature(); 3233 return nullptr; 3234 } 3235 } 3236 3237 // Process the target method's signature. This signature may or may not 3238 MethodParamListDescriptorIterator it(res_method); 3239 return VerifyInvocationArgsFromIterator<MethodParamListDescriptorIterator>(&it, inst, method_type, 3240 is_range, res_method); 3241} 3242 3243mirror::ArtMethod* MethodVerifier::GetQuickInvokedMethod(const Instruction* inst, 3244 RegisterLine* reg_line, bool is_range) { 3245 DCHECK(inst->Opcode() == Instruction::INVOKE_VIRTUAL_QUICK || 3246 inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE_QUICK); 3247 const RegType& actual_arg_type = reg_line->GetInvocationThis(inst, is_range); 3248 if (!actual_arg_type.HasClass()) { 3249 VLOG(verifier) << "Failed to get mirror::Class* from '" << actual_arg_type << "'"; 3250 return nullptr; 3251 } 3252 mirror::ObjectArray<mirror::ArtMethod>* vtable = nullptr; 3253 mirror::Class* klass = actual_arg_type.GetClass(); 3254 if (klass->IsInterface()) { 3255 // Derive Object.class from Class.class.getSuperclass(). 3256 mirror::Class* object_klass = klass->GetClass()->GetSuperClass(); 3257 CHECK(object_klass->IsObjectClass()); 3258 vtable = object_klass->GetVTable(); 3259 } else { 3260 vtable = klass->GetVTable(); 3261 } 3262 CHECK(vtable != nullptr) << PrettyDescriptor(klass); 3263 uint16_t vtable_index = is_range ? inst->VRegB_3rc() : inst->VRegB_35c(); 3264 CHECK_LT(static_cast<int32_t>(vtable_index), vtable->GetLength()) << PrettyDescriptor(klass); 3265 mirror::ArtMethod* res_method = vtable->Get(vtable_index); 3266 CHECK(!Thread::Current()->IsExceptionPending()); 3267 return res_method; 3268} 3269 3270mirror::ArtMethod* MethodVerifier::VerifyInvokeVirtualQuickArgs(const Instruction* inst, 3271 bool is_range) { 3272 DCHECK(Runtime::Current()->IsStarted()); 3273 mirror::ArtMethod* res_method = GetQuickInvokedMethod(inst, work_line_.get(), 3274 is_range); 3275 if (res_method == NULL) { 3276 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Cannot infer method from " << inst->Name(); 3277 return NULL; 3278 } 3279 CHECK(!res_method->IsDirect() && !res_method->IsStatic()); 3280 3281 // We use vAA as our expected arg count, rather than res_method->insSize, because we need to 3282 // match the call to the signature. Also, we might be calling through an abstract method 3283 // definition (which doesn't have register count values). 3284 const RegType& actual_arg_type = work_line_->GetInvocationThis(inst, is_range); 3285 if (actual_arg_type.IsConflict()) { // GetInvocationThis failed. 3286 return NULL; 3287 } 3288 const size_t expected_args = (is_range) ? inst->VRegA_3rc() : inst->VRegA_35c(); 3289 /* caught by static verifier */ 3290 DCHECK(is_range || expected_args <= 5); 3291 if (expected_args > code_item_->outs_size_) { 3292 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid argument count (" << expected_args 3293 << ") exceeds outsSize (" << code_item_->outs_size_ << ")"; 3294 return NULL; 3295 } 3296 3297 /* 3298 * Check the "this" argument, which must be an instance of the class that declared the method. 3299 * For an interface class, we don't do the full interface merge (see JoinClass), so we can't do a 3300 * rigorous check here (which is okay since we have to do it at runtime). 3301 */ 3302 if (actual_arg_type.IsUninitializedReference() && !res_method->IsConstructor()) { 3303 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "'this' arg must be initialized"; 3304 return NULL; 3305 } 3306 if (!actual_arg_type.IsZero()) { 3307 mirror::Class* klass = res_method->GetDeclaringClass(); 3308 const RegType& res_method_class = 3309 reg_types_.FromClass(klass->GetDescriptor().c_str(), klass, 3310 klass->CannotBeAssignedFromOtherTypes()); 3311 if (!res_method_class.IsAssignableFrom(actual_arg_type)) { 3312 Fail(actual_arg_type.IsUnresolvedTypes() ? VERIFY_ERROR_NO_CLASS : 3313 VERIFY_ERROR_BAD_CLASS_SOFT) << "'this' argument '" << actual_arg_type 3314 << "' not instance of '" << res_method_class << "'"; 3315 return NULL; 3316 } 3317 } 3318 /* 3319 * Process the target method's signature. This signature may or may not 3320 * have been verified, so we can't assume it's properly formed. 3321 */ 3322 const DexFile::TypeList* params = res_method->GetParameterTypeList(); 3323 size_t params_size = params == NULL ? 0 : params->Size(); 3324 uint32_t arg[5]; 3325 if (!is_range) { 3326 inst->GetVarArgs(arg); 3327 } 3328 size_t actual_args = 1; 3329 for (size_t param_index = 0; param_index < params_size; param_index++) { 3330 if (actual_args >= expected_args) { 3331 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invalid call to '" << PrettyMethod(res_method) 3332 << "'. Expected " << expected_args 3333 << " arguments, processing argument " << actual_args 3334 << " (where longs/doubles count twice)."; 3335 return NULL; 3336 } 3337 const char* descriptor = 3338 res_method->GetTypeDescriptorFromTypeIdx(params->GetTypeItem(param_index).type_idx_); 3339 if (descriptor == NULL) { 3340 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation of " << PrettyMethod(res_method) 3341 << " missing signature component"; 3342 return NULL; 3343 } 3344 const RegType& reg_type = reg_types_.FromDescriptor(class_loader_->Get(), descriptor, false); 3345 uint32_t get_reg = is_range ? inst->VRegC_3rc() + actual_args : arg[actual_args]; 3346 if (!work_line_->VerifyRegisterType(get_reg, reg_type)) { 3347 return res_method; 3348 } 3349 actual_args = reg_type.IsLongOrDoubleTypes() ? actual_args + 2 : actual_args + 1; 3350 } 3351 if (actual_args != expected_args) { 3352 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation of " << PrettyMethod(res_method) 3353 << " expected " << expected_args << " arguments, found " << actual_args; 3354 return NULL; 3355 } else { 3356 return res_method; 3357 } 3358} 3359 3360void MethodVerifier::VerifyNewArray(const Instruction* inst, bool is_filled, bool is_range) { 3361 uint32_t type_idx; 3362 if (!is_filled) { 3363 DCHECK_EQ(inst->Opcode(), Instruction::NEW_ARRAY); 3364 type_idx = inst->VRegC_22c(); 3365 } else if (!is_range) { 3366 DCHECK_EQ(inst->Opcode(), Instruction::FILLED_NEW_ARRAY); 3367 type_idx = inst->VRegB_35c(); 3368 } else { 3369 DCHECK_EQ(inst->Opcode(), Instruction::FILLED_NEW_ARRAY_RANGE); 3370 type_idx = inst->VRegB_3rc(); 3371 } 3372 const RegType& res_type = ResolveClassAndCheckAccess(type_idx); 3373 if (res_type.IsConflict()) { // bad class 3374 DCHECK_NE(failures_.size(), 0U); 3375 } else { 3376 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved 3377 if (!res_type.IsArrayTypes()) { 3378 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "new-array on non-array class " << res_type; 3379 } else if (!is_filled) { 3380 /* make sure "size" register is valid type */ 3381 work_line_->VerifyRegisterType(inst->VRegB_22c(), reg_types_.Integer()); 3382 /* set register type to array class */ 3383 const RegType& precise_type = reg_types_.FromUninitialized(res_type); 3384 work_line_->SetRegisterType(inst->VRegA_22c(), precise_type); 3385 } else { 3386 // Verify each register. If "arg_count" is bad, VerifyRegisterType() will run off the end of 3387 // the list and fail. It's legal, if silly, for arg_count to be zero. 3388 const RegType& expected_type = reg_types_.GetComponentType(res_type, class_loader_->Get()); 3389 uint32_t arg_count = (is_range) ? inst->VRegA_3rc() : inst->VRegA_35c(); 3390 uint32_t arg[5]; 3391 if (!is_range) { 3392 inst->GetVarArgs(arg); 3393 } 3394 for (size_t ui = 0; ui < arg_count; ui++) { 3395 uint32_t get_reg = is_range ? inst->VRegC_3rc() + ui : arg[ui]; 3396 if (!work_line_->VerifyRegisterType(get_reg, expected_type)) { 3397 work_line_->SetResultRegisterType(reg_types_.Conflict()); 3398 return; 3399 } 3400 } 3401 // filled-array result goes into "result" register 3402 const RegType& precise_type = reg_types_.FromUninitialized(res_type); 3403 work_line_->SetResultRegisterType(precise_type); 3404 } 3405 } 3406} 3407 3408void MethodVerifier::VerifyAGet(const Instruction* inst, 3409 const RegType& insn_type, bool is_primitive) { 3410 const RegType& index_type = work_line_->GetRegisterType(inst->VRegC_23x()); 3411 if (!index_type.IsArrayIndexTypes()) { 3412 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Invalid reg type for array index (" << index_type << ")"; 3413 } else { 3414 const RegType& array_type = work_line_->GetRegisterType(inst->VRegB_23x()); 3415 if (array_type.IsZero()) { 3416 // Null array class; this code path will fail at runtime. Infer a merge-able type from the 3417 // instruction type. TODO: have a proper notion of bottom here. 3418 if (!is_primitive || insn_type.IsCategory1Types()) { 3419 // Reference or category 1 3420 work_line_->SetRegisterType(inst->VRegA_23x(), reg_types_.Zero()); 3421 } else { 3422 // Category 2 3423 work_line_->SetRegisterTypeWide(inst->VRegA_23x(), reg_types_.FromCat2ConstLo(0, false), 3424 reg_types_.FromCat2ConstHi(0, false)); 3425 } 3426 } else if (!array_type.IsArrayTypes()) { 3427 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "not array type " << array_type << " with aget"; 3428 } else { 3429 /* verify the class */ 3430 const RegType& component_type = reg_types_.GetComponentType(array_type, class_loader_->Get()); 3431 if (!component_type.IsReferenceTypes() && !is_primitive) { 3432 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "primitive array type " << array_type 3433 << " source for aget-object"; 3434 } else if (component_type.IsNonZeroReferenceTypes() && is_primitive) { 3435 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "reference array type " << array_type 3436 << " source for category 1 aget"; 3437 } else if (is_primitive && !insn_type.Equals(component_type) && 3438 !((insn_type.IsInteger() && component_type.IsFloat()) || 3439 (insn_type.IsLong() && component_type.IsDouble()))) { 3440 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array type " << array_type 3441 << " incompatible with aget of type " << insn_type; 3442 } else { 3443 // Use knowledge of the field type which is stronger than the type inferred from the 3444 // instruction, which can't differentiate object types and ints from floats, longs from 3445 // doubles. 3446 if (!component_type.IsLowHalf()) { 3447 work_line_->SetRegisterType(inst->VRegA_23x(), component_type); 3448 } else { 3449 work_line_->SetRegisterTypeWide(inst->VRegA_23x(), component_type, 3450 component_type.HighHalf(®_types_)); 3451 } 3452 } 3453 } 3454 } 3455} 3456 3457void MethodVerifier::VerifyPrimitivePut(const RegType& target_type, const RegType& insn_type, 3458 const uint32_t vregA) { 3459 // Primitive assignability rules are weaker than regular assignability rules. 3460 bool instruction_compatible; 3461 bool value_compatible; 3462 const RegType& value_type = work_line_->GetRegisterType(vregA); 3463 if (target_type.IsIntegralTypes()) { 3464 instruction_compatible = target_type.Equals(insn_type); 3465 value_compatible = value_type.IsIntegralTypes(); 3466 } else if (target_type.IsFloat()) { 3467 instruction_compatible = insn_type.IsInteger(); // no put-float, so expect put-int 3468 value_compatible = value_type.IsFloatTypes(); 3469 } else if (target_type.IsLong()) { 3470 instruction_compatible = insn_type.IsLong(); 3471 value_compatible = value_type.IsLongTypes(); 3472 } else if (target_type.IsDouble()) { 3473 instruction_compatible = insn_type.IsLong(); // no put-double, so expect put-long 3474 value_compatible = value_type.IsDoubleTypes(); 3475 } else { 3476 instruction_compatible = false; // reference with primitive store 3477 value_compatible = false; // unused 3478 } 3479 if (!instruction_compatible) { 3480 // This is a global failure rather than a class change failure as the instructions and 3481 // the descriptors for the type should have been consistent within the same file at 3482 // compile time. 3483 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "put insn has type '" << insn_type 3484 << "' but expected type '" << target_type << "'"; 3485 return; 3486 } 3487 if (!value_compatible) { 3488 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected value in v" << vregA 3489 << " of type " << value_type << " but expected " << target_type << " for put"; 3490 return; 3491 } 3492} 3493 3494void MethodVerifier::VerifyAPut(const Instruction* inst, 3495 const RegType& insn_type, bool is_primitive) { 3496 const RegType& index_type = work_line_->GetRegisterType(inst->VRegC_23x()); 3497 if (!index_type.IsArrayIndexTypes()) { 3498 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Invalid reg type for array index (" << index_type << ")"; 3499 } else { 3500 const RegType& array_type = work_line_->GetRegisterType(inst->VRegB_23x()); 3501 if (array_type.IsZero()) { 3502 // Null array type; this code path will fail at runtime. Infer a merge-able type from the 3503 // instruction type. 3504 } else if (!array_type.IsArrayTypes()) { 3505 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "not array type " << array_type << " with aput"; 3506 } else { 3507 const RegType& component_type = reg_types_.GetComponentType(array_type, class_loader_->Get()); 3508 const uint32_t vregA = inst->VRegA_23x(); 3509 if (is_primitive) { 3510 VerifyPrimitivePut(component_type, insn_type, vregA); 3511 } else { 3512 if (!component_type.IsReferenceTypes()) { 3513 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "primitive array type " << array_type 3514 << " source for aput-object"; 3515 } else { 3516 // The instruction agrees with the type of array, confirm the value to be stored does too 3517 // Note: we use the instruction type (rather than the component type) for aput-object as 3518 // incompatible classes will be caught at runtime as an array store exception 3519 work_line_->VerifyRegisterType(vregA, insn_type); 3520 } 3521 } 3522 } 3523 } 3524} 3525 3526mirror::ArtField* MethodVerifier::GetStaticField(int field_idx) { 3527 const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx); 3528 // Check access to class 3529 const RegType& klass_type = ResolveClassAndCheckAccess(field_id.class_idx_); 3530 if (klass_type.IsConflict()) { // bad class 3531 AppendToLastFailMessage(StringPrintf(" in attempt to access static field %d (%s) in %s", 3532 field_idx, dex_file_->GetFieldName(field_id), 3533 dex_file_->GetFieldDeclaringClassDescriptor(field_id))); 3534 return NULL; 3535 } 3536 if (klass_type.IsUnresolvedTypes()) { 3537 return NULL; // Can't resolve Class so no more to do here, will do checking at runtime. 3538 } 3539 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 3540 mirror::ArtField* field = class_linker->ResolveFieldJLS(*dex_file_, field_idx, *dex_cache_, 3541 *class_loader_); 3542 if (field == NULL) { 3543 VLOG(verifier) << "Unable to resolve static field " << field_idx << " (" 3544 << dex_file_->GetFieldName(field_id) << ") in " 3545 << dex_file_->GetFieldDeclaringClassDescriptor(field_id); 3546 DCHECK(Thread::Current()->IsExceptionPending()); 3547 Thread::Current()->ClearException(); 3548 return NULL; 3549 } else if (!GetDeclaringClass().CanAccessMember(field->GetDeclaringClass(), 3550 field->GetAccessFlags())) { 3551 Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot access static field " << PrettyField(field) 3552 << " from " << GetDeclaringClass(); 3553 return NULL; 3554 } else if (!field->IsStatic()) { 3555 Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected field " << PrettyField(field) << " to be static"; 3556 return NULL; 3557 } 3558 return field; 3559} 3560 3561mirror::ArtField* MethodVerifier::GetInstanceField(const RegType& obj_type, int field_idx) { 3562 const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx); 3563 // Check access to class 3564 const RegType& klass_type = ResolveClassAndCheckAccess(field_id.class_idx_); 3565 if (klass_type.IsConflict()) { 3566 AppendToLastFailMessage(StringPrintf(" in attempt to access instance field %d (%s) in %s", 3567 field_idx, dex_file_->GetFieldName(field_id), 3568 dex_file_->GetFieldDeclaringClassDescriptor(field_id))); 3569 return NULL; 3570 } 3571 if (klass_type.IsUnresolvedTypes()) { 3572 return NULL; // Can't resolve Class so no more to do here 3573 } 3574 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 3575 mirror::ArtField* field = class_linker->ResolveFieldJLS(*dex_file_, field_idx, *dex_cache_, 3576 *class_loader_); 3577 if (field == NULL) { 3578 VLOG(verifier) << "Unable to resolve instance field " << field_idx << " (" 3579 << dex_file_->GetFieldName(field_id) << ") in " 3580 << dex_file_->GetFieldDeclaringClassDescriptor(field_id); 3581 DCHECK(Thread::Current()->IsExceptionPending()); 3582 Thread::Current()->ClearException(); 3583 return NULL; 3584 } else if (!GetDeclaringClass().CanAccessMember(field->GetDeclaringClass(), 3585 field->GetAccessFlags())) { 3586 Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot access instance field " << PrettyField(field) 3587 << " from " << GetDeclaringClass(); 3588 return NULL; 3589 } else if (field->IsStatic()) { 3590 Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected field " << PrettyField(field) 3591 << " to not be static"; 3592 return NULL; 3593 } else if (obj_type.IsZero()) { 3594 // Cannot infer and check type, however, access will cause null pointer exception 3595 return field; 3596 } else { 3597 mirror::Class* klass = field->GetDeclaringClass(); 3598 const RegType& field_klass = 3599 reg_types_.FromClass(dex_file_->GetFieldDeclaringClassDescriptor(field_id), 3600 klass, klass->CannotBeAssignedFromOtherTypes()); 3601 if (obj_type.IsUninitializedTypes() && 3602 (!IsConstructor() || GetDeclaringClass().Equals(obj_type) || 3603 !field_klass.Equals(GetDeclaringClass()))) { 3604 // Field accesses through uninitialized references are only allowable for constructors where 3605 // the field is declared in this class 3606 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "cannot access instance field " << PrettyField(field) 3607 << " of a not fully initialized object within the context" 3608 << " of " << PrettyMethod(dex_method_idx_, *dex_file_); 3609 return NULL; 3610 } else if (!field_klass.IsAssignableFrom(obj_type)) { 3611 // Trying to access C1.field1 using reference of type C2, which is neither C1 or a sub-class 3612 // of C1. For resolution to occur the declared class of the field must be compatible with 3613 // obj_type, we've discovered this wasn't so, so report the field didn't exist. 3614 Fail(VERIFY_ERROR_NO_FIELD) << "cannot access instance field " << PrettyField(field) 3615 << " from object of type " << obj_type; 3616 return NULL; 3617 } else { 3618 return field; 3619 } 3620 } 3621} 3622 3623void MethodVerifier::VerifyISGet(const Instruction* inst, const RegType& insn_type, 3624 bool is_primitive, bool is_static) { 3625 uint32_t field_idx = is_static ? inst->VRegB_21c() : inst->VRegC_22c(); 3626 mirror::ArtField* field; 3627 if (is_static) { 3628 field = GetStaticField(field_idx); 3629 } else { 3630 const RegType& object_type = work_line_->GetRegisterType(inst->VRegB_22c()); 3631 field = GetInstanceField(object_type, field_idx); 3632 } 3633 const RegType* field_type = nullptr; 3634 if (field != NULL) { 3635 Thread* self = Thread::Current(); 3636 mirror::Class* field_type_class; 3637 { 3638 StackHandleScope<1> hs(self); 3639 HandleWrapper<mirror::ArtField> h_field(hs.NewHandleWrapper(&field)); 3640 field_type_class = FieldHelper(h_field).GetType(can_load_classes_); 3641 } 3642 if (field_type_class != nullptr) { 3643 field_type = ®_types_.FromClass(field->GetTypeDescriptor(), field_type_class, 3644 field_type_class->CannotBeAssignedFromOtherTypes()); 3645 } else { 3646 DCHECK(!can_load_classes_ || self->IsExceptionPending()); 3647 self->ClearException(); 3648 } 3649 } 3650 if (field_type == nullptr) { 3651 const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx); 3652 const char* descriptor = dex_file_->GetFieldTypeDescriptor(field_id); 3653 field_type = ®_types_.FromDescriptor(class_loader_->Get(), descriptor, false); 3654 } 3655 DCHECK(field_type != nullptr); 3656 const uint32_t vregA = (is_static) ? inst->VRegA_21c() : inst->VRegA_22c(); 3657 if (is_primitive) { 3658 if (field_type->Equals(insn_type) || 3659 (field_type->IsFloat() && insn_type.IsInteger()) || 3660 (field_type->IsDouble() && insn_type.IsLong())) { 3661 // expected that read is of the correct primitive type or that int reads are reading 3662 // floats or long reads are reading doubles 3663 } else { 3664 // This is a global failure rather than a class change failure as the instructions and 3665 // the descriptors for the type should have been consistent within the same file at 3666 // compile time 3667 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected field " << PrettyField(field) 3668 << " to be of type '" << insn_type 3669 << "' but found type '" << *field_type << "' in get"; 3670 return; 3671 } 3672 } else { 3673 if (!insn_type.IsAssignableFrom(*field_type)) { 3674 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "expected field " << PrettyField(field) 3675 << " to be compatible with type '" << insn_type 3676 << "' but found type '" << *field_type 3677 << "' in Get-object"; 3678 work_line_->SetRegisterType(vregA, reg_types_.Conflict()); 3679 return; 3680 } 3681 } 3682 if (!field_type->IsLowHalf()) { 3683 work_line_->SetRegisterType(vregA, *field_type); 3684 } else { 3685 work_line_->SetRegisterTypeWide(vregA, *field_type, field_type->HighHalf(®_types_)); 3686 } 3687} 3688 3689void MethodVerifier::VerifyISPut(const Instruction* inst, const RegType& insn_type, 3690 bool is_primitive, bool is_static) { 3691 uint32_t field_idx = is_static ? inst->VRegB_21c() : inst->VRegC_22c(); 3692 mirror::ArtField* field; 3693 if (is_static) { 3694 field = GetStaticField(field_idx); 3695 } else { 3696 const RegType& object_type = work_line_->GetRegisterType(inst->VRegB_22c()); 3697 field = GetInstanceField(object_type, field_idx); 3698 } 3699 const RegType* field_type = nullptr; 3700 if (field != NULL) { 3701 if (field->IsFinal() && field->GetDeclaringClass() != GetDeclaringClass().GetClass()) { 3702 Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot modify final field " << PrettyField(field) 3703 << " from other class " << GetDeclaringClass(); 3704 return; 3705 } 3706 mirror::Class* field_type_class; 3707 { 3708 StackHandleScope<1> hs(Thread::Current()); 3709 HandleWrapper<mirror::ArtField> h_field(hs.NewHandleWrapper(&field)); 3710 FieldHelper fh(h_field); 3711 field_type_class = fh.GetType(can_load_classes_); 3712 } 3713 if (field_type_class != nullptr) { 3714 field_type = ®_types_.FromClass(field->GetTypeDescriptor(), field_type_class, 3715 field_type_class->CannotBeAssignedFromOtherTypes()); 3716 } else { 3717 Thread* self = Thread::Current(); 3718 DCHECK(!can_load_classes_ || self->IsExceptionPending()); 3719 self->ClearException(); 3720 } 3721 } 3722 if (field_type == nullptr) { 3723 const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx); 3724 const char* descriptor = dex_file_->GetFieldTypeDescriptor(field_id); 3725 field_type = ®_types_.FromDescriptor(class_loader_->Get(), descriptor, false); 3726 } 3727 DCHECK(field_type != nullptr); 3728 const uint32_t vregA = (is_static) ? inst->VRegA_21c() : inst->VRegA_22c(); 3729 if (is_primitive) { 3730 VerifyPrimitivePut(*field_type, insn_type, vregA); 3731 } else { 3732 if (!insn_type.IsAssignableFrom(*field_type)) { 3733 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "expected field " << PrettyField(field) 3734 << " to be compatible with type '" << insn_type 3735 << "' but found type '" << *field_type 3736 << "' in put-object"; 3737 return; 3738 } 3739 work_line_->VerifyRegisterType(vregA, *field_type); 3740 } 3741} 3742 3743mirror::ArtField* MethodVerifier::GetQuickFieldAccess(const Instruction* inst, 3744 RegisterLine* reg_line) { 3745 DCHECK(inst->Opcode() == Instruction::IGET_QUICK || 3746 inst->Opcode() == Instruction::IGET_WIDE_QUICK || 3747 inst->Opcode() == Instruction::IGET_OBJECT_QUICK || 3748 inst->Opcode() == Instruction::IPUT_QUICK || 3749 inst->Opcode() == Instruction::IPUT_WIDE_QUICK || 3750 inst->Opcode() == Instruction::IPUT_OBJECT_QUICK); 3751 const RegType& object_type = reg_line->GetRegisterType(inst->VRegB_22c()); 3752 if (!object_type.HasClass()) { 3753 VLOG(verifier) << "Failed to get mirror::Class* from '" << object_type << "'"; 3754 return nullptr; 3755 } 3756 uint32_t field_offset = static_cast<uint32_t>(inst->VRegC_22c()); 3757 mirror::ArtField* f = mirror::ArtField::FindInstanceFieldWithOffset(object_type.GetClass(), 3758 field_offset); 3759 if (f == nullptr) { 3760 VLOG(verifier) << "Failed to find instance field at offset '" << field_offset 3761 << "' from '" << PrettyDescriptor(object_type.GetClass()) << "'"; 3762 } 3763 return f; 3764} 3765 3766void MethodVerifier::VerifyIGetQuick(const Instruction* inst, const RegType& insn_type, 3767 bool is_primitive) { 3768 DCHECK(Runtime::Current()->IsStarted()); 3769 mirror::ArtField* field = GetQuickFieldAccess(inst, work_line_.get()); 3770 if (field == NULL) { 3771 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Cannot infer field from " << inst->Name(); 3772 return; 3773 } 3774 mirror::Class* field_type_class; 3775 { 3776 StackHandleScope<1> hs(Thread::Current()); 3777 HandleWrapper<mirror::ArtField> h_field(hs.NewHandleWrapper(&field)); 3778 FieldHelper fh(h_field); 3779 field_type_class = fh.GetType(can_load_classes_); 3780 } 3781 const RegType* field_type; 3782 if (field_type_class != nullptr) { 3783 field_type = ®_types_.FromClass(field->GetTypeDescriptor(), field_type_class, 3784 field_type_class->CannotBeAssignedFromOtherTypes()); 3785 } else { 3786 Thread* self = Thread::Current(); 3787 DCHECK(!can_load_classes_ || self->IsExceptionPending()); 3788 self->ClearException(); 3789 field_type = ®_types_.FromDescriptor(field->GetDeclaringClass()->GetClassLoader(), 3790 field->GetTypeDescriptor(), false); 3791 } 3792 DCHECK(field_type != nullptr); 3793 const uint32_t vregA = inst->VRegA_22c(); 3794 if (is_primitive) { 3795 if (field_type->Equals(insn_type) || 3796 (field_type->IsFloat() && insn_type.IsIntegralTypes()) || 3797 (field_type->IsDouble() && insn_type.IsLongTypes())) { 3798 // expected that read is of the correct primitive type or that int reads are reading 3799 // floats or long reads are reading doubles 3800 } else { 3801 // This is a global failure rather than a class change failure as the instructions and 3802 // the descriptors for the type should have been consistent within the same file at 3803 // compile time 3804 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected field " << PrettyField(field) 3805 << " to be of type '" << insn_type 3806 << "' but found type '" << *field_type << "' in Get"; 3807 return; 3808 } 3809 } else { 3810 if (!insn_type.IsAssignableFrom(*field_type)) { 3811 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "expected field " << PrettyField(field) 3812 << " to be compatible with type '" << insn_type 3813 << "' but found type '" << *field_type 3814 << "' in get-object"; 3815 work_line_->SetRegisterType(vregA, reg_types_.Conflict()); 3816 return; 3817 } 3818 } 3819 if (!field_type->IsLowHalf()) { 3820 work_line_->SetRegisterType(vregA, *field_type); 3821 } else { 3822 work_line_->SetRegisterTypeWide(vregA, *field_type, field_type->HighHalf(®_types_)); 3823 } 3824} 3825 3826void MethodVerifier::VerifyIPutQuick(const Instruction* inst, const RegType& insn_type, 3827 bool is_primitive) { 3828 DCHECK(Runtime::Current()->IsStarted()); 3829 mirror::ArtField* field = GetQuickFieldAccess(inst, work_line_.get()); 3830 if (field == NULL) { 3831 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Cannot infer field from " << inst->Name(); 3832 return; 3833 } 3834 const char* descriptor = field->GetTypeDescriptor(); 3835 mirror::ClassLoader* loader = field->GetDeclaringClass()->GetClassLoader(); 3836 const RegType& field_type = reg_types_.FromDescriptor(loader, descriptor, false); 3837 if (field != NULL) { 3838 if (field->IsFinal() && field->GetDeclaringClass() != GetDeclaringClass().GetClass()) { 3839 Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot modify final field " << PrettyField(field) 3840 << " from other class " << GetDeclaringClass(); 3841 return; 3842 } 3843 } 3844 const uint32_t vregA = inst->VRegA_22c(); 3845 if (is_primitive) { 3846 // Primitive field assignability rules are weaker than regular assignability rules 3847 bool instruction_compatible; 3848 bool value_compatible; 3849 const RegType& value_type = work_line_->GetRegisterType(vregA); 3850 if (field_type.IsIntegralTypes()) { 3851 instruction_compatible = insn_type.IsIntegralTypes(); 3852 value_compatible = value_type.IsIntegralTypes(); 3853 } else if (field_type.IsFloat()) { 3854 instruction_compatible = insn_type.IsInteger(); // no [is]put-float, so expect [is]put-int 3855 value_compatible = value_type.IsFloatTypes(); 3856 } else if (field_type.IsLong()) { 3857 instruction_compatible = insn_type.IsLong(); 3858 value_compatible = value_type.IsLongTypes(); 3859 } else if (field_type.IsDouble()) { 3860 instruction_compatible = insn_type.IsLong(); // no [is]put-double, so expect [is]put-long 3861 value_compatible = value_type.IsDoubleTypes(); 3862 } else { 3863 instruction_compatible = false; // reference field with primitive store 3864 value_compatible = false; // unused 3865 } 3866 if (!instruction_compatible) { 3867 // This is a global failure rather than a class change failure as the instructions and 3868 // the descriptors for the type should have been consistent within the same file at 3869 // compile time 3870 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected field " << PrettyField(field) 3871 << " to be of type '" << insn_type 3872 << "' but found type '" << field_type 3873 << "' in put"; 3874 return; 3875 } 3876 if (!value_compatible) { 3877 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected value in v" << vregA 3878 << " of type " << value_type 3879 << " but expected " << field_type 3880 << " for store to " << PrettyField(field) << " in put"; 3881 return; 3882 } 3883 } else { 3884 if (!insn_type.IsAssignableFrom(field_type)) { 3885 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "expected field " << PrettyField(field) 3886 << " to be compatible with type '" << insn_type 3887 << "' but found type '" << field_type 3888 << "' in put-object"; 3889 return; 3890 } 3891 work_line_->VerifyRegisterType(vregA, field_type); 3892 } 3893} 3894 3895bool MethodVerifier::CheckNotMoveException(const uint16_t* insns, int insn_idx) { 3896 if ((insns[insn_idx] & 0xff) == Instruction::MOVE_EXCEPTION) { 3897 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid use of move-exception"; 3898 return false; 3899 } 3900 return true; 3901} 3902 3903bool MethodVerifier::UpdateRegisters(uint32_t next_insn, RegisterLine* merge_line, 3904 bool update_merge_line) { 3905 bool changed = true; 3906 RegisterLine* target_line = reg_table_.GetLine(next_insn); 3907 if (!insn_flags_[next_insn].IsVisitedOrChanged()) { 3908 /* 3909 * We haven't processed this instruction before, and we haven't touched the registers here, so 3910 * there's nothing to "merge". Copy the registers over and mark it as changed. (This is the 3911 * only way a register can transition out of "unknown", so this is not just an optimization.) 3912 */ 3913 if (!insn_flags_[next_insn].IsReturn()) { 3914 target_line->CopyFromLine(merge_line); 3915 } else { 3916 // Verify that the monitor stack is empty on return. 3917 if (!merge_line->VerifyMonitorStackEmpty()) { 3918 return false; 3919 } 3920 // For returns we only care about the operand to the return, all other registers are dead. 3921 // Initialize them as conflicts so they don't add to GC and deoptimization information. 3922 const Instruction* ret_inst = Instruction::At(code_item_->insns_ + next_insn); 3923 Instruction::Code opcode = ret_inst->Opcode(); 3924 if ((opcode == Instruction::RETURN_VOID) || (opcode == Instruction::RETURN_VOID_BARRIER)) { 3925 target_line->MarkAllRegistersAsConflicts(); 3926 } else { 3927 target_line->CopyFromLine(merge_line); 3928 if (opcode == Instruction::RETURN_WIDE) { 3929 target_line->MarkAllRegistersAsConflictsExceptWide(ret_inst->VRegA_11x()); 3930 } else { 3931 target_line->MarkAllRegistersAsConflictsExcept(ret_inst->VRegA_11x()); 3932 } 3933 } 3934 } 3935 } else { 3936 std::unique_ptr<RegisterLine> copy(gDebugVerify ? 3937 RegisterLine::Create(target_line->NumRegs(), this) : 3938 NULL); 3939 if (gDebugVerify) { 3940 copy->CopyFromLine(target_line); 3941 } 3942 changed = target_line->MergeRegisters(merge_line); 3943 if (have_pending_hard_failure_) { 3944 return false; 3945 } 3946 if (gDebugVerify && changed) { 3947 LogVerifyInfo() << "Merging at [" << reinterpret_cast<void*>(work_insn_idx_) << "]" 3948 << " to [" << reinterpret_cast<void*>(next_insn) << "]: " << "\n" 3949 << *copy.get() << " MERGE\n" 3950 << *merge_line << " ==\n" 3951 << *target_line << "\n"; 3952 } 3953 if (update_merge_line && changed) { 3954 merge_line->CopyFromLine(target_line); 3955 } 3956 } 3957 if (changed) { 3958 insn_flags_[next_insn].SetChanged(); 3959 } 3960 return true; 3961} 3962 3963InstructionFlags* MethodVerifier::CurrentInsnFlags() { 3964 return &insn_flags_[work_insn_idx_]; 3965} 3966 3967const RegType& MethodVerifier::GetMethodReturnType() { 3968 if (return_type_ == nullptr) { 3969 if (mirror_method_ != NULL) { 3970 Thread* self = Thread::Current(); 3971 StackHandleScope<1> hs(self); 3972 mirror::Class* return_type_class; 3973 { 3974 HandleWrapper<mirror::ArtMethod> h_mirror_method(hs.NewHandleWrapper(&mirror_method_)); 3975 return_type_class = MethodHelper(h_mirror_method).GetReturnType(can_load_classes_); 3976 } 3977 if (return_type_class != nullptr) { 3978 return_type_ = ®_types_.FromClass(mirror_method_->GetReturnTypeDescriptor(), 3979 return_type_class, 3980 return_type_class->CannotBeAssignedFromOtherTypes()); 3981 } else { 3982 DCHECK(!can_load_classes_ || self->IsExceptionPending()); 3983 self->ClearException(); 3984 } 3985 } 3986 if (return_type_ == nullptr) { 3987 const DexFile::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx_); 3988 const DexFile::ProtoId& proto_id = dex_file_->GetMethodPrototype(method_id); 3989 uint16_t return_type_idx = proto_id.return_type_idx_; 3990 const char* descriptor = dex_file_->GetTypeDescriptor(dex_file_->GetTypeId(return_type_idx)); 3991 return_type_ = ®_types_.FromDescriptor(class_loader_->Get(), descriptor, false); 3992 } 3993 } 3994 return *return_type_; 3995} 3996 3997const RegType& MethodVerifier::GetDeclaringClass() { 3998 if (declaring_class_ == NULL) { 3999 const DexFile::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx_); 4000 const char* descriptor 4001 = dex_file_->GetTypeDescriptor(dex_file_->GetTypeId(method_id.class_idx_)); 4002 if (mirror_method_ != NULL) { 4003 mirror::Class* klass = mirror_method_->GetDeclaringClass(); 4004 declaring_class_ = ®_types_.FromClass(descriptor, klass, 4005 klass->CannotBeAssignedFromOtherTypes()); 4006 } else { 4007 declaring_class_ = ®_types_.FromDescriptor(class_loader_->Get(), descriptor, false); 4008 } 4009 } 4010 return *declaring_class_; 4011} 4012 4013std::vector<int32_t> MethodVerifier::DescribeVRegs(uint32_t dex_pc) { 4014 RegisterLine* line = reg_table_.GetLine(dex_pc); 4015 DCHECK(line != nullptr) << "No register line at DEX pc " << StringPrintf("0x%x", dex_pc); 4016 std::vector<int32_t> result; 4017 for (size_t i = 0; i < line->NumRegs(); ++i) { 4018 const RegType& type = line->GetRegisterType(i); 4019 if (type.IsConstant()) { 4020 result.push_back(type.IsPreciseConstant() ? kConstant : kImpreciseConstant); 4021 result.push_back(type.ConstantValue()); 4022 } else if (type.IsConstantLo()) { 4023 result.push_back(type.IsPreciseConstantLo() ? kConstant : kImpreciseConstant); 4024 result.push_back(type.ConstantValueLo()); 4025 } else if (type.IsConstantHi()) { 4026 result.push_back(type.IsPreciseConstantHi() ? kConstant : kImpreciseConstant); 4027 result.push_back(type.ConstantValueHi()); 4028 } else if (type.IsIntegralTypes()) { 4029 result.push_back(kIntVReg); 4030 result.push_back(0); 4031 } else if (type.IsFloat()) { 4032 result.push_back(kFloatVReg); 4033 result.push_back(0); 4034 } else if (type.IsLong()) { 4035 result.push_back(kLongLoVReg); 4036 result.push_back(0); 4037 result.push_back(kLongHiVReg); 4038 result.push_back(0); 4039 ++i; 4040 } else if (type.IsDouble()) { 4041 result.push_back(kDoubleLoVReg); 4042 result.push_back(0); 4043 result.push_back(kDoubleHiVReg); 4044 result.push_back(0); 4045 ++i; 4046 } else if (type.IsUndefined() || type.IsConflict() || type.IsHighHalf()) { 4047 result.push_back(kUndefined); 4048 result.push_back(0); 4049 } else { 4050 CHECK(type.IsNonZeroReferenceTypes()); 4051 result.push_back(kReferenceVReg); 4052 result.push_back(0); 4053 } 4054 } 4055 return result; 4056} 4057 4058const RegType& MethodVerifier::DetermineCat1Constant(int32_t value, bool precise) { 4059 if (precise) { 4060 // Precise constant type. 4061 return reg_types_.FromCat1Const(value, true); 4062 } else { 4063 // Imprecise constant type. 4064 if (value < -32768) { 4065 return reg_types_.IntConstant(); 4066 } else if (value < -128) { 4067 return reg_types_.ShortConstant(); 4068 } else if (value < 0) { 4069 return reg_types_.ByteConstant(); 4070 } else if (value == 0) { 4071 return reg_types_.Zero(); 4072 } else if (value == 1) { 4073 return reg_types_.One(); 4074 } else if (value < 128) { 4075 return reg_types_.PosByteConstant(); 4076 } else if (value < 32768) { 4077 return reg_types_.PosShortConstant(); 4078 } else if (value < 65536) { 4079 return reg_types_.CharConstant(); 4080 } else { 4081 return reg_types_.IntConstant(); 4082 } 4083 } 4084} 4085 4086void MethodVerifier::Init() { 4087 art::verifier::RegTypeCache::Init(); 4088} 4089 4090void MethodVerifier::Shutdown() { 4091 verifier::RegTypeCache::ShutDown(); 4092} 4093 4094void MethodVerifier::VisitRoots(RootCallback* callback, void* arg) { 4095 reg_types_.VisitRoots(callback, arg); 4096} 4097 4098} // namespace verifier 4099} // namespace art 4100