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