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