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