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