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