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