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