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