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