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