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