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