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