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