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