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