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