method_verifier.cc revision 2ed76f95dd5a7edada82407a1853be803c9853a9
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(), true, 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 nullptr; 379 } 380 RegisterLine* register_line = reg_table_.GetLine(dex_pc); 381 if (register_line == NULL) { 382 return nullptr; 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(), true, 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 = ResolveClassAndCheckAccess(iterator.GetTypeIdx()); 1180 if (!reg_type.IsNonZeroReferenceTypes()) { 1181 DCHECK(HasFailures()); 1182 return false; 1183 } 1184 reg_line->SetRegisterType(arg_start + cur_arg, reg_type); 1185 } 1186 break; 1187 case 'Z': 1188 reg_line->SetRegisterType(arg_start + cur_arg, reg_types_.Boolean()); 1189 break; 1190 case 'C': 1191 reg_line->SetRegisterType(arg_start + cur_arg, reg_types_.Char()); 1192 break; 1193 case 'B': 1194 reg_line->SetRegisterType(arg_start + cur_arg, reg_types_.Byte()); 1195 break; 1196 case 'I': 1197 reg_line->SetRegisterType(arg_start + cur_arg, reg_types_.Integer()); 1198 break; 1199 case 'S': 1200 reg_line->SetRegisterType(arg_start + cur_arg, reg_types_.Short()); 1201 break; 1202 case 'F': 1203 reg_line->SetRegisterType(arg_start + cur_arg, reg_types_.Float()); 1204 break; 1205 case 'J': 1206 case 'D': { 1207 const RegType& lo_half = descriptor[0] == 'J' ? reg_types_.LongLo() : reg_types_.DoubleLo(); 1208 const RegType& hi_half = descriptor[0] == 'J' ? reg_types_.LongHi() : reg_types_.DoubleHi(); 1209 reg_line->SetRegisterTypeWide(arg_start + cur_arg, lo_half, hi_half); 1210 cur_arg++; 1211 break; 1212 } 1213 default: 1214 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected signature type char '" 1215 << descriptor << "'"; 1216 return false; 1217 } 1218 cur_arg++; 1219 } 1220 if (cur_arg != expected_args) { 1221 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected " << expected_args 1222 << " arguments, found " << cur_arg; 1223 return false; 1224 } 1225 const char* descriptor = dex_file_->GetReturnTypeDescriptor(proto_id); 1226 // Validate return type. We don't do the type lookup; just want to make sure that it has the right 1227 // format. Only major difference from the method argument format is that 'V' is supported. 1228 bool result; 1229 if (IsPrimitiveDescriptor(descriptor[0]) || descriptor[0] == 'V') { 1230 result = descriptor[1] == '\0'; 1231 } else if (descriptor[0] == '[') { // single/multi-dimensional array of object/primitive 1232 size_t i = 0; 1233 do { 1234 i++; 1235 } while (descriptor[i] == '['); // process leading [ 1236 if (descriptor[i] == 'L') { // object array 1237 do { 1238 i++; // find closing ; 1239 } while (descriptor[i] != ';' && descriptor[i] != '\0'); 1240 result = descriptor[i] == ';'; 1241 } else { // primitive array 1242 result = IsPrimitiveDescriptor(descriptor[i]) && descriptor[i + 1] == '\0'; 1243 } 1244 } else if (descriptor[0] == 'L') { 1245 // could be more thorough here, but shouldn't be required 1246 size_t i = 0; 1247 do { 1248 i++; 1249 } while (descriptor[i] != ';' && descriptor[i] != '\0'); 1250 result = descriptor[i] == ';'; 1251 } else { 1252 result = false; 1253 } 1254 if (!result) { 1255 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected char in return type descriptor '" 1256 << descriptor << "'"; 1257 } 1258 return result; 1259} 1260 1261bool MethodVerifier::CodeFlowVerifyMethod() { 1262 const uint16_t* insns = code_item_->insns_; 1263 const uint32_t insns_size = code_item_->insns_size_in_code_units_; 1264 1265 /* Begin by marking the first instruction as "changed". */ 1266 insn_flags_[0].SetChanged(); 1267 uint32_t start_guess = 0; 1268 1269 /* Continue until no instructions are marked "changed". */ 1270 while (true) { 1271 // Find the first marked one. Use "start_guess" as a way to find one quickly. 1272 uint32_t insn_idx = start_guess; 1273 for (; insn_idx < insns_size; insn_idx++) { 1274 if (insn_flags_[insn_idx].IsChanged()) 1275 break; 1276 } 1277 if (insn_idx == insns_size) { 1278 if (start_guess != 0) { 1279 /* try again, starting from the top */ 1280 start_guess = 0; 1281 continue; 1282 } else { 1283 /* all flags are clear */ 1284 break; 1285 } 1286 } 1287 // We carry the working set of registers from instruction to instruction. If this address can 1288 // be the target of a branch (or throw) instruction, or if we're skipping around chasing 1289 // "changed" flags, we need to load the set of registers from the table. 1290 // Because we always prefer to continue on to the next instruction, we should never have a 1291 // situation where we have a stray "changed" flag set on an instruction that isn't a branch 1292 // target. 1293 work_insn_idx_ = insn_idx; 1294 if (insn_flags_[insn_idx].IsBranchTarget()) { 1295 work_line_->CopyFromLine(reg_table_.GetLine(insn_idx)); 1296 } else { 1297#ifndef NDEBUG 1298 /* 1299 * Sanity check: retrieve the stored register line (assuming 1300 * a full table) and make sure it actually matches. 1301 */ 1302 RegisterLine* register_line = reg_table_.GetLine(insn_idx); 1303 if (register_line != NULL) { 1304 if (work_line_->CompareLine(register_line) != 0) { 1305 Dump(std::cout); 1306 std::cout << info_messages_.str(); 1307 LOG(FATAL) << "work_line diverged in " << PrettyMethod(dex_method_idx_, *dex_file_) 1308 << "@" << reinterpret_cast<void*>(work_insn_idx_) << "\n" 1309 << " work_line=" << *work_line_ << "\n" 1310 << " expected=" << *register_line; 1311 } 1312 } 1313#endif 1314 } 1315 if (!CodeFlowVerifyInstruction(&start_guess)) { 1316 std::string prepend(PrettyMethod(dex_method_idx_, *dex_file_)); 1317 prepend += " failed to verify: "; 1318 PrependToLastFailMessage(prepend); 1319 return false; 1320 } 1321 /* Clear "changed" and mark as visited. */ 1322 insn_flags_[insn_idx].SetVisited(); 1323 insn_flags_[insn_idx].ClearChanged(); 1324 } 1325 1326 if (gDebugVerify) { 1327 /* 1328 * Scan for dead code. There's nothing "evil" about dead code 1329 * (besides the wasted space), but it indicates a flaw somewhere 1330 * down the line, possibly in the verifier. 1331 * 1332 * If we've substituted "always throw" instructions into the stream, 1333 * we are almost certainly going to have some dead code. 1334 */ 1335 int dead_start = -1; 1336 uint32_t insn_idx = 0; 1337 for (; insn_idx < insns_size; insn_idx += insn_flags_[insn_idx].GetLengthInCodeUnits()) { 1338 /* 1339 * Switch-statement data doesn't get "visited" by scanner. It 1340 * may or may not be preceded by a padding NOP (for alignment). 1341 */ 1342 if (insns[insn_idx] == Instruction::kPackedSwitchSignature || 1343 insns[insn_idx] == Instruction::kSparseSwitchSignature || 1344 insns[insn_idx] == Instruction::kArrayDataSignature || 1345 (insns[insn_idx] == Instruction::NOP && (insn_idx + 1 < insns_size) && 1346 (insns[insn_idx + 1] == Instruction::kPackedSwitchSignature || 1347 insns[insn_idx + 1] == Instruction::kSparseSwitchSignature || 1348 insns[insn_idx + 1] == Instruction::kArrayDataSignature))) { 1349 insn_flags_[insn_idx].SetVisited(); 1350 } 1351 1352 if (!insn_flags_[insn_idx].IsVisited()) { 1353 if (dead_start < 0) 1354 dead_start = insn_idx; 1355 } else if (dead_start >= 0) { 1356 LogVerifyInfo() << "dead code " << reinterpret_cast<void*>(dead_start) 1357 << "-" << reinterpret_cast<void*>(insn_idx - 1); 1358 dead_start = -1; 1359 } 1360 } 1361 if (dead_start >= 0) { 1362 LogVerifyInfo() << "dead code " << reinterpret_cast<void*>(dead_start) 1363 << "-" << reinterpret_cast<void*>(insn_idx - 1); 1364 } 1365 // To dump the state of the verify after a method, do something like: 1366 // if (PrettyMethod(dex_method_idx_, *dex_file_) == 1367 // "boolean java.lang.String.equals(java.lang.Object)") { 1368 // LOG(INFO) << info_messages_.str(); 1369 // } 1370 } 1371 return true; 1372} 1373 1374bool MethodVerifier::CodeFlowVerifyInstruction(uint32_t* start_guess) { 1375 // If we're doing FindLocksAtDexPc, check whether we're at the dex pc we care about. 1376 // We want the state _before_ the instruction, for the case where the dex pc we're 1377 // interested in is itself a monitor-enter instruction (which is a likely place 1378 // for a thread to be suspended). 1379 if (monitor_enter_dex_pcs_ != NULL && work_insn_idx_ == interesting_dex_pc_) { 1380 monitor_enter_dex_pcs_->clear(); // The new work line is more accurate than the previous one. 1381 for (size_t i = 0; i < work_line_->GetMonitorEnterCount(); ++i) { 1382 monitor_enter_dex_pcs_->push_back(work_line_->GetMonitorEnterDexPc(i)); 1383 } 1384 } 1385 1386 /* 1387 * Once we finish decoding the instruction, we need to figure out where 1388 * we can go from here. There are three possible ways to transfer 1389 * control to another statement: 1390 * 1391 * (1) Continue to the next instruction. Applies to all but 1392 * unconditional branches, method returns, and exception throws. 1393 * (2) Branch to one or more possible locations. Applies to branches 1394 * and switch statements. 1395 * (3) Exception handlers. Applies to any instruction that can 1396 * throw an exception that is handled by an encompassing "try" 1397 * block. 1398 * 1399 * We can also return, in which case there is no successor instruction 1400 * from this point. 1401 * 1402 * The behavior can be determined from the opcode flags. 1403 */ 1404 const uint16_t* insns = code_item_->insns_ + work_insn_idx_; 1405 const Instruction* inst = Instruction::At(insns); 1406 int opcode_flags = Instruction::FlagsOf(inst->Opcode()); 1407 1408 int32_t branch_target = 0; 1409 bool just_set_result = false; 1410 if (gDebugVerify) { 1411 // Generate processing back trace to debug verifier 1412 LogVerifyInfo() << "Processing " << inst->DumpString(dex_file_) << "\n" 1413 << *work_line_.get() << "\n"; 1414 } 1415 1416 /* 1417 * Make a copy of the previous register state. If the instruction 1418 * can throw an exception, we will copy/merge this into the "catch" 1419 * address rather than work_line, because we don't want the result 1420 * from the "successful" code path (e.g. a check-cast that "improves" 1421 * a type) to be visible to the exception handler. 1422 */ 1423 if ((opcode_flags & Instruction::kThrow) != 0 && CurrentInsnFlags()->IsInTry()) { 1424 saved_line_->CopyFromLine(work_line_.get()); 1425 } else { 1426#ifndef NDEBUG 1427 saved_line_->FillWithGarbage(); 1428#endif 1429 } 1430 1431 1432 // We need to ensure the work line is consistent while performing validation. When we spot a 1433 // peephole pattern we compute a new line for either the fallthrough instruction or the 1434 // branch target. 1435 UniquePtr<RegisterLine> branch_line; 1436 UniquePtr<RegisterLine> fallthrough_line; 1437 1438 // We need precise constant types only for deoptimization which happens at runtime. 1439 const bool need_precise_constant = !Runtime::Current()->IsCompiler(); 1440 1441 switch (inst->Opcode()) { 1442 case Instruction::NOP: 1443 /* 1444 * A "pure" NOP has no effect on anything. Data tables start with 1445 * a signature that looks like a NOP; if we see one of these in 1446 * the course of executing code then we have a problem. 1447 */ 1448 if (inst->VRegA_10x() != 0) { 1449 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "encountered data table in instruction stream"; 1450 } 1451 break; 1452 1453 case Instruction::MOVE: 1454 work_line_->CopyRegister1(inst->VRegA_12x(), inst->VRegB_12x(), kTypeCategory1nr); 1455 break; 1456 case Instruction::MOVE_FROM16: 1457 work_line_->CopyRegister1(inst->VRegA_22x(), inst->VRegB_22x(), kTypeCategory1nr); 1458 break; 1459 case Instruction::MOVE_16: 1460 work_line_->CopyRegister1(inst->VRegA_32x(), inst->VRegB_32x(), kTypeCategory1nr); 1461 break; 1462 case Instruction::MOVE_WIDE: 1463 work_line_->CopyRegister2(inst->VRegA_12x(), inst->VRegB_12x()); 1464 break; 1465 case Instruction::MOVE_WIDE_FROM16: 1466 work_line_->CopyRegister2(inst->VRegA_22x(), inst->VRegB_22x()); 1467 break; 1468 case Instruction::MOVE_WIDE_16: 1469 work_line_->CopyRegister2(inst->VRegA_32x(), inst->VRegB_32x()); 1470 break; 1471 case Instruction::MOVE_OBJECT: 1472 work_line_->CopyRegister1(inst->VRegA_12x(), inst->VRegB_12x(), kTypeCategoryRef); 1473 break; 1474 case Instruction::MOVE_OBJECT_FROM16: 1475 work_line_->CopyRegister1(inst->VRegA_22x(), inst->VRegB_22x(), kTypeCategoryRef); 1476 break; 1477 case Instruction::MOVE_OBJECT_16: 1478 work_line_->CopyRegister1(inst->VRegA_32x(), inst->VRegB_32x(), kTypeCategoryRef); 1479 break; 1480 1481 /* 1482 * The move-result instructions copy data out of a "pseudo-register" 1483 * with the results from the last method invocation. In practice we 1484 * might want to hold the result in an actual CPU register, so the 1485 * Dalvik spec requires that these only appear immediately after an 1486 * invoke or filled-new-array. 1487 * 1488 * These calls invalidate the "result" register. (This is now 1489 * redundant with the reset done below, but it can make the debug info 1490 * easier to read in some cases.) 1491 */ 1492 case Instruction::MOVE_RESULT: 1493 work_line_->CopyResultRegister1(inst->VRegA_11x(), false); 1494 break; 1495 case Instruction::MOVE_RESULT_WIDE: 1496 work_line_->CopyResultRegister2(inst->VRegA_11x()); 1497 break; 1498 case Instruction::MOVE_RESULT_OBJECT: 1499 work_line_->CopyResultRegister1(inst->VRegA_11x(), true); 1500 break; 1501 1502 case Instruction::MOVE_EXCEPTION: { 1503 /* 1504 * This statement can only appear as the first instruction in an exception handler. We verify 1505 * that as part of extracting the exception type from the catch block list. 1506 */ 1507 const RegType& res_type = GetCaughtExceptionType(); 1508 work_line_->SetRegisterType(inst->VRegA_11x(), res_type); 1509 break; 1510 } 1511 case Instruction::RETURN_VOID: 1512 if (!IsConstructor() || work_line_->CheckConstructorReturn()) { 1513 if (!GetMethodReturnType().IsConflict()) { 1514 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-void not expected"; 1515 } 1516 } 1517 break; 1518 case Instruction::RETURN: 1519 if (!IsConstructor() || work_line_->CheckConstructorReturn()) { 1520 /* check the method signature */ 1521 const RegType& return_type = GetMethodReturnType(); 1522 if (!return_type.IsCategory1Types()) { 1523 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected non-category 1 return type " 1524 << return_type; 1525 } else { 1526 // Compilers may generate synthetic functions that write byte values into boolean fields. 1527 // Also, it may use integer values for boolean, byte, short, and character return types. 1528 const uint32_t vregA = inst->VRegA_11x(); 1529 const RegType& src_type = work_line_->GetRegisterType(vregA); 1530 bool use_src = ((return_type.IsBoolean() && src_type.IsByte()) || 1531 ((return_type.IsBoolean() || return_type.IsByte() || 1532 return_type.IsShort() || return_type.IsChar()) && 1533 src_type.IsInteger())); 1534 /* check the register contents */ 1535 bool success = 1536 work_line_->VerifyRegisterType(vregA, use_src ? src_type : return_type); 1537 if (!success) { 1538 AppendToLastFailMessage(StringPrintf(" return-1nr on invalid register v%d", vregA)); 1539 } 1540 } 1541 } 1542 break; 1543 case Instruction::RETURN_WIDE: 1544 if (!IsConstructor() || work_line_->CheckConstructorReturn()) { 1545 /* check the method signature */ 1546 const RegType& return_type = GetMethodReturnType(); 1547 if (!return_type.IsCategory2Types()) { 1548 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-wide not expected"; 1549 } else { 1550 /* check the register contents */ 1551 const uint32_t vregA = inst->VRegA_11x(); 1552 bool success = work_line_->VerifyRegisterType(vregA, return_type); 1553 if (!success) { 1554 AppendToLastFailMessage(StringPrintf(" return-wide on invalid register v%d", vregA)); 1555 } 1556 } 1557 } 1558 break; 1559 case Instruction::RETURN_OBJECT: 1560 if (!IsConstructor() || work_line_->CheckConstructorReturn()) { 1561 const RegType& return_type = GetMethodReturnType(); 1562 if (!return_type.IsReferenceTypes()) { 1563 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-object not expected"; 1564 } else { 1565 /* return_type is the *expected* return type, not register value */ 1566 DCHECK(!return_type.IsZero()); 1567 DCHECK(!return_type.IsUninitializedReference()); 1568 const uint32_t vregA = inst->VRegA_11x(); 1569 const RegType& reg_type = work_line_->GetRegisterType(vregA); 1570 // Disallow returning uninitialized values and verify that the reference in vAA is an 1571 // instance of the "return_type" 1572 if (reg_type.IsUninitializedTypes()) { 1573 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "returning uninitialized object '" 1574 << reg_type << "'"; 1575 } else if (!return_type.IsAssignableFrom(reg_type)) { 1576 if (reg_type.IsUnresolvedTypes() || return_type.IsUnresolvedTypes()) { 1577 Fail(VERIFY_ERROR_NO_CLASS) << " can't resolve returned type '" << return_type 1578 << "' or '" << reg_type << "'"; 1579 } else { 1580 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "returning '" << reg_type 1581 << "', but expected from declaration '" << return_type << "'"; 1582 } 1583 } 1584 } 1585 } 1586 break; 1587 1588 /* could be boolean, int, float, or a null reference */ 1589 case Instruction::CONST_4: { 1590 int32_t val = static_cast<int32_t>(inst->VRegB_11n() << 28) >> 28; 1591 work_line_->SetRegisterType(inst->VRegA_11n(), 1592 DetermineCat1Constant(val, need_precise_constant)); 1593 break; 1594 } 1595 case Instruction::CONST_16: { 1596 int16_t val = static_cast<int16_t>(inst->VRegB_21s()); 1597 work_line_->SetRegisterType(inst->VRegA_21s(), 1598 DetermineCat1Constant(val, need_precise_constant)); 1599 break; 1600 } 1601 case Instruction::CONST: { 1602 int32_t val = inst->VRegB_31i(); 1603 work_line_->SetRegisterType(inst->VRegA_31i(), 1604 DetermineCat1Constant(val, need_precise_constant)); 1605 break; 1606 } 1607 case Instruction::CONST_HIGH16: { 1608 int32_t val = static_cast<int32_t>(inst->VRegB_21h() << 16); 1609 work_line_->SetRegisterType(inst->VRegA_21h(), 1610 DetermineCat1Constant(val, need_precise_constant)); 1611 break; 1612 } 1613 /* could be long or double; resolved upon use */ 1614 case Instruction::CONST_WIDE_16: { 1615 int64_t val = static_cast<int16_t>(inst->VRegB_21s()); 1616 const RegType& lo = reg_types_.FromCat2ConstLo(static_cast<int32_t>(val), true); 1617 const RegType& hi = reg_types_.FromCat2ConstHi(static_cast<int32_t>(val >> 32), true); 1618 work_line_->SetRegisterTypeWide(inst->VRegA_21s(), lo, hi); 1619 break; 1620 } 1621 case Instruction::CONST_WIDE_32: { 1622 int64_t val = static_cast<int32_t>(inst->VRegB_31i()); 1623 const RegType& lo = reg_types_.FromCat2ConstLo(static_cast<int32_t>(val), true); 1624 const RegType& hi = reg_types_.FromCat2ConstHi(static_cast<int32_t>(val >> 32), true); 1625 work_line_->SetRegisterTypeWide(inst->VRegA_31i(), lo, hi); 1626 break; 1627 } 1628 case Instruction::CONST_WIDE: { 1629 int64_t val = inst->VRegB_51l(); 1630 const RegType& lo = reg_types_.FromCat2ConstLo(static_cast<int32_t>(val), true); 1631 const RegType& hi = reg_types_.FromCat2ConstHi(static_cast<int32_t>(val >> 32), true); 1632 work_line_->SetRegisterTypeWide(inst->VRegA_51l(), lo, hi); 1633 break; 1634 } 1635 case Instruction::CONST_WIDE_HIGH16: { 1636 int64_t val = static_cast<uint64_t>(inst->VRegB_21h()) << 48; 1637 const RegType& lo = reg_types_.FromCat2ConstLo(static_cast<int32_t>(val), true); 1638 const RegType& hi = reg_types_.FromCat2ConstHi(static_cast<int32_t>(val >> 32), true); 1639 work_line_->SetRegisterTypeWide(inst->VRegA_21h(), lo, hi); 1640 break; 1641 } 1642 case Instruction::CONST_STRING: 1643 work_line_->SetRegisterType(inst->VRegA_21c(), reg_types_.JavaLangString()); 1644 break; 1645 case Instruction::CONST_STRING_JUMBO: 1646 work_line_->SetRegisterType(inst->VRegA_31c(), reg_types_.JavaLangString()); 1647 break; 1648 case Instruction::CONST_CLASS: { 1649 // Get type from instruction if unresolved then we need an access check 1650 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved 1651 const RegType& res_type = ResolveClassAndCheckAccess(inst->VRegB_21c()); 1652 // Register holds class, ie its type is class, on error it will hold Conflict. 1653 work_line_->SetRegisterType(inst->VRegA_21c(), 1654 res_type.IsConflict() ? res_type 1655 : reg_types_.JavaLangClass(true)); 1656 break; 1657 } 1658 case Instruction::MONITOR_ENTER: 1659 work_line_->PushMonitor(inst->VRegA_11x(), work_insn_idx_); 1660 break; 1661 case Instruction::MONITOR_EXIT: 1662 /* 1663 * monitor-exit instructions are odd. They can throw exceptions, 1664 * but when they do they act as if they succeeded and the PC is 1665 * pointing to the following instruction. (This behavior goes back 1666 * to the need to handle asynchronous exceptions, a now-deprecated 1667 * feature that Dalvik doesn't support.) 1668 * 1669 * In practice we don't need to worry about this. The only 1670 * exceptions that can be thrown from monitor-exit are for a 1671 * null reference and -exit without a matching -enter. If the 1672 * structured locking checks are working, the former would have 1673 * failed on the -enter instruction, and the latter is impossible. 1674 * 1675 * This is fortunate, because issue 3221411 prevents us from 1676 * chasing the "can throw" path when monitor verification is 1677 * enabled. If we can fully verify the locking we can ignore 1678 * some catch blocks (which will show up as "dead" code when 1679 * we skip them here); if we can't, then the code path could be 1680 * "live" so we still need to check it. 1681 */ 1682 opcode_flags &= ~Instruction::kThrow; 1683 work_line_->PopMonitor(inst->VRegA_11x()); 1684 break; 1685 1686 case Instruction::CHECK_CAST: 1687 case Instruction::INSTANCE_OF: { 1688 /* 1689 * If this instruction succeeds, we will "downcast" register vA to the type in vB. (This 1690 * could be a "upcast" -- not expected, so we don't try to address it.) 1691 * 1692 * If it fails, an exception is thrown, which we deal with later by ignoring the update to 1693 * dec_insn.vA when branching to a handler. 1694 */ 1695 const bool is_checkcast = (inst->Opcode() == Instruction::CHECK_CAST); 1696 const uint32_t type_idx = (is_checkcast) ? inst->VRegB_21c() : inst->VRegC_22c(); 1697 const RegType& res_type = ResolveClassAndCheckAccess(type_idx); 1698 if (res_type.IsConflict()) { 1699 DCHECK_NE(failures_.size(), 0U); 1700 if (!is_checkcast) { 1701 work_line_->SetRegisterType(inst->VRegA_22c(), reg_types_.Boolean()); 1702 } 1703 break; // bad class 1704 } 1705 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved 1706 uint32_t orig_type_reg = (is_checkcast) ? inst->VRegA_21c() : inst->VRegB_22c(); 1707 const RegType& orig_type = work_line_->GetRegisterType(orig_type_reg); 1708 if (!res_type.IsNonZeroReferenceTypes()) { 1709 if (is_checkcast) { 1710 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "check-cast on unexpected class " << res_type; 1711 } else { 1712 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "instance-of on unexpected class " << res_type; 1713 } 1714 } else if (!orig_type.IsReferenceTypes()) { 1715 if (is_checkcast) { 1716 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "check-cast on non-reference in v" << orig_type_reg; 1717 } else { 1718 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "instance-of on non-reference in v" << orig_type_reg; 1719 } 1720 } else { 1721 if (is_checkcast) { 1722 work_line_->SetRegisterType(inst->VRegA_21c(), res_type); 1723 } else { 1724 work_line_->SetRegisterType(inst->VRegA_22c(), reg_types_.Boolean()); 1725 } 1726 } 1727 break; 1728 } 1729 case Instruction::ARRAY_LENGTH: { 1730 const RegType& res_type = work_line_->GetRegisterType(inst->VRegB_12x()); 1731 if (res_type.IsReferenceTypes()) { 1732 if (!res_type.IsArrayTypes() && !res_type.IsZero()) { // ie not an array or null 1733 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array-length on non-array " << res_type; 1734 } else { 1735 work_line_->SetRegisterType(inst->VRegA_12x(), reg_types_.Integer()); 1736 } 1737 } 1738 break; 1739 } 1740 case Instruction::NEW_INSTANCE: { 1741 const RegType& res_type = ResolveClassAndCheckAccess(inst->VRegB_21c()); 1742 if (res_type.IsConflict()) { 1743 DCHECK_NE(failures_.size(), 0U); 1744 break; // bad class 1745 } 1746 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved 1747 // can't create an instance of an interface or abstract class */ 1748 if (!res_type.IsInstantiableTypes()) { 1749 Fail(VERIFY_ERROR_INSTANTIATION) 1750 << "new-instance on primitive, interface or abstract class" << res_type; 1751 // Soft failure so carry on to set register type. 1752 } 1753 const RegType& uninit_type = reg_types_.Uninitialized(res_type, work_insn_idx_); 1754 // Any registers holding previous allocations from this address that have not yet been 1755 // initialized must be marked invalid. 1756 work_line_->MarkUninitRefsAsInvalid(uninit_type); 1757 // add the new uninitialized reference to the register state 1758 work_line_->SetRegisterType(inst->VRegA_21c(), uninit_type); 1759 break; 1760 } 1761 case Instruction::NEW_ARRAY: 1762 VerifyNewArray(inst, false, false); 1763 break; 1764 case Instruction::FILLED_NEW_ARRAY: 1765 VerifyNewArray(inst, true, false); 1766 just_set_result = true; // Filled new array sets result register 1767 break; 1768 case Instruction::FILLED_NEW_ARRAY_RANGE: 1769 VerifyNewArray(inst, true, true); 1770 just_set_result = true; // Filled new array range sets result register 1771 break; 1772 case Instruction::CMPL_FLOAT: 1773 case Instruction::CMPG_FLOAT: 1774 if (!work_line_->VerifyRegisterType(inst->VRegB_23x(), reg_types_.Float())) { 1775 break; 1776 } 1777 if (!work_line_->VerifyRegisterType(inst->VRegC_23x(), reg_types_.Float())) { 1778 break; 1779 } 1780 work_line_->SetRegisterType(inst->VRegA_23x(), reg_types_.Integer()); 1781 break; 1782 case Instruction::CMPL_DOUBLE: 1783 case Instruction::CMPG_DOUBLE: 1784 if (!work_line_->VerifyRegisterTypeWide(inst->VRegB_23x(), reg_types_.DoubleLo(), 1785 reg_types_.DoubleHi())) { 1786 break; 1787 } 1788 if (!work_line_->VerifyRegisterTypeWide(inst->VRegC_23x(), reg_types_.DoubleLo(), 1789 reg_types_.DoubleHi())) { 1790 break; 1791 } 1792 work_line_->SetRegisterType(inst->VRegA_23x(), reg_types_.Integer()); 1793 break; 1794 case Instruction::CMP_LONG: 1795 if (!work_line_->VerifyRegisterTypeWide(inst->VRegB_23x(), reg_types_.LongLo(), 1796 reg_types_.LongHi())) { 1797 break; 1798 } 1799 if (!work_line_->VerifyRegisterTypeWide(inst->VRegC_23x(), reg_types_.LongLo(), 1800 reg_types_.LongHi())) { 1801 break; 1802 } 1803 work_line_->SetRegisterType(inst->VRegA_23x(), reg_types_.Integer()); 1804 break; 1805 case Instruction::THROW: { 1806 const RegType& res_type = work_line_->GetRegisterType(inst->VRegA_11x()); 1807 if (!reg_types_.JavaLangThrowable(false).IsAssignableFrom(res_type)) { 1808 Fail(res_type.IsUnresolvedTypes() ? VERIFY_ERROR_NO_CLASS : VERIFY_ERROR_BAD_CLASS_SOFT) 1809 << "thrown class " << res_type << " not instanceof Throwable"; 1810 } 1811 break; 1812 } 1813 case Instruction::GOTO: 1814 case Instruction::GOTO_16: 1815 case Instruction::GOTO_32: 1816 /* no effect on or use of registers */ 1817 break; 1818 1819 case Instruction::PACKED_SWITCH: 1820 case Instruction::SPARSE_SWITCH: 1821 /* verify that vAA is an integer, or can be converted to one */ 1822 work_line_->VerifyRegisterType(inst->VRegA_31t(), reg_types_.Integer()); 1823 break; 1824 1825 case Instruction::FILL_ARRAY_DATA: { 1826 /* Similar to the verification done for APUT */ 1827 const RegType& array_type = work_line_->GetRegisterType(inst->VRegA_31t()); 1828 /* array_type can be null if the reg type is Zero */ 1829 if (!array_type.IsZero()) { 1830 if (!array_type.IsArrayTypes()) { 1831 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid fill-array-data with array type " 1832 << array_type; 1833 } else { 1834 const RegType& component_type = reg_types_.GetComponentType(array_type, 1835 class_loader_->get()); 1836 DCHECK(!component_type.IsConflict()); 1837 if (component_type.IsNonZeroReferenceTypes()) { 1838 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid fill-array-data with component type " 1839 << component_type; 1840 } else { 1841 // Now verify if the element width in the table matches the element width declared in 1842 // the array 1843 const uint16_t* array_data = insns + (insns[1] | (((int32_t) insns[2]) << 16)); 1844 if (array_data[0] != Instruction::kArrayDataSignature) { 1845 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid magic for array-data"; 1846 } else { 1847 size_t elem_width = Primitive::ComponentSize(component_type.GetPrimitiveType()); 1848 // Since we don't compress the data in Dex, expect to see equal width of data stored 1849 // in the table and expected from the array class. 1850 if (array_data[1] != elem_width) { 1851 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array-data size mismatch (" << array_data[1] 1852 << " vs " << elem_width << ")"; 1853 } 1854 } 1855 } 1856 } 1857 } 1858 break; 1859 } 1860 case Instruction::IF_EQ: 1861 case Instruction::IF_NE: { 1862 const RegType& reg_type1 = work_line_->GetRegisterType(inst->VRegA_22t()); 1863 const RegType& reg_type2 = work_line_->GetRegisterType(inst->VRegB_22t()); 1864 bool mismatch = false; 1865 if (reg_type1.IsZero()) { // zero then integral or reference expected 1866 mismatch = !reg_type2.IsReferenceTypes() && !reg_type2.IsIntegralTypes(); 1867 } else if (reg_type1.IsReferenceTypes()) { // both references? 1868 mismatch = !reg_type2.IsReferenceTypes(); 1869 } else { // both integral? 1870 mismatch = !reg_type1.IsIntegralTypes() || !reg_type2.IsIntegralTypes(); 1871 } 1872 if (mismatch) { 1873 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "args to if-eq/if-ne (" << reg_type1 << "," 1874 << reg_type2 << ") must both be references or integral"; 1875 } 1876 break; 1877 } 1878 case Instruction::IF_LT: 1879 case Instruction::IF_GE: 1880 case Instruction::IF_GT: 1881 case Instruction::IF_LE: { 1882 const RegType& reg_type1 = work_line_->GetRegisterType(inst->VRegA_22t()); 1883 const RegType& reg_type2 = work_line_->GetRegisterType(inst->VRegB_22t()); 1884 if (!reg_type1.IsIntegralTypes() || !reg_type2.IsIntegralTypes()) { 1885 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "args to 'if' (" << reg_type1 << "," 1886 << reg_type2 << ") must be integral"; 1887 } 1888 break; 1889 } 1890 case Instruction::IF_EQZ: 1891 case Instruction::IF_NEZ: { 1892 const RegType& reg_type = work_line_->GetRegisterType(inst->VRegA_21t()); 1893 if (!reg_type.IsReferenceTypes() && !reg_type.IsIntegralTypes()) { 1894 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "type " << reg_type 1895 << " unexpected as arg to if-eqz/if-nez"; 1896 } 1897 1898 // Find previous instruction - its existence is a precondition to peephole optimization. 1899 uint32_t instance_of_idx = 0; 1900 if (0 != work_insn_idx_) { 1901 instance_of_idx = work_insn_idx_ - 1; 1902 while (0 != instance_of_idx && !insn_flags_[instance_of_idx].IsOpcode()) { 1903 instance_of_idx--; 1904 } 1905 CHECK(insn_flags_[instance_of_idx].IsOpcode()); 1906 } else { 1907 break; 1908 } 1909 1910 const Instruction* instance_of_inst = Instruction::At(code_item_->insns_ + instance_of_idx); 1911 1912 /* Check for peep-hole pattern of: 1913 * ...; 1914 * instance-of vX, vY, T; 1915 * ifXXX vX, label ; 1916 * ...; 1917 * label: 1918 * ...; 1919 * and sharpen the type of vY to be type T. 1920 * Note, this pattern can't be if: 1921 * - if there are other branches to this branch, 1922 * - when vX == vY. 1923 */ 1924 if (!CurrentInsnFlags()->IsBranchTarget() && 1925 (Instruction::INSTANCE_OF == instance_of_inst->Opcode()) && 1926 (inst->VRegA_21t() == instance_of_inst->VRegA_22c()) && 1927 (instance_of_inst->VRegA_22c() != instance_of_inst->VRegB_22c())) { 1928 // Check that the we are not attempting conversion to interface types, 1929 // which is not done because of the multiple inheritance implications. 1930 // Also don't change the type if it would result in an upcast. 1931 const RegType& orig_type = work_line_->GetRegisterType(instance_of_inst->VRegB_22c()); 1932 const RegType& cast_type = ResolveClassAndCheckAccess(instance_of_inst->VRegC_22c()); 1933 1934 if (!cast_type.IsUnresolvedTypes() && !orig_type.IsUnresolvedTypes() && 1935 !cast_type.GetClass()->IsInterface() && !cast_type.IsAssignableFrom(orig_type)) { 1936 RegisterLine* update_line = RegisterLine::Create(code_item_->registers_size_, this); 1937 if (inst->Opcode() == Instruction::IF_EQZ) { 1938 fallthrough_line.reset(update_line); 1939 } else { 1940 branch_line.reset(update_line); 1941 } 1942 update_line->CopyFromLine(work_line_.get()); 1943 update_line->SetRegisterType(instance_of_inst->VRegB_22c(), cast_type); 1944 if (!insn_flags_[instance_of_idx].IsBranchTarget() && 0 != instance_of_idx) { 1945 // See if instance-of was preceded by a move-object operation, common due to the small 1946 // register encoding space of instance-of, and propagate type information to the source 1947 // of the move-object. 1948 uint32_t move_idx = instance_of_idx - 1; 1949 while (0 != move_idx && !insn_flags_[move_idx].IsOpcode()) { 1950 move_idx--; 1951 } 1952 CHECK(insn_flags_[move_idx].IsOpcode()); 1953 const Instruction* move_inst = Instruction::At(code_item_->insns_ + move_idx); 1954 switch (move_inst->Opcode()) { 1955 case Instruction::MOVE_OBJECT: 1956 if (move_inst->VRegA_12x() == instance_of_inst->VRegB_22c()) { 1957 update_line->SetRegisterType(move_inst->VRegB_12x(), cast_type); 1958 } 1959 break; 1960 case Instruction::MOVE_OBJECT_FROM16: 1961 if (move_inst->VRegA_22x() == instance_of_inst->VRegB_22c()) { 1962 update_line->SetRegisterType(move_inst->VRegB_22x(), cast_type); 1963 } 1964 break; 1965 case Instruction::MOVE_OBJECT_16: 1966 if (move_inst->VRegA_32x() == instance_of_inst->VRegB_22c()) { 1967 update_line->SetRegisterType(move_inst->VRegB_32x(), cast_type); 1968 } 1969 break; 1970 default: 1971 break; 1972 } 1973 } 1974 } 1975 } 1976 1977 break; 1978 } 1979 case Instruction::IF_LTZ: 1980 case Instruction::IF_GEZ: 1981 case Instruction::IF_GTZ: 1982 case Instruction::IF_LEZ: { 1983 const RegType& reg_type = work_line_->GetRegisterType(inst->VRegA_21t()); 1984 if (!reg_type.IsIntegralTypes()) { 1985 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "type " << reg_type 1986 << " unexpected as arg to if-ltz/if-gez/if-gtz/if-lez"; 1987 } 1988 break; 1989 } 1990 case Instruction::AGET_BOOLEAN: 1991 VerifyAGet(inst, reg_types_.Boolean(), true); 1992 break; 1993 case Instruction::AGET_BYTE: 1994 VerifyAGet(inst, reg_types_.Byte(), true); 1995 break; 1996 case Instruction::AGET_CHAR: 1997 VerifyAGet(inst, reg_types_.Char(), true); 1998 break; 1999 case Instruction::AGET_SHORT: 2000 VerifyAGet(inst, reg_types_.Short(), true); 2001 break; 2002 case Instruction::AGET: 2003 VerifyAGet(inst, reg_types_.Integer(), true); 2004 break; 2005 case Instruction::AGET_WIDE: 2006 VerifyAGet(inst, reg_types_.LongLo(), true); 2007 break; 2008 case Instruction::AGET_OBJECT: 2009 VerifyAGet(inst, reg_types_.JavaLangObject(false), false); 2010 break; 2011 2012 case Instruction::APUT_BOOLEAN: 2013 VerifyAPut(inst, reg_types_.Boolean(), true); 2014 break; 2015 case Instruction::APUT_BYTE: 2016 VerifyAPut(inst, reg_types_.Byte(), true); 2017 break; 2018 case Instruction::APUT_CHAR: 2019 VerifyAPut(inst, reg_types_.Char(), true); 2020 break; 2021 case Instruction::APUT_SHORT: 2022 VerifyAPut(inst, reg_types_.Short(), true); 2023 break; 2024 case Instruction::APUT: 2025 VerifyAPut(inst, reg_types_.Integer(), true); 2026 break; 2027 case Instruction::APUT_WIDE: 2028 VerifyAPut(inst, reg_types_.LongLo(), true); 2029 break; 2030 case Instruction::APUT_OBJECT: 2031 VerifyAPut(inst, reg_types_.JavaLangObject(false), false); 2032 break; 2033 2034 case Instruction::IGET_BOOLEAN: 2035 VerifyISGet(inst, reg_types_.Boolean(), true, false); 2036 break; 2037 case Instruction::IGET_BYTE: 2038 VerifyISGet(inst, reg_types_.Byte(), true, false); 2039 break; 2040 case Instruction::IGET_CHAR: 2041 VerifyISGet(inst, reg_types_.Char(), true, false); 2042 break; 2043 case Instruction::IGET_SHORT: 2044 VerifyISGet(inst, reg_types_.Short(), true, false); 2045 break; 2046 case Instruction::IGET: 2047 VerifyISGet(inst, reg_types_.Integer(), true, false); 2048 break; 2049 case Instruction::IGET_WIDE: 2050 VerifyISGet(inst, reg_types_.LongLo(), true, false); 2051 break; 2052 case Instruction::IGET_OBJECT: 2053 VerifyISGet(inst, reg_types_.JavaLangObject(false), false, false); 2054 break; 2055 2056 case Instruction::IPUT_BOOLEAN: 2057 VerifyISPut(inst, reg_types_.Boolean(), true, false); 2058 break; 2059 case Instruction::IPUT_BYTE: 2060 VerifyISPut(inst, reg_types_.Byte(), true, false); 2061 break; 2062 case Instruction::IPUT_CHAR: 2063 VerifyISPut(inst, reg_types_.Char(), true, false); 2064 break; 2065 case Instruction::IPUT_SHORT: 2066 VerifyISPut(inst, reg_types_.Short(), true, false); 2067 break; 2068 case Instruction::IPUT: 2069 VerifyISPut(inst, reg_types_.Integer(), true, false); 2070 break; 2071 case Instruction::IPUT_WIDE: 2072 VerifyISPut(inst, reg_types_.LongLo(), true, false); 2073 break; 2074 case Instruction::IPUT_OBJECT: 2075 VerifyISPut(inst, reg_types_.JavaLangObject(false), false, false); 2076 break; 2077 2078 case Instruction::SGET_BOOLEAN: 2079 VerifyISGet(inst, reg_types_.Boolean(), true, true); 2080 break; 2081 case Instruction::SGET_BYTE: 2082 VerifyISGet(inst, reg_types_.Byte(), true, true); 2083 break; 2084 case Instruction::SGET_CHAR: 2085 VerifyISGet(inst, reg_types_.Char(), true, true); 2086 break; 2087 case Instruction::SGET_SHORT: 2088 VerifyISGet(inst, reg_types_.Short(), true, true); 2089 break; 2090 case Instruction::SGET: 2091 VerifyISGet(inst, reg_types_.Integer(), true, true); 2092 break; 2093 case Instruction::SGET_WIDE: 2094 VerifyISGet(inst, reg_types_.LongLo(), true, true); 2095 break; 2096 case Instruction::SGET_OBJECT: 2097 VerifyISGet(inst, reg_types_.JavaLangObject(false), false, true); 2098 break; 2099 2100 case Instruction::SPUT_BOOLEAN: 2101 VerifyISPut(inst, reg_types_.Boolean(), true, true); 2102 break; 2103 case Instruction::SPUT_BYTE: 2104 VerifyISPut(inst, reg_types_.Byte(), true, true); 2105 break; 2106 case Instruction::SPUT_CHAR: 2107 VerifyISPut(inst, reg_types_.Char(), true, true); 2108 break; 2109 case Instruction::SPUT_SHORT: 2110 VerifyISPut(inst, reg_types_.Short(), true, true); 2111 break; 2112 case Instruction::SPUT: 2113 VerifyISPut(inst, reg_types_.Integer(), true, true); 2114 break; 2115 case Instruction::SPUT_WIDE: 2116 VerifyISPut(inst, reg_types_.LongLo(), true, true); 2117 break; 2118 case Instruction::SPUT_OBJECT: 2119 VerifyISPut(inst, reg_types_.JavaLangObject(false), false, true); 2120 break; 2121 2122 case Instruction::INVOKE_VIRTUAL: 2123 case Instruction::INVOKE_VIRTUAL_RANGE: 2124 case Instruction::INVOKE_SUPER: 2125 case Instruction::INVOKE_SUPER_RANGE: { 2126 bool is_range = (inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE || 2127 inst->Opcode() == Instruction::INVOKE_SUPER_RANGE); 2128 bool is_super = (inst->Opcode() == Instruction::INVOKE_SUPER || 2129 inst->Opcode() == Instruction::INVOKE_SUPER_RANGE); 2130 mirror::ArtMethod* called_method = VerifyInvocationArgs(inst, METHOD_VIRTUAL, 2131 is_range, is_super); 2132 const RegType* return_type = nullptr; 2133 if (called_method != nullptr) { 2134 MethodHelper mh(called_method); 2135 mirror::Class* return_type_class = mh.GetReturnType(can_load_classes_); 2136 if (return_type_class != nullptr) { 2137 return_type = ®_types_.FromClass(mh.GetReturnTypeDescriptor(), return_type_class, 2138 return_type_class->CannotBeAssignedFromOtherTypes()); 2139 } else { 2140 Thread* self = Thread::Current(); 2141 DCHECK(!can_load_classes_ || self->IsExceptionPending()); 2142 self->ClearException(); 2143 } 2144 } 2145 if (return_type == nullptr) { 2146 uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); 2147 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx); 2148 uint32_t return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_; 2149 const char* descriptor = dex_file_->StringByTypeIdx(return_type_idx); 2150 return_type = ®_types_.FromDescriptor(class_loader_->get(), descriptor, false); 2151 } 2152 if (!return_type->IsLowHalf()) { 2153 work_line_->SetResultRegisterType(*return_type); 2154 } else { 2155 work_line_->SetResultRegisterTypeWide(*return_type, return_type->HighHalf(®_types_)); 2156 } 2157 just_set_result = true; 2158 break; 2159 } 2160 case Instruction::INVOKE_DIRECT: 2161 case Instruction::INVOKE_DIRECT_RANGE: { 2162 bool is_range = (inst->Opcode() == Instruction::INVOKE_DIRECT_RANGE); 2163 mirror::ArtMethod* called_method = VerifyInvocationArgs(inst, METHOD_DIRECT, 2164 is_range, false); 2165 const char* return_type_descriptor; 2166 bool is_constructor; 2167 if (called_method == NULL) { 2168 uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); 2169 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx); 2170 is_constructor = strcmp("<init>", dex_file_->StringDataByIdx(method_id.name_idx_)) == 0; 2171 uint32_t return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_; 2172 return_type_descriptor = dex_file_->StringByTypeIdx(return_type_idx); 2173 } else { 2174 is_constructor = called_method->IsConstructor(); 2175 return_type_descriptor = MethodHelper(called_method).GetReturnTypeDescriptor(); 2176 } 2177 if (is_constructor) { 2178 /* 2179 * Some additional checks when calling a constructor. We know from the invocation arg check 2180 * that the "this" argument is an instance of called_method->klass. Now we further restrict 2181 * that to require that called_method->klass is the same as this->klass or this->super, 2182 * allowing the latter only if the "this" argument is the same as the "this" argument to 2183 * this method (which implies that we're in a constructor ourselves). 2184 */ 2185 const RegType& this_type = work_line_->GetInvocationThis(inst, is_range); 2186 if (this_type.IsConflict()) // failure. 2187 break; 2188 2189 /* no null refs allowed (?) */ 2190 if (this_type.IsZero()) { 2191 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unable to initialize null ref"; 2192 break; 2193 } 2194 2195 /* must be in same class or in superclass */ 2196 // const RegType& this_super_klass = this_type.GetSuperClass(®_types_); 2197 // TODO: re-enable constructor type verification 2198 // if (this_super_klass.IsConflict()) { 2199 // Unknown super class, fail so we re-check at runtime. 2200 // Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "super class unknown for '" << this_type << "'"; 2201 // break; 2202 // } 2203 2204 /* arg must be an uninitialized reference */ 2205 if (!this_type.IsUninitializedTypes()) { 2206 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Expected initialization on uninitialized reference " 2207 << this_type; 2208 break; 2209 } 2210 2211 /* 2212 * Replace the uninitialized reference with an initialized one. We need to do this for all 2213 * registers that have the same object instance in them, not just the "this" register. 2214 */ 2215 work_line_->MarkRefsAsInitialized(this_type); 2216 } 2217 const RegType& return_type = reg_types_.FromDescriptor(class_loader_->get(), 2218 return_type_descriptor, false); 2219 if (!return_type.IsLowHalf()) { 2220 work_line_->SetResultRegisterType(return_type); 2221 } else { 2222 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(®_types_)); 2223 } 2224 just_set_result = true; 2225 break; 2226 } 2227 case Instruction::INVOKE_STATIC: 2228 case Instruction::INVOKE_STATIC_RANGE: { 2229 bool is_range = (inst->Opcode() == Instruction::INVOKE_STATIC_RANGE); 2230 mirror::ArtMethod* called_method = VerifyInvocationArgs(inst, 2231 METHOD_STATIC, 2232 is_range, 2233 false); 2234 const char* descriptor; 2235 if (called_method == NULL) { 2236 uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); 2237 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx); 2238 uint32_t return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_; 2239 descriptor = dex_file_->StringByTypeIdx(return_type_idx); 2240 } else { 2241 descriptor = MethodHelper(called_method).GetReturnTypeDescriptor(); 2242 } 2243 const RegType& return_type = reg_types_.FromDescriptor(class_loader_->get(), descriptor, 2244 false); 2245 if (!return_type.IsLowHalf()) { 2246 work_line_->SetResultRegisterType(return_type); 2247 } else { 2248 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(®_types_)); 2249 } 2250 just_set_result = true; 2251 } 2252 break; 2253 case Instruction::INVOKE_INTERFACE: 2254 case Instruction::INVOKE_INTERFACE_RANGE: { 2255 bool is_range = (inst->Opcode() == Instruction::INVOKE_INTERFACE_RANGE); 2256 mirror::ArtMethod* abs_method = VerifyInvocationArgs(inst, 2257 METHOD_INTERFACE, 2258 is_range, 2259 false); 2260 if (abs_method != NULL) { 2261 mirror::Class* called_interface = abs_method->GetDeclaringClass(); 2262 if (!called_interface->IsInterface() && !called_interface->IsObjectClass()) { 2263 Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected interface class in invoke-interface '" 2264 << PrettyMethod(abs_method) << "'"; 2265 break; 2266 } 2267 } 2268 /* Get the type of the "this" arg, which should either be a sub-interface of called 2269 * interface or Object (see comments in RegType::JoinClass). 2270 */ 2271 const RegType& this_type = work_line_->GetInvocationThis(inst, is_range); 2272 if (this_type.IsZero()) { 2273 /* null pointer always passes (and always fails at runtime) */ 2274 } else { 2275 if (this_type.IsUninitializedTypes()) { 2276 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "interface call on uninitialized object " 2277 << this_type; 2278 break; 2279 } 2280 // In the past we have tried to assert that "called_interface" is assignable 2281 // from "this_type.GetClass()", however, as we do an imprecise Join 2282 // (RegType::JoinClass) we don't have full information on what interfaces are 2283 // implemented by "this_type". For example, two classes may implement the same 2284 // interfaces and have a common parent that doesn't implement the interface. The 2285 // join will set "this_type" to the parent class and a test that this implements 2286 // the interface will incorrectly fail. 2287 } 2288 /* 2289 * We don't have an object instance, so we can't find the concrete method. However, all of 2290 * the type information is in the abstract method, so we're good. 2291 */ 2292 const char* descriptor; 2293 if (abs_method == NULL) { 2294 uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); 2295 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx); 2296 uint32_t return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_; 2297 descriptor = dex_file_->StringByTypeIdx(return_type_idx); 2298 } else { 2299 descriptor = MethodHelper(abs_method).GetReturnTypeDescriptor(); 2300 } 2301 const RegType& return_type = reg_types_.FromDescriptor(class_loader_->get(), descriptor, 2302 false); 2303 if (!return_type.IsLowHalf()) { 2304 work_line_->SetResultRegisterType(return_type); 2305 } else { 2306 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(®_types_)); 2307 } 2308 just_set_result = true; 2309 break; 2310 } 2311 case Instruction::NEG_INT: 2312 case Instruction::NOT_INT: 2313 work_line_->CheckUnaryOp(inst, reg_types_.Integer(), reg_types_.Integer()); 2314 break; 2315 case Instruction::NEG_LONG: 2316 case Instruction::NOT_LONG: 2317 work_line_->CheckUnaryOpWide(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2318 reg_types_.LongLo(), reg_types_.LongHi()); 2319 break; 2320 case Instruction::NEG_FLOAT: 2321 work_line_->CheckUnaryOp(inst, reg_types_.Float(), reg_types_.Float()); 2322 break; 2323 case Instruction::NEG_DOUBLE: 2324 work_line_->CheckUnaryOpWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2325 reg_types_.DoubleLo(), reg_types_.DoubleHi()); 2326 break; 2327 case Instruction::INT_TO_LONG: 2328 work_line_->CheckUnaryOpToWide(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2329 reg_types_.Integer()); 2330 break; 2331 case Instruction::INT_TO_FLOAT: 2332 work_line_->CheckUnaryOp(inst, reg_types_.Float(), reg_types_.Integer()); 2333 break; 2334 case Instruction::INT_TO_DOUBLE: 2335 work_line_->CheckUnaryOpToWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2336 reg_types_.Integer()); 2337 break; 2338 case Instruction::LONG_TO_INT: 2339 work_line_->CheckUnaryOpFromWide(inst, reg_types_.Integer(), 2340 reg_types_.LongLo(), reg_types_.LongHi()); 2341 break; 2342 case Instruction::LONG_TO_FLOAT: 2343 work_line_->CheckUnaryOpFromWide(inst, reg_types_.Float(), 2344 reg_types_.LongLo(), reg_types_.LongHi()); 2345 break; 2346 case Instruction::LONG_TO_DOUBLE: 2347 work_line_->CheckUnaryOpWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2348 reg_types_.LongLo(), reg_types_.LongHi()); 2349 break; 2350 case Instruction::FLOAT_TO_INT: 2351 work_line_->CheckUnaryOp(inst, reg_types_.Integer(), reg_types_.Float()); 2352 break; 2353 case Instruction::FLOAT_TO_LONG: 2354 work_line_->CheckUnaryOpToWide(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2355 reg_types_.Float()); 2356 break; 2357 case Instruction::FLOAT_TO_DOUBLE: 2358 work_line_->CheckUnaryOpToWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2359 reg_types_.Float()); 2360 break; 2361 case Instruction::DOUBLE_TO_INT: 2362 work_line_->CheckUnaryOpFromWide(inst, reg_types_.Integer(), 2363 reg_types_.DoubleLo(), reg_types_.DoubleHi()); 2364 break; 2365 case Instruction::DOUBLE_TO_LONG: 2366 work_line_->CheckUnaryOpWide(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2367 reg_types_.DoubleLo(), reg_types_.DoubleHi()); 2368 break; 2369 case Instruction::DOUBLE_TO_FLOAT: 2370 work_line_->CheckUnaryOpFromWide(inst, reg_types_.Float(), 2371 reg_types_.DoubleLo(), reg_types_.DoubleHi()); 2372 break; 2373 case Instruction::INT_TO_BYTE: 2374 work_line_->CheckUnaryOp(inst, reg_types_.Byte(), reg_types_.Integer()); 2375 break; 2376 case Instruction::INT_TO_CHAR: 2377 work_line_->CheckUnaryOp(inst, reg_types_.Char(), reg_types_.Integer()); 2378 break; 2379 case Instruction::INT_TO_SHORT: 2380 work_line_->CheckUnaryOp(inst, reg_types_.Short(), reg_types_.Integer()); 2381 break; 2382 2383 case Instruction::ADD_INT: 2384 case Instruction::SUB_INT: 2385 case Instruction::MUL_INT: 2386 case Instruction::REM_INT: 2387 case Instruction::DIV_INT: 2388 case Instruction::SHL_INT: 2389 case Instruction::SHR_INT: 2390 case Instruction::USHR_INT: 2391 work_line_->CheckBinaryOp(inst, reg_types_.Integer(), reg_types_.Integer(), 2392 reg_types_.Integer(), false); 2393 break; 2394 case Instruction::AND_INT: 2395 case Instruction::OR_INT: 2396 case Instruction::XOR_INT: 2397 work_line_->CheckBinaryOp(inst, reg_types_.Integer(), reg_types_.Integer(), 2398 reg_types_.Integer(), true); 2399 break; 2400 case Instruction::ADD_LONG: 2401 case Instruction::SUB_LONG: 2402 case Instruction::MUL_LONG: 2403 case Instruction::DIV_LONG: 2404 case Instruction::REM_LONG: 2405 case Instruction::AND_LONG: 2406 case Instruction::OR_LONG: 2407 case Instruction::XOR_LONG: 2408 work_line_->CheckBinaryOpWide(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2409 reg_types_.LongLo(), reg_types_.LongHi(), 2410 reg_types_.LongLo(), reg_types_.LongHi()); 2411 break; 2412 case Instruction::SHL_LONG: 2413 case Instruction::SHR_LONG: 2414 case Instruction::USHR_LONG: 2415 /* shift distance is Int, making these different from other binary operations */ 2416 work_line_->CheckBinaryOpWideShift(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2417 reg_types_.Integer()); 2418 break; 2419 case Instruction::ADD_FLOAT: 2420 case Instruction::SUB_FLOAT: 2421 case Instruction::MUL_FLOAT: 2422 case Instruction::DIV_FLOAT: 2423 case Instruction::REM_FLOAT: 2424 work_line_->CheckBinaryOp(inst, 2425 reg_types_.Float(), 2426 reg_types_.Float(), 2427 reg_types_.Float(), 2428 false); 2429 break; 2430 case Instruction::ADD_DOUBLE: 2431 case Instruction::SUB_DOUBLE: 2432 case Instruction::MUL_DOUBLE: 2433 case Instruction::DIV_DOUBLE: 2434 case Instruction::REM_DOUBLE: 2435 work_line_->CheckBinaryOpWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2436 reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2437 reg_types_.DoubleLo(), reg_types_.DoubleHi()); 2438 break; 2439 case Instruction::ADD_INT_2ADDR: 2440 case Instruction::SUB_INT_2ADDR: 2441 case Instruction::MUL_INT_2ADDR: 2442 case Instruction::REM_INT_2ADDR: 2443 case Instruction::SHL_INT_2ADDR: 2444 case Instruction::SHR_INT_2ADDR: 2445 case Instruction::USHR_INT_2ADDR: 2446 work_line_->CheckBinaryOp2addr(inst, 2447 reg_types_.Integer(), 2448 reg_types_.Integer(), 2449 reg_types_.Integer(), 2450 false); 2451 break; 2452 case Instruction::AND_INT_2ADDR: 2453 case Instruction::OR_INT_2ADDR: 2454 case Instruction::XOR_INT_2ADDR: 2455 work_line_->CheckBinaryOp2addr(inst, 2456 reg_types_.Integer(), 2457 reg_types_.Integer(), 2458 reg_types_.Integer(), 2459 true); 2460 break; 2461 case Instruction::DIV_INT_2ADDR: 2462 work_line_->CheckBinaryOp2addr(inst, 2463 reg_types_.Integer(), 2464 reg_types_.Integer(), 2465 reg_types_.Integer(), 2466 false); 2467 break; 2468 case Instruction::ADD_LONG_2ADDR: 2469 case Instruction::SUB_LONG_2ADDR: 2470 case Instruction::MUL_LONG_2ADDR: 2471 case Instruction::DIV_LONG_2ADDR: 2472 case Instruction::REM_LONG_2ADDR: 2473 case Instruction::AND_LONG_2ADDR: 2474 case Instruction::OR_LONG_2ADDR: 2475 case Instruction::XOR_LONG_2ADDR: 2476 work_line_->CheckBinaryOp2addrWide(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2477 reg_types_.LongLo(), reg_types_.LongHi(), 2478 reg_types_.LongLo(), reg_types_.LongHi()); 2479 break; 2480 case Instruction::SHL_LONG_2ADDR: 2481 case Instruction::SHR_LONG_2ADDR: 2482 case Instruction::USHR_LONG_2ADDR: 2483 work_line_->CheckBinaryOp2addrWideShift(inst, reg_types_.LongLo(), reg_types_.LongHi(), 2484 reg_types_.Integer()); 2485 break; 2486 case Instruction::ADD_FLOAT_2ADDR: 2487 case Instruction::SUB_FLOAT_2ADDR: 2488 case Instruction::MUL_FLOAT_2ADDR: 2489 case Instruction::DIV_FLOAT_2ADDR: 2490 case Instruction::REM_FLOAT_2ADDR: 2491 work_line_->CheckBinaryOp2addr(inst, 2492 reg_types_.Float(), 2493 reg_types_.Float(), 2494 reg_types_.Float(), 2495 false); 2496 break; 2497 case Instruction::ADD_DOUBLE_2ADDR: 2498 case Instruction::SUB_DOUBLE_2ADDR: 2499 case Instruction::MUL_DOUBLE_2ADDR: 2500 case Instruction::DIV_DOUBLE_2ADDR: 2501 case Instruction::REM_DOUBLE_2ADDR: 2502 work_line_->CheckBinaryOp2addrWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2503 reg_types_.DoubleLo(), reg_types_.DoubleHi(), 2504 reg_types_.DoubleLo(), reg_types_.DoubleHi()); 2505 break; 2506 case Instruction::ADD_INT_LIT16: 2507 case Instruction::RSUB_INT: 2508 case Instruction::MUL_INT_LIT16: 2509 case Instruction::DIV_INT_LIT16: 2510 case Instruction::REM_INT_LIT16: 2511 work_line_->CheckLiteralOp(inst, reg_types_.Integer(), reg_types_.Integer(), false, true); 2512 break; 2513 case Instruction::AND_INT_LIT16: 2514 case Instruction::OR_INT_LIT16: 2515 case Instruction::XOR_INT_LIT16: 2516 work_line_->CheckLiteralOp(inst, reg_types_.Integer(), reg_types_.Integer(), true, true); 2517 break; 2518 case Instruction::ADD_INT_LIT8: 2519 case Instruction::RSUB_INT_LIT8: 2520 case Instruction::MUL_INT_LIT8: 2521 case Instruction::DIV_INT_LIT8: 2522 case Instruction::REM_INT_LIT8: 2523 case Instruction::SHL_INT_LIT8: 2524 case Instruction::SHR_INT_LIT8: 2525 case Instruction::USHR_INT_LIT8: 2526 work_line_->CheckLiteralOp(inst, reg_types_.Integer(), reg_types_.Integer(), false, false); 2527 break; 2528 case Instruction::AND_INT_LIT8: 2529 case Instruction::OR_INT_LIT8: 2530 case Instruction::XOR_INT_LIT8: 2531 work_line_->CheckLiteralOp(inst, reg_types_.Integer(), reg_types_.Integer(), true, false); 2532 break; 2533 2534 // Special instructions. 2535 case Instruction::RETURN_VOID_BARRIER: 2536 if (!IsConstructor() || IsStatic()) { 2537 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-void-barrier not expected"; 2538 } 2539 break; 2540 // Note: the following instructions encode offsets derived from class linking. 2541 // As such they use Class*/Field*/AbstractMethod* as these offsets only have 2542 // meaning if the class linking and resolution were successful. 2543 case Instruction::IGET_QUICK: 2544 VerifyIGetQuick(inst, reg_types_.Integer(), true); 2545 break; 2546 case Instruction::IGET_WIDE_QUICK: 2547 VerifyIGetQuick(inst, reg_types_.LongLo(), true); 2548 break; 2549 case Instruction::IGET_OBJECT_QUICK: 2550 VerifyIGetQuick(inst, reg_types_.JavaLangObject(false), false); 2551 break; 2552 case Instruction::IPUT_QUICK: 2553 VerifyIPutQuick(inst, reg_types_.Integer(), true); 2554 break; 2555 case Instruction::IPUT_WIDE_QUICK: 2556 VerifyIPutQuick(inst, reg_types_.LongLo(), true); 2557 break; 2558 case Instruction::IPUT_OBJECT_QUICK: 2559 VerifyIPutQuick(inst, reg_types_.JavaLangObject(false), false); 2560 break; 2561 case Instruction::INVOKE_VIRTUAL_QUICK: 2562 case Instruction::INVOKE_VIRTUAL_RANGE_QUICK: { 2563 bool is_range = (inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE_QUICK); 2564 mirror::ArtMethod* called_method = VerifyInvokeVirtualQuickArgs(inst, is_range); 2565 if (called_method != NULL) { 2566 const char* descriptor = MethodHelper(called_method).GetReturnTypeDescriptor(); 2567 const RegType& return_type = reg_types_.FromDescriptor(class_loader_->get(), descriptor, 2568 false); 2569 if (!return_type.IsLowHalf()) { 2570 work_line_->SetResultRegisterType(return_type); 2571 } else { 2572 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(®_types_)); 2573 } 2574 just_set_result = true; 2575 } 2576 break; 2577 } 2578 2579 /* These should never appear during verification. */ 2580 case Instruction::UNUSED_3E: 2581 case Instruction::UNUSED_3F: 2582 case Instruction::UNUSED_40: 2583 case Instruction::UNUSED_41: 2584 case Instruction::UNUSED_42: 2585 case Instruction::UNUSED_43: 2586 case Instruction::UNUSED_79: 2587 case Instruction::UNUSED_7A: 2588 case Instruction::UNUSED_EB: 2589 case Instruction::UNUSED_EC: 2590 case Instruction::UNUSED_ED: 2591 case Instruction::UNUSED_EE: 2592 case Instruction::UNUSED_EF: 2593 case Instruction::UNUSED_F0: 2594 case Instruction::UNUSED_F1: 2595 case Instruction::UNUSED_F2: 2596 case Instruction::UNUSED_F3: 2597 case Instruction::UNUSED_F4: 2598 case Instruction::UNUSED_F5: 2599 case Instruction::UNUSED_F6: 2600 case Instruction::UNUSED_F7: 2601 case Instruction::UNUSED_F8: 2602 case Instruction::UNUSED_F9: 2603 case Instruction::UNUSED_FA: 2604 case Instruction::UNUSED_FB: 2605 case Instruction::UNUSED_FC: 2606 case Instruction::UNUSED_FD: 2607 case Instruction::UNUSED_FE: 2608 case Instruction::UNUSED_FF: 2609 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Unexpected opcode " << inst->DumpString(dex_file_); 2610 break; 2611 2612 /* 2613 * DO NOT add a "default" clause here. Without it the compiler will 2614 * complain if an instruction is missing (which is desirable). 2615 */ 2616 } // end - switch (dec_insn.opcode) 2617 2618 if (have_pending_hard_failure_) { 2619 if (Runtime::Current()->IsCompiler()) { 2620 /* When compiling, check that the last failure is a hard failure */ 2621 CHECK_EQ(failures_[failures_.size() - 1], VERIFY_ERROR_BAD_CLASS_HARD); 2622 } 2623 /* immediate failure, reject class */ 2624 info_messages_ << "Rejecting opcode " << inst->DumpString(dex_file_); 2625 return false; 2626 } else if (have_pending_runtime_throw_failure_) { 2627 /* checking interpreter will throw, mark following code as unreachable */ 2628 opcode_flags = Instruction::kThrow; 2629 } 2630 /* 2631 * If we didn't just set the result register, clear it out. This ensures that you can only use 2632 * "move-result" immediately after the result is set. (We could check this statically, but it's 2633 * not expensive and it makes our debugging output cleaner.) 2634 */ 2635 if (!just_set_result) { 2636 work_line_->SetResultTypeToUnknown(); 2637 } 2638 2639 2640 2641 /* 2642 * Handle "branch". Tag the branch target. 2643 * 2644 * NOTE: instructions like Instruction::EQZ provide information about the 2645 * state of the register when the branch is taken or not taken. For example, 2646 * somebody could get a reference field, check it for zero, and if the 2647 * branch is taken immediately store that register in a boolean field 2648 * since the value is known to be zero. We do not currently account for 2649 * that, and will reject the code. 2650 * 2651 * TODO: avoid re-fetching the branch target 2652 */ 2653 if ((opcode_flags & Instruction::kBranch) != 0) { 2654 bool isConditional, selfOkay; 2655 if (!GetBranchOffset(work_insn_idx_, &branch_target, &isConditional, &selfOkay)) { 2656 /* should never happen after static verification */ 2657 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad branch"; 2658 return false; 2659 } 2660 DCHECK_EQ(isConditional, (opcode_flags & Instruction::kContinue) != 0); 2661 if (!CheckNotMoveException(code_item_->insns_, work_insn_idx_ + branch_target)) { 2662 return false; 2663 } 2664 /* update branch target, set "changed" if appropriate */ 2665 if (NULL != branch_line.get()) { 2666 if (!UpdateRegisters(work_insn_idx_ + branch_target, branch_line.get())) { 2667 return false; 2668 } 2669 } else { 2670 if (!UpdateRegisters(work_insn_idx_ + branch_target, work_line_.get())) { 2671 return false; 2672 } 2673 } 2674 } 2675 2676 /* 2677 * Handle "switch". Tag all possible branch targets. 2678 * 2679 * We've already verified that the table is structurally sound, so we 2680 * just need to walk through and tag the targets. 2681 */ 2682 if ((opcode_flags & Instruction::kSwitch) != 0) { 2683 int offset_to_switch = insns[1] | (((int32_t) insns[2]) << 16); 2684 const uint16_t* switch_insns = insns + offset_to_switch; 2685 int switch_count = switch_insns[1]; 2686 int offset_to_targets, targ; 2687 2688 if ((*insns & 0xff) == Instruction::PACKED_SWITCH) { 2689 /* 0 = sig, 1 = count, 2/3 = first key */ 2690 offset_to_targets = 4; 2691 } else { 2692 /* 0 = sig, 1 = count, 2..count * 2 = keys */ 2693 DCHECK((*insns & 0xff) == Instruction::SPARSE_SWITCH); 2694 offset_to_targets = 2 + 2 * switch_count; 2695 } 2696 2697 /* verify each switch target */ 2698 for (targ = 0; targ < switch_count; targ++) { 2699 int offset; 2700 uint32_t abs_offset; 2701 2702 /* offsets are 32-bit, and only partly endian-swapped */ 2703 offset = switch_insns[offset_to_targets + targ * 2] | 2704 (((int32_t) switch_insns[offset_to_targets + targ * 2 + 1]) << 16); 2705 abs_offset = work_insn_idx_ + offset; 2706 DCHECK_LT(abs_offset, code_item_->insns_size_in_code_units_); 2707 if (!CheckNotMoveException(code_item_->insns_, abs_offset)) { 2708 return false; 2709 } 2710 if (!UpdateRegisters(abs_offset, work_line_.get())) 2711 return false; 2712 } 2713 } 2714 2715 /* 2716 * Handle instructions that can throw and that are sitting in a "try" block. (If they're not in a 2717 * "try" block when they throw, control transfers out of the method.) 2718 */ 2719 if ((opcode_flags & Instruction::kThrow) != 0 && insn_flags_[work_insn_idx_].IsInTry()) { 2720 bool within_catch_all = false; 2721 CatchHandlerIterator iterator(*code_item_, work_insn_idx_); 2722 2723 for (; iterator.HasNext(); iterator.Next()) { 2724 if (iterator.GetHandlerTypeIndex() == DexFile::kDexNoIndex16) { 2725 within_catch_all = true; 2726 } 2727 /* 2728 * Merge registers into the "catch" block. We want to use the "savedRegs" rather than 2729 * "work_regs", because at runtime the exception will be thrown before the instruction 2730 * modifies any registers. 2731 */ 2732 if (!UpdateRegisters(iterator.GetHandlerAddress(), saved_line_.get())) { 2733 return false; 2734 } 2735 } 2736 2737 /* 2738 * If the monitor stack depth is nonzero, there must be a "catch all" handler for this 2739 * instruction. This does apply to monitor-exit because of async exception handling. 2740 */ 2741 if (work_line_->MonitorStackDepth() > 0 && !within_catch_all) { 2742 /* 2743 * The state in work_line reflects the post-execution state. If the current instruction is a 2744 * monitor-enter and the monitor stack was empty, we don't need a catch-all (if it throws, 2745 * it will do so before grabbing the lock). 2746 */ 2747 if (inst->Opcode() != Instruction::MONITOR_ENTER || work_line_->MonitorStackDepth() != 1) { 2748 Fail(VERIFY_ERROR_BAD_CLASS_HARD) 2749 << "expected to be within a catch-all for an instruction where a monitor is held"; 2750 return false; 2751 } 2752 } 2753 } 2754 2755 /* Handle "continue". Tag the next consecutive instruction. 2756 * Note: Keep the code handling "continue" case below the "branch" and "switch" cases, 2757 * because it changes work_line_ when performing peephole optimization 2758 * and this change should not be used in those cases. 2759 */ 2760 if ((opcode_flags & Instruction::kContinue) != 0) { 2761 uint32_t next_insn_idx = work_insn_idx_ + CurrentInsnFlags()->GetLengthInCodeUnits(); 2762 if (next_insn_idx >= code_item_->insns_size_in_code_units_) { 2763 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Execution can walk off end of code area"; 2764 return false; 2765 } 2766 // The only way to get to a move-exception instruction is to get thrown there. Make sure the 2767 // next instruction isn't one. 2768 if (!CheckNotMoveException(code_item_->insns_, next_insn_idx)) { 2769 return false; 2770 } 2771 if (NULL != fallthrough_line.get()) { 2772 // Make workline consistent with fallthrough computed from peephole optimization. 2773 work_line_->CopyFromLine(fallthrough_line.get()); 2774 } 2775 if (insn_flags_[next_insn_idx].IsReturn()) { 2776 // For returns we only care about the operand to the return, all other registers are dead. 2777 const Instruction* ret_inst = Instruction::At(code_item_->insns_ + next_insn_idx); 2778 Instruction::Code opcode = ret_inst->Opcode(); 2779 if ((opcode == Instruction::RETURN_VOID) || (opcode == Instruction::RETURN_VOID_BARRIER)) { 2780 work_line_->MarkAllRegistersAsConflicts(); 2781 } else { 2782 if (opcode == Instruction::RETURN_WIDE) { 2783 work_line_->MarkAllRegistersAsConflictsExceptWide(ret_inst->VRegA_11x()); 2784 } else { 2785 work_line_->MarkAllRegistersAsConflictsExcept(ret_inst->VRegA_11x()); 2786 } 2787 } 2788 } 2789 RegisterLine* next_line = reg_table_.GetLine(next_insn_idx); 2790 if (next_line != NULL) { 2791 // Merge registers into what we have for the next instruction, 2792 // and set the "changed" flag if needed. 2793 if (!UpdateRegisters(next_insn_idx, work_line_.get())) { 2794 return false; 2795 } 2796 } else { 2797 /* 2798 * We're not recording register data for the next instruction, so we don't know what the 2799 * prior state was. We have to assume that something has changed and re-evaluate it. 2800 */ 2801 insn_flags_[next_insn_idx].SetChanged(); 2802 } 2803 } 2804 2805 /* If we're returning from the method, make sure monitor stack is empty. */ 2806 if ((opcode_flags & Instruction::kReturn) != 0) { 2807 if (!work_line_->VerifyMonitorStackEmpty()) { 2808 return false; 2809 } 2810 } 2811 2812 /* 2813 * Update start_guess. Advance to the next instruction of that's 2814 * possible, otherwise use the branch target if one was found. If 2815 * neither of those exists we're in a return or throw; leave start_guess 2816 * alone and let the caller sort it out. 2817 */ 2818 if ((opcode_flags & Instruction::kContinue) != 0) { 2819 *start_guess = work_insn_idx_ + insn_flags_[work_insn_idx_].GetLengthInCodeUnits(); 2820 } else if ((opcode_flags & Instruction::kBranch) != 0) { 2821 /* we're still okay if branch_target is zero */ 2822 *start_guess = work_insn_idx_ + branch_target; 2823 } 2824 2825 DCHECK_LT(*start_guess, code_item_->insns_size_in_code_units_); 2826 DCHECK(insn_flags_[*start_guess].IsOpcode()); 2827 2828 return true; 2829} // NOLINT(readability/fn_size) 2830 2831const RegType& MethodVerifier::ResolveClassAndCheckAccess(uint32_t class_idx) { 2832 const char* descriptor = dex_file_->StringByTypeIdx(class_idx); 2833 const RegType& referrer = GetDeclaringClass(); 2834 mirror::Class* klass = (*dex_cache_)->GetResolvedType(class_idx); 2835 const RegType& result = 2836 klass != NULL ? reg_types_.FromClass(descriptor, klass, 2837 klass->CannotBeAssignedFromOtherTypes()) 2838 : reg_types_.FromDescriptor(class_loader_->get(), descriptor, false); 2839 if (result.IsConflict()) { 2840 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "accessing broken descriptor '" << descriptor 2841 << "' in " << referrer; 2842 return result; 2843 } 2844 if (klass == NULL && !result.IsUnresolvedTypes()) { 2845 (*dex_cache_)->SetResolvedType(class_idx, result.GetClass()); 2846 } 2847 // Check if access is allowed. Unresolved types use xxxWithAccessCheck to 2848 // check at runtime if access is allowed and so pass here. If result is 2849 // primitive, skip the access check. 2850 if (result.IsNonZeroReferenceTypes() && !result.IsUnresolvedTypes() && 2851 !referrer.IsUnresolvedTypes() && !referrer.CanAccess(result)) { 2852 Fail(VERIFY_ERROR_ACCESS_CLASS) << "illegal class access: '" 2853 << referrer << "' -> '" << result << "'"; 2854 } 2855 return result; 2856} 2857 2858const RegType& MethodVerifier::GetCaughtExceptionType() { 2859 const RegType* common_super = NULL; 2860 if (code_item_->tries_size_ != 0) { 2861 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item_, 0); 2862 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr); 2863 for (uint32_t i = 0; i < handlers_size; i++) { 2864 CatchHandlerIterator iterator(handlers_ptr); 2865 for (; iterator.HasNext(); iterator.Next()) { 2866 if (iterator.GetHandlerAddress() == (uint32_t) work_insn_idx_) { 2867 if (iterator.GetHandlerTypeIndex() == DexFile::kDexNoIndex16) { 2868 common_super = ®_types_.JavaLangThrowable(false); 2869 } else { 2870 const RegType& exception = ResolveClassAndCheckAccess(iterator.GetHandlerTypeIndex()); 2871 if (common_super == NULL) { 2872 // Unconditionally assign for the first handler. We don't assert this is a Throwable 2873 // as that is caught at runtime 2874 common_super = &exception; 2875 } else if (!reg_types_.JavaLangThrowable(false).IsAssignableFrom(exception)) { 2876 if (exception.IsUnresolvedTypes()) { 2877 // We don't know enough about the type. Fail here and let runtime handle it. 2878 Fail(VERIFY_ERROR_NO_CLASS) << "unresolved exception class " << exception; 2879 return exception; 2880 } else { 2881 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "unexpected non-exception class " << exception; 2882 return reg_types_.Conflict(); 2883 } 2884 } else if (common_super->Equals(exception)) { 2885 // odd case, but nothing to do 2886 } else { 2887 common_super = &common_super->Merge(exception, ®_types_); 2888 CHECK(reg_types_.JavaLangThrowable(false).IsAssignableFrom(*common_super)); 2889 } 2890 } 2891 } 2892 } 2893 handlers_ptr = iterator.EndDataPointer(); 2894 } 2895 } 2896 if (common_super == NULL) { 2897 /* no catch blocks, or no catches with classes we can find */ 2898 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "unable to find exception handler"; 2899 return reg_types_.Conflict(); 2900 } 2901 return *common_super; 2902} 2903 2904mirror::ArtMethod* MethodVerifier::ResolveMethodAndCheckAccess(uint32_t dex_method_idx, 2905 MethodType method_type) { 2906 const DexFile::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx); 2907 const RegType& klass_type = ResolveClassAndCheckAccess(method_id.class_idx_); 2908 if (klass_type.IsConflict()) { 2909 std::string append(" in attempt to access method "); 2910 append += dex_file_->GetMethodName(method_id); 2911 AppendToLastFailMessage(append); 2912 return NULL; 2913 } 2914 if (klass_type.IsUnresolvedTypes()) { 2915 return NULL; // Can't resolve Class so no more to do here 2916 } 2917 mirror::Class* klass = klass_type.GetClass(); 2918 const RegType& referrer = GetDeclaringClass(); 2919 mirror::ArtMethod* res_method = (*dex_cache_)->GetResolvedMethod(dex_method_idx); 2920 if (res_method == NULL) { 2921 const char* name = dex_file_->GetMethodName(method_id); 2922 const Signature signature = dex_file_->GetMethodSignature(method_id); 2923 2924 if (method_type == METHOD_DIRECT || method_type == METHOD_STATIC) { 2925 res_method = klass->FindDirectMethod(name, signature); 2926 } else if (method_type == METHOD_INTERFACE) { 2927 res_method = klass->FindInterfaceMethod(name, signature); 2928 } else { 2929 res_method = klass->FindVirtualMethod(name, signature); 2930 } 2931 if (res_method != NULL) { 2932 (*dex_cache_)->SetResolvedMethod(dex_method_idx, res_method); 2933 } else { 2934 // If a virtual or interface method wasn't found with the expected type, look in 2935 // the direct methods. This can happen when the wrong invoke type is used or when 2936 // a class has changed, and will be flagged as an error in later checks. 2937 if (method_type == METHOD_INTERFACE || method_type == METHOD_VIRTUAL) { 2938 res_method = klass->FindDirectMethod(name, signature); 2939 } 2940 if (res_method == NULL) { 2941 Fail(VERIFY_ERROR_NO_METHOD) << "couldn't find method " 2942 << PrettyDescriptor(klass) << "." << name 2943 << " " << signature; 2944 return NULL; 2945 } 2946 } 2947 } 2948 // Make sure calls to constructors are "direct". There are additional restrictions but we don't 2949 // enforce them here. 2950 if (res_method->IsConstructor() && method_type != METHOD_DIRECT) { 2951 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "rejecting non-direct call to constructor " 2952 << PrettyMethod(res_method); 2953 return NULL; 2954 } 2955 // Disallow any calls to class initializers. 2956 if (MethodHelper(res_method).IsClassInitializer()) { 2957 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "rejecting call to class initializer " 2958 << PrettyMethod(res_method); 2959 return NULL; 2960 } 2961 // Check if access is allowed. 2962 if (!referrer.CanAccessMember(res_method->GetDeclaringClass(), res_method->GetAccessFlags())) { 2963 Fail(VERIFY_ERROR_ACCESS_METHOD) << "illegal method access (call " << PrettyMethod(res_method) 2964 << " from " << referrer << ")"; 2965 return res_method; 2966 } 2967 // Check that invoke-virtual and invoke-super are not used on private methods of the same class. 2968 if (res_method->IsPrivate() && method_type == METHOD_VIRTUAL) { 2969 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invoke-super/virtual can't be used on private method " 2970 << PrettyMethod(res_method); 2971 return NULL; 2972 } 2973 // Check that interface methods match interface classes. 2974 if (klass->IsInterface() && method_type != METHOD_INTERFACE) { 2975 Fail(VERIFY_ERROR_CLASS_CHANGE) << "non-interface method " << PrettyMethod(res_method) 2976 << " is in an interface class " << PrettyClass(klass); 2977 return NULL; 2978 } else if (!klass->IsInterface() && method_type == METHOD_INTERFACE) { 2979 Fail(VERIFY_ERROR_CLASS_CHANGE) << "interface method " << PrettyMethod(res_method) 2980 << " is in a non-interface class " << PrettyClass(klass); 2981 return NULL; 2982 } 2983 // See if the method type implied by the invoke instruction matches the access flags for the 2984 // target method. 2985 if ((method_type == METHOD_DIRECT && !res_method->IsDirect()) || 2986 (method_type == METHOD_STATIC && !res_method->IsStatic()) || 2987 ((method_type == METHOD_VIRTUAL || method_type == METHOD_INTERFACE) && res_method->IsDirect()) 2988 ) { 2989 Fail(VERIFY_ERROR_CLASS_CHANGE) << "invoke type (" << method_type << ") does not match method " 2990 " type of " << PrettyMethod(res_method); 2991 return NULL; 2992 } 2993 return res_method; 2994} 2995 2996mirror::ArtMethod* MethodVerifier::VerifyInvocationArgs(const Instruction* inst, 2997 MethodType method_type, 2998 bool is_range, 2999 bool is_super) { 3000 // Resolve the method. This could be an abstract or concrete method depending on what sort of call 3001 // we're making. 3002 const uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c(); 3003 mirror::ArtMethod* res_method = ResolveMethodAndCheckAccess(method_idx, method_type); 3004 if (res_method == NULL) { // error or class is unresolved 3005 return NULL; 3006 } 3007 3008 // If we're using invoke-super(method), make sure that the executing method's class' superclass 3009 // has a vtable entry for the target method. 3010 if (is_super) { 3011 DCHECK(method_type == METHOD_VIRTUAL); 3012 const RegType& super = GetDeclaringClass().GetSuperClass(®_types_); 3013 if (super.IsUnresolvedTypes()) { 3014 Fail(VERIFY_ERROR_NO_METHOD) << "unknown super class in invoke-super from " 3015 << PrettyMethod(dex_method_idx_, *dex_file_) 3016 << " to super " << PrettyMethod(res_method); 3017 return NULL; 3018 } 3019 mirror::Class* super_klass = super.GetClass(); 3020 if (res_method->GetMethodIndex() >= super_klass->GetVTable()->GetLength()) { 3021 MethodHelper mh(res_method); 3022 Fail(VERIFY_ERROR_NO_METHOD) << "invalid invoke-super from " 3023 << PrettyMethod(dex_method_idx_, *dex_file_) 3024 << " to super " << super 3025 << "." << mh.GetName() 3026 << mh.GetSignature(); 3027 return NULL; 3028 } 3029 } 3030 // We use vAA as our expected arg count, rather than res_method->insSize, because we need to 3031 // match the call to the signature. Also, we might be calling through an abstract method 3032 // definition (which doesn't have register count values). 3033 const size_t expected_args = (is_range) ? inst->VRegA_3rc() : inst->VRegA_35c(); 3034 /* caught by static verifier */ 3035 DCHECK(is_range || expected_args <= 5); 3036 if (expected_args > code_item_->outs_size_) { 3037 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid argument count (" << expected_args 3038 << ") exceeds outsSize (" << code_item_->outs_size_ << ")"; 3039 return NULL; 3040 } 3041 3042 /* 3043 * Check the "this" argument, which must be an instance of the class that declared the method. 3044 * For an interface class, we don't do the full interface merge (see JoinClass), so we can't do a 3045 * rigorous check here (which is okay since we have to do it at runtime). 3046 */ 3047 size_t actual_args = 0; 3048 if (!res_method->IsStatic()) { 3049 const RegType& actual_arg_type = work_line_->GetInvocationThis(inst, is_range); 3050 if (actual_arg_type.IsConflict()) { // GetInvocationThis failed. 3051 return NULL; 3052 } 3053 if (actual_arg_type.IsUninitializedReference() && !res_method->IsConstructor()) { 3054 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "'this' arg must be initialized"; 3055 return NULL; 3056 } 3057 if (method_type != METHOD_INTERFACE && !actual_arg_type.IsZero()) { 3058 mirror::Class* klass = res_method->GetDeclaringClass(); 3059 const RegType& res_method_class = 3060 reg_types_.FromClass(ClassHelper(klass).GetDescriptor(), klass, 3061 klass->CannotBeAssignedFromOtherTypes()); 3062 if (!res_method_class.IsAssignableFrom(actual_arg_type)) { 3063 Fail(actual_arg_type.IsUnresolvedTypes() ? VERIFY_ERROR_NO_CLASS: 3064 VERIFY_ERROR_BAD_CLASS_SOFT) << "'this' argument '" << actual_arg_type 3065 << "' not instance of '" << res_method_class << "'"; 3066 return NULL; 3067 } 3068 } 3069 actual_args++; 3070 } 3071 /* 3072 * Process the target method's signature. This signature may or may not 3073 * have been verified, so we can't assume it's properly formed. 3074 */ 3075 MethodHelper mh(res_method); 3076 const DexFile::TypeList* params = mh.GetParameterTypeList(); 3077 size_t params_size = params == NULL ? 0 : params->Size(); 3078 uint32_t arg[5]; 3079 if (!is_range) { 3080 inst->GetArgs(arg); 3081 } 3082 for (size_t param_index = 0; param_index < params_size; param_index++) { 3083 if (actual_args >= expected_args) { 3084 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invalid call to '" << PrettyMethod(res_method) 3085 << "'. Expected " << expected_args << " arguments, processing argument " << actual_args 3086 << " (where longs/doubles count twice)."; 3087 return NULL; 3088 } 3089 const char* descriptor = 3090 mh.GetTypeDescriptorFromTypeIdx(params->GetTypeItem(param_index).type_idx_); 3091 if (descriptor == NULL) { 3092 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation of " << PrettyMethod(res_method) 3093 << " missing signature component"; 3094 return NULL; 3095 } 3096 const RegType& reg_type = reg_types_.FromDescriptor(class_loader_->get(), descriptor, false); 3097 uint32_t get_reg = is_range ? inst->VRegC_3rc() + actual_args : arg[actual_args]; 3098 if (reg_type.IsIntegralTypes()) { 3099 const RegType& src_type = work_line_->GetRegisterType(get_reg); 3100 if (!src_type.IsIntegralTypes()) { 3101 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "register v" << get_reg << " has type " << src_type 3102 << " but expected " << reg_type; 3103 return res_method; 3104 } 3105 } else if (!work_line_->VerifyRegisterType(get_reg, reg_type)) { 3106 return res_method; 3107 } 3108 actual_args = reg_type.IsLongOrDoubleTypes() ? actual_args + 2 : actual_args + 1; 3109 } 3110 if (actual_args != expected_args) { 3111 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation of " << PrettyMethod(res_method) 3112 << " expected " << expected_args << " arguments, found " << actual_args; 3113 return NULL; 3114 } else { 3115 return res_method; 3116 } 3117} 3118 3119mirror::ArtMethod* MethodVerifier::GetQuickInvokedMethod(const Instruction* inst, 3120 RegisterLine* reg_line, bool is_range) { 3121 DCHECK(inst->Opcode() == Instruction::INVOKE_VIRTUAL_QUICK || 3122 inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE_QUICK); 3123 const RegType& actual_arg_type = reg_line->GetInvocationThis(inst, is_range); 3124 if (!actual_arg_type.HasClass()) { 3125 VLOG(verifier) << "Failed to get mirror::Class* from '" << actual_arg_type << "'"; 3126 return nullptr; 3127 } 3128 mirror::ObjectArray<mirror::ArtMethod>* vtable = actual_arg_type.GetClass()->GetVTable(); 3129 CHECK(vtable != nullptr); 3130 uint16_t vtable_index = is_range ? inst->VRegB_3rc() : inst->VRegB_35c(); 3131 CHECK_LT(static_cast<int32_t>(vtable_index), vtable->GetLength()); 3132 mirror::ArtMethod* res_method = vtable->Get(vtable_index); 3133 CHECK(!Thread::Current()->IsExceptionPending()); 3134 return res_method; 3135} 3136 3137mirror::ArtMethod* MethodVerifier::VerifyInvokeVirtualQuickArgs(const Instruction* inst, 3138 bool is_range) { 3139 DCHECK(Runtime::Current()->IsStarted()); 3140 mirror::ArtMethod* res_method = GetQuickInvokedMethod(inst, work_line_.get(), 3141 is_range); 3142 if (res_method == NULL) { 3143 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Cannot infer method from " << inst->Name(); 3144 return NULL; 3145 } 3146 CHECK(!res_method->IsDirect() && !res_method->IsStatic()); 3147 3148 // We use vAA as our expected arg count, rather than res_method->insSize, because we need to 3149 // match the call to the signature. Also, we might be calling through an abstract method 3150 // definition (which doesn't have register count values). 3151 const RegType& actual_arg_type = work_line_->GetInvocationThis(inst, is_range); 3152 if (actual_arg_type.IsConflict()) { // GetInvocationThis failed. 3153 return NULL; 3154 } 3155 const size_t expected_args = (is_range) ? inst->VRegA_3rc() : inst->VRegA_35c(); 3156 /* caught by static verifier */ 3157 DCHECK(is_range || expected_args <= 5); 3158 if (expected_args > code_item_->outs_size_) { 3159 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid argument count (" << expected_args 3160 << ") exceeds outsSize (" << code_item_->outs_size_ << ")"; 3161 return NULL; 3162 } 3163 3164 /* 3165 * Check the "this" argument, which must be an instance of the class that declared the method. 3166 * For an interface class, we don't do the full interface merge (see JoinClass), so we can't do a 3167 * rigorous check here (which is okay since we have to do it at runtime). 3168 */ 3169 if (actual_arg_type.IsUninitializedReference() && !res_method->IsConstructor()) { 3170 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "'this' arg must be initialized"; 3171 return NULL; 3172 } 3173 if (!actual_arg_type.IsZero()) { 3174 mirror::Class* klass = res_method->GetDeclaringClass(); 3175 const RegType& res_method_class = 3176 reg_types_.FromClass(ClassHelper(klass).GetDescriptor(), klass, 3177 klass->CannotBeAssignedFromOtherTypes()); 3178 if (!res_method_class.IsAssignableFrom(actual_arg_type)) { 3179 Fail(actual_arg_type.IsUnresolvedTypes() ? VERIFY_ERROR_NO_CLASS : 3180 VERIFY_ERROR_BAD_CLASS_SOFT) << "'this' argument '" << actual_arg_type 3181 << "' not instance of '" << res_method_class << "'"; 3182 return NULL; 3183 } 3184 } 3185 /* 3186 * Process the target method's signature. This signature may or may not 3187 * have been verified, so we can't assume it's properly formed. 3188 */ 3189 MethodHelper mh(res_method); 3190 const DexFile::TypeList* params = mh.GetParameterTypeList(); 3191 size_t params_size = params == NULL ? 0 : params->Size(); 3192 uint32_t arg[5]; 3193 if (!is_range) { 3194 inst->GetArgs(arg); 3195 } 3196 size_t actual_args = 1; 3197 for (size_t param_index = 0; param_index < params_size; param_index++) { 3198 if (actual_args >= expected_args) { 3199 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invalid call to '" << PrettyMethod(res_method) 3200 << "'. Expected " << expected_args 3201 << " arguments, processing argument " << actual_args 3202 << " (where longs/doubles count twice)."; 3203 return NULL; 3204 } 3205 const char* descriptor = 3206 mh.GetTypeDescriptorFromTypeIdx(params->GetTypeItem(param_index).type_idx_); 3207 if (descriptor == NULL) { 3208 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation of " << PrettyMethod(res_method) 3209 << " missing signature component"; 3210 return NULL; 3211 } 3212 const RegType& reg_type = reg_types_.FromDescriptor(class_loader_->get(), descriptor, false); 3213 uint32_t get_reg = is_range ? inst->VRegC_3rc() + actual_args : arg[actual_args]; 3214 if (!work_line_->VerifyRegisterType(get_reg, reg_type)) { 3215 return res_method; 3216 } 3217 actual_args = reg_type.IsLongOrDoubleTypes() ? actual_args + 2 : actual_args + 1; 3218 } 3219 if (actual_args != expected_args) { 3220 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation of " << PrettyMethod(res_method) 3221 << " expected " << expected_args << " arguments, found " << actual_args; 3222 return NULL; 3223 } else { 3224 return res_method; 3225 } 3226} 3227 3228void MethodVerifier::VerifyNewArray(const Instruction* inst, bool is_filled, bool is_range) { 3229 uint32_t type_idx; 3230 if (!is_filled) { 3231 DCHECK_EQ(inst->Opcode(), Instruction::NEW_ARRAY); 3232 type_idx = inst->VRegC_22c(); 3233 } else if (!is_range) { 3234 DCHECK_EQ(inst->Opcode(), Instruction::FILLED_NEW_ARRAY); 3235 type_idx = inst->VRegB_35c(); 3236 } else { 3237 DCHECK_EQ(inst->Opcode(), Instruction::FILLED_NEW_ARRAY_RANGE); 3238 type_idx = inst->VRegB_3rc(); 3239 } 3240 const RegType& res_type = ResolveClassAndCheckAccess(type_idx); 3241 if (res_type.IsConflict()) { // bad class 3242 DCHECK_NE(failures_.size(), 0U); 3243 } else { 3244 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved 3245 if (!res_type.IsArrayTypes()) { 3246 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "new-array on non-array class " << res_type; 3247 } else if (!is_filled) { 3248 /* make sure "size" register is valid type */ 3249 work_line_->VerifyRegisterType(inst->VRegB_22c(), reg_types_.Integer()); 3250 /* set register type to array class */ 3251 const RegType& precise_type = reg_types_.FromUninitialized(res_type); 3252 work_line_->SetRegisterType(inst->VRegA_22c(), precise_type); 3253 } else { 3254 // Verify each register. If "arg_count" is bad, VerifyRegisterType() will run off the end of 3255 // the list and fail. It's legal, if silly, for arg_count to be zero. 3256 const RegType& expected_type = reg_types_.GetComponentType(res_type, class_loader_->get()); 3257 uint32_t arg_count = (is_range) ? inst->VRegA_3rc() : inst->VRegA_35c(); 3258 uint32_t arg[5]; 3259 if (!is_range) { 3260 inst->GetArgs(arg); 3261 } 3262 for (size_t ui = 0; ui < arg_count; ui++) { 3263 uint32_t get_reg = is_range ? inst->VRegC_3rc() + ui : arg[ui]; 3264 if (!work_line_->VerifyRegisterType(get_reg, expected_type)) { 3265 work_line_->SetResultRegisterType(reg_types_.Conflict()); 3266 return; 3267 } 3268 } 3269 // filled-array result goes into "result" register 3270 const RegType& precise_type = reg_types_.FromUninitialized(res_type); 3271 work_line_->SetResultRegisterType(precise_type); 3272 } 3273 } 3274} 3275 3276void MethodVerifier::VerifyAGet(const Instruction* inst, 3277 const RegType& insn_type, bool is_primitive) { 3278 const RegType& index_type = work_line_->GetRegisterType(inst->VRegC_23x()); 3279 if (!index_type.IsArrayIndexTypes()) { 3280 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Invalid reg type for array index (" << index_type << ")"; 3281 } else { 3282 const RegType& array_type = work_line_->GetRegisterType(inst->VRegB_23x()); 3283 if (array_type.IsZero()) { 3284 // Null array class; this code path will fail at runtime. Infer a merge-able type from the 3285 // instruction type. TODO: have a proper notion of bottom here. 3286 if (!is_primitive || insn_type.IsCategory1Types()) { 3287 // Reference or category 1 3288 work_line_->SetRegisterType(inst->VRegA_23x(), reg_types_.Zero()); 3289 } else { 3290 // Category 2 3291 work_line_->SetRegisterTypeWide(inst->VRegA_23x(), reg_types_.FromCat2ConstLo(0, false), 3292 reg_types_.FromCat2ConstHi(0, false)); 3293 } 3294 } else if (!array_type.IsArrayTypes()) { 3295 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "not array type " << array_type << " with aget"; 3296 } else { 3297 /* verify the class */ 3298 const RegType& component_type = reg_types_.GetComponentType(array_type, class_loader_->get()); 3299 if (!component_type.IsReferenceTypes() && !is_primitive) { 3300 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "primitive array type " << array_type 3301 << " source for aget-object"; 3302 } else if (component_type.IsNonZeroReferenceTypes() && is_primitive) { 3303 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "reference array type " << array_type 3304 << " source for category 1 aget"; 3305 } else if (is_primitive && !insn_type.Equals(component_type) && 3306 !((insn_type.IsInteger() && component_type.IsFloat()) || 3307 (insn_type.IsLong() && component_type.IsDouble()))) { 3308 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array type " << array_type 3309 << " incompatible with aget of type " << insn_type; 3310 } else { 3311 // Use knowledge of the field type which is stronger than the type inferred from the 3312 // instruction, which can't differentiate object types and ints from floats, longs from 3313 // doubles. 3314 if (!component_type.IsLowHalf()) { 3315 work_line_->SetRegisterType(inst->VRegA_23x(), component_type); 3316 } else { 3317 work_line_->SetRegisterTypeWide(inst->VRegA_23x(), component_type, 3318 component_type.HighHalf(®_types_)); 3319 } 3320 } 3321 } 3322 } 3323} 3324 3325void MethodVerifier::VerifyPrimitivePut(const RegType& target_type, const RegType& insn_type, 3326 const uint32_t vregA) { 3327 // Primitive assignability rules are weaker than regular assignability rules. 3328 bool instruction_compatible; 3329 bool value_compatible; 3330 const RegType& value_type = work_line_->GetRegisterType(vregA); 3331 if (target_type.IsIntegralTypes()) { 3332 instruction_compatible = target_type.Equals(insn_type); 3333 value_compatible = value_type.IsIntegralTypes(); 3334 } else if (target_type.IsFloat()) { 3335 instruction_compatible = insn_type.IsInteger(); // no put-float, so expect put-int 3336 value_compatible = value_type.IsFloatTypes(); 3337 } else if (target_type.IsLong()) { 3338 instruction_compatible = insn_type.IsLong(); 3339 value_compatible = value_type.IsLongTypes(); 3340 } else if (target_type.IsDouble()) { 3341 instruction_compatible = insn_type.IsLong(); // no put-double, so expect put-long 3342 value_compatible = value_type.IsDoubleTypes(); 3343 } else { 3344 instruction_compatible = false; // reference with primitive store 3345 value_compatible = false; // unused 3346 } 3347 if (!instruction_compatible) { 3348 // This is a global failure rather than a class change failure as the instructions and 3349 // the descriptors for the type should have been consistent within the same file at 3350 // compile time. 3351 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "put insn has type '" << insn_type 3352 << "' but expected type '" << target_type << "'"; 3353 return; 3354 } 3355 if (!value_compatible) { 3356 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected value in v" << vregA 3357 << " of type " << value_type << " but expected " << target_type << " for put"; 3358 return; 3359 } 3360} 3361 3362void MethodVerifier::VerifyAPut(const Instruction* inst, 3363 const RegType& insn_type, bool is_primitive) { 3364 const RegType& index_type = work_line_->GetRegisterType(inst->VRegC_23x()); 3365 if (!index_type.IsArrayIndexTypes()) { 3366 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Invalid reg type for array index (" << index_type << ")"; 3367 } else { 3368 const RegType& array_type = work_line_->GetRegisterType(inst->VRegB_23x()); 3369 if (array_type.IsZero()) { 3370 // Null array type; this code path will fail at runtime. Infer a merge-able type from the 3371 // instruction type. 3372 } else if (!array_type.IsArrayTypes()) { 3373 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "not array type " << array_type << " with aput"; 3374 } else { 3375 const RegType& component_type = reg_types_.GetComponentType(array_type, class_loader_->get()); 3376 const uint32_t vregA = inst->VRegA_23x(); 3377 if (is_primitive) { 3378 VerifyPrimitivePut(component_type, insn_type, vregA); 3379 } else { 3380 if (!component_type.IsReferenceTypes()) { 3381 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "primitive array type " << array_type 3382 << " source for aput-object"; 3383 } else { 3384 // The instruction agrees with the type of array, confirm the value to be stored does too 3385 // Note: we use the instruction type (rather than the component type) for aput-object as 3386 // incompatible classes will be caught at runtime as an array store exception 3387 work_line_->VerifyRegisterType(vregA, insn_type); 3388 } 3389 } 3390 } 3391 } 3392} 3393 3394mirror::ArtField* MethodVerifier::GetStaticField(int field_idx) { 3395 const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx); 3396 // Check access to class 3397 const RegType& klass_type = ResolveClassAndCheckAccess(field_id.class_idx_); 3398 if (klass_type.IsConflict()) { // bad class 3399 AppendToLastFailMessage(StringPrintf(" in attempt to access static field %d (%s) in %s", 3400 field_idx, dex_file_->GetFieldName(field_id), 3401 dex_file_->GetFieldDeclaringClassDescriptor(field_id))); 3402 return NULL; 3403 } 3404 if (klass_type.IsUnresolvedTypes()) { 3405 return NULL; // Can't resolve Class so no more to do here, will do checking at runtime. 3406 } 3407 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 3408 mirror::ArtField* field = class_linker->ResolveFieldJLS(*dex_file_, field_idx, *dex_cache_, 3409 *class_loader_); 3410 if (field == NULL) { 3411 VLOG(verifier) << "Unable to resolve static field " << field_idx << " (" 3412 << dex_file_->GetFieldName(field_id) << ") in " 3413 << dex_file_->GetFieldDeclaringClassDescriptor(field_id); 3414 DCHECK(Thread::Current()->IsExceptionPending()); 3415 Thread::Current()->ClearException(); 3416 return NULL; 3417 } else if (!GetDeclaringClass().CanAccessMember(field->GetDeclaringClass(), 3418 field->GetAccessFlags())) { 3419 Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot access static field " << PrettyField(field) 3420 << " from " << GetDeclaringClass(); 3421 return NULL; 3422 } else if (!field->IsStatic()) { 3423 Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected field " << PrettyField(field) << " to be static"; 3424 return NULL; 3425 } 3426 return field; 3427} 3428 3429mirror::ArtField* MethodVerifier::GetInstanceField(const RegType& obj_type, int field_idx) { 3430 const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx); 3431 // Check access to class 3432 const RegType& klass_type = ResolveClassAndCheckAccess(field_id.class_idx_); 3433 if (klass_type.IsConflict()) { 3434 AppendToLastFailMessage(StringPrintf(" in attempt to access instance field %d (%s) in %s", 3435 field_idx, dex_file_->GetFieldName(field_id), 3436 dex_file_->GetFieldDeclaringClassDescriptor(field_id))); 3437 return NULL; 3438 } 3439 if (klass_type.IsUnresolvedTypes()) { 3440 return NULL; // Can't resolve Class so no more to do here 3441 } 3442 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 3443 mirror::ArtField* field = class_linker->ResolveFieldJLS(*dex_file_, field_idx, *dex_cache_, 3444 *class_loader_); 3445 if (field == NULL) { 3446 VLOG(verifier) << "Unable to resolve instance field " << field_idx << " (" 3447 << dex_file_->GetFieldName(field_id) << ") in " 3448 << dex_file_->GetFieldDeclaringClassDescriptor(field_id); 3449 DCHECK(Thread::Current()->IsExceptionPending()); 3450 Thread::Current()->ClearException(); 3451 return NULL; 3452 } else if (!GetDeclaringClass().CanAccessMember(field->GetDeclaringClass(), 3453 field->GetAccessFlags())) { 3454 Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot access instance field " << PrettyField(field) 3455 << " from " << GetDeclaringClass(); 3456 return NULL; 3457 } else if (field->IsStatic()) { 3458 Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected field " << PrettyField(field) 3459 << " to not be static"; 3460 return NULL; 3461 } else if (obj_type.IsZero()) { 3462 // Cannot infer and check type, however, access will cause null pointer exception 3463 return field; 3464 } else { 3465 mirror::Class* klass = field->GetDeclaringClass(); 3466 const RegType& field_klass = 3467 reg_types_.FromClass(dex_file_->GetFieldDeclaringClassDescriptor(field_id), 3468 klass, klass->CannotBeAssignedFromOtherTypes()); 3469 if (obj_type.IsUninitializedTypes() && 3470 (!IsConstructor() || GetDeclaringClass().Equals(obj_type) || 3471 !field_klass.Equals(GetDeclaringClass()))) { 3472 // Field accesses through uninitialized references are only allowable for constructors where 3473 // the field is declared in this class 3474 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "cannot access instance field " << PrettyField(field) 3475 << " of a not fully initialized object within the context" 3476 << " of " << PrettyMethod(dex_method_idx_, *dex_file_); 3477 return NULL; 3478 } else if (!field_klass.IsAssignableFrom(obj_type)) { 3479 // Trying to access C1.field1 using reference of type C2, which is neither C1 or a sub-class 3480 // of C1. For resolution to occur the declared class of the field must be compatible with 3481 // obj_type, we've discovered this wasn't so, so report the field didn't exist. 3482 Fail(VERIFY_ERROR_NO_FIELD) << "cannot access instance field " << PrettyField(field) 3483 << " from object of type " << obj_type; 3484 return NULL; 3485 } else { 3486 return field; 3487 } 3488 } 3489} 3490 3491void MethodVerifier::VerifyISGet(const Instruction* inst, const RegType& insn_type, 3492 bool is_primitive, bool is_static) { 3493 uint32_t field_idx = is_static ? inst->VRegB_21c() : inst->VRegC_22c(); 3494 mirror::ArtField* field; 3495 if (is_static) { 3496 field = GetStaticField(field_idx); 3497 } else { 3498 const RegType& object_type = work_line_->GetRegisterType(inst->VRegB_22c()); 3499 field = GetInstanceField(object_type, field_idx); 3500 } 3501 const RegType* field_type = nullptr; 3502 if (field != NULL) { 3503 FieldHelper fh(field); 3504 mirror::Class* field_type_class = fh.GetType(can_load_classes_); 3505 if (field_type_class != nullptr) { 3506 field_type = ®_types_.FromClass(fh.GetTypeDescriptor(), field_type_class, 3507 field_type_class->CannotBeAssignedFromOtherTypes()); 3508 } else { 3509 Thread* self = Thread::Current(); 3510 DCHECK(!can_load_classes_ || self->IsExceptionPending()); 3511 self->ClearException(); 3512 } 3513 } 3514 if (field_type == nullptr) { 3515 const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx); 3516 const char* descriptor = dex_file_->GetFieldTypeDescriptor(field_id); 3517 field_type = ®_types_.FromDescriptor(class_loader_->get(), descriptor, false); 3518 } 3519 DCHECK(field_type != nullptr); 3520 const uint32_t vregA = (is_static) ? inst->VRegA_21c() : inst->VRegA_22c(); 3521 if (is_primitive) { 3522 if (field_type->Equals(insn_type) || 3523 (field_type->IsFloat() && insn_type.IsInteger()) || 3524 (field_type->IsDouble() && insn_type.IsLong())) { 3525 // expected that read is of the correct primitive type or that int reads are reading 3526 // floats or long reads are reading doubles 3527 } else { 3528 // This is a global failure rather than a class change failure as the instructions and 3529 // the descriptors for the type should have been consistent within the same file at 3530 // compile time 3531 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected field " << PrettyField(field) 3532 << " to be of type '" << insn_type 3533 << "' but found type '" << *field_type << "' in get"; 3534 return; 3535 } 3536 } else { 3537 if (!insn_type.IsAssignableFrom(*field_type)) { 3538 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "expected field " << PrettyField(field) 3539 << " to be compatible with type '" << insn_type 3540 << "' but found type '" << *field_type 3541 << "' in get-object"; 3542 work_line_->SetRegisterType(vregA, reg_types_.Conflict()); 3543 return; 3544 } 3545 } 3546 if (!field_type->IsLowHalf()) { 3547 work_line_->SetRegisterType(vregA, *field_type); 3548 } else { 3549 work_line_->SetRegisterTypeWide(vregA, *field_type, field_type->HighHalf(®_types_)); 3550 } 3551} 3552 3553void MethodVerifier::VerifyISPut(const Instruction* inst, const RegType& insn_type, 3554 bool is_primitive, bool is_static) { 3555 uint32_t field_idx = is_static ? inst->VRegB_21c() : inst->VRegC_22c(); 3556 mirror::ArtField* field; 3557 if (is_static) { 3558 field = GetStaticField(field_idx); 3559 } else { 3560 const RegType& object_type = work_line_->GetRegisterType(inst->VRegB_22c()); 3561 field = GetInstanceField(object_type, field_idx); 3562 } 3563 const RegType* field_type = nullptr; 3564 if (field != NULL) { 3565 if (field->IsFinal() && field->GetDeclaringClass() != GetDeclaringClass().GetClass()) { 3566 Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot modify final field " << PrettyField(field) 3567 << " from other class " << GetDeclaringClass(); 3568 return; 3569 } 3570 FieldHelper fh(field); 3571 mirror::Class* field_type_class = fh.GetType(can_load_classes_); 3572 if (field_type_class != nullptr) { 3573 field_type = ®_types_.FromClass(fh.GetTypeDescriptor(), field_type_class, 3574 field_type_class->CannotBeAssignedFromOtherTypes()); 3575 } else { 3576 Thread* self = Thread::Current(); 3577 DCHECK(!can_load_classes_ || self->IsExceptionPending()); 3578 self->ClearException(); 3579 } 3580 } 3581 if (field_type == nullptr) { 3582 const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx); 3583 const char* descriptor = dex_file_->GetFieldTypeDescriptor(field_id); 3584 field_type = ®_types_.FromDescriptor(class_loader_->get(), descriptor, false); 3585 } 3586 DCHECK(field_type != nullptr); 3587 const uint32_t vregA = (is_static) ? inst->VRegA_21c() : inst->VRegA_22c(); 3588 if (is_primitive) { 3589 VerifyPrimitivePut(*field_type, insn_type, vregA); 3590 } else { 3591 if (!insn_type.IsAssignableFrom(*field_type)) { 3592 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "expected field " << PrettyField(field) 3593 << " to be compatible with type '" << insn_type 3594 << "' but found type '" << *field_type 3595 << "' in put-object"; 3596 return; 3597 } 3598 work_line_->VerifyRegisterType(vregA, *field_type); 3599 } 3600} 3601 3602// Look for an instance field with this offset. 3603// TODO: we may speed up the search if offsets are sorted by doing a quick search. 3604static mirror::ArtField* FindInstanceFieldWithOffset(mirror::Class* klass, uint32_t field_offset) 3605 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 3606 mirror::ObjectArray<mirror::ArtField>* instance_fields = klass->GetIFields(); 3607 if (instance_fields != NULL) { 3608 for (int32_t i = 0, e = instance_fields->GetLength(); i < e; ++i) { 3609 mirror::ArtField* field = instance_fields->Get(i); 3610 if (field->GetOffset().Uint32Value() == field_offset) { 3611 return field; 3612 } 3613 } 3614 } 3615 // We did not find field in class: look into superclass. 3616 if (klass->GetSuperClass() != NULL) { 3617 return FindInstanceFieldWithOffset(klass->GetSuperClass(), field_offset); 3618 } else { 3619 VLOG(verifier) << "Failed to find instance field at offset '" << field_offset 3620 << "' from '" << PrettyDescriptor(klass) << "'"; 3621 return nullptr; 3622 } 3623} 3624 3625mirror::ArtField* MethodVerifier::GetQuickFieldAccess(const Instruction* inst, 3626 RegisterLine* reg_line) { 3627 DCHECK(inst->Opcode() == Instruction::IGET_QUICK || 3628 inst->Opcode() == Instruction::IGET_WIDE_QUICK || 3629 inst->Opcode() == Instruction::IGET_OBJECT_QUICK || 3630 inst->Opcode() == Instruction::IPUT_QUICK || 3631 inst->Opcode() == Instruction::IPUT_WIDE_QUICK || 3632 inst->Opcode() == Instruction::IPUT_OBJECT_QUICK); 3633 const RegType& object_type = reg_line->GetRegisterType(inst->VRegB_22c()); 3634 if (!object_type.HasClass()) { 3635 VLOG(verifier) << "Failed to get mirror::Class* from '" << object_type << "'"; 3636 return nullptr; 3637 } 3638 uint32_t field_offset = static_cast<uint32_t>(inst->VRegC_22c()); 3639 return FindInstanceFieldWithOffset(object_type.GetClass(), field_offset); 3640} 3641 3642void MethodVerifier::VerifyIGetQuick(const Instruction* inst, const RegType& insn_type, 3643 bool is_primitive) { 3644 DCHECK(Runtime::Current()->IsStarted()); 3645 mirror::ArtField* field = GetQuickFieldAccess(inst, work_line_.get()); 3646 if (field == NULL) { 3647 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Cannot infer field from " << inst->Name(); 3648 return; 3649 } 3650 FieldHelper fh(field); 3651 mirror::Class* field_type_class = fh.GetType(can_load_classes_); 3652 const RegType* field_type; 3653 if (field_type_class != nullptr) { 3654 field_type = ®_types_.FromClass(fh.GetTypeDescriptor(), field_type_class, 3655 field_type_class->CannotBeAssignedFromOtherTypes()); 3656 } else { 3657 Thread* self = Thread::Current(); 3658 DCHECK(!can_load_classes_ || self->IsExceptionPending()); 3659 self->ClearException(); 3660 field_type = ®_types_.FromDescriptor(field->GetDeclaringClass()->GetClassLoader(), 3661 fh.GetTypeDescriptor(), false); 3662 } 3663 DCHECK(field_type != nullptr); 3664 const uint32_t vregA = inst->VRegA_22c(); 3665 if (is_primitive) { 3666 if (field_type->Equals(insn_type) || 3667 (field_type->IsFloat() && insn_type.IsIntegralTypes()) || 3668 (field_type->IsDouble() && insn_type.IsLongTypes())) { 3669 // expected that read is of the correct primitive type or that int reads are reading 3670 // floats or long reads are reading doubles 3671 } else { 3672 // This is a global failure rather than a class change failure as the instructions and 3673 // the descriptors for the type should have been consistent within the same file at 3674 // compile time 3675 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected field " << PrettyField(field) 3676 << " to be of type '" << insn_type 3677 << "' but found type '" << *field_type << "' in get"; 3678 return; 3679 } 3680 } else { 3681 if (!insn_type.IsAssignableFrom(*field_type)) { 3682 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "expected field " << PrettyField(field) 3683 << " to be compatible with type '" << insn_type 3684 << "' but found type '" << *field_type 3685 << "' in get-object"; 3686 work_line_->SetRegisterType(vregA, reg_types_.Conflict()); 3687 return; 3688 } 3689 } 3690 if (!field_type->IsLowHalf()) { 3691 work_line_->SetRegisterType(vregA, *field_type); 3692 } else { 3693 work_line_->SetRegisterTypeWide(vregA, *field_type, field_type->HighHalf(®_types_)); 3694 } 3695} 3696 3697void MethodVerifier::VerifyIPutQuick(const Instruction* inst, const RegType& insn_type, 3698 bool is_primitive) { 3699 DCHECK(Runtime::Current()->IsStarted()); 3700 mirror::ArtField* field = GetQuickFieldAccess(inst, work_line_.get()); 3701 if (field == NULL) { 3702 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Cannot infer field from " << inst->Name(); 3703 return; 3704 } 3705 const char* descriptor = FieldHelper(field).GetTypeDescriptor(); 3706 mirror::ClassLoader* loader = field->GetDeclaringClass()->GetClassLoader(); 3707 const RegType& field_type = reg_types_.FromDescriptor(loader, descriptor, false); 3708 if (field != NULL) { 3709 if (field->IsFinal() && field->GetDeclaringClass() != GetDeclaringClass().GetClass()) { 3710 Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot modify final field " << PrettyField(field) 3711 << " from other class " << GetDeclaringClass(); 3712 return; 3713 } 3714 } 3715 const uint32_t vregA = inst->VRegA_22c(); 3716 if (is_primitive) { 3717 // Primitive field assignability rules are weaker than regular assignability rules 3718 bool instruction_compatible; 3719 bool value_compatible; 3720 const RegType& value_type = work_line_->GetRegisterType(vregA); 3721 if (field_type.IsIntegralTypes()) { 3722 instruction_compatible = insn_type.IsIntegralTypes(); 3723 value_compatible = value_type.IsIntegralTypes(); 3724 } else if (field_type.IsFloat()) { 3725 instruction_compatible = insn_type.IsInteger(); // no [is]put-float, so expect [is]put-int 3726 value_compatible = value_type.IsFloatTypes(); 3727 } else if (field_type.IsLong()) { 3728 instruction_compatible = insn_type.IsLong(); 3729 value_compatible = value_type.IsLongTypes(); 3730 } else if (field_type.IsDouble()) { 3731 instruction_compatible = insn_type.IsLong(); // no [is]put-double, so expect [is]put-long 3732 value_compatible = value_type.IsDoubleTypes(); 3733 } else { 3734 instruction_compatible = false; // reference field with primitive store 3735 value_compatible = false; // unused 3736 } 3737 if (!instruction_compatible) { 3738 // This is a global failure rather than a class change failure as the instructions and 3739 // the descriptors for the type should have been consistent within the same file at 3740 // compile time 3741 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected field " << PrettyField(field) 3742 << " to be of type '" << insn_type 3743 << "' but found type '" << field_type 3744 << "' in put"; 3745 return; 3746 } 3747 if (!value_compatible) { 3748 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected value in v" << vregA 3749 << " of type " << value_type 3750 << " but expected " << field_type 3751 << " for store to " << PrettyField(field) << " in put"; 3752 return; 3753 } 3754 } else { 3755 if (!insn_type.IsAssignableFrom(field_type)) { 3756 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "expected field " << PrettyField(field) 3757 << " to be compatible with type '" << insn_type 3758 << "' but found type '" << field_type 3759 << "' in put-object"; 3760 return; 3761 } 3762 work_line_->VerifyRegisterType(vregA, field_type); 3763 } 3764} 3765 3766bool MethodVerifier::CheckNotMoveException(const uint16_t* insns, int insn_idx) { 3767 if ((insns[insn_idx] & 0xff) == Instruction::MOVE_EXCEPTION) { 3768 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid use of move-exception"; 3769 return false; 3770 } 3771 return true; 3772} 3773 3774bool MethodVerifier::UpdateRegisters(uint32_t next_insn, const RegisterLine* merge_line) { 3775 bool changed = true; 3776 RegisterLine* target_line = reg_table_.GetLine(next_insn); 3777 if (!insn_flags_[next_insn].IsVisitedOrChanged()) { 3778 /* 3779 * We haven't processed this instruction before, and we haven't touched the registers here, so 3780 * there's nothing to "merge". Copy the registers over and mark it as changed. (This is the 3781 * only way a register can transition out of "unknown", so this is not just an optimization.) 3782 */ 3783 if (!insn_flags_[next_insn].IsReturn()) { 3784 target_line->CopyFromLine(merge_line); 3785 } else { 3786 // Verify that the monitor stack is empty on return. 3787 if (!merge_line->VerifyMonitorStackEmpty()) { 3788 return false; 3789 } 3790 // For returns we only care about the operand to the return, all other registers are dead. 3791 // Initialize them as conflicts so they don't add to GC and deoptimization information. 3792 const Instruction* ret_inst = Instruction::At(code_item_->insns_ + next_insn); 3793 Instruction::Code opcode = ret_inst->Opcode(); 3794 if ((opcode == Instruction::RETURN_VOID) || (opcode == Instruction::RETURN_VOID_BARRIER)) { 3795 target_line->MarkAllRegistersAsConflicts(); 3796 } else { 3797 target_line->CopyFromLine(merge_line); 3798 if (opcode == Instruction::RETURN_WIDE) { 3799 target_line->MarkAllRegistersAsConflictsExceptWide(ret_inst->VRegA_11x()); 3800 } else { 3801 target_line->MarkAllRegistersAsConflictsExcept(ret_inst->VRegA_11x()); 3802 } 3803 } 3804 } 3805 } else { 3806 UniquePtr<RegisterLine> copy(gDebugVerify ? 3807 RegisterLine::Create(target_line->NumRegs(), this) : 3808 NULL); 3809 if (gDebugVerify) { 3810 copy->CopyFromLine(target_line); 3811 } 3812 changed = target_line->MergeRegisters(merge_line); 3813 if (have_pending_hard_failure_) { 3814 return false; 3815 } 3816 if (gDebugVerify && changed) { 3817 LogVerifyInfo() << "Merging at [" << reinterpret_cast<void*>(work_insn_idx_) << "]" 3818 << " to [" << reinterpret_cast<void*>(next_insn) << "]: " << "\n" 3819 << *copy.get() << " MERGE\n" 3820 << *merge_line << " ==\n" 3821 << *target_line << "\n"; 3822 } 3823 } 3824 if (changed) { 3825 insn_flags_[next_insn].SetChanged(); 3826 } 3827 return true; 3828} 3829 3830InstructionFlags* MethodVerifier::CurrentInsnFlags() { 3831 return &insn_flags_[work_insn_idx_]; 3832} 3833 3834const RegType& MethodVerifier::GetMethodReturnType() { 3835 if (return_type_ == nullptr) { 3836 if (mirror_method_ != NULL) { 3837 MethodHelper mh(mirror_method_); 3838 mirror::Class* return_type_class = mh.GetReturnType(can_load_classes_); 3839 if (return_type_class != nullptr) { 3840 return_type_ = ®_types_.FromClass(mh.GetReturnTypeDescriptor(), return_type_class, 3841 return_type_class->CannotBeAssignedFromOtherTypes()); 3842 } else { 3843 Thread* self = Thread::Current(); 3844 DCHECK(!can_load_classes_ || self->IsExceptionPending()); 3845 self->ClearException(); 3846 } 3847 } 3848 if (return_type_ == nullptr) { 3849 const DexFile::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx_); 3850 const DexFile::ProtoId& proto_id = dex_file_->GetMethodPrototype(method_id); 3851 uint16_t return_type_idx = proto_id.return_type_idx_; 3852 const char* descriptor = dex_file_->GetTypeDescriptor(dex_file_->GetTypeId(return_type_idx)); 3853 return_type_ = ®_types_.FromDescriptor(class_loader_->get(), descriptor, false); 3854 } 3855 } 3856 return *return_type_; 3857} 3858 3859const RegType& MethodVerifier::GetDeclaringClass() { 3860 if (declaring_class_ == NULL) { 3861 const DexFile::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx_); 3862 const char* descriptor 3863 = dex_file_->GetTypeDescriptor(dex_file_->GetTypeId(method_id.class_idx_)); 3864 if (mirror_method_ != NULL) { 3865 mirror::Class* klass = mirror_method_->GetDeclaringClass(); 3866 declaring_class_ = ®_types_.FromClass(descriptor, klass, 3867 klass->CannotBeAssignedFromOtherTypes()); 3868 } else { 3869 declaring_class_ = ®_types_.FromDescriptor(class_loader_->get(), descriptor, false); 3870 } 3871 } 3872 return *declaring_class_; 3873} 3874 3875std::vector<int32_t> MethodVerifier::DescribeVRegs(uint32_t dex_pc) { 3876 RegisterLine* line = reg_table_.GetLine(dex_pc); 3877 DCHECK(line != nullptr) << "No register line at DEX pc " << StringPrintf("0x%x", dex_pc); 3878 std::vector<int32_t> result; 3879 for (size_t i = 0; i < line->NumRegs(); ++i) { 3880 const RegType& type = line->GetRegisterType(i); 3881 if (type.IsConstant()) { 3882 result.push_back(type.IsPreciseConstant() ? kConstant : kImpreciseConstant); 3883 result.push_back(type.ConstantValue()); 3884 } else if (type.IsConstantLo()) { 3885 result.push_back(type.IsPreciseConstantLo() ? kConstant : kImpreciseConstant); 3886 result.push_back(type.ConstantValueLo()); 3887 } else if (type.IsConstantHi()) { 3888 result.push_back(type.IsPreciseConstantHi() ? kConstant : kImpreciseConstant); 3889 result.push_back(type.ConstantValueHi()); 3890 } else if (type.IsIntegralTypes()) { 3891 result.push_back(kIntVReg); 3892 result.push_back(0); 3893 } else if (type.IsFloat()) { 3894 result.push_back(kFloatVReg); 3895 result.push_back(0); 3896 } else if (type.IsLong()) { 3897 result.push_back(kLongLoVReg); 3898 result.push_back(0); 3899 result.push_back(kLongHiVReg); 3900 result.push_back(0); 3901 ++i; 3902 } else if (type.IsDouble()) { 3903 result.push_back(kDoubleLoVReg); 3904 result.push_back(0); 3905 result.push_back(kDoubleHiVReg); 3906 result.push_back(0); 3907 ++i; 3908 } else if (type.IsUndefined() || type.IsConflict() || type.IsHighHalf()) { 3909 result.push_back(kUndefined); 3910 result.push_back(0); 3911 } else { 3912 CHECK(type.IsNonZeroReferenceTypes()); 3913 result.push_back(kReferenceVReg); 3914 result.push_back(0); 3915 } 3916 } 3917 return result; 3918} 3919 3920const RegType& MethodVerifier::DetermineCat1Constant(int32_t value, bool precise) { 3921 if (precise) { 3922 // Precise constant type. 3923 return reg_types_.FromCat1Const(value, true); 3924 } else { 3925 // Imprecise constant type. 3926 if (value < -32768) { 3927 return reg_types_.IntConstant(); 3928 } else if (value < -128) { 3929 return reg_types_.ShortConstant(); 3930 } else if (value < 0) { 3931 return reg_types_.ByteConstant(); 3932 } else if (value == 0) { 3933 return reg_types_.Zero(); 3934 } else if (value == 1) { 3935 return reg_types_.One(); 3936 } else if (value < 128) { 3937 return reg_types_.PosByteConstant(); 3938 } else if (value < 32768) { 3939 return reg_types_.PosShortConstant(); 3940 } else if (value < 65536) { 3941 return reg_types_.CharConstant(); 3942 } else { 3943 return reg_types_.IntConstant(); 3944 } 3945 } 3946} 3947 3948void MethodVerifier::Init() { 3949 art::verifier::RegTypeCache::Init(); 3950} 3951 3952void MethodVerifier::Shutdown() { 3953 verifier::RegTypeCache::ShutDown(); 3954} 3955 3956void MethodVerifier::VisitRoots(RootCallback* callback, void* arg) { 3957 reg_types_.VisitRoots(callback, arg); 3958} 3959 3960} // namespace verifier 3961} // namespace art 3962