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