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