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