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