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