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