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