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