method_verifier.cc revision 4c6427a757cae2b1c79aafca71be780e54620e68
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      } else {
1778        Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array-length on non-array " << res_type;
1779      }
1780      break;
1781    }
1782    case Instruction::NEW_INSTANCE: {
1783      const RegType& res_type = ResolveClassAndCheckAccess(inst->VRegB_21c());
1784      if (res_type.IsConflict()) {
1785        DCHECK_NE(failures_.size(), 0U);
1786        break;  // bad class
1787      }
1788      // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved
1789      // can't create an instance of an interface or abstract class */
1790      if (!res_type.IsInstantiableTypes()) {
1791        Fail(VERIFY_ERROR_INSTANTIATION)
1792            << "new-instance on primitive, interface or abstract class" << res_type;
1793        // Soft failure so carry on to set register type.
1794      }
1795      const RegType& uninit_type = reg_types_.Uninitialized(res_type, work_insn_idx_);
1796      // Any registers holding previous allocations from this address that have not yet been
1797      // initialized must be marked invalid.
1798      work_line_->MarkUninitRefsAsInvalid(uninit_type);
1799      // add the new uninitialized reference to the register state
1800      work_line_->SetRegisterType(inst->VRegA_21c(), uninit_type);
1801      break;
1802    }
1803    case Instruction::NEW_ARRAY:
1804      VerifyNewArray(inst, false, false);
1805      break;
1806    case Instruction::FILLED_NEW_ARRAY:
1807      VerifyNewArray(inst, true, false);
1808      just_set_result = true;  // Filled new array sets result register
1809      break;
1810    case Instruction::FILLED_NEW_ARRAY_RANGE:
1811      VerifyNewArray(inst, true, true);
1812      just_set_result = true;  // Filled new array range sets result register
1813      break;
1814    case Instruction::CMPL_FLOAT:
1815    case Instruction::CMPG_FLOAT:
1816      if (!work_line_->VerifyRegisterType(inst->VRegB_23x(), reg_types_.Float())) {
1817        break;
1818      }
1819      if (!work_line_->VerifyRegisterType(inst->VRegC_23x(), reg_types_.Float())) {
1820        break;
1821      }
1822      work_line_->SetRegisterType(inst->VRegA_23x(), reg_types_.Integer());
1823      break;
1824    case Instruction::CMPL_DOUBLE:
1825    case Instruction::CMPG_DOUBLE:
1826      if (!work_line_->VerifyRegisterTypeWide(inst->VRegB_23x(), reg_types_.DoubleLo(),
1827                                              reg_types_.DoubleHi())) {
1828        break;
1829      }
1830      if (!work_line_->VerifyRegisterTypeWide(inst->VRegC_23x(), reg_types_.DoubleLo(),
1831                                              reg_types_.DoubleHi())) {
1832        break;
1833      }
1834      work_line_->SetRegisterType(inst->VRegA_23x(), reg_types_.Integer());
1835      break;
1836    case Instruction::CMP_LONG:
1837      if (!work_line_->VerifyRegisterTypeWide(inst->VRegB_23x(), reg_types_.LongLo(),
1838                                              reg_types_.LongHi())) {
1839        break;
1840      }
1841      if (!work_line_->VerifyRegisterTypeWide(inst->VRegC_23x(), reg_types_.LongLo(),
1842                                              reg_types_.LongHi())) {
1843        break;
1844      }
1845      work_line_->SetRegisterType(inst->VRegA_23x(), reg_types_.Integer());
1846      break;
1847    case Instruction::THROW: {
1848      const RegType& res_type = work_line_->GetRegisterType(inst->VRegA_11x());
1849      if (!reg_types_.JavaLangThrowable(false).IsAssignableFrom(res_type)) {
1850        Fail(res_type.IsUnresolvedTypes() ? VERIFY_ERROR_NO_CLASS : VERIFY_ERROR_BAD_CLASS_SOFT)
1851            << "thrown class " << res_type << " not instanceof Throwable";
1852      }
1853      break;
1854    }
1855    case Instruction::GOTO:
1856    case Instruction::GOTO_16:
1857    case Instruction::GOTO_32:
1858      /* no effect on or use of registers */
1859      break;
1860
1861    case Instruction::PACKED_SWITCH:
1862    case Instruction::SPARSE_SWITCH:
1863      /* verify that vAA is an integer, or can be converted to one */
1864      work_line_->VerifyRegisterType(inst->VRegA_31t(), reg_types_.Integer());
1865      break;
1866
1867    case Instruction::FILL_ARRAY_DATA: {
1868      /* Similar to the verification done for APUT */
1869      const RegType& array_type = work_line_->GetRegisterType(inst->VRegA_31t());
1870      /* array_type can be null if the reg type is Zero */
1871      if (!array_type.IsZero()) {
1872        if (!array_type.IsArrayTypes()) {
1873          Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid fill-array-data with array type "
1874                                            << array_type;
1875        } else {
1876          const RegType& component_type = reg_types_.GetComponentType(array_type,
1877                                                                      class_loader_->Get());
1878          DCHECK(!component_type.IsConflict());
1879          if (component_type.IsNonZeroReferenceTypes()) {
1880            Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid fill-array-data with component type "
1881                                              << component_type;
1882          } else {
1883            // Now verify if the element width in the table matches the element width declared in
1884            // the array
1885            const uint16_t* array_data = insns + (insns[1] | (((int32_t) insns[2]) << 16));
1886            if (array_data[0] != Instruction::kArrayDataSignature) {
1887              Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid magic for array-data";
1888            } else {
1889              size_t elem_width = Primitive::ComponentSize(component_type.GetPrimitiveType());
1890              // Since we don't compress the data in Dex, expect to see equal width of data stored
1891              // in the table and expected from the array class.
1892              if (array_data[1] != elem_width) {
1893                Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array-data size mismatch (" << array_data[1]
1894                                                  << " vs " << elem_width << ")";
1895              }
1896            }
1897          }
1898        }
1899      }
1900      break;
1901    }
1902    case Instruction::IF_EQ:
1903    case Instruction::IF_NE: {
1904      const RegType& reg_type1 = work_line_->GetRegisterType(inst->VRegA_22t());
1905      const RegType& reg_type2 = work_line_->GetRegisterType(inst->VRegB_22t());
1906      bool mismatch = false;
1907      if (reg_type1.IsZero()) {  // zero then integral or reference expected
1908        mismatch = !reg_type2.IsReferenceTypes() && !reg_type2.IsIntegralTypes();
1909      } else if (reg_type1.IsReferenceTypes()) {  // both references?
1910        mismatch = !reg_type2.IsReferenceTypes();
1911      } else {  // both integral?
1912        mismatch = !reg_type1.IsIntegralTypes() || !reg_type2.IsIntegralTypes();
1913      }
1914      if (mismatch) {
1915        Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "args to if-eq/if-ne (" << reg_type1 << ","
1916                                          << reg_type2 << ") must both be references or integral";
1917      }
1918      break;
1919    }
1920    case Instruction::IF_LT:
1921    case Instruction::IF_GE:
1922    case Instruction::IF_GT:
1923    case Instruction::IF_LE: {
1924      const RegType& reg_type1 = work_line_->GetRegisterType(inst->VRegA_22t());
1925      const RegType& reg_type2 = work_line_->GetRegisterType(inst->VRegB_22t());
1926      if (!reg_type1.IsIntegralTypes() || !reg_type2.IsIntegralTypes()) {
1927        Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "args to 'if' (" << reg_type1 << ","
1928                                          << reg_type2 << ") must be integral";
1929      }
1930      break;
1931    }
1932    case Instruction::IF_EQZ:
1933    case Instruction::IF_NEZ: {
1934      const RegType& reg_type = work_line_->GetRegisterType(inst->VRegA_21t());
1935      if (!reg_type.IsReferenceTypes() && !reg_type.IsIntegralTypes()) {
1936        Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "type " << reg_type
1937                                          << " unexpected as arg to if-eqz/if-nez";
1938      }
1939
1940      // Find previous instruction - its existence is a precondition to peephole optimization.
1941      uint32_t instance_of_idx = 0;
1942      if (0 != work_insn_idx_) {
1943        instance_of_idx = work_insn_idx_ - 1;
1944        while (0 != instance_of_idx && !insn_flags_[instance_of_idx].IsOpcode()) {
1945          instance_of_idx--;
1946        }
1947        CHECK(insn_flags_[instance_of_idx].IsOpcode());
1948      } else {
1949        break;
1950      }
1951
1952      const Instruction* instance_of_inst = Instruction::At(code_item_->insns_ + instance_of_idx);
1953
1954      /* Check for peep-hole pattern of:
1955       *    ...;
1956       *    instance-of vX, vY, T;
1957       *    ifXXX vX, label ;
1958       *    ...;
1959       * label:
1960       *    ...;
1961       * and sharpen the type of vY to be type T.
1962       * Note, this pattern can't be if:
1963       *  - if there are other branches to this branch,
1964       *  - when vX == vY.
1965       */
1966      if (!CurrentInsnFlags()->IsBranchTarget() &&
1967          (Instruction::INSTANCE_OF == instance_of_inst->Opcode()) &&
1968          (inst->VRegA_21t() == instance_of_inst->VRegA_22c()) &&
1969          (instance_of_inst->VRegA_22c() != instance_of_inst->VRegB_22c())) {
1970        // Check the type of the instance-of is different than that of registers type, as if they
1971        // are the same there is no work to be done here. Check that the conversion is not to or
1972        // from an unresolved type as type information is imprecise. If the instance-of is to an
1973        // interface then ignore the type information as interfaces can only be treated as Objects
1974        // and we don't want to disallow field and other operations on the object. If the value
1975        // being instance-of checked against is known null (zero) then allow the optimization as
1976        // we didn't have type information. If the merge of the instance-of type with the original
1977        // type is assignable to the original then allow optimization. This check is performed to
1978        // ensure that subsequent merges don't lose type information - such as becoming an
1979        // interface from a class that would lose information relevant to field checks.
1980        const RegType& orig_type = work_line_->GetRegisterType(instance_of_inst->VRegB_22c());
1981        const RegType& cast_type = ResolveClassAndCheckAccess(instance_of_inst->VRegC_22c());
1982
1983        if (!orig_type.Equals(cast_type) &&
1984            !cast_type.IsUnresolvedTypes() && !orig_type.IsUnresolvedTypes() &&
1985            cast_type.HasClass() &&             // Could be conflict type, make sure it has a class.
1986            !cast_type.GetClass()->IsInterface() &&
1987            (orig_type.IsZero() ||
1988                orig_type.IsStrictlyAssignableFrom(cast_type.Merge(orig_type, &reg_types_)))) {
1989          RegisterLine* update_line = RegisterLine::Create(code_item_->registers_size_, this);
1990          if (inst->Opcode() == Instruction::IF_EQZ) {
1991            fallthrough_line.reset(update_line);
1992          } else {
1993            branch_line.reset(update_line);
1994          }
1995          update_line->CopyFromLine(work_line_.get());
1996          update_line->SetRegisterType(instance_of_inst->VRegB_22c(), cast_type);
1997          if (!insn_flags_[instance_of_idx].IsBranchTarget() && 0 != instance_of_idx) {
1998            // See if instance-of was preceded by a move-object operation, common due to the small
1999            // register encoding space of instance-of, and propagate type information to the source
2000            // of the move-object.
2001            uint32_t move_idx = instance_of_idx - 1;
2002            while (0 != move_idx && !insn_flags_[move_idx].IsOpcode()) {
2003              move_idx--;
2004            }
2005            CHECK(insn_flags_[move_idx].IsOpcode());
2006            const Instruction* move_inst = Instruction::At(code_item_->insns_ + move_idx);
2007            switch (move_inst->Opcode()) {
2008              case Instruction::MOVE_OBJECT:
2009                if (move_inst->VRegA_12x() == instance_of_inst->VRegB_22c()) {
2010                  update_line->SetRegisterType(move_inst->VRegB_12x(), cast_type);
2011                }
2012                break;
2013              case Instruction::MOVE_OBJECT_FROM16:
2014                if (move_inst->VRegA_22x() == instance_of_inst->VRegB_22c()) {
2015                  update_line->SetRegisterType(move_inst->VRegB_22x(), cast_type);
2016                }
2017                break;
2018              case Instruction::MOVE_OBJECT_16:
2019                if (move_inst->VRegA_32x() == instance_of_inst->VRegB_22c()) {
2020                  update_line->SetRegisterType(move_inst->VRegB_32x(), cast_type);
2021                }
2022                break;
2023              default:
2024                break;
2025            }
2026          }
2027        }
2028      }
2029
2030      break;
2031    }
2032    case Instruction::IF_LTZ:
2033    case Instruction::IF_GEZ:
2034    case Instruction::IF_GTZ:
2035    case Instruction::IF_LEZ: {
2036      const RegType& reg_type = work_line_->GetRegisterType(inst->VRegA_21t());
2037      if (!reg_type.IsIntegralTypes()) {
2038        Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "type " << reg_type
2039                                          << " unexpected as arg to if-ltz/if-gez/if-gtz/if-lez";
2040      }
2041      break;
2042    }
2043    case Instruction::AGET_BOOLEAN:
2044      VerifyAGet(inst, reg_types_.Boolean(), true);
2045      break;
2046    case Instruction::AGET_BYTE:
2047      VerifyAGet(inst, reg_types_.Byte(), true);
2048      break;
2049    case Instruction::AGET_CHAR:
2050      VerifyAGet(inst, reg_types_.Char(), true);
2051      break;
2052    case Instruction::AGET_SHORT:
2053      VerifyAGet(inst, reg_types_.Short(), true);
2054      break;
2055    case Instruction::AGET:
2056      VerifyAGet(inst, reg_types_.Integer(), true);
2057      break;
2058    case Instruction::AGET_WIDE:
2059      VerifyAGet(inst, reg_types_.LongLo(), true);
2060      break;
2061    case Instruction::AGET_OBJECT:
2062      VerifyAGet(inst, reg_types_.JavaLangObject(false), false);
2063      break;
2064
2065    case Instruction::APUT_BOOLEAN:
2066      VerifyAPut(inst, reg_types_.Boolean(), true);
2067      break;
2068    case Instruction::APUT_BYTE:
2069      VerifyAPut(inst, reg_types_.Byte(), true);
2070      break;
2071    case Instruction::APUT_CHAR:
2072      VerifyAPut(inst, reg_types_.Char(), true);
2073      break;
2074    case Instruction::APUT_SHORT:
2075      VerifyAPut(inst, reg_types_.Short(), true);
2076      break;
2077    case Instruction::APUT:
2078      VerifyAPut(inst, reg_types_.Integer(), true);
2079      break;
2080    case Instruction::APUT_WIDE:
2081      VerifyAPut(inst, reg_types_.LongLo(), true);
2082      break;
2083    case Instruction::APUT_OBJECT:
2084      VerifyAPut(inst, reg_types_.JavaLangObject(false), false);
2085      break;
2086
2087    case Instruction::IGET_BOOLEAN:
2088      VerifyISGet(inst, reg_types_.Boolean(), true, false);
2089      break;
2090    case Instruction::IGET_BYTE:
2091      VerifyISGet(inst, reg_types_.Byte(), true, false);
2092      break;
2093    case Instruction::IGET_CHAR:
2094      VerifyISGet(inst, reg_types_.Char(), true, false);
2095      break;
2096    case Instruction::IGET_SHORT:
2097      VerifyISGet(inst, reg_types_.Short(), true, false);
2098      break;
2099    case Instruction::IGET:
2100      VerifyISGet(inst, reg_types_.Integer(), true, false);
2101      break;
2102    case Instruction::IGET_WIDE:
2103      VerifyISGet(inst, reg_types_.LongLo(), true, false);
2104      break;
2105    case Instruction::IGET_OBJECT:
2106      VerifyISGet(inst, reg_types_.JavaLangObject(false), false, false);
2107      break;
2108
2109    case Instruction::IPUT_BOOLEAN:
2110      VerifyISPut(inst, reg_types_.Boolean(), true, false);
2111      break;
2112    case Instruction::IPUT_BYTE:
2113      VerifyISPut(inst, reg_types_.Byte(), true, false);
2114      break;
2115    case Instruction::IPUT_CHAR:
2116      VerifyISPut(inst, reg_types_.Char(), true, false);
2117      break;
2118    case Instruction::IPUT_SHORT:
2119      VerifyISPut(inst, reg_types_.Short(), true, false);
2120      break;
2121    case Instruction::IPUT:
2122      VerifyISPut(inst, reg_types_.Integer(), true, false);
2123      break;
2124    case Instruction::IPUT_WIDE:
2125      VerifyISPut(inst, reg_types_.LongLo(), true, false);
2126      break;
2127    case Instruction::IPUT_OBJECT:
2128      VerifyISPut(inst, reg_types_.JavaLangObject(false), false, false);
2129      break;
2130
2131    case Instruction::SGET_BOOLEAN:
2132      VerifyISGet(inst, reg_types_.Boolean(), true, true);
2133      break;
2134    case Instruction::SGET_BYTE:
2135      VerifyISGet(inst, reg_types_.Byte(), true, true);
2136      break;
2137    case Instruction::SGET_CHAR:
2138      VerifyISGet(inst, reg_types_.Char(), true, true);
2139      break;
2140    case Instruction::SGET_SHORT:
2141      VerifyISGet(inst, reg_types_.Short(), true, true);
2142      break;
2143    case Instruction::SGET:
2144      VerifyISGet(inst, reg_types_.Integer(), true, true);
2145      break;
2146    case Instruction::SGET_WIDE:
2147      VerifyISGet(inst, reg_types_.LongLo(), true, true);
2148      break;
2149    case Instruction::SGET_OBJECT:
2150      VerifyISGet(inst, reg_types_.JavaLangObject(false), false, true);
2151      break;
2152
2153    case Instruction::SPUT_BOOLEAN:
2154      VerifyISPut(inst, reg_types_.Boolean(), true, true);
2155      break;
2156    case Instruction::SPUT_BYTE:
2157      VerifyISPut(inst, reg_types_.Byte(), true, true);
2158      break;
2159    case Instruction::SPUT_CHAR:
2160      VerifyISPut(inst, reg_types_.Char(), true, true);
2161      break;
2162    case Instruction::SPUT_SHORT:
2163      VerifyISPut(inst, reg_types_.Short(), true, true);
2164      break;
2165    case Instruction::SPUT:
2166      VerifyISPut(inst, reg_types_.Integer(), true, true);
2167      break;
2168    case Instruction::SPUT_WIDE:
2169      VerifyISPut(inst, reg_types_.LongLo(), true, true);
2170      break;
2171    case Instruction::SPUT_OBJECT:
2172      VerifyISPut(inst, reg_types_.JavaLangObject(false), false, true);
2173      break;
2174
2175    case Instruction::INVOKE_VIRTUAL:
2176    case Instruction::INVOKE_VIRTUAL_RANGE:
2177    case Instruction::INVOKE_SUPER:
2178    case Instruction::INVOKE_SUPER_RANGE: {
2179      bool is_range = (inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE ||
2180                       inst->Opcode() == Instruction::INVOKE_SUPER_RANGE);
2181      bool is_super = (inst->Opcode() == Instruction::INVOKE_SUPER ||
2182                       inst->Opcode() == Instruction::INVOKE_SUPER_RANGE);
2183      mirror::ArtMethod* called_method = VerifyInvocationArgs(inst, METHOD_VIRTUAL, is_range,
2184                                                              is_super);
2185      const RegType* return_type = nullptr;
2186      if (called_method != nullptr) {
2187        Thread* self = Thread::Current();
2188        StackHandleScope<1> hs(self);
2189        Handle<mirror::ArtMethod> h_called_method(hs.NewHandle(called_method));
2190        MethodHelper mh(h_called_method);
2191        mirror::Class* return_type_class = mh.GetReturnType(can_load_classes_);
2192        if (return_type_class != nullptr) {
2193          return_type = &reg_types_.FromClass(h_called_method->GetReturnTypeDescriptor(),
2194                                              return_type_class,
2195                                              return_type_class->CannotBeAssignedFromOtherTypes());
2196        } else {
2197          DCHECK(!can_load_classes_ || self->IsExceptionPending());
2198          self->ClearException();
2199        }
2200      }
2201      if (return_type == nullptr) {
2202        uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c();
2203        const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx);
2204        uint32_t return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_;
2205        const char* descriptor = dex_file_->StringByTypeIdx(return_type_idx);
2206        return_type = &reg_types_.FromDescriptor(class_loader_->Get(), descriptor, false);
2207      }
2208      if (!return_type->IsLowHalf()) {
2209        work_line_->SetResultRegisterType(*return_type);
2210      } else {
2211        work_line_->SetResultRegisterTypeWide(*return_type, return_type->HighHalf(&reg_types_));
2212      }
2213      just_set_result = true;
2214      break;
2215    }
2216    case Instruction::INVOKE_DIRECT:
2217    case Instruction::INVOKE_DIRECT_RANGE: {
2218      bool is_range = (inst->Opcode() == Instruction::INVOKE_DIRECT_RANGE);
2219      mirror::ArtMethod* called_method = VerifyInvocationArgs(inst, METHOD_DIRECT,
2220                                                                   is_range, false);
2221      const char* return_type_descriptor;
2222      bool is_constructor;
2223      if (called_method == NULL) {
2224        uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c();
2225        const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx);
2226        is_constructor = strcmp("<init>", dex_file_->StringDataByIdx(method_id.name_idx_)) == 0;
2227        uint32_t return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_;
2228        return_type_descriptor =  dex_file_->StringByTypeIdx(return_type_idx);
2229      } else {
2230        is_constructor = called_method->IsConstructor();
2231        return_type_descriptor = called_method->GetReturnTypeDescriptor();
2232      }
2233      if (is_constructor) {
2234        /*
2235         * Some additional checks when calling a constructor. We know from the invocation arg check
2236         * that the "this" argument is an instance of called_method->klass. Now we further restrict
2237         * that to require that called_method->klass is the same as this->klass or this->super,
2238         * allowing the latter only if the "this" argument is the same as the "this" argument to
2239         * this method (which implies that we're in a constructor ourselves).
2240         */
2241        const RegType& this_type = work_line_->GetInvocationThis(inst, is_range);
2242        if (this_type.IsConflict())  // failure.
2243          break;
2244
2245        /* no null refs allowed (?) */
2246        if (this_type.IsZero()) {
2247          Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unable to initialize null ref";
2248          break;
2249        }
2250
2251        /* must be in same class or in superclass */
2252        // const RegType& this_super_klass = this_type.GetSuperClass(&reg_types_);
2253        // TODO: re-enable constructor type verification
2254        // if (this_super_klass.IsConflict()) {
2255          // Unknown super class, fail so we re-check at runtime.
2256          // Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "super class unknown for '" << this_type << "'";
2257          // break;
2258        // }
2259
2260        /* arg must be an uninitialized reference */
2261        if (!this_type.IsUninitializedTypes()) {
2262          Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Expected initialization on uninitialized reference "
2263              << this_type;
2264          break;
2265        }
2266
2267        /*
2268         * Replace the uninitialized reference with an initialized one. We need to do this for all
2269         * registers that have the same object instance in them, not just the "this" register.
2270         */
2271        work_line_->MarkRefsAsInitialized(this_type);
2272      }
2273      const RegType& return_type = reg_types_.FromDescriptor(class_loader_->Get(),
2274                                                             return_type_descriptor, false);
2275      if (!return_type.IsLowHalf()) {
2276        work_line_->SetResultRegisterType(return_type);
2277      } else {
2278        work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(&reg_types_));
2279      }
2280      just_set_result = true;
2281      break;
2282    }
2283    case Instruction::INVOKE_STATIC:
2284    case Instruction::INVOKE_STATIC_RANGE: {
2285        bool is_range = (inst->Opcode() == Instruction::INVOKE_STATIC_RANGE);
2286        mirror::ArtMethod* called_method = VerifyInvocationArgs(inst,
2287                                                                     METHOD_STATIC,
2288                                                                     is_range,
2289                                                                     false);
2290        const char* descriptor;
2291        if (called_method == NULL) {
2292          uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c();
2293          const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx);
2294          uint32_t return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_;
2295          descriptor = dex_file_->StringByTypeIdx(return_type_idx);
2296        } else {
2297          descriptor = called_method->GetReturnTypeDescriptor();
2298        }
2299        const RegType& return_type = reg_types_.FromDescriptor(class_loader_->Get(), descriptor,
2300                                                               false);
2301        if (!return_type.IsLowHalf()) {
2302          work_line_->SetResultRegisterType(return_type);
2303        } else {
2304          work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(&reg_types_));
2305        }
2306        just_set_result = true;
2307      }
2308      break;
2309    case Instruction::INVOKE_INTERFACE:
2310    case Instruction::INVOKE_INTERFACE_RANGE: {
2311      bool is_range =  (inst->Opcode() == Instruction::INVOKE_INTERFACE_RANGE);
2312      mirror::ArtMethod* abs_method = VerifyInvocationArgs(inst,
2313                                                                METHOD_INTERFACE,
2314                                                                is_range,
2315                                                                false);
2316      if (abs_method != NULL) {
2317        mirror::Class* called_interface = abs_method->GetDeclaringClass();
2318        if (!called_interface->IsInterface() && !called_interface->IsObjectClass()) {
2319          Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected interface class in invoke-interface '"
2320              << PrettyMethod(abs_method) << "'";
2321          break;
2322        }
2323      }
2324      /* Get the type of the "this" arg, which should either be a sub-interface of called
2325       * interface or Object (see comments in RegType::JoinClass).
2326       */
2327      const RegType& this_type = work_line_->GetInvocationThis(inst, is_range);
2328      if (this_type.IsZero()) {
2329        /* null pointer always passes (and always fails at runtime) */
2330      } else {
2331        if (this_type.IsUninitializedTypes()) {
2332          Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "interface call on uninitialized object "
2333              << this_type;
2334          break;
2335        }
2336        // In the past we have tried to assert that "called_interface" is assignable
2337        // from "this_type.GetClass()", however, as we do an imprecise Join
2338        // (RegType::JoinClass) we don't have full information on what interfaces are
2339        // implemented by "this_type". For example, two classes may implement the same
2340        // interfaces and have a common parent that doesn't implement the interface. The
2341        // join will set "this_type" to the parent class and a test that this implements
2342        // the interface will incorrectly fail.
2343      }
2344      /*
2345       * We don't have an object instance, so we can't find the concrete method. However, all of
2346       * the type information is in the abstract method, so we're good.
2347       */
2348      const char* descriptor;
2349      if (abs_method == NULL) {
2350        uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c();
2351        const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx);
2352        uint32_t return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_;
2353        descriptor =  dex_file_->StringByTypeIdx(return_type_idx);
2354      } else {
2355        descriptor = abs_method->GetReturnTypeDescriptor();
2356      }
2357      const RegType& return_type = reg_types_.FromDescriptor(class_loader_->Get(), descriptor,
2358                                                             false);
2359      if (!return_type.IsLowHalf()) {
2360        work_line_->SetResultRegisterType(return_type);
2361      } else {
2362        work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(&reg_types_));
2363      }
2364      just_set_result = true;
2365      break;
2366    }
2367    case Instruction::NEG_INT:
2368    case Instruction::NOT_INT:
2369      work_line_->CheckUnaryOp(inst, reg_types_.Integer(), reg_types_.Integer());
2370      break;
2371    case Instruction::NEG_LONG:
2372    case Instruction::NOT_LONG:
2373      work_line_->CheckUnaryOpWide(inst, reg_types_.LongLo(), reg_types_.LongHi(),
2374                                   reg_types_.LongLo(), reg_types_.LongHi());
2375      break;
2376    case Instruction::NEG_FLOAT:
2377      work_line_->CheckUnaryOp(inst, reg_types_.Float(), reg_types_.Float());
2378      break;
2379    case Instruction::NEG_DOUBLE:
2380      work_line_->CheckUnaryOpWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(),
2381                                   reg_types_.DoubleLo(), reg_types_.DoubleHi());
2382      break;
2383    case Instruction::INT_TO_LONG:
2384      work_line_->CheckUnaryOpToWide(inst, reg_types_.LongLo(), reg_types_.LongHi(),
2385                                     reg_types_.Integer());
2386      break;
2387    case Instruction::INT_TO_FLOAT:
2388      work_line_->CheckUnaryOp(inst, reg_types_.Float(), reg_types_.Integer());
2389      break;
2390    case Instruction::INT_TO_DOUBLE:
2391      work_line_->CheckUnaryOpToWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(),
2392                                     reg_types_.Integer());
2393      break;
2394    case Instruction::LONG_TO_INT:
2395      work_line_->CheckUnaryOpFromWide(inst, reg_types_.Integer(),
2396                                       reg_types_.LongLo(), reg_types_.LongHi());
2397      break;
2398    case Instruction::LONG_TO_FLOAT:
2399      work_line_->CheckUnaryOpFromWide(inst, reg_types_.Float(),
2400                                       reg_types_.LongLo(), reg_types_.LongHi());
2401      break;
2402    case Instruction::LONG_TO_DOUBLE:
2403      work_line_->CheckUnaryOpWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(),
2404                                   reg_types_.LongLo(), reg_types_.LongHi());
2405      break;
2406    case Instruction::FLOAT_TO_INT:
2407      work_line_->CheckUnaryOp(inst, reg_types_.Integer(), reg_types_.Float());
2408      break;
2409    case Instruction::FLOAT_TO_LONG:
2410      work_line_->CheckUnaryOpToWide(inst, reg_types_.LongLo(), reg_types_.LongHi(),
2411                                     reg_types_.Float());
2412      break;
2413    case Instruction::FLOAT_TO_DOUBLE:
2414      work_line_->CheckUnaryOpToWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(),
2415                                     reg_types_.Float());
2416      break;
2417    case Instruction::DOUBLE_TO_INT:
2418      work_line_->CheckUnaryOpFromWide(inst, reg_types_.Integer(),
2419                                       reg_types_.DoubleLo(), reg_types_.DoubleHi());
2420      break;
2421    case Instruction::DOUBLE_TO_LONG:
2422      work_line_->CheckUnaryOpWide(inst, reg_types_.LongLo(), reg_types_.LongHi(),
2423                                   reg_types_.DoubleLo(), reg_types_.DoubleHi());
2424      break;
2425    case Instruction::DOUBLE_TO_FLOAT:
2426      work_line_->CheckUnaryOpFromWide(inst, reg_types_.Float(),
2427                                       reg_types_.DoubleLo(), reg_types_.DoubleHi());
2428      break;
2429    case Instruction::INT_TO_BYTE:
2430      work_line_->CheckUnaryOp(inst, reg_types_.Byte(), reg_types_.Integer());
2431      break;
2432    case Instruction::INT_TO_CHAR:
2433      work_line_->CheckUnaryOp(inst, reg_types_.Char(), reg_types_.Integer());
2434      break;
2435    case Instruction::INT_TO_SHORT:
2436      work_line_->CheckUnaryOp(inst, reg_types_.Short(), reg_types_.Integer());
2437      break;
2438
2439    case Instruction::ADD_INT:
2440    case Instruction::SUB_INT:
2441    case Instruction::MUL_INT:
2442    case Instruction::REM_INT:
2443    case Instruction::DIV_INT:
2444    case Instruction::SHL_INT:
2445    case Instruction::SHR_INT:
2446    case Instruction::USHR_INT:
2447      work_line_->CheckBinaryOp(inst, reg_types_.Integer(), reg_types_.Integer(),
2448                                reg_types_.Integer(), false);
2449      break;
2450    case Instruction::AND_INT:
2451    case Instruction::OR_INT:
2452    case Instruction::XOR_INT:
2453      work_line_->CheckBinaryOp(inst, reg_types_.Integer(), reg_types_.Integer(),
2454                                reg_types_.Integer(), true);
2455      break;
2456    case Instruction::ADD_LONG:
2457    case Instruction::SUB_LONG:
2458    case Instruction::MUL_LONG:
2459    case Instruction::DIV_LONG:
2460    case Instruction::REM_LONG:
2461    case Instruction::AND_LONG:
2462    case Instruction::OR_LONG:
2463    case Instruction::XOR_LONG:
2464      work_line_->CheckBinaryOpWide(inst, reg_types_.LongLo(), reg_types_.LongHi(),
2465                                    reg_types_.LongLo(), reg_types_.LongHi(),
2466                                    reg_types_.LongLo(), reg_types_.LongHi());
2467      break;
2468    case Instruction::SHL_LONG:
2469    case Instruction::SHR_LONG:
2470    case Instruction::USHR_LONG:
2471      /* shift distance is Int, making these different from other binary operations */
2472      work_line_->CheckBinaryOpWideShift(inst, reg_types_.LongLo(), reg_types_.LongHi(),
2473                                         reg_types_.Integer());
2474      break;
2475    case Instruction::ADD_FLOAT:
2476    case Instruction::SUB_FLOAT:
2477    case Instruction::MUL_FLOAT:
2478    case Instruction::DIV_FLOAT:
2479    case Instruction::REM_FLOAT:
2480      work_line_->CheckBinaryOp(inst,
2481                                reg_types_.Float(),
2482                                reg_types_.Float(),
2483                                reg_types_.Float(),
2484                                false);
2485      break;
2486    case Instruction::ADD_DOUBLE:
2487    case Instruction::SUB_DOUBLE:
2488    case Instruction::MUL_DOUBLE:
2489    case Instruction::DIV_DOUBLE:
2490    case Instruction::REM_DOUBLE:
2491      work_line_->CheckBinaryOpWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(),
2492                                    reg_types_.DoubleLo(), reg_types_.DoubleHi(),
2493                                    reg_types_.DoubleLo(), reg_types_.DoubleHi());
2494      break;
2495    case Instruction::ADD_INT_2ADDR:
2496    case Instruction::SUB_INT_2ADDR:
2497    case Instruction::MUL_INT_2ADDR:
2498    case Instruction::REM_INT_2ADDR:
2499    case Instruction::SHL_INT_2ADDR:
2500    case Instruction::SHR_INT_2ADDR:
2501    case Instruction::USHR_INT_2ADDR:
2502      work_line_->CheckBinaryOp2addr(inst,
2503                                     reg_types_.Integer(),
2504                                     reg_types_.Integer(),
2505                                     reg_types_.Integer(),
2506                                     false);
2507      break;
2508    case Instruction::AND_INT_2ADDR:
2509    case Instruction::OR_INT_2ADDR:
2510    case Instruction::XOR_INT_2ADDR:
2511      work_line_->CheckBinaryOp2addr(inst,
2512                                     reg_types_.Integer(),
2513                                     reg_types_.Integer(),
2514                                     reg_types_.Integer(),
2515                                     true);
2516      break;
2517    case Instruction::DIV_INT_2ADDR:
2518      work_line_->CheckBinaryOp2addr(inst,
2519                                     reg_types_.Integer(),
2520                                     reg_types_.Integer(),
2521                                     reg_types_.Integer(),
2522                                     false);
2523      break;
2524    case Instruction::ADD_LONG_2ADDR:
2525    case Instruction::SUB_LONG_2ADDR:
2526    case Instruction::MUL_LONG_2ADDR:
2527    case Instruction::DIV_LONG_2ADDR:
2528    case Instruction::REM_LONG_2ADDR:
2529    case Instruction::AND_LONG_2ADDR:
2530    case Instruction::OR_LONG_2ADDR:
2531    case Instruction::XOR_LONG_2ADDR:
2532      work_line_->CheckBinaryOp2addrWide(inst, reg_types_.LongLo(), reg_types_.LongHi(),
2533                                         reg_types_.LongLo(), reg_types_.LongHi(),
2534                                         reg_types_.LongLo(), reg_types_.LongHi());
2535      break;
2536    case Instruction::SHL_LONG_2ADDR:
2537    case Instruction::SHR_LONG_2ADDR:
2538    case Instruction::USHR_LONG_2ADDR:
2539      work_line_->CheckBinaryOp2addrWideShift(inst, reg_types_.LongLo(), reg_types_.LongHi(),
2540                                              reg_types_.Integer());
2541      break;
2542    case Instruction::ADD_FLOAT_2ADDR:
2543    case Instruction::SUB_FLOAT_2ADDR:
2544    case Instruction::MUL_FLOAT_2ADDR:
2545    case Instruction::DIV_FLOAT_2ADDR:
2546    case Instruction::REM_FLOAT_2ADDR:
2547      work_line_->CheckBinaryOp2addr(inst,
2548                                     reg_types_.Float(),
2549                                     reg_types_.Float(),
2550                                     reg_types_.Float(),
2551                                     false);
2552      break;
2553    case Instruction::ADD_DOUBLE_2ADDR:
2554    case Instruction::SUB_DOUBLE_2ADDR:
2555    case Instruction::MUL_DOUBLE_2ADDR:
2556    case Instruction::DIV_DOUBLE_2ADDR:
2557    case Instruction::REM_DOUBLE_2ADDR:
2558      work_line_->CheckBinaryOp2addrWide(inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(),
2559                                         reg_types_.DoubleLo(),  reg_types_.DoubleHi(),
2560                                         reg_types_.DoubleLo(), reg_types_.DoubleHi());
2561      break;
2562    case Instruction::ADD_INT_LIT16:
2563    case Instruction::RSUB_INT:
2564    case Instruction::MUL_INT_LIT16:
2565    case Instruction::DIV_INT_LIT16:
2566    case Instruction::REM_INT_LIT16:
2567      work_line_->CheckLiteralOp(inst, reg_types_.Integer(), reg_types_.Integer(), false, true);
2568      break;
2569    case Instruction::AND_INT_LIT16:
2570    case Instruction::OR_INT_LIT16:
2571    case Instruction::XOR_INT_LIT16:
2572      work_line_->CheckLiteralOp(inst, reg_types_.Integer(), reg_types_.Integer(), true, true);
2573      break;
2574    case Instruction::ADD_INT_LIT8:
2575    case Instruction::RSUB_INT_LIT8:
2576    case Instruction::MUL_INT_LIT8:
2577    case Instruction::DIV_INT_LIT8:
2578    case Instruction::REM_INT_LIT8:
2579    case Instruction::SHL_INT_LIT8:
2580    case Instruction::SHR_INT_LIT8:
2581    case Instruction::USHR_INT_LIT8:
2582      work_line_->CheckLiteralOp(inst, reg_types_.Integer(), reg_types_.Integer(), false, false);
2583      break;
2584    case Instruction::AND_INT_LIT8:
2585    case Instruction::OR_INT_LIT8:
2586    case Instruction::XOR_INT_LIT8:
2587      work_line_->CheckLiteralOp(inst, reg_types_.Integer(), reg_types_.Integer(), true, false);
2588      break;
2589
2590    // Special instructions.
2591    case Instruction::RETURN_VOID_BARRIER:
2592      if (!IsConstructor() || IsStatic()) {
2593          Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-void-barrier not expected";
2594      }
2595      break;
2596    // Note: the following instructions encode offsets derived from class linking.
2597    // As such they use Class*/Field*/AbstractMethod* as these offsets only have
2598    // meaning if the class linking and resolution were successful.
2599    case Instruction::IGET_QUICK:
2600      VerifyIGetQuick(inst, reg_types_.Integer(), true);
2601      break;
2602    case Instruction::IGET_WIDE_QUICK:
2603      VerifyIGetQuick(inst, reg_types_.LongLo(), true);
2604      break;
2605    case Instruction::IGET_OBJECT_QUICK:
2606      VerifyIGetQuick(inst, reg_types_.JavaLangObject(false), false);
2607      break;
2608    case Instruction::IPUT_QUICK:
2609      VerifyIPutQuick(inst, reg_types_.Integer(), true);
2610      break;
2611    case Instruction::IPUT_WIDE_QUICK:
2612      VerifyIPutQuick(inst, reg_types_.LongLo(), true);
2613      break;
2614    case Instruction::IPUT_OBJECT_QUICK:
2615      VerifyIPutQuick(inst, reg_types_.JavaLangObject(false), false);
2616      break;
2617    case Instruction::INVOKE_VIRTUAL_QUICK:
2618    case Instruction::INVOKE_VIRTUAL_RANGE_QUICK: {
2619      bool is_range = (inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE_QUICK);
2620      mirror::ArtMethod* called_method = VerifyInvokeVirtualQuickArgs(inst, is_range);
2621      if (called_method != NULL) {
2622        const char* descriptor = called_method->GetReturnTypeDescriptor();
2623        const RegType& return_type = reg_types_.FromDescriptor(class_loader_->Get(), descriptor,
2624                                                               false);
2625        if (!return_type.IsLowHalf()) {
2626          work_line_->SetResultRegisterType(return_type);
2627        } else {
2628          work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(&reg_types_));
2629        }
2630        just_set_result = true;
2631      }
2632      break;
2633    }
2634
2635    /* These should never appear during verification. */
2636    case Instruction::UNUSED_3E:
2637    case Instruction::UNUSED_3F:
2638    case Instruction::UNUSED_40:
2639    case Instruction::UNUSED_41:
2640    case Instruction::UNUSED_42:
2641    case Instruction::UNUSED_43:
2642    case Instruction::UNUSED_79:
2643    case Instruction::UNUSED_7A:
2644    case Instruction::UNUSED_EB:
2645    case Instruction::UNUSED_EC:
2646    case Instruction::UNUSED_ED:
2647    case Instruction::UNUSED_EE:
2648    case Instruction::UNUSED_EF:
2649    case Instruction::UNUSED_F0:
2650    case Instruction::UNUSED_F1:
2651    case Instruction::UNUSED_F2:
2652    case Instruction::UNUSED_F3:
2653    case Instruction::UNUSED_F4:
2654    case Instruction::UNUSED_F5:
2655    case Instruction::UNUSED_F6:
2656    case Instruction::UNUSED_F7:
2657    case Instruction::UNUSED_F8:
2658    case Instruction::UNUSED_F9:
2659    case Instruction::UNUSED_FA:
2660    case Instruction::UNUSED_FB:
2661    case Instruction::UNUSED_FC:
2662    case Instruction::UNUSED_FD:
2663    case Instruction::UNUSED_FE:
2664    case Instruction::UNUSED_FF:
2665      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Unexpected opcode " << inst->DumpString(dex_file_);
2666      break;
2667
2668    /*
2669     * DO NOT add a "default" clause here. Without it the compiler will
2670     * complain if an instruction is missing (which is desirable).
2671     */
2672  }  // end - switch (dec_insn.opcode)
2673
2674  if (have_pending_hard_failure_) {
2675    if (Runtime::Current()->IsCompiler()) {
2676      /* When compiling, check that the last failure is a hard failure */
2677      CHECK_EQ(failures_[failures_.size() - 1], VERIFY_ERROR_BAD_CLASS_HARD);
2678    }
2679    /* immediate failure, reject class */
2680    info_messages_ << "Rejecting opcode " << inst->DumpString(dex_file_);
2681    return false;
2682  } else if (have_pending_runtime_throw_failure_) {
2683    /* checking interpreter will throw, mark following code as unreachable */
2684    opcode_flags = Instruction::kThrow;
2685  }
2686  /*
2687   * If we didn't just set the result register, clear it out. This ensures that you can only use
2688   * "move-result" immediately after the result is set. (We could check this statically, but it's
2689   * not expensive and it makes our debugging output cleaner.)
2690   */
2691  if (!just_set_result) {
2692    work_line_->SetResultTypeToUnknown();
2693  }
2694
2695
2696
2697  /*
2698   * Handle "branch". Tag the branch target.
2699   *
2700   * NOTE: instructions like Instruction::EQZ provide information about the
2701   * state of the register when the branch is taken or not taken. For example,
2702   * somebody could get a reference field, check it for zero, and if the
2703   * branch is taken immediately store that register in a boolean field
2704   * since the value is known to be zero. We do not currently account for
2705   * that, and will reject the code.
2706   *
2707   * TODO: avoid re-fetching the branch target
2708   */
2709  if ((opcode_flags & Instruction::kBranch) != 0) {
2710    bool isConditional, selfOkay;
2711    if (!GetBranchOffset(work_insn_idx_, &branch_target, &isConditional, &selfOkay)) {
2712      /* should never happen after static verification */
2713      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad branch";
2714      return false;
2715    }
2716    DCHECK_EQ(isConditional, (opcode_flags & Instruction::kContinue) != 0);
2717    if (!CheckNotMoveException(code_item_->insns_, work_insn_idx_ + branch_target)) {
2718      return false;
2719    }
2720    /* update branch target, set "changed" if appropriate */
2721    if (NULL != branch_line.get()) {
2722      if (!UpdateRegisters(work_insn_idx_ + branch_target, branch_line.get(), false)) {
2723        return false;
2724      }
2725    } else {
2726      if (!UpdateRegisters(work_insn_idx_ + branch_target, work_line_.get(), false)) {
2727        return false;
2728      }
2729    }
2730  }
2731
2732  /*
2733   * Handle "switch". Tag all possible branch targets.
2734   *
2735   * We've already verified that the table is structurally sound, so we
2736   * just need to walk through and tag the targets.
2737   */
2738  if ((opcode_flags & Instruction::kSwitch) != 0) {
2739    int offset_to_switch = insns[1] | (((int32_t) insns[2]) << 16);
2740    const uint16_t* switch_insns = insns + offset_to_switch;
2741    int switch_count = switch_insns[1];
2742    int offset_to_targets, targ;
2743
2744    if ((*insns & 0xff) == Instruction::PACKED_SWITCH) {
2745      /* 0 = sig, 1 = count, 2/3 = first key */
2746      offset_to_targets = 4;
2747    } else {
2748      /* 0 = sig, 1 = count, 2..count * 2 = keys */
2749      DCHECK((*insns & 0xff) == Instruction::SPARSE_SWITCH);
2750      offset_to_targets = 2 + 2 * switch_count;
2751    }
2752
2753    /* verify each switch target */
2754    for (targ = 0; targ < switch_count; targ++) {
2755      int offset;
2756      uint32_t abs_offset;
2757
2758      /* offsets are 32-bit, and only partly endian-swapped */
2759      offset = switch_insns[offset_to_targets + targ * 2] |
2760         (((int32_t) switch_insns[offset_to_targets + targ * 2 + 1]) << 16);
2761      abs_offset = work_insn_idx_ + offset;
2762      DCHECK_LT(abs_offset, code_item_->insns_size_in_code_units_);
2763      if (!CheckNotMoveException(code_item_->insns_, abs_offset)) {
2764        return false;
2765      }
2766      if (!UpdateRegisters(abs_offset, work_line_.get(), false)) {
2767        return false;
2768      }
2769    }
2770  }
2771
2772  /*
2773   * Handle instructions that can throw and that are sitting in a "try" block. (If they're not in a
2774   * "try" block when they throw, control transfers out of the method.)
2775   */
2776  if ((opcode_flags & Instruction::kThrow) != 0 && insn_flags_[work_insn_idx_].IsInTry()) {
2777    bool has_catch_all_handler = false;
2778    CatchHandlerIterator iterator(*code_item_, work_insn_idx_);
2779
2780    // Need the linker to try and resolve the handled class to check if it's Throwable.
2781    ClassLinker* linker = Runtime::Current()->GetClassLinker();
2782
2783    for (; iterator.HasNext(); iterator.Next()) {
2784      uint16_t handler_type_idx = iterator.GetHandlerTypeIndex();
2785      if (handler_type_idx == DexFile::kDexNoIndex16) {
2786        has_catch_all_handler = true;
2787      } else {
2788        // It is also a catch-all if it is java.lang.Throwable.
2789        mirror::Class* klass = linker->ResolveType(*dex_file_, handler_type_idx, *dex_cache_,
2790                                                   *class_loader_);
2791        if (klass != nullptr) {
2792          if (klass == mirror::Throwable::GetJavaLangThrowable()) {
2793            has_catch_all_handler = true;
2794          }
2795        } else {
2796          // Clear exception.
2797          Thread* self = Thread::Current();
2798          DCHECK(self->IsExceptionPending());
2799          self->ClearException();
2800        }
2801      }
2802      /*
2803       * Merge registers into the "catch" block. We want to use the "savedRegs" rather than
2804       * "work_regs", because at runtime the exception will be thrown before the instruction
2805       * modifies any registers.
2806       */
2807      if (!UpdateRegisters(iterator.GetHandlerAddress(), saved_line_.get(), false)) {
2808        return false;
2809      }
2810    }
2811
2812    /*
2813     * If the monitor stack depth is nonzero, there must be a "catch all" handler for this
2814     * instruction. This does apply to monitor-exit because of async exception handling.
2815     */
2816    if (work_line_->MonitorStackDepth() > 0 && !has_catch_all_handler) {
2817      /*
2818       * The state in work_line reflects the post-execution state. If the current instruction is a
2819       * monitor-enter and the monitor stack was empty, we don't need a catch-all (if it throws,
2820       * it will do so before grabbing the lock).
2821       */
2822      if (inst->Opcode() != Instruction::MONITOR_ENTER || work_line_->MonitorStackDepth() != 1) {
2823        Fail(VERIFY_ERROR_BAD_CLASS_HARD)
2824            << "expected to be within a catch-all for an instruction where a monitor is held";
2825        return false;
2826      }
2827    }
2828  }
2829
2830  /* Handle "continue". Tag the next consecutive instruction.
2831   *  Note: Keep the code handling "continue" case below the "branch" and "switch" cases,
2832   *        because it changes work_line_ when performing peephole optimization
2833   *        and this change should not be used in those cases.
2834   */
2835  if ((opcode_flags & Instruction::kContinue) != 0) {
2836    uint32_t next_insn_idx = work_insn_idx_ + CurrentInsnFlags()->GetLengthInCodeUnits();
2837    if (next_insn_idx >= code_item_->insns_size_in_code_units_) {
2838      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Execution can walk off end of code area";
2839      return false;
2840    }
2841    // The only way to get to a move-exception instruction is to get thrown there. Make sure the
2842    // next instruction isn't one.
2843    if (!CheckNotMoveException(code_item_->insns_, next_insn_idx)) {
2844      return false;
2845    }
2846    if (NULL != fallthrough_line.get()) {
2847      // Make workline consistent with fallthrough computed from peephole optimization.
2848      work_line_->CopyFromLine(fallthrough_line.get());
2849    }
2850    if (insn_flags_[next_insn_idx].IsReturn()) {
2851      // For returns we only care about the operand to the return, all other registers are dead.
2852      const Instruction* ret_inst = Instruction::At(code_item_->insns_ + next_insn_idx);
2853      Instruction::Code opcode = ret_inst->Opcode();
2854      if ((opcode == Instruction::RETURN_VOID) || (opcode == Instruction::RETURN_VOID_BARRIER)) {
2855        work_line_->MarkAllRegistersAsConflicts();
2856      } else {
2857        if (opcode == Instruction::RETURN_WIDE) {
2858          work_line_->MarkAllRegistersAsConflictsExceptWide(ret_inst->VRegA_11x());
2859        } else {
2860          work_line_->MarkAllRegistersAsConflictsExcept(ret_inst->VRegA_11x());
2861        }
2862      }
2863    }
2864    RegisterLine* next_line = reg_table_.GetLine(next_insn_idx);
2865    if (next_line != NULL) {
2866      // Merge registers into what we have for the next instruction, and set the "changed" flag if
2867      // needed. If the merge changes the state of the registers then the work line will be
2868      // updated.
2869      if (!UpdateRegisters(next_insn_idx, work_line_.get(), true)) {
2870        return false;
2871      }
2872    } else {
2873      /*
2874       * We're not recording register data for the next instruction, so we don't know what the
2875       * prior state was. We have to assume that something has changed and re-evaluate it.
2876       */
2877      insn_flags_[next_insn_idx].SetChanged();
2878    }
2879  }
2880
2881  /* If we're returning from the method, make sure monitor stack is empty. */
2882  if ((opcode_flags & Instruction::kReturn) != 0) {
2883    if (!work_line_->VerifyMonitorStackEmpty()) {
2884      return false;
2885    }
2886  }
2887
2888  /*
2889   * Update start_guess. Advance to the next instruction of that's
2890   * possible, otherwise use the branch target if one was found. If
2891   * neither of those exists we're in a return or throw; leave start_guess
2892   * alone and let the caller sort it out.
2893   */
2894  if ((opcode_flags & Instruction::kContinue) != 0) {
2895    *start_guess = work_insn_idx_ + insn_flags_[work_insn_idx_].GetLengthInCodeUnits();
2896  } else if ((opcode_flags & Instruction::kBranch) != 0) {
2897    /* we're still okay if branch_target is zero */
2898    *start_guess = work_insn_idx_ + branch_target;
2899  }
2900
2901  DCHECK_LT(*start_guess, code_item_->insns_size_in_code_units_);
2902  DCHECK(insn_flags_[*start_guess].IsOpcode());
2903
2904  return true;
2905}  // NOLINT(readability/fn_size)
2906
2907const RegType& MethodVerifier::ResolveClassAndCheckAccess(uint32_t class_idx) {
2908  const char* descriptor = dex_file_->StringByTypeIdx(class_idx);
2909  const RegType& referrer = GetDeclaringClass();
2910  mirror::Class* klass = (*dex_cache_)->GetResolvedType(class_idx);
2911  const RegType& result =
2912      klass != NULL ? reg_types_.FromClass(descriptor, klass,
2913                                           klass->CannotBeAssignedFromOtherTypes())
2914                    : reg_types_.FromDescriptor(class_loader_->Get(), descriptor, false);
2915  if (result.IsConflict()) {
2916    Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "accessing broken descriptor '" << descriptor
2917        << "' in " << referrer;
2918    return result;
2919  }
2920  if (klass == NULL && !result.IsUnresolvedTypes()) {
2921    (*dex_cache_)->SetResolvedType(class_idx, result.GetClass());
2922  }
2923  // Check if access is allowed. Unresolved types use xxxWithAccessCheck to
2924  // check at runtime if access is allowed and so pass here. If result is
2925  // primitive, skip the access check.
2926  if (result.IsNonZeroReferenceTypes() && !result.IsUnresolvedTypes() &&
2927      !referrer.IsUnresolvedTypes() && !referrer.CanAccess(result)) {
2928    Fail(VERIFY_ERROR_ACCESS_CLASS) << "illegal class access: '"
2929                                    << referrer << "' -> '" << result << "'";
2930  }
2931  return result;
2932}
2933
2934const RegType& MethodVerifier::GetCaughtExceptionType() {
2935  const RegType* common_super = NULL;
2936  if (code_item_->tries_size_ != 0) {
2937    const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item_, 0);
2938    uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
2939    for (uint32_t i = 0; i < handlers_size; i++) {
2940      CatchHandlerIterator iterator(handlers_ptr);
2941      for (; iterator.HasNext(); iterator.Next()) {
2942        if (iterator.GetHandlerAddress() == (uint32_t) work_insn_idx_) {
2943          if (iterator.GetHandlerTypeIndex() == DexFile::kDexNoIndex16) {
2944            common_super = &reg_types_.JavaLangThrowable(false);
2945          } else {
2946            const RegType& exception = ResolveClassAndCheckAccess(iterator.GetHandlerTypeIndex());
2947            if (!reg_types_.JavaLangThrowable(false).IsAssignableFrom(exception)) {
2948              if (exception.IsUnresolvedTypes()) {
2949                // We don't know enough about the type. Fail here and let runtime handle it.
2950                Fail(VERIFY_ERROR_NO_CLASS) << "unresolved exception class " << exception;
2951                return exception;
2952              } else {
2953                Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "unexpected non-exception class " << exception;
2954                return reg_types_.Conflict();
2955              }
2956            } else if (common_super == nullptr) {
2957              common_super = &exception;
2958            } else if (common_super->Equals(exception)) {
2959              // odd case, but nothing to do
2960            } else {
2961              common_super = &common_super->Merge(exception, &reg_types_);
2962              CHECK(reg_types_.JavaLangThrowable(false).IsAssignableFrom(*common_super));
2963            }
2964          }
2965        }
2966      }
2967      handlers_ptr = iterator.EndDataPointer();
2968    }
2969  }
2970  if (common_super == NULL) {
2971    /* no catch blocks, or no catches with classes we can find */
2972    Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "unable to find exception handler";
2973    return reg_types_.Conflict();
2974  }
2975  return *common_super;
2976}
2977
2978mirror::ArtMethod* MethodVerifier::ResolveMethodAndCheckAccess(uint32_t dex_method_idx,
2979                                                               MethodType method_type) {
2980  const DexFile::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx);
2981  const RegType& klass_type = ResolveClassAndCheckAccess(method_id.class_idx_);
2982  if (klass_type.IsConflict()) {
2983    std::string append(" in attempt to access method ");
2984    append += dex_file_->GetMethodName(method_id);
2985    AppendToLastFailMessage(append);
2986    return NULL;
2987  }
2988  if (klass_type.IsUnresolvedTypes()) {
2989    return NULL;  // Can't resolve Class so no more to do here
2990  }
2991  mirror::Class* klass = klass_type.GetClass();
2992  const RegType& referrer = GetDeclaringClass();
2993  mirror::ArtMethod* res_method = (*dex_cache_)->GetResolvedMethod(dex_method_idx);
2994  if (res_method == NULL) {
2995    const char* name = dex_file_->GetMethodName(method_id);
2996    const Signature signature = dex_file_->GetMethodSignature(method_id);
2997
2998    if (method_type == METHOD_DIRECT || method_type == METHOD_STATIC) {
2999      res_method = klass->FindDirectMethod(name, signature);
3000    } else if (method_type == METHOD_INTERFACE) {
3001      res_method = klass->FindInterfaceMethod(name, signature);
3002    } else {
3003      res_method = klass->FindVirtualMethod(name, signature);
3004    }
3005    if (res_method != NULL) {
3006      (*dex_cache_)->SetResolvedMethod(dex_method_idx, res_method);
3007    } else {
3008      // If a virtual or interface method wasn't found with the expected type, look in
3009      // the direct methods. This can happen when the wrong invoke type is used or when
3010      // a class has changed, and will be flagged as an error in later checks.
3011      if (method_type == METHOD_INTERFACE || method_type == METHOD_VIRTUAL) {
3012        res_method = klass->FindDirectMethod(name, signature);
3013      }
3014      if (res_method == NULL) {
3015        Fail(VERIFY_ERROR_NO_METHOD) << "couldn't find method "
3016                                     << PrettyDescriptor(klass) << "." << name
3017                                     << " " << signature;
3018        return NULL;
3019      }
3020    }
3021  }
3022  // Make sure calls to constructors are "direct". There are additional restrictions but we don't
3023  // enforce them here.
3024  if (res_method->IsConstructor() && method_type != METHOD_DIRECT) {
3025    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "rejecting non-direct call to constructor "
3026                                      << PrettyMethod(res_method);
3027    return NULL;
3028  }
3029  // Disallow any calls to class initializers.
3030  if (res_method->IsClassInitializer()) {
3031    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "rejecting call to class initializer "
3032                                      << PrettyMethod(res_method);
3033    return NULL;
3034  }
3035  // Check if access is allowed.
3036  if (!referrer.CanAccessMember(res_method->GetDeclaringClass(), res_method->GetAccessFlags())) {
3037    Fail(VERIFY_ERROR_ACCESS_METHOD) << "illegal method access (call " << PrettyMethod(res_method)
3038                                     << " from " << referrer << ")";
3039    return res_method;
3040  }
3041  // Check that invoke-virtual and invoke-super are not used on private methods of the same class.
3042  if (res_method->IsPrivate() && method_type == METHOD_VIRTUAL) {
3043    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invoke-super/virtual can't be used on private method "
3044                                      << PrettyMethod(res_method);
3045    return NULL;
3046  }
3047  // Check that interface methods match interface classes.
3048  if (klass->IsInterface() && method_type != METHOD_INTERFACE) {
3049    Fail(VERIFY_ERROR_CLASS_CHANGE) << "non-interface method " << PrettyMethod(res_method)
3050                                    << " is in an interface class " << PrettyClass(klass);
3051    return NULL;
3052  } else if (!klass->IsInterface() && method_type == METHOD_INTERFACE) {
3053    Fail(VERIFY_ERROR_CLASS_CHANGE) << "interface method " << PrettyMethod(res_method)
3054                                    << " is in a non-interface class " << PrettyClass(klass);
3055    return NULL;
3056  }
3057  // See if the method type implied by the invoke instruction matches the access flags for the
3058  // target method.
3059  if ((method_type == METHOD_DIRECT && !res_method->IsDirect()) ||
3060      (method_type == METHOD_STATIC && !res_method->IsStatic()) ||
3061      ((method_type == METHOD_VIRTUAL || method_type == METHOD_INTERFACE) && res_method->IsDirect())
3062      ) {
3063    Fail(VERIFY_ERROR_CLASS_CHANGE) << "invoke type (" << method_type << ") does not match method "
3064                                       " type of " << PrettyMethod(res_method);
3065    return NULL;
3066  }
3067  return res_method;
3068}
3069
3070template <class T>
3071mirror::ArtMethod* MethodVerifier::VerifyInvocationArgsFromIterator(T* it, const Instruction* inst,
3072                                                                    MethodType method_type,
3073                                                                    bool is_range,
3074                                                                    mirror::ArtMethod* res_method) {
3075  // We use vAA as our expected arg count, rather than res_method->insSize, because we need to
3076  // match the call to the signature. Also, we might be calling through an abstract method
3077  // definition (which doesn't have register count values).
3078  const size_t expected_args = (is_range) ? inst->VRegA_3rc() : inst->VRegA_35c();
3079  /* caught by static verifier */
3080  DCHECK(is_range || expected_args <= 5);
3081  if (expected_args > code_item_->outs_size_) {
3082    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid argument count (" << expected_args
3083        << ") exceeds outsSize (" << code_item_->outs_size_ << ")";
3084    return nullptr;
3085  }
3086
3087  uint32_t arg[5];
3088  if (!is_range) {
3089    inst->GetVarArgs(arg);
3090  }
3091  uint32_t sig_registers = 0;
3092
3093  /*
3094   * Check the "this" argument, which must be an instance of the class that declared the method.
3095   * For an interface class, we don't do the full interface merge (see JoinClass), so we can't do a
3096   * rigorous check here (which is okay since we have to do it at runtime).
3097   */
3098  if (method_type != METHOD_STATIC) {
3099    const RegType& actual_arg_type = work_line_->GetInvocationThis(inst, is_range);
3100    if (actual_arg_type.IsConflict()) {  // GetInvocationThis failed.
3101      CHECK(have_pending_hard_failure_);
3102      return nullptr;
3103    }
3104    if (actual_arg_type.IsUninitializedReference()) {
3105      if (res_method) {
3106        if (!res_method->IsConstructor()) {
3107          Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "'this' arg must be initialized";
3108          return nullptr;
3109        }
3110      } else {
3111        // Check whether the name of the called method is "<init>"
3112        const uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c();
3113        if (strcmp(dex_file_->GetMethodName(dex_file_->GetMethodId(method_idx)), "init") != 0) {
3114          Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "'this' arg must be initialized";
3115          return nullptr;
3116        }
3117      }
3118    }
3119    if (method_type != METHOD_INTERFACE && !actual_arg_type.IsZero()) {
3120      const RegType* res_method_class;
3121      if (res_method != nullptr) {
3122        mirror::Class* klass = res_method->GetDeclaringClass();
3123        res_method_class = &reg_types_.FromClass(klass->GetDescriptor().c_str(), klass,
3124                                                 klass->CannotBeAssignedFromOtherTypes());
3125      } else {
3126        const uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c();
3127        const uint16_t class_idx = dex_file_->GetMethodId(method_idx).class_idx_;
3128        res_method_class = &reg_types_.FromDescriptor(class_loader_->Get(),
3129                                                      dex_file_->StringByTypeIdx(class_idx),
3130                                                      false);
3131      }
3132      if (!res_method_class->IsAssignableFrom(actual_arg_type)) {
3133        Fail(actual_arg_type.IsUnresolvedTypes() ? VERIFY_ERROR_NO_CLASS:
3134            VERIFY_ERROR_BAD_CLASS_SOFT) << "'this' argument '" << actual_arg_type
3135                << "' not instance of '" << *res_method_class << "'";
3136        // Continue on soft failures. We need to find possible hard failures to avoid problems in
3137        // the compiler.
3138        if (have_pending_hard_failure_) {
3139          return nullptr;
3140        }
3141      }
3142    }
3143    sig_registers = 1;
3144  }
3145
3146  for ( ; it->HasNext(); it->Next()) {
3147    if (sig_registers >= expected_args) {
3148      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation, expected " << inst->VRegA() <<
3149          " arguments, found " << sig_registers << " or more.";
3150      return nullptr;
3151    }
3152
3153    const char* param_descriptor = it->GetDescriptor();
3154
3155    if (param_descriptor == nullptr) {
3156      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation because of missing signature "
3157          "component";
3158      return nullptr;
3159    }
3160
3161    const RegType& reg_type = reg_types_.FromDescriptor(class_loader_->Get(), param_descriptor,
3162                                                        false);
3163    uint32_t get_reg = is_range ? inst->VRegC_3rc() + static_cast<uint32_t>(sig_registers) :
3164        arg[sig_registers];
3165    if (reg_type.IsIntegralTypes()) {
3166      const RegType& src_type = work_line_->GetRegisterType(get_reg);
3167      if (!src_type.IsIntegralTypes()) {
3168        Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "register v" << get_reg << " has type " << src_type
3169            << " but expected " << reg_type;
3170        return res_method;
3171      }
3172    } else if (!work_line_->VerifyRegisterType(get_reg, reg_type)) {
3173      // Continue on soft failures. We need to find possible hard failures to avoid problems in the
3174      // compiler.
3175      if (have_pending_hard_failure_) {
3176        return res_method;
3177      }
3178    }
3179    sig_registers += reg_type.IsLongOrDoubleTypes() ?  2 : 1;
3180  }
3181  if (expected_args != sig_registers) {
3182    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation, expected " << expected_args <<
3183        " arguments, found " << sig_registers;
3184    return nullptr;
3185  }
3186  return res_method;
3187}
3188
3189void MethodVerifier::VerifyInvocationArgsUnresolvedMethod(const Instruction* inst,
3190                                                          MethodType method_type,
3191                                                          bool is_range) {
3192  // As the method may not have been resolved, make this static check against what we expect.
3193  // The main reason for this code block is to fail hard when we find an illegal use, e.g.,
3194  // wrong number of arguments or wrong primitive types, even if the method could not be resolved.
3195  const uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c();
3196  DexFileParameterIterator it(*dex_file_,
3197                              dex_file_->GetProtoId(dex_file_->GetMethodId(method_idx).proto_idx_));
3198  VerifyInvocationArgsFromIterator<DexFileParameterIterator>(&it, inst, method_type, is_range,
3199                                                             nullptr);
3200}
3201
3202class MethodParamListDescriptorIterator {
3203 public:
3204  explicit MethodParamListDescriptorIterator(mirror::ArtMethod* res_method) :
3205      res_method_(res_method), pos_(0), params_(res_method->GetParameterTypeList()),
3206      params_size_(params_ == nullptr ? 0 : params_->Size()) {
3207  }
3208
3209  bool HasNext() {
3210    return pos_ < params_size_;
3211  }
3212
3213  void Next() {
3214    ++pos_;
3215  }
3216
3217  const char* GetDescriptor() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3218    return res_method_->GetTypeDescriptorFromTypeIdx(params_->GetTypeItem(pos_).type_idx_);
3219  }
3220
3221 private:
3222  mirror::ArtMethod* res_method_;
3223  size_t pos_;
3224  const DexFile::TypeList* params_;
3225  const size_t params_size_;
3226};
3227
3228mirror::ArtMethod* MethodVerifier::VerifyInvocationArgs(const Instruction* inst,
3229                                                             MethodType method_type,
3230                                                             bool is_range,
3231                                                             bool is_super) {
3232  // Resolve the method. This could be an abstract or concrete method depending on what sort of call
3233  // we're making.
3234  const uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c();
3235
3236  mirror::ArtMethod* res_method = ResolveMethodAndCheckAccess(method_idx, method_type);
3237  if (res_method == NULL) {  // error or class is unresolved
3238    // Check what we can statically.
3239    if (!have_pending_hard_failure_) {
3240      VerifyInvocationArgsUnresolvedMethod(inst, method_type, is_range);
3241    }
3242    return nullptr;
3243  }
3244
3245  // If we're using invoke-super(method), make sure that the executing method's class' superclass
3246  // has a vtable entry for the target method.
3247  if (is_super) {
3248    DCHECK(method_type == METHOD_VIRTUAL);
3249    const RegType& super = GetDeclaringClass().GetSuperClass(&reg_types_);
3250    if (super.IsUnresolvedTypes()) {
3251      Fail(VERIFY_ERROR_NO_METHOD) << "unknown super class in invoke-super from "
3252                                   << PrettyMethod(dex_method_idx_, *dex_file_)
3253                                   << " to super " << PrettyMethod(res_method);
3254      return nullptr;
3255    }
3256    mirror::Class* super_klass = super.GetClass();
3257    if (res_method->GetMethodIndex() >= super_klass->GetVTable()->GetLength()) {
3258      Fail(VERIFY_ERROR_NO_METHOD) << "invalid invoke-super from "
3259                                   << PrettyMethod(dex_method_idx_, *dex_file_)
3260                                   << " to super " << super
3261                                   << "." << res_method->GetName()
3262                                   << res_method->GetSignature();
3263      return nullptr;
3264    }
3265  }
3266
3267  // Process the target method's signature. This signature may or may not
3268  MethodParamListDescriptorIterator it(res_method);
3269  return VerifyInvocationArgsFromIterator<MethodParamListDescriptorIterator>(&it, inst, method_type,
3270                                                                             is_range, res_method);
3271}
3272
3273mirror::ArtMethod* MethodVerifier::GetQuickInvokedMethod(const Instruction* inst,
3274                                                         RegisterLine* reg_line, bool is_range) {
3275  DCHECK(inst->Opcode() == Instruction::INVOKE_VIRTUAL_QUICK ||
3276         inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE_QUICK);
3277  const RegType& actual_arg_type = reg_line->GetInvocationThis(inst, is_range);
3278  if (!actual_arg_type.HasClass()) {
3279    VLOG(verifier) << "Failed to get mirror::Class* from '" << actual_arg_type << "'";
3280    return nullptr;
3281  }
3282  mirror::ObjectArray<mirror::ArtMethod>* vtable = nullptr;
3283  mirror::Class* klass = actual_arg_type.GetClass();
3284  if (klass->IsInterface()) {
3285    // Derive Object.class from Class.class.getSuperclass().
3286    mirror::Class* object_klass = klass->GetClass()->GetSuperClass();
3287    CHECK(object_klass->IsObjectClass());
3288    vtable = object_klass->GetVTable();
3289  } else {
3290    vtable = klass->GetVTable();
3291  }
3292  CHECK(vtable != nullptr) << PrettyDescriptor(klass);
3293  uint16_t vtable_index = is_range ? inst->VRegB_3rc() : inst->VRegB_35c();
3294  CHECK_LT(static_cast<int32_t>(vtable_index), vtable->GetLength()) << PrettyDescriptor(klass);
3295  mirror::ArtMethod* res_method = vtable->Get(vtable_index);
3296  CHECK(!Thread::Current()->IsExceptionPending());
3297  return res_method;
3298}
3299
3300mirror::ArtMethod* MethodVerifier::VerifyInvokeVirtualQuickArgs(const Instruction* inst,
3301                                                                     bool is_range) {
3302  DCHECK(Runtime::Current()->IsStarted());
3303  mirror::ArtMethod* res_method = GetQuickInvokedMethod(inst, work_line_.get(),
3304                                                             is_range);
3305  if (res_method == NULL) {
3306    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Cannot infer method from " << inst->Name();
3307    return NULL;
3308  }
3309  CHECK(!res_method->IsDirect() && !res_method->IsStatic());
3310
3311  // We use vAA as our expected arg count, rather than res_method->insSize, because we need to
3312  // match the call to the signature. Also, we might be calling through an abstract method
3313  // definition (which doesn't have register count values).
3314  const RegType& actual_arg_type = work_line_->GetInvocationThis(inst, is_range);
3315  if (actual_arg_type.IsConflict()) {  // GetInvocationThis failed.
3316    return NULL;
3317  }
3318  const size_t expected_args = (is_range) ? inst->VRegA_3rc() : inst->VRegA_35c();
3319  /* caught by static verifier */
3320  DCHECK(is_range || expected_args <= 5);
3321  if (expected_args > code_item_->outs_size_) {
3322    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid argument count (" << expected_args
3323        << ") exceeds outsSize (" << code_item_->outs_size_ << ")";
3324    return NULL;
3325  }
3326
3327  /*
3328   * Check the "this" argument, which must be an instance of the class that declared the method.
3329   * For an interface class, we don't do the full interface merge (see JoinClass), so we can't do a
3330   * rigorous check here (which is okay since we have to do it at runtime).
3331   */
3332  if (actual_arg_type.IsUninitializedReference() && !res_method->IsConstructor()) {
3333    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "'this' arg must be initialized";
3334    return NULL;
3335  }
3336  if (!actual_arg_type.IsZero()) {
3337    mirror::Class* klass = res_method->GetDeclaringClass();
3338    const RegType& res_method_class =
3339        reg_types_.FromClass(klass->GetDescriptor().c_str(), klass,
3340                             klass->CannotBeAssignedFromOtherTypes());
3341    if (!res_method_class.IsAssignableFrom(actual_arg_type)) {
3342      Fail(actual_arg_type.IsUnresolvedTypes() ? VERIFY_ERROR_NO_CLASS :
3343          VERIFY_ERROR_BAD_CLASS_SOFT) << "'this' argument '" << actual_arg_type
3344          << "' not instance of '" << res_method_class << "'";
3345      return NULL;
3346    }
3347  }
3348  /*
3349   * Process the target method's signature. This signature may or may not
3350   * have been verified, so we can't assume it's properly formed.
3351   */
3352  const DexFile::TypeList* params = res_method->GetParameterTypeList();
3353  size_t params_size = params == NULL ? 0 : params->Size();
3354  uint32_t arg[5];
3355  if (!is_range) {
3356    inst->GetVarArgs(arg);
3357  }
3358  size_t actual_args = 1;
3359  for (size_t param_index = 0; param_index < params_size; param_index++) {
3360    if (actual_args >= expected_args) {
3361      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invalid call to '" << PrettyMethod(res_method)
3362                                        << "'. Expected " << expected_args
3363                                         << " arguments, processing argument " << actual_args
3364                                        << " (where longs/doubles count twice).";
3365      return NULL;
3366    }
3367    const char* descriptor =
3368        res_method->GetTypeDescriptorFromTypeIdx(params->GetTypeItem(param_index).type_idx_);
3369    if (descriptor == NULL) {
3370      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation of " << PrettyMethod(res_method)
3371                                        << " missing signature component";
3372      return NULL;
3373    }
3374    const RegType& reg_type = reg_types_.FromDescriptor(class_loader_->Get(), descriptor, false);
3375    uint32_t get_reg = is_range ? inst->VRegC_3rc() + actual_args : arg[actual_args];
3376    if (!work_line_->VerifyRegisterType(get_reg, reg_type)) {
3377      return res_method;
3378    }
3379    actual_args = reg_type.IsLongOrDoubleTypes() ? actual_args + 2 : actual_args + 1;
3380  }
3381  if (actual_args != expected_args) {
3382    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation of " << PrettyMethod(res_method)
3383              << " expected " << expected_args << " arguments, found " << actual_args;
3384    return NULL;
3385  } else {
3386    return res_method;
3387  }
3388}
3389
3390void MethodVerifier::VerifyNewArray(const Instruction* inst, bool is_filled, bool is_range) {
3391  uint32_t type_idx;
3392  if (!is_filled) {
3393    DCHECK_EQ(inst->Opcode(), Instruction::NEW_ARRAY);
3394    type_idx = inst->VRegC_22c();
3395  } else if (!is_range) {
3396    DCHECK_EQ(inst->Opcode(), Instruction::FILLED_NEW_ARRAY);
3397    type_idx = inst->VRegB_35c();
3398  } else {
3399    DCHECK_EQ(inst->Opcode(), Instruction::FILLED_NEW_ARRAY_RANGE);
3400    type_idx = inst->VRegB_3rc();
3401  }
3402  const RegType& res_type = ResolveClassAndCheckAccess(type_idx);
3403  if (res_type.IsConflict()) {  // bad class
3404    DCHECK_NE(failures_.size(), 0U);
3405  } else {
3406    // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved
3407    if (!res_type.IsArrayTypes()) {
3408      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "new-array on non-array class " << res_type;
3409    } else if (!is_filled) {
3410      /* make sure "size" register is valid type */
3411      work_line_->VerifyRegisterType(inst->VRegB_22c(), reg_types_.Integer());
3412      /* set register type to array class */
3413      const RegType& precise_type = reg_types_.FromUninitialized(res_type);
3414      work_line_->SetRegisterType(inst->VRegA_22c(), precise_type);
3415    } else {
3416      // Verify each register. If "arg_count" is bad, VerifyRegisterType() will run off the end of
3417      // the list and fail. It's legal, if silly, for arg_count to be zero.
3418      const RegType& expected_type = reg_types_.GetComponentType(res_type, class_loader_->Get());
3419      uint32_t arg_count = (is_range) ? inst->VRegA_3rc() : inst->VRegA_35c();
3420      uint32_t arg[5];
3421      if (!is_range) {
3422        inst->GetVarArgs(arg);
3423      }
3424      for (size_t ui = 0; ui < arg_count; ui++) {
3425        uint32_t get_reg = is_range ? inst->VRegC_3rc() + ui : arg[ui];
3426        if (!work_line_->VerifyRegisterType(get_reg, expected_type)) {
3427          work_line_->SetResultRegisterType(reg_types_.Conflict());
3428          return;
3429        }
3430      }
3431      // filled-array result goes into "result" register
3432      const RegType& precise_type = reg_types_.FromUninitialized(res_type);
3433      work_line_->SetResultRegisterType(precise_type);
3434    }
3435  }
3436}
3437
3438void MethodVerifier::VerifyAGet(const Instruction* inst,
3439                                const RegType& insn_type, bool is_primitive) {
3440  const RegType& index_type = work_line_->GetRegisterType(inst->VRegC_23x());
3441  if (!index_type.IsArrayIndexTypes()) {
3442    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Invalid reg type for array index (" << index_type << ")";
3443  } else {
3444    const RegType& array_type = work_line_->GetRegisterType(inst->VRegB_23x());
3445    if (array_type.IsZero()) {
3446      // Null array class; this code path will fail at runtime. Infer a merge-able type from the
3447      // instruction type. TODO: have a proper notion of bottom here.
3448      if (!is_primitive || insn_type.IsCategory1Types()) {
3449        // Reference or category 1
3450        work_line_->SetRegisterType(inst->VRegA_23x(), reg_types_.Zero());
3451      } else {
3452        // Category 2
3453        work_line_->SetRegisterTypeWide(inst->VRegA_23x(), reg_types_.FromCat2ConstLo(0, false),
3454                                        reg_types_.FromCat2ConstHi(0, false));
3455      }
3456    } else if (!array_type.IsArrayTypes()) {
3457      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "not array type " << array_type << " with aget";
3458    } else {
3459      /* verify the class */
3460      const RegType& component_type = reg_types_.GetComponentType(array_type, class_loader_->Get());
3461      if (!component_type.IsReferenceTypes() && !is_primitive) {
3462        Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "primitive array type " << array_type
3463            << " source for aget-object";
3464      } else if (component_type.IsNonZeroReferenceTypes() && is_primitive) {
3465        Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "reference array type " << array_type
3466            << " source for category 1 aget";
3467      } else if (is_primitive && !insn_type.Equals(component_type) &&
3468                 !((insn_type.IsInteger() && component_type.IsFloat()) ||
3469                 (insn_type.IsLong() && component_type.IsDouble()))) {
3470        Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array type " << array_type
3471            << " incompatible with aget of type " << insn_type;
3472      } else {
3473        // Use knowledge of the field type which is stronger than the type inferred from the
3474        // instruction, which can't differentiate object types and ints from floats, longs from
3475        // doubles.
3476        if (!component_type.IsLowHalf()) {
3477          work_line_->SetRegisterType(inst->VRegA_23x(), component_type);
3478        } else {
3479          work_line_->SetRegisterTypeWide(inst->VRegA_23x(), component_type,
3480                                          component_type.HighHalf(&reg_types_));
3481        }
3482      }
3483    }
3484  }
3485}
3486
3487void MethodVerifier::VerifyPrimitivePut(const RegType& target_type, const RegType& insn_type,
3488                                        const uint32_t vregA) {
3489  // Primitive assignability rules are weaker than regular assignability rules.
3490  bool instruction_compatible;
3491  bool value_compatible;
3492  const RegType& value_type = work_line_->GetRegisterType(vregA);
3493  if (target_type.IsIntegralTypes()) {
3494    instruction_compatible = target_type.Equals(insn_type);
3495    value_compatible = value_type.IsIntegralTypes();
3496  } else if (target_type.IsFloat()) {
3497    instruction_compatible = insn_type.IsInteger();  // no put-float, so expect put-int
3498    value_compatible = value_type.IsFloatTypes();
3499  } else if (target_type.IsLong()) {
3500    instruction_compatible = insn_type.IsLong();
3501    const RegType& value_type_hi = work_line_->GetRegisterType(vregA + 1);
3502    value_compatible = value_type.IsLongTypes() && value_type.CheckWidePair(value_type_hi);
3503  } else if (target_type.IsDouble()) {
3504    instruction_compatible = insn_type.IsLong();  // no put-double, so expect put-long
3505    const RegType& value_type_hi = work_line_->GetRegisterType(vregA + 1);
3506    value_compatible = value_type.IsDoubleTypes() && value_type.CheckWidePair(value_type_hi);
3507  } else {
3508    instruction_compatible = false;  // reference with primitive store
3509    value_compatible = false;  // unused
3510  }
3511  if (!instruction_compatible) {
3512    // This is a global failure rather than a class change failure as the instructions and
3513    // the descriptors for the type should have been consistent within the same file at
3514    // compile time.
3515    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "put insn has type '" << insn_type
3516        << "' but expected type '" << target_type << "'";
3517    return;
3518  }
3519  if (!value_compatible) {
3520    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected value in v" << vregA
3521        << " of type " << value_type << " but expected " << target_type << " for put";
3522    return;
3523  }
3524}
3525
3526void MethodVerifier::VerifyAPut(const Instruction* inst,
3527                                const RegType& insn_type, bool is_primitive) {
3528  const RegType& index_type = work_line_->GetRegisterType(inst->VRegC_23x());
3529  if (!index_type.IsArrayIndexTypes()) {
3530    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Invalid reg type for array index (" << index_type << ")";
3531  } else {
3532    const RegType& array_type = work_line_->GetRegisterType(inst->VRegB_23x());
3533    if (array_type.IsZero()) {
3534      // Null array type; this code path will fail at runtime. Infer a merge-able type from the
3535      // instruction type.
3536    } else if (!array_type.IsArrayTypes()) {
3537      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "not array type " << array_type << " with aput";
3538    } else {
3539      const RegType& component_type = reg_types_.GetComponentType(array_type, class_loader_->Get());
3540      const uint32_t vregA = inst->VRegA_23x();
3541      if (is_primitive) {
3542        VerifyPrimitivePut(component_type, insn_type, vregA);
3543      } else {
3544        if (!component_type.IsReferenceTypes()) {
3545          Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "primitive array type " << array_type
3546              << " source for aput-object";
3547        } else {
3548          // The instruction agrees with the type of array, confirm the value to be stored does too
3549          // Note: we use the instruction type (rather than the component type) for aput-object as
3550          // incompatible classes will be caught at runtime as an array store exception
3551          work_line_->VerifyRegisterType(vregA, insn_type);
3552        }
3553      }
3554    }
3555  }
3556}
3557
3558mirror::ArtField* MethodVerifier::GetStaticField(int field_idx) {
3559  const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx);
3560  // Check access to class
3561  const RegType& klass_type = ResolveClassAndCheckAccess(field_id.class_idx_);
3562  if (klass_type.IsConflict()) {  // bad class
3563    AppendToLastFailMessage(StringPrintf(" in attempt to access static field %d (%s) in %s",
3564                                         field_idx, dex_file_->GetFieldName(field_id),
3565                                         dex_file_->GetFieldDeclaringClassDescriptor(field_id)));
3566    return NULL;
3567  }
3568  if (klass_type.IsUnresolvedTypes()) {
3569    return NULL;  // Can't resolve Class so no more to do here, will do checking at runtime.
3570  }
3571  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
3572  mirror::ArtField* field = class_linker->ResolveFieldJLS(*dex_file_, field_idx, *dex_cache_,
3573                                                          *class_loader_);
3574  if (field == NULL) {
3575    VLOG(verifier) << "Unable to resolve static field " << field_idx << " ("
3576              << dex_file_->GetFieldName(field_id) << ") in "
3577              << dex_file_->GetFieldDeclaringClassDescriptor(field_id);
3578    DCHECK(Thread::Current()->IsExceptionPending());
3579    Thread::Current()->ClearException();
3580    return NULL;
3581  } else if (!GetDeclaringClass().CanAccessMember(field->GetDeclaringClass(),
3582                                                  field->GetAccessFlags())) {
3583    Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot access static field " << PrettyField(field)
3584                                    << " from " << GetDeclaringClass();
3585    return NULL;
3586  } else if (!field->IsStatic()) {
3587    Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected field " << PrettyField(field) << " to be static";
3588    return NULL;
3589  }
3590  return field;
3591}
3592
3593mirror::ArtField* MethodVerifier::GetInstanceField(const RegType& obj_type, int field_idx) {
3594  const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx);
3595  // Check access to class
3596  const RegType& klass_type = ResolveClassAndCheckAccess(field_id.class_idx_);
3597  if (klass_type.IsConflict()) {
3598    AppendToLastFailMessage(StringPrintf(" in attempt to access instance field %d (%s) in %s",
3599                                         field_idx, dex_file_->GetFieldName(field_id),
3600                                         dex_file_->GetFieldDeclaringClassDescriptor(field_id)));
3601    return NULL;
3602  }
3603  if (klass_type.IsUnresolvedTypes()) {
3604    return NULL;  // Can't resolve Class so no more to do here
3605  }
3606  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
3607  mirror::ArtField* field = class_linker->ResolveFieldJLS(*dex_file_, field_idx, *dex_cache_,
3608                                                          *class_loader_);
3609  if (field == NULL) {
3610    VLOG(verifier) << "Unable to resolve instance field " << field_idx << " ("
3611              << dex_file_->GetFieldName(field_id) << ") in "
3612              << dex_file_->GetFieldDeclaringClassDescriptor(field_id);
3613    DCHECK(Thread::Current()->IsExceptionPending());
3614    Thread::Current()->ClearException();
3615    return NULL;
3616  } else if (!GetDeclaringClass().CanAccessMember(field->GetDeclaringClass(),
3617                                                  field->GetAccessFlags())) {
3618    Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot access instance field " << PrettyField(field)
3619                                    << " from " << GetDeclaringClass();
3620    return NULL;
3621  } else if (field->IsStatic()) {
3622    Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected field " << PrettyField(field)
3623                                    << " to not be static";
3624    return NULL;
3625  } else if (obj_type.IsZero()) {
3626    // Cannot infer and check type, however, access will cause null pointer exception
3627    return field;
3628  } else {
3629    mirror::Class* klass = field->GetDeclaringClass();
3630    const RegType& field_klass =
3631        reg_types_.FromClass(dex_file_->GetFieldDeclaringClassDescriptor(field_id),
3632                             klass, klass->CannotBeAssignedFromOtherTypes());
3633    if (obj_type.IsUninitializedTypes() &&
3634        (!IsConstructor() || GetDeclaringClass().Equals(obj_type) ||
3635            !field_klass.Equals(GetDeclaringClass()))) {
3636      // Field accesses through uninitialized references are only allowable for constructors where
3637      // the field is declared in this class
3638      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "cannot access instance field " << PrettyField(field)
3639                                        << " of a not fully initialized object within the context"
3640                                        << " of " << PrettyMethod(dex_method_idx_, *dex_file_);
3641      return NULL;
3642    } else if (!field_klass.IsAssignableFrom(obj_type)) {
3643      // Trying to access C1.field1 using reference of type C2, which is neither C1 or a sub-class
3644      // of C1. For resolution to occur the declared class of the field must be compatible with
3645      // obj_type, we've discovered this wasn't so, so report the field didn't exist.
3646      Fail(VERIFY_ERROR_NO_FIELD) << "cannot access instance field " << PrettyField(field)
3647                                  << " from object of type " << obj_type;
3648      return NULL;
3649    } else {
3650      return field;
3651    }
3652  }
3653}
3654
3655void MethodVerifier::VerifyISGet(const Instruction* inst, const RegType& insn_type,
3656                                 bool is_primitive, bool is_static) {
3657  uint32_t field_idx = is_static ? inst->VRegB_21c() : inst->VRegC_22c();
3658  mirror::ArtField* field;
3659  if (is_static) {
3660    field = GetStaticField(field_idx);
3661  } else {
3662    const RegType& object_type = work_line_->GetRegisterType(inst->VRegB_22c());
3663    field = GetInstanceField(object_type, field_idx);
3664  }
3665  const RegType* field_type = nullptr;
3666  if (field != NULL) {
3667    Thread* self = Thread::Current();
3668    mirror::Class* field_type_class;
3669    {
3670      StackHandleScope<1> hs(self);
3671      HandleWrapper<mirror::ArtField> h_field(hs.NewHandleWrapper(&field));
3672      field_type_class = FieldHelper(h_field).GetType(can_load_classes_);
3673    }
3674    if (field_type_class != nullptr) {
3675      field_type = &reg_types_.FromClass(field->GetTypeDescriptor(), field_type_class,
3676                                         field_type_class->CannotBeAssignedFromOtherTypes());
3677    } else {
3678      DCHECK(!can_load_classes_ || self->IsExceptionPending());
3679      self->ClearException();
3680    }
3681  }
3682  if (field_type == nullptr) {
3683    const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx);
3684    const char* descriptor = dex_file_->GetFieldTypeDescriptor(field_id);
3685    field_type = &reg_types_.FromDescriptor(class_loader_->Get(), descriptor, false);
3686  }
3687  DCHECK(field_type != nullptr);
3688  const uint32_t vregA = (is_static) ? inst->VRegA_21c() : inst->VRegA_22c();
3689  if (is_primitive) {
3690    if (field_type->Equals(insn_type) ||
3691        (field_type->IsFloat() && insn_type.IsInteger()) ||
3692        (field_type->IsDouble() && insn_type.IsLong())) {
3693      // expected that read is of the correct primitive type or that int reads are reading
3694      // floats or long reads are reading doubles
3695    } else {
3696      // This is a global failure rather than a class change failure as the instructions and
3697      // the descriptors for the type should have been consistent within the same file at
3698      // compile time
3699      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected field " << PrettyField(field)
3700                                        << " to be of type '" << insn_type
3701                                        << "' but found type '" << *field_type << "' in get";
3702      return;
3703    }
3704  } else {
3705    if (!insn_type.IsAssignableFrom(*field_type)) {
3706      Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "expected field " << PrettyField(field)
3707                                        << " to be compatible with type '" << insn_type
3708                                        << "' but found type '" << *field_type
3709                                        << "' in Get-object";
3710      work_line_->SetRegisterType(vregA, reg_types_.Conflict());
3711      return;
3712    }
3713  }
3714  if (!field_type->IsLowHalf()) {
3715    work_line_->SetRegisterType(vregA, *field_type);
3716  } else {
3717    work_line_->SetRegisterTypeWide(vregA, *field_type, field_type->HighHalf(&reg_types_));
3718  }
3719}
3720
3721void MethodVerifier::VerifyISPut(const Instruction* inst, const RegType& insn_type,
3722                                 bool is_primitive, bool is_static) {
3723  uint32_t field_idx = is_static ? inst->VRegB_21c() : inst->VRegC_22c();
3724  mirror::ArtField* field;
3725  if (is_static) {
3726    field = GetStaticField(field_idx);
3727  } else {
3728    const RegType& object_type = work_line_->GetRegisterType(inst->VRegB_22c());
3729    field = GetInstanceField(object_type, field_idx);
3730  }
3731  const RegType* field_type = nullptr;
3732  if (field != NULL) {
3733    if (field->IsFinal() && field->GetDeclaringClass() != GetDeclaringClass().GetClass()) {
3734      Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot modify final field " << PrettyField(field)
3735                                      << " from other class " << GetDeclaringClass();
3736      return;
3737    }
3738    mirror::Class* field_type_class;
3739    {
3740      StackHandleScope<1> hs(Thread::Current());
3741      HandleWrapper<mirror::ArtField> h_field(hs.NewHandleWrapper(&field));
3742      FieldHelper fh(h_field);
3743      field_type_class = fh.GetType(can_load_classes_);
3744    }
3745    if (field_type_class != nullptr) {
3746      field_type = &reg_types_.FromClass(field->GetTypeDescriptor(), field_type_class,
3747                                         field_type_class->CannotBeAssignedFromOtherTypes());
3748    } else {
3749      Thread* self = Thread::Current();
3750      DCHECK(!can_load_classes_ || self->IsExceptionPending());
3751      self->ClearException();
3752    }
3753  }
3754  if (field_type == nullptr) {
3755    const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx);
3756    const char* descriptor = dex_file_->GetFieldTypeDescriptor(field_id);
3757    field_type = &reg_types_.FromDescriptor(class_loader_->Get(), descriptor, false);
3758  }
3759  DCHECK(field_type != nullptr);
3760  const uint32_t vregA = (is_static) ? inst->VRegA_21c() : inst->VRegA_22c();
3761  if (is_primitive) {
3762    VerifyPrimitivePut(*field_type, insn_type, vregA);
3763  } else {
3764    if (!insn_type.IsAssignableFrom(*field_type)) {
3765      Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "expected field " << PrettyField(field)
3766                                        << " to be compatible with type '" << insn_type
3767                                        << "' but found type '" << *field_type
3768                                        << "' in put-object";
3769      return;
3770    }
3771    work_line_->VerifyRegisterType(vregA, *field_type);
3772  }
3773}
3774
3775mirror::ArtField* MethodVerifier::GetQuickFieldAccess(const Instruction* inst,
3776                                                      RegisterLine* reg_line) {
3777  DCHECK(inst->Opcode() == Instruction::IGET_QUICK ||
3778         inst->Opcode() == Instruction::IGET_WIDE_QUICK ||
3779         inst->Opcode() == Instruction::IGET_OBJECT_QUICK ||
3780         inst->Opcode() == Instruction::IPUT_QUICK ||
3781         inst->Opcode() == Instruction::IPUT_WIDE_QUICK ||
3782         inst->Opcode() == Instruction::IPUT_OBJECT_QUICK);
3783  const RegType& object_type = reg_line->GetRegisterType(inst->VRegB_22c());
3784  if (!object_type.HasClass()) {
3785    VLOG(verifier) << "Failed to get mirror::Class* from '" << object_type << "'";
3786    return nullptr;
3787  }
3788  uint32_t field_offset = static_cast<uint32_t>(inst->VRegC_22c());
3789  mirror::ArtField* f = mirror::ArtField::FindInstanceFieldWithOffset(object_type.GetClass(),
3790                                                                      field_offset);
3791  if (f == nullptr) {
3792    VLOG(verifier) << "Failed to find instance field at offset '" << field_offset
3793                   << "' from '" << PrettyDescriptor(object_type.GetClass()) << "'";
3794  }
3795  return f;
3796}
3797
3798void MethodVerifier::VerifyIGetQuick(const Instruction* inst, const RegType& insn_type,
3799                                     bool is_primitive) {
3800  DCHECK(Runtime::Current()->IsStarted());
3801  mirror::ArtField* field = GetQuickFieldAccess(inst, work_line_.get());
3802  if (field == NULL) {
3803    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Cannot infer field from " << inst->Name();
3804    return;
3805  }
3806  mirror::Class* field_type_class;
3807  {
3808    StackHandleScope<1> hs(Thread::Current());
3809    HandleWrapper<mirror::ArtField> h_field(hs.NewHandleWrapper(&field));
3810    FieldHelper fh(h_field);
3811    field_type_class = fh.GetType(can_load_classes_);
3812  }
3813  const RegType* field_type;
3814  if (field_type_class != nullptr) {
3815    field_type = &reg_types_.FromClass(field->GetTypeDescriptor(), field_type_class,
3816                                       field_type_class->CannotBeAssignedFromOtherTypes());
3817  } else {
3818    Thread* self = Thread::Current();
3819    DCHECK(!can_load_classes_ || self->IsExceptionPending());
3820    self->ClearException();
3821    field_type = &reg_types_.FromDescriptor(field->GetDeclaringClass()->GetClassLoader(),
3822                                            field->GetTypeDescriptor(), false);
3823  }
3824  DCHECK(field_type != nullptr);
3825  const uint32_t vregA = inst->VRegA_22c();
3826  if (is_primitive) {
3827    if (field_type->Equals(insn_type) ||
3828        (field_type->IsFloat() && insn_type.IsIntegralTypes()) ||
3829        (field_type->IsDouble() && insn_type.IsLongTypes())) {
3830      // expected that read is of the correct primitive type or that int reads are reading
3831      // floats or long reads are reading doubles
3832    } else {
3833      // This is a global failure rather than a class change failure as the instructions and
3834      // the descriptors for the type should have been consistent within the same file at
3835      // compile time
3836      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected field " << PrettyField(field)
3837                                        << " to be of type '" << insn_type
3838                                        << "' but found type '" << *field_type << "' in Get";
3839      return;
3840    }
3841  } else {
3842    if (!insn_type.IsAssignableFrom(*field_type)) {
3843      Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "expected field " << PrettyField(field)
3844                                        << " to be compatible with type '" << insn_type
3845                                        << "' but found type '" << *field_type
3846                                        << "' in get-object";
3847      work_line_->SetRegisterType(vregA, reg_types_.Conflict());
3848      return;
3849    }
3850  }
3851  if (!field_type->IsLowHalf()) {
3852    work_line_->SetRegisterType(vregA, *field_type);
3853  } else {
3854    work_line_->SetRegisterTypeWide(vregA, *field_type, field_type->HighHalf(&reg_types_));
3855  }
3856}
3857
3858void MethodVerifier::VerifyIPutQuick(const Instruction* inst, const RegType& insn_type,
3859                                     bool is_primitive) {
3860  DCHECK(Runtime::Current()->IsStarted());
3861  mirror::ArtField* field = GetQuickFieldAccess(inst, work_line_.get());
3862  if (field == NULL) {
3863    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Cannot infer field from " << inst->Name();
3864    return;
3865  }
3866  const char* descriptor = field->GetTypeDescriptor();
3867  mirror::ClassLoader* loader = field->GetDeclaringClass()->GetClassLoader();
3868  const RegType& field_type = reg_types_.FromDescriptor(loader, descriptor, false);
3869  if (field != NULL) {
3870    if (field->IsFinal() && field->GetDeclaringClass() != GetDeclaringClass().GetClass()) {
3871      Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot modify final field " << PrettyField(field)
3872                                      << " from other class " << GetDeclaringClass();
3873      return;
3874    }
3875  }
3876  const uint32_t vregA = inst->VRegA_22c();
3877  if (is_primitive) {
3878    // Primitive field assignability rules are weaker than regular assignability rules
3879    bool instruction_compatible;
3880    bool value_compatible;
3881    const RegType& value_type = work_line_->GetRegisterType(vregA);
3882    if (field_type.IsIntegralTypes()) {
3883      instruction_compatible = insn_type.IsIntegralTypes();
3884      value_compatible = value_type.IsIntegralTypes();
3885    } else if (field_type.IsFloat()) {
3886      instruction_compatible = insn_type.IsInteger();  // no [is]put-float, so expect [is]put-int
3887      value_compatible = value_type.IsFloatTypes();
3888    } else if (field_type.IsLong()) {
3889      instruction_compatible = insn_type.IsLong();
3890      value_compatible = value_type.IsLongTypes();
3891    } else if (field_type.IsDouble()) {
3892      instruction_compatible = insn_type.IsLong();  // no [is]put-double, so expect [is]put-long
3893      value_compatible = value_type.IsDoubleTypes();
3894    } else {
3895      instruction_compatible = false;  // reference field with primitive store
3896      value_compatible = false;  // unused
3897    }
3898    if (!instruction_compatible) {
3899      // This is a global failure rather than a class change failure as the instructions and
3900      // the descriptors for the type should have been consistent within the same file at
3901      // compile time
3902      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected field " << PrettyField(field)
3903                                        << " to be of type '" << insn_type
3904                                        << "' but found type '" << field_type
3905                                        << "' in put";
3906      return;
3907    }
3908    if (!value_compatible) {
3909      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected value in v" << vregA
3910          << " of type " << value_type
3911          << " but expected " << field_type
3912          << " for store to " << PrettyField(field) << " in put";
3913      return;
3914    }
3915  } else {
3916    if (!insn_type.IsAssignableFrom(field_type)) {
3917      Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "expected field " << PrettyField(field)
3918                                        << " to be compatible with type '" << insn_type
3919                                        << "' but found type '" << field_type
3920                                        << "' in put-object";
3921      return;
3922    }
3923    work_line_->VerifyRegisterType(vregA, field_type);
3924  }
3925}
3926
3927bool MethodVerifier::CheckNotMoveException(const uint16_t* insns, int insn_idx) {
3928  if ((insns[insn_idx] & 0xff) == Instruction::MOVE_EXCEPTION) {
3929    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid use of move-exception";
3930    return false;
3931  }
3932  return true;
3933}
3934
3935bool MethodVerifier::UpdateRegisters(uint32_t next_insn, RegisterLine* merge_line,
3936                                     bool update_merge_line) {
3937  bool changed = true;
3938  RegisterLine* target_line = reg_table_.GetLine(next_insn);
3939  if (!insn_flags_[next_insn].IsVisitedOrChanged()) {
3940    /*
3941     * We haven't processed this instruction before, and we haven't touched the registers here, so
3942     * there's nothing to "merge". Copy the registers over and mark it as changed. (This is the
3943     * only way a register can transition out of "unknown", so this is not just an optimization.)
3944     */
3945    if (!insn_flags_[next_insn].IsReturn()) {
3946      target_line->CopyFromLine(merge_line);
3947    } else {
3948      // Verify that the monitor stack is empty on return.
3949      if (!merge_line->VerifyMonitorStackEmpty()) {
3950        return false;
3951      }
3952      // For returns we only care about the operand to the return, all other registers are dead.
3953      // Initialize them as conflicts so they don't add to GC and deoptimization information.
3954      const Instruction* ret_inst = Instruction::At(code_item_->insns_ + next_insn);
3955      Instruction::Code opcode = ret_inst->Opcode();
3956      if ((opcode == Instruction::RETURN_VOID) || (opcode == Instruction::RETURN_VOID_BARRIER)) {
3957        target_line->MarkAllRegistersAsConflicts();
3958      } else {
3959        target_line->CopyFromLine(merge_line);
3960        if (opcode == Instruction::RETURN_WIDE) {
3961          target_line->MarkAllRegistersAsConflictsExceptWide(ret_inst->VRegA_11x());
3962        } else {
3963          target_line->MarkAllRegistersAsConflictsExcept(ret_inst->VRegA_11x());
3964        }
3965      }
3966    }
3967  } else {
3968    std::unique_ptr<RegisterLine> copy(gDebugVerify ?
3969                                 RegisterLine::Create(target_line->NumRegs(), this) :
3970                                 NULL);
3971    if (gDebugVerify) {
3972      copy->CopyFromLine(target_line);
3973    }
3974    changed = target_line->MergeRegisters(merge_line);
3975    if (have_pending_hard_failure_) {
3976      return false;
3977    }
3978    if (gDebugVerify && changed) {
3979      LogVerifyInfo() << "Merging at [" << reinterpret_cast<void*>(work_insn_idx_) << "]"
3980                      << " to [" << reinterpret_cast<void*>(next_insn) << "]: " << "\n"
3981                      << *copy.get() << "  MERGE\n"
3982                      << *merge_line << "  ==\n"
3983                      << *target_line << "\n";
3984    }
3985    if (update_merge_line && changed) {
3986      merge_line->CopyFromLine(target_line);
3987    }
3988  }
3989  if (changed) {
3990    insn_flags_[next_insn].SetChanged();
3991  }
3992  return true;
3993}
3994
3995InstructionFlags* MethodVerifier::CurrentInsnFlags() {
3996  return &insn_flags_[work_insn_idx_];
3997}
3998
3999const RegType& MethodVerifier::GetMethodReturnType() {
4000  if (return_type_ == nullptr) {
4001    if (mirror_method_ != NULL) {
4002      Thread* self = Thread::Current();
4003      StackHandleScope<1> hs(self);
4004      mirror::Class* return_type_class;
4005      {
4006        HandleWrapper<mirror::ArtMethod> h_mirror_method(hs.NewHandleWrapper(&mirror_method_));
4007        return_type_class = MethodHelper(h_mirror_method).GetReturnType(can_load_classes_);
4008      }
4009      if (return_type_class != nullptr) {
4010        return_type_ = &reg_types_.FromClass(mirror_method_->GetReturnTypeDescriptor(),
4011                                             return_type_class,
4012                                             return_type_class->CannotBeAssignedFromOtherTypes());
4013      } else {
4014        DCHECK(!can_load_classes_ || self->IsExceptionPending());
4015        self->ClearException();
4016      }
4017    }
4018    if (return_type_ == nullptr) {
4019      const DexFile::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx_);
4020      const DexFile::ProtoId& proto_id = dex_file_->GetMethodPrototype(method_id);
4021      uint16_t return_type_idx = proto_id.return_type_idx_;
4022      const char* descriptor = dex_file_->GetTypeDescriptor(dex_file_->GetTypeId(return_type_idx));
4023      return_type_ = &reg_types_.FromDescriptor(class_loader_->Get(), descriptor, false);
4024    }
4025  }
4026  return *return_type_;
4027}
4028
4029const RegType& MethodVerifier::GetDeclaringClass() {
4030  if (declaring_class_ == NULL) {
4031    const DexFile::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx_);
4032    const char* descriptor
4033        = dex_file_->GetTypeDescriptor(dex_file_->GetTypeId(method_id.class_idx_));
4034    if (mirror_method_ != NULL) {
4035      mirror::Class* klass = mirror_method_->GetDeclaringClass();
4036      declaring_class_ = &reg_types_.FromClass(descriptor, klass,
4037                                               klass->CannotBeAssignedFromOtherTypes());
4038    } else {
4039      declaring_class_ = &reg_types_.FromDescriptor(class_loader_->Get(), descriptor, false);
4040    }
4041  }
4042  return *declaring_class_;
4043}
4044
4045std::vector<int32_t> MethodVerifier::DescribeVRegs(uint32_t dex_pc) {
4046  RegisterLine* line = reg_table_.GetLine(dex_pc);
4047  DCHECK(line != nullptr) << "No register line at DEX pc " << StringPrintf("0x%x", dex_pc);
4048  std::vector<int32_t> result;
4049  for (size_t i = 0; i < line->NumRegs(); ++i) {
4050    const RegType& type = line->GetRegisterType(i);
4051    if (type.IsConstant()) {
4052      result.push_back(type.IsPreciseConstant() ? kConstant : kImpreciseConstant);
4053      result.push_back(type.ConstantValue());
4054    } else if (type.IsConstantLo()) {
4055      result.push_back(type.IsPreciseConstantLo() ? kConstant : kImpreciseConstant);
4056      result.push_back(type.ConstantValueLo());
4057    } else if (type.IsConstantHi()) {
4058      result.push_back(type.IsPreciseConstantHi() ? kConstant : kImpreciseConstant);
4059      result.push_back(type.ConstantValueHi());
4060    } else if (type.IsIntegralTypes()) {
4061      result.push_back(kIntVReg);
4062      result.push_back(0);
4063    } else if (type.IsFloat()) {
4064      result.push_back(kFloatVReg);
4065      result.push_back(0);
4066    } else if (type.IsLong()) {
4067      result.push_back(kLongLoVReg);
4068      result.push_back(0);
4069      result.push_back(kLongHiVReg);
4070      result.push_back(0);
4071      ++i;
4072    } else if (type.IsDouble()) {
4073      result.push_back(kDoubleLoVReg);
4074      result.push_back(0);
4075      result.push_back(kDoubleHiVReg);
4076      result.push_back(0);
4077      ++i;
4078    } else if (type.IsUndefined() || type.IsConflict() || type.IsHighHalf()) {
4079      result.push_back(kUndefined);
4080      result.push_back(0);
4081    } else {
4082      CHECK(type.IsNonZeroReferenceTypes());
4083      result.push_back(kReferenceVReg);
4084      result.push_back(0);
4085    }
4086  }
4087  return result;
4088}
4089
4090const RegType& MethodVerifier::DetermineCat1Constant(int32_t value, bool precise) {
4091  if (precise) {
4092    // Precise constant type.
4093    return reg_types_.FromCat1Const(value, true);
4094  } else {
4095    // Imprecise constant type.
4096    if (value < -32768) {
4097      return reg_types_.IntConstant();
4098    } else if (value < -128) {
4099      return reg_types_.ShortConstant();
4100    } else if (value < 0) {
4101      return reg_types_.ByteConstant();
4102    } else if (value == 0) {
4103      return reg_types_.Zero();
4104    } else if (value == 1) {
4105      return reg_types_.One();
4106    } else if (value < 128) {
4107      return reg_types_.PosByteConstant();
4108    } else if (value < 32768) {
4109      return reg_types_.PosShortConstant();
4110    } else if (value < 65536) {
4111      return reg_types_.CharConstant();
4112    } else {
4113      return reg_types_.IntConstant();
4114    }
4115  }
4116}
4117
4118void MethodVerifier::Init() {
4119  art::verifier::RegTypeCache::Init();
4120}
4121
4122void MethodVerifier::Shutdown() {
4123  verifier::RegTypeCache::ShutDown();
4124}
4125
4126void MethodVerifier::VisitRoots(RootCallback* callback, void* arg) {
4127  reg_types_.VisitRoots(callback, arg);
4128}
4129
4130}  // namespace verifier
4131}  // namespace art
4132