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