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