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