method_verifier.cc revision 834b394ee759ed31c5371d8093d7cd8cd90014a8
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());
2511      if (!IsConstructor()) {
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.
2823  if (!result.IsUnresolvedTypes() && !referrer.IsUnresolvedTypes() && !referrer.CanAccess(result)) {
2824    Fail(VERIFY_ERROR_ACCESS_CLASS) << "illegal class access: '"
2825                                    << referrer << "' -> '" << result << "'";
2826  }
2827  return result;
2828}
2829
2830const RegType& MethodVerifier::GetCaughtExceptionType() {
2831  const RegType* common_super = NULL;
2832  if (code_item_->tries_size_ != 0) {
2833    const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item_, 0);
2834    uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
2835    for (uint32_t i = 0; i < handlers_size; i++) {
2836      CatchHandlerIterator iterator(handlers_ptr);
2837      for (; iterator.HasNext(); iterator.Next()) {
2838        if (iterator.GetHandlerAddress() == (uint32_t) work_insn_idx_) {
2839          if (iterator.GetHandlerTypeIndex() == DexFile::kDexNoIndex16) {
2840            common_super = &reg_types_.JavaLangThrowable(false);
2841          } else {
2842            const RegType& exception = ResolveClassAndCheckAccess(iterator.GetHandlerTypeIndex());
2843            if (common_super == NULL) {
2844              // Unconditionally assign for the first handler. We don't assert this is a Throwable
2845              // as that is caught at runtime
2846              common_super = &exception;
2847            } else if (!reg_types_.JavaLangThrowable(false).IsAssignableFrom(exception)) {
2848              // We don't know enough about the type and the common path merge will result in
2849              // Conflict. Fail here knowing the correct thing can be done at runtime.
2850              Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "unexpected non-exception class " << exception;
2851              return reg_types_.Conflict();
2852            } else if (common_super->Equals(exception)) {
2853              // odd case, but nothing to do
2854            } else {
2855              common_super = &common_super->Merge(exception, &reg_types_);
2856              CHECK(reg_types_.JavaLangThrowable(false).IsAssignableFrom(*common_super));
2857            }
2858          }
2859        }
2860      }
2861      handlers_ptr = iterator.EndDataPointer();
2862    }
2863  }
2864  if (common_super == NULL) {
2865    /* no catch blocks, or no catches with classes we can find */
2866    Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "unable to find exception handler";
2867    return reg_types_.Conflict();
2868  }
2869  return *common_super;
2870}
2871
2872mirror::AbstractMethod* MethodVerifier::ResolveMethodAndCheckAccess(uint32_t dex_method_idx,
2873                                                                    MethodType method_type) {
2874  const DexFile::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx);
2875  const RegType& klass_type = ResolveClassAndCheckAccess(method_id.class_idx_);
2876  if (klass_type.IsConflict()) {
2877    std::string append(" in attempt to access method ");
2878    append += dex_file_->GetMethodName(method_id);
2879    AppendToLastFailMessage(append);
2880    return NULL;
2881  }
2882  if (klass_type.IsUnresolvedTypes()) {
2883    return NULL;  // Can't resolve Class so no more to do here
2884  }
2885  mirror::Class* klass = klass_type.GetClass();
2886  const RegType& referrer = GetDeclaringClass();
2887  mirror::AbstractMethod* res_method = dex_cache_->GetResolvedMethod(dex_method_idx);
2888  if (res_method == NULL) {
2889    const char* name = dex_file_->GetMethodName(method_id);
2890    std::string signature(dex_file_->CreateMethodSignature(method_id.proto_idx_, NULL));
2891
2892    if (method_type == METHOD_DIRECT || method_type == METHOD_STATIC) {
2893      res_method = klass->FindDirectMethod(name, signature);
2894    } else if (method_type == METHOD_INTERFACE) {
2895      res_method = klass->FindInterfaceMethod(name, signature);
2896    } else {
2897      res_method = klass->FindVirtualMethod(name, signature);
2898    }
2899    if (res_method != NULL) {
2900      dex_cache_->SetResolvedMethod(dex_method_idx, res_method);
2901    } else {
2902      // If a virtual or interface method wasn't found with the expected type, look in
2903      // the direct methods. This can happen when the wrong invoke type is used or when
2904      // a class has changed, and will be flagged as an error in later checks.
2905      if (method_type == METHOD_INTERFACE || method_type == METHOD_VIRTUAL) {
2906        res_method = klass->FindDirectMethod(name, signature);
2907      }
2908      if (res_method == NULL) {
2909        Fail(VERIFY_ERROR_NO_METHOD) << "couldn't find method "
2910                                     << PrettyDescriptor(klass) << "." << name
2911                                     << " " << signature;
2912        return NULL;
2913      }
2914    }
2915  }
2916  // Make sure calls to constructors are "direct". There are additional restrictions but we don't
2917  // enforce them here.
2918  if (res_method->IsConstructor() && method_type != METHOD_DIRECT) {
2919    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "rejecting non-direct call to constructor "
2920                                      << PrettyMethod(res_method);
2921    return NULL;
2922  }
2923  // Disallow any calls to class initializers.
2924  if (MethodHelper(res_method).IsClassInitializer()) {
2925    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "rejecting call to class initializer "
2926                                      << PrettyMethod(res_method);
2927    return NULL;
2928  }
2929  // Check if access is allowed.
2930  if (!referrer.CanAccessMember(res_method->GetDeclaringClass(), res_method->GetAccessFlags())) {
2931    Fail(VERIFY_ERROR_ACCESS_METHOD) << "illegal method access (call " << PrettyMethod(res_method)
2932                                     << " from " << referrer << ")";
2933    return res_method;
2934  }
2935  // Check that invoke-virtual and invoke-super are not used on private methods of the same class.
2936  if (res_method->IsPrivate() && method_type == METHOD_VIRTUAL) {
2937    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invoke-super/virtual can't be used on private method "
2938                                      << PrettyMethod(res_method);
2939    return NULL;
2940  }
2941  // Check that interface methods match interface classes.
2942  if (klass->IsInterface() && method_type != METHOD_INTERFACE) {
2943    Fail(VERIFY_ERROR_CLASS_CHANGE) << "non-interface method " << PrettyMethod(res_method)
2944                                    << " is in an interface class " << PrettyClass(klass);
2945    return NULL;
2946  } else if (!klass->IsInterface() && method_type == METHOD_INTERFACE) {
2947    Fail(VERIFY_ERROR_CLASS_CHANGE) << "interface method " << PrettyMethod(res_method)
2948                                    << " is in a non-interface class " << PrettyClass(klass);
2949    return NULL;
2950  }
2951  // See if the method type implied by the invoke instruction matches the access flags for the
2952  // target method.
2953  if ((method_type == METHOD_DIRECT && !res_method->IsDirect()) ||
2954      (method_type == METHOD_STATIC && !res_method->IsStatic()) ||
2955      ((method_type == METHOD_VIRTUAL || method_type == METHOD_INTERFACE) && res_method->IsDirect())
2956      ) {
2957    Fail(VERIFY_ERROR_CLASS_CHANGE) << "invoke type (" << method_type << ") does not match method "
2958                                       " type of " << PrettyMethod(res_method);
2959    return NULL;
2960  }
2961  return res_method;
2962}
2963
2964mirror::AbstractMethod* MethodVerifier::VerifyInvocationArgs(const Instruction* inst,
2965                                                             MethodType method_type,
2966                                                             bool is_range,
2967                                                             bool is_super) {
2968  // Resolve the method. This could be an abstract or concrete method depending on what sort of call
2969  // we're making.
2970  const uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c();
2971  mirror::AbstractMethod* res_method = ResolveMethodAndCheckAccess(method_idx, method_type);
2972  if (res_method == NULL) {  // error or class is unresolved
2973    return NULL;
2974  }
2975
2976  // If we're using invoke-super(method), make sure that the executing method's class' superclass
2977  // has a vtable entry for the target method.
2978  if (is_super) {
2979    DCHECK(method_type == METHOD_VIRTUAL);
2980    const RegType& super = GetDeclaringClass().GetSuperClass(&reg_types_);
2981    if (super.IsUnresolvedTypes()) {
2982      Fail(VERIFY_ERROR_NO_METHOD) << "unknown super class in invoke-super from "
2983                                   << PrettyMethod(dex_method_idx_, *dex_file_)
2984                                   << " to super " << PrettyMethod(res_method);
2985      return NULL;
2986    }
2987    mirror::Class* super_klass = super.GetClass();
2988    if (res_method->GetMethodIndex() >= super_klass->GetVTable()->GetLength()) {
2989      MethodHelper mh(res_method);
2990      Fail(VERIFY_ERROR_NO_METHOD) << "invalid invoke-super from "
2991                                   << PrettyMethod(dex_method_idx_, *dex_file_)
2992                                   << " to super " << super
2993                                   << "." << mh.GetName()
2994                                   << mh.GetSignature();
2995      return NULL;
2996    }
2997  }
2998  // We use vAA as our expected arg count, rather than res_method->insSize, because we need to
2999  // match the call to the signature. Also, we might be calling through an abstract method
3000  // definition (which doesn't have register count values).
3001  const size_t expected_args = (is_range) ? inst->VRegA_3rc() : inst->VRegA_35c();
3002  /* caught by static verifier */
3003  DCHECK(is_range || expected_args <= 5);
3004  if (expected_args > code_item_->outs_size_) {
3005    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid argument count (" << expected_args
3006        << ") exceeds outsSize (" << code_item_->outs_size_ << ")";
3007    return NULL;
3008  }
3009
3010  /*
3011   * Check the "this" argument, which must be an instance of the class that declared the method.
3012   * For an interface class, we don't do the full interface merge (see JoinClass), so we can't do a
3013   * rigorous check here (which is okay since we have to do it at runtime).
3014   */
3015  size_t actual_args = 0;
3016  if (!res_method->IsStatic()) {
3017    const RegType& actual_arg_type = work_line_->GetInvocationThis(inst, is_range);
3018    if (actual_arg_type.IsConflict()) {  // GetInvocationThis failed.
3019      return NULL;
3020    }
3021    if (actual_arg_type.IsUninitializedReference() && !res_method->IsConstructor()) {
3022      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "'this' arg must be initialized";
3023      return NULL;
3024    }
3025    if (method_type != METHOD_INTERFACE && !actual_arg_type.IsZero()) {
3026      mirror::Class* klass = res_method->GetDeclaringClass();
3027      const RegType& res_method_class =
3028          reg_types_.FromClass(ClassHelper(klass).GetDescriptor(), klass,
3029                               klass->CannotBeAssignedFromOtherTypes());
3030      if (!res_method_class.IsAssignableFrom(actual_arg_type)) {
3031        Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "'this' argument '" << actual_arg_type
3032            << "' not instance of '" << res_method_class << "'";
3033        return NULL;
3034      }
3035    }
3036    actual_args++;
3037  }
3038  /*
3039   * Process the target method's signature. This signature may or may not
3040   * have been verified, so we can't assume it's properly formed.
3041   */
3042  MethodHelper mh(res_method);
3043  const DexFile::TypeList* params = mh.GetParameterTypeList();
3044  size_t params_size = params == NULL ? 0 : params->Size();
3045  uint32_t arg[5];
3046  if (!is_range) {
3047    inst->GetArgs(arg);
3048  }
3049  for (size_t param_index = 0; param_index < params_size; param_index++) {
3050    if (actual_args >= expected_args) {
3051      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invalid call to '" << PrettyMethod(res_method)
3052          << "'. Expected " << expected_args << " arguments, processing argument " << actual_args
3053          << " (where longs/doubles count twice).";
3054      return NULL;
3055    }
3056    const char* descriptor =
3057        mh.GetTypeDescriptorFromTypeIdx(params->GetTypeItem(param_index).type_idx_);
3058    if (descriptor == NULL) {
3059      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation of " << PrettyMethod(res_method)
3060          << " missing signature component";
3061      return NULL;
3062    }
3063    const RegType& reg_type = reg_types_.FromDescriptor(class_loader_, descriptor, false);
3064    uint32_t get_reg = is_range ? inst->VRegC_3rc() + actual_args : arg[actual_args];
3065    if (!work_line_->VerifyRegisterType(get_reg, reg_type)) {
3066      return res_method;
3067    }
3068    actual_args = reg_type.IsLongOrDoubleTypes() ? actual_args + 2 : actual_args + 1;
3069  }
3070  if (actual_args != expected_args) {
3071    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation of " << PrettyMethod(res_method)
3072        << " expected " << expected_args << " arguments, found " << actual_args;
3073    return NULL;
3074  } else {
3075    return res_method;
3076  }
3077}
3078
3079mirror::AbstractMethod* MethodVerifier::GetQuickInvokedMethod(const Instruction* inst,
3080                                                              RegisterLine* reg_line,
3081                                                              bool is_range) {
3082  DCHECK(inst->Opcode() == Instruction::INVOKE_VIRTUAL_QUICK ||
3083         inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE_QUICK);
3084  const RegType& actual_arg_type = reg_line->GetInvocationThis(inst, is_range);
3085  if (actual_arg_type.IsConflict()) {  // GetInvocationThis failed.
3086    return NULL;
3087  }
3088  mirror::Class* this_class = NULL;
3089  if (!actual_arg_type.IsUnresolvedTypes()) {
3090    this_class = actual_arg_type.GetClass();
3091  } else {
3092    const std::string& descriptor(actual_arg_type.GetDescriptor());
3093    ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
3094    this_class = class_linker->FindClass(descriptor.c_str(), class_loader_);
3095    if (this_class == NULL) {
3096      Thread::Current()->ClearException();
3097      // Look for a system class
3098      this_class = class_linker->FindClass(descriptor.c_str(), NULL);
3099    }
3100  }
3101  if (this_class == NULL) {
3102    return NULL;
3103  }
3104  mirror::ObjectArray<mirror::AbstractMethod>* vtable = this_class->GetVTable();
3105  CHECK(vtable != NULL);
3106  uint16_t vtable_index = is_range ? inst->VRegB_3rc() : inst->VRegB_35c();
3107  CHECK(vtable_index < vtable->GetLength());
3108  mirror::AbstractMethod* res_method = vtable->Get(vtable_index);
3109  CHECK(!Thread::Current()->IsExceptionPending());
3110  return res_method;
3111}
3112
3113mirror::AbstractMethod* MethodVerifier::VerifyInvokeVirtualQuickArgs(const Instruction* inst,
3114                                                                     bool is_range) {
3115  DCHECK(Runtime::Current()->IsStarted());
3116  mirror::AbstractMethod* res_method = GetQuickInvokedMethod(inst, work_line_.get(),
3117                                                             is_range);
3118  if (res_method == NULL) {
3119    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Cannot infer method from " << inst->Name();
3120    return NULL;
3121  }
3122  CHECK(!res_method->IsDirect() && !res_method->IsStatic());
3123
3124  // We use vAA as our expected arg count, rather than res_method->insSize, because we need to
3125  // match the call to the signature. Also, we might be calling through an abstract method
3126  // definition (which doesn't have register count values).
3127  const RegType& actual_arg_type = work_line_->GetInvocationThis(inst, is_range);
3128  if (actual_arg_type.IsConflict()) {  // GetInvocationThis failed.
3129    return NULL;
3130  }
3131  const size_t expected_args = (is_range) ? inst->VRegA_3rc() : inst->VRegA_35c();
3132  /* caught by static verifier */
3133  DCHECK(is_range || expected_args <= 5);
3134  if (expected_args > code_item_->outs_size_) {
3135    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid argument count (" << expected_args
3136        << ") exceeds outsSize (" << code_item_->outs_size_ << ")";
3137    return NULL;
3138  }
3139
3140  /*
3141   * Check the "this" argument, which must be an instance of the class that declared the method.
3142   * For an interface class, we don't do the full interface merge (see JoinClass), so we can't do a
3143   * rigorous check here (which is okay since we have to do it at runtime).
3144   */
3145  if (actual_arg_type.IsUninitializedReference() && !res_method->IsConstructor()) {
3146    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "'this' arg must be initialized";
3147    return NULL;
3148  }
3149  if (!actual_arg_type.IsZero()) {
3150    mirror::Class* klass = res_method->GetDeclaringClass();
3151    const RegType& res_method_class =
3152        reg_types_.FromClass(ClassHelper(klass).GetDescriptor(), klass,
3153                             klass->CannotBeAssignedFromOtherTypes());
3154    if (!res_method_class.IsAssignableFrom(actual_arg_type)) {
3155      Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "'this' argument '" << actual_arg_type
3156          << "' not instance of '" << res_method_class << "'";
3157      return NULL;
3158    }
3159  }
3160  /*
3161   * Process the target method's signature. This signature may or may not
3162   * have been verified, so we can't assume it's properly formed.
3163   */
3164  MethodHelper mh(res_method);
3165  const DexFile::TypeList* params = mh.GetParameterTypeList();
3166  size_t params_size = params == NULL ? 0 : params->Size();
3167  uint32_t arg[5];
3168  if (!is_range) {
3169    inst->GetArgs(arg);
3170  }
3171  size_t actual_args = 1;
3172  for (size_t param_index = 0; param_index < params_size; param_index++) {
3173    if (actual_args >= expected_args) {
3174      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invalid call to '" << PrettyMethod(res_method)
3175                                        << "'. Expected " << expected_args
3176                                         << " arguments, processing argument " << actual_args
3177                                        << " (where longs/doubles count twice).";
3178      return NULL;
3179    }
3180    const char* descriptor =
3181        mh.GetTypeDescriptorFromTypeIdx(params->GetTypeItem(param_index).type_idx_);
3182    if (descriptor == NULL) {
3183      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation of " << PrettyMethod(res_method)
3184                                        << " missing signature component";
3185      return NULL;
3186    }
3187    const RegType& reg_type = reg_types_.FromDescriptor(class_loader_, descriptor, false);
3188    uint32_t get_reg = is_range ? inst->VRegC_3rc() + actual_args : arg[actual_args];
3189    if (!work_line_->VerifyRegisterType(get_reg, reg_type)) {
3190      return res_method;
3191    }
3192    actual_args = reg_type.IsLongOrDoubleTypes() ? actual_args + 2 : actual_args + 1;
3193  }
3194  if (actual_args != expected_args) {
3195    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation of " << PrettyMethod(res_method)
3196              << " expected " << expected_args << " arguments, found " << actual_args;
3197    return NULL;
3198  } else {
3199    return res_method;
3200  }
3201}
3202
3203void MethodVerifier::VerifyNewArray(const Instruction* inst, bool is_filled, bool is_range) {
3204  uint32_t type_idx;
3205  if (!is_filled) {
3206    DCHECK_EQ(inst->Opcode(), Instruction::NEW_ARRAY);
3207    type_idx = inst->VRegC_22c();
3208  } else if (!is_range) {
3209    DCHECK_EQ(inst->Opcode(), Instruction::FILLED_NEW_ARRAY);
3210    type_idx = inst->VRegB_35c();
3211  } else {
3212    DCHECK_EQ(inst->Opcode(), Instruction::FILLED_NEW_ARRAY_RANGE);
3213    type_idx = inst->VRegB_3rc();
3214  }
3215  const RegType& res_type = ResolveClassAndCheckAccess(type_idx);
3216  if (res_type.IsConflict()) {  // bad class
3217    DCHECK_NE(failures_.size(), 0U);
3218  } else {
3219    // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved
3220    if (!res_type.IsArrayTypes()) {
3221      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "new-array on non-array class " << res_type;
3222    } else if (!is_filled) {
3223      /* make sure "size" register is valid type */
3224      work_line_->VerifyRegisterType(inst->VRegB_22c(), reg_types_.Integer());
3225      /* set register type to array class */
3226      const RegType& precise_type = reg_types_.FromUninitialized(res_type);
3227      work_line_->SetRegisterType(inst->VRegA_22c(), precise_type);
3228    } else {
3229      // Verify each register. If "arg_count" is bad, VerifyRegisterType() will run off the end of
3230      // the list and fail. It's legal, if silly, for arg_count to be zero.
3231      const RegType& expected_type = reg_types_.GetComponentType(res_type, class_loader_);
3232      uint32_t arg_count = (is_range) ? inst->VRegA_3rc() : inst->VRegA_35c();
3233      uint32_t arg[5];
3234      if (!is_range) {
3235        inst->GetArgs(arg);
3236      }
3237      for (size_t ui = 0; ui < arg_count; ui++) {
3238        uint32_t get_reg = is_range ? inst->VRegC_3rc() + ui : arg[ui];
3239        if (!work_line_->VerifyRegisterType(get_reg, expected_type)) {
3240          work_line_->SetResultRegisterType(reg_types_.Conflict());
3241          return;
3242        }
3243      }
3244      // filled-array result goes into "result" register
3245      const RegType& precise_type = reg_types_.FromUninitialized(res_type);
3246      work_line_->SetResultRegisterType(precise_type);
3247    }
3248  }
3249}
3250
3251void MethodVerifier::VerifyAGet(const Instruction* inst,
3252                                const RegType& insn_type, bool is_primitive) {
3253  const RegType& index_type = work_line_->GetRegisterType(inst->VRegC_23x());
3254  if (!index_type.IsArrayIndexTypes()) {
3255    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Invalid reg type for array index (" << index_type << ")";
3256  } else {
3257    const RegType& array_type = work_line_->GetRegisterType(inst->VRegB_23x());
3258    if (array_type.IsZero()) {
3259      // Null array class; this code path will fail at runtime. Infer a merge-able type from the
3260      // instruction type. TODO: have a proper notion of bottom here.
3261      if (!is_primitive || insn_type.IsCategory1Types()) {
3262        // Reference or category 1
3263        work_line_->SetRegisterType(inst->VRegA_23x(), reg_types_.Zero());
3264      } else {
3265        // Category 2
3266        work_line_->SetRegisterTypeWide(inst->VRegA_23x(), reg_types_.FromCat2ConstLo(0, false),
3267                                        reg_types_.FromCat2ConstHi(0, false));
3268      }
3269    } else if (!array_type.IsArrayTypes()) {
3270      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "not array type " << array_type << " with aget";
3271    } else {
3272      /* verify the class */
3273      const RegType& component_type = reg_types_.GetComponentType(array_type, class_loader_);
3274      if (!component_type.IsReferenceTypes() && !is_primitive) {
3275        Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "primitive array type " << array_type
3276            << " source for aget-object";
3277      } else if (component_type.IsNonZeroReferenceTypes() && is_primitive) {
3278        Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "reference array type " << array_type
3279            << " source for category 1 aget";
3280      } else if (is_primitive && !insn_type.Equals(component_type) &&
3281                 !((insn_type.IsInteger() && component_type.IsFloat()) ||
3282                 (insn_type.IsLong() && component_type.IsDouble()))) {
3283        Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array type " << array_type
3284            << " incompatible with aget of type " << insn_type;
3285      } else {
3286        // Use knowledge of the field type which is stronger than the type inferred from the
3287        // instruction, which can't differentiate object types and ints from floats, longs from
3288        // doubles.
3289        if (!component_type.IsLowHalf()) {
3290          work_line_->SetRegisterType(inst->VRegA_23x(), component_type);
3291        } else {
3292          work_line_->SetRegisterTypeWide(inst->VRegA_23x(), component_type,
3293                                          component_type.HighHalf(&reg_types_));
3294        }
3295      }
3296    }
3297  }
3298}
3299
3300void MethodVerifier::VerifyAPut(const Instruction* inst,
3301                             const RegType& insn_type, bool is_primitive) {
3302  const RegType& index_type = work_line_->GetRegisterType(inst->VRegC_23x());
3303  if (!index_type.IsArrayIndexTypes()) {
3304    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Invalid reg type for array index (" << index_type << ")";
3305  } else {
3306    const RegType& array_type = work_line_->GetRegisterType(inst->VRegB_23x());
3307    if (array_type.IsZero()) {
3308      // Null array type; this code path will fail at runtime. Infer a merge-able type from the
3309      // instruction type.
3310    } else if (!array_type.IsArrayTypes()) {
3311      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "not array type " << array_type << " with aput";
3312    } else {
3313      /* verify the class */
3314      const RegType& component_type = reg_types_.GetComponentType(array_type, class_loader_);
3315      if (!component_type.IsReferenceTypes() && !is_primitive) {
3316        Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "primitive array type " << array_type
3317            << " source for aput-object";
3318      } else if (component_type.IsNonZeroReferenceTypes() && is_primitive) {
3319        Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "reference array type " << array_type
3320            << " source for category 1 aput";
3321      } else if (is_primitive && !insn_type.Equals(component_type) &&
3322                 !((insn_type.IsInteger() && component_type.IsFloat()) ||
3323                   (insn_type.IsLong() && component_type.IsDouble()))) {
3324        Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array type " << array_type
3325            << " incompatible with aput of type " << insn_type;
3326      } else {
3327        // The instruction agrees with the type of array, confirm the value to be stored does too
3328        // Note: we use the instruction type (rather than the component type) for aput-object as
3329        // incompatible classes will be caught at runtime as an array store exception
3330        work_line_->VerifyRegisterType(inst->VRegA_23x(),
3331                                       is_primitive ? component_type : insn_type);
3332      }
3333    }
3334  }
3335}
3336
3337mirror::Field* MethodVerifier::GetStaticField(int field_idx) {
3338  const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx);
3339  // Check access to class
3340  const RegType& klass_type = ResolveClassAndCheckAccess(field_id.class_idx_);
3341  if (klass_type.IsConflict()) {  // bad class
3342    AppendToLastFailMessage(StringPrintf(" in attempt to access static field %d (%s) in %s",
3343                                         field_idx, dex_file_->GetFieldName(field_id),
3344                                         dex_file_->GetFieldDeclaringClassDescriptor(field_id)));
3345    return NULL;
3346  }
3347  if (klass_type.IsUnresolvedTypes()) {
3348    return NULL;  // Can't resolve Class so no more to do here, will do checking at runtime.
3349  }
3350  mirror::Field* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(*dex_file_,
3351                                                                               field_idx,
3352                                                                               dex_cache_,
3353                                                                               class_loader_);
3354  if (field == NULL) {
3355    LOG(INFO) << "Unable to resolve static field " << field_idx << " ("
3356              << dex_file_->GetFieldName(field_id) << ") in "
3357              << dex_file_->GetFieldDeclaringClassDescriptor(field_id);
3358    DCHECK(Thread::Current()->IsExceptionPending());
3359    Thread::Current()->ClearException();
3360    return NULL;
3361  } else if (!GetDeclaringClass().CanAccessMember(field->GetDeclaringClass(),
3362                                                  field->GetAccessFlags())) {
3363    Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot access static field " << PrettyField(field)
3364                                    << " from " << GetDeclaringClass();
3365    return NULL;
3366  } else if (!field->IsStatic()) {
3367    Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected field " << PrettyField(field) << " to be static";
3368    return NULL;
3369  } else {
3370    return field;
3371  }
3372}
3373
3374mirror::Field* MethodVerifier::GetInstanceField(const RegType& obj_type, int field_idx) {
3375  const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx);
3376  // Check access to class
3377  const RegType& klass_type = ResolveClassAndCheckAccess(field_id.class_idx_);
3378  if (klass_type.IsConflict()) {
3379    AppendToLastFailMessage(StringPrintf(" in attempt to access instance field %d (%s) in %s",
3380                                         field_idx, dex_file_->GetFieldName(field_id),
3381                                         dex_file_->GetFieldDeclaringClassDescriptor(field_id)));
3382    return NULL;
3383  }
3384  if (klass_type.IsUnresolvedTypes()) {
3385    return NULL;  // Can't resolve Class so no more to do here
3386  }
3387  mirror::Field* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(*dex_file_,
3388                                                                               field_idx,
3389                                                                               dex_cache_,
3390                                                                               class_loader_);
3391  if (field == NULL) {
3392    LOG(INFO) << "Unable to resolve instance field " << field_idx << " ("
3393              << dex_file_->GetFieldName(field_id) << ") in "
3394              << dex_file_->GetFieldDeclaringClassDescriptor(field_id);
3395    DCHECK(Thread::Current()->IsExceptionPending());
3396    Thread::Current()->ClearException();
3397    return NULL;
3398  } else if (!GetDeclaringClass().CanAccessMember(field->GetDeclaringClass(),
3399                                                  field->GetAccessFlags())) {
3400    Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot access instance field " << PrettyField(field)
3401                                    << " from " << GetDeclaringClass();
3402    return NULL;
3403  } else if (field->IsStatic()) {
3404    Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected field " << PrettyField(field)
3405                                    << " to not be static";
3406    return NULL;
3407  } else if (obj_type.IsZero()) {
3408    // Cannot infer and check type, however, access will cause null pointer exception
3409    return field;
3410  } else {
3411    mirror::Class* klass = field->GetDeclaringClass();
3412    const RegType& field_klass =
3413        reg_types_.FromClass(dex_file_->GetFieldDeclaringClassDescriptor(field_id),
3414                             klass, klass->CannotBeAssignedFromOtherTypes());
3415    if (obj_type.IsUninitializedTypes() &&
3416        (!IsConstructor() || GetDeclaringClass().Equals(obj_type) ||
3417            !field_klass.Equals(GetDeclaringClass()))) {
3418      // Field accesses through uninitialized references are only allowable for constructors where
3419      // the field is declared in this class
3420      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "cannot access instance field " << PrettyField(field)
3421                                        << " of a not fully initialized object within the context"
3422                                        << " of " << PrettyMethod(dex_method_idx_, *dex_file_);
3423      return NULL;
3424    } else if (!field_klass.IsAssignableFrom(obj_type)) {
3425      // Trying to access C1.field1 using reference of type C2, which is neither C1 or a sub-class
3426      // of C1. For resolution to occur the declared class of the field must be compatible with
3427      // obj_type, we've discovered this wasn't so, so report the field didn't exist.
3428      Fail(VERIFY_ERROR_NO_FIELD) << "cannot access instance field " << PrettyField(field)
3429                                  << " from object of type " << obj_type;
3430      return NULL;
3431    } else {
3432      return field;
3433    }
3434  }
3435}
3436
3437void MethodVerifier::VerifyISGet(const Instruction* inst, const RegType& insn_type,
3438                                 bool is_primitive, bool is_static) {
3439  uint32_t field_idx = is_static ? inst->VRegB_21c() : inst->VRegC_22c();
3440  mirror::Field* field;
3441  if (is_static) {
3442    field = GetStaticField(field_idx);
3443  } else {
3444    const RegType& object_type = work_line_->GetRegisterType(inst->VRegB_22c());
3445    field = GetInstanceField(object_type, field_idx);
3446  }
3447  const char* descriptor;
3448  mirror::ClassLoader* loader;
3449  if (field != NULL) {
3450    descriptor = FieldHelper(field).GetTypeDescriptor();
3451    loader = field->GetDeclaringClass()->GetClassLoader();
3452  } else {
3453    const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx);
3454    descriptor = dex_file_->GetFieldTypeDescriptor(field_id);
3455    loader = class_loader_;
3456  }
3457  const RegType& field_type = reg_types_.FromDescriptor(loader, descriptor, false);
3458  const uint32_t vregA = (is_static) ? inst->VRegA_21c() : inst->VRegA_22c();
3459  if (is_primitive) {
3460    if (field_type.Equals(insn_type) ||
3461        (field_type.IsFloat() && insn_type.IsIntegralTypes()) ||
3462        (field_type.IsDouble() && insn_type.IsLongTypes())) {
3463      // expected that read is of the correct primitive type or that int reads are reading
3464      // floats or long reads are reading doubles
3465    } else {
3466      // This is a global failure rather than a class change failure as the instructions and
3467      // the descriptors for the type should have been consistent within the same file at
3468      // compile time
3469      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected field " << PrettyField(field)
3470                                        << " to be of type '" << insn_type
3471                                        << "' but found type '" << field_type << "' in get";
3472      return;
3473    }
3474  } else {
3475    if (!insn_type.IsAssignableFrom(field_type)) {
3476      Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "expected field " << PrettyField(field)
3477                                        << " to be compatible with type '" << insn_type
3478                                        << "' but found type '" << field_type
3479                                        << "' in get-object";
3480      work_line_->SetRegisterType(vregA, reg_types_.Conflict());
3481      return;
3482    }
3483  }
3484  if (!field_type.IsLowHalf()) {
3485    work_line_->SetRegisterType(vregA, field_type);
3486  } else {
3487    work_line_->SetRegisterTypeWide(vregA, field_type, field_type.HighHalf(&reg_types_));
3488  }
3489}
3490
3491void MethodVerifier::VerifyISPut(const Instruction* inst, const RegType& insn_type,
3492                                 bool is_primitive, bool is_static) {
3493  uint32_t field_idx = is_static ? inst->VRegB_21c() : inst->VRegC_22c();
3494  mirror::Field* field;
3495  if (is_static) {
3496    field = GetStaticField(field_idx);
3497  } else {
3498    const RegType& object_type = work_line_->GetRegisterType(inst->VRegB_22c());
3499    field = GetInstanceField(object_type, field_idx);
3500  }
3501  const char* descriptor;
3502  mirror::ClassLoader* loader;
3503  if (field != NULL) {
3504    descriptor = FieldHelper(field).GetTypeDescriptor();
3505    loader = field->GetDeclaringClass()->GetClassLoader();
3506  } else {
3507    const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx);
3508    descriptor = dex_file_->GetFieldTypeDescriptor(field_id);
3509    loader = class_loader_;
3510  }
3511  const RegType& field_type = reg_types_.FromDescriptor(loader, descriptor, false);
3512  if (field != NULL) {
3513    if (field->IsFinal() && field->GetDeclaringClass() != GetDeclaringClass().GetClass()) {
3514      Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot modify final field " << PrettyField(field)
3515                                      << " from other class " << GetDeclaringClass();
3516      return;
3517    }
3518  }
3519  const uint32_t vregA = (is_static) ? inst->VRegA_21c() : inst->VRegA_22c();
3520  if (is_primitive) {
3521    // Primitive field assignability rules are weaker than regular assignability rules
3522    bool instruction_compatible;
3523    bool value_compatible;
3524    const RegType& value_type = work_line_->GetRegisterType(vregA);
3525    if (field_type.IsIntegralTypes()) {
3526      instruction_compatible = insn_type.IsIntegralTypes();
3527      value_compatible = value_type.IsIntegralTypes();
3528    } else if (field_type.IsFloat()) {
3529      instruction_compatible = insn_type.IsInteger();  // no [is]put-float, so expect [is]put-int
3530      value_compatible = value_type.IsFloatTypes();
3531    } else if (field_type.IsLong()) {
3532      instruction_compatible = insn_type.IsLong();
3533      value_compatible = value_type.IsLongTypes();
3534    } else if (field_type.IsDouble()) {
3535      instruction_compatible = insn_type.IsLong();  // no [is]put-double, so expect [is]put-long
3536      value_compatible = value_type.IsDoubleTypes();
3537    } else {
3538      instruction_compatible = false;  // reference field with primitive store
3539      value_compatible = false;  // unused
3540    }
3541    if (!instruction_compatible) {
3542      // This is a global failure rather than a class change failure as the instructions and
3543      // the descriptors for the type should have been consistent within the same file at
3544      // compile time
3545      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected field " << PrettyField(field)
3546                                        << " to be of type '" << insn_type
3547                                        << "' but found type '" << field_type
3548                                        << "' in put";
3549      return;
3550    }
3551    if (!value_compatible) {
3552      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected value in v" << vregA
3553          << " of type " << value_type
3554          << " but expected " << field_type
3555          << " for store to " << PrettyField(field) << " in put";
3556      return;
3557    }
3558  } else {
3559    if (!insn_type.IsAssignableFrom(field_type)) {
3560      Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "expected field " << PrettyField(field)
3561                                        << " to be compatible with type '" << insn_type
3562                                        << "' but found type '" << field_type
3563                                        << "' in put-object";
3564      return;
3565    }
3566    work_line_->VerifyRegisterType(vregA, field_type);
3567  }
3568}
3569
3570// Look for an instance field with this offset.
3571// TODO: we may speed up the search if offsets are sorted by doing a quick search.
3572static mirror::Field* FindInstanceFieldWithOffset(const mirror::Class* klass,
3573                                                  uint32_t field_offset)
3574    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3575  const mirror::ObjectArray<mirror::Field>* instance_fields = klass->GetIFields();
3576  if (instance_fields != NULL) {
3577    for (int32_t i = 0, e = instance_fields->GetLength(); i < e; ++i) {
3578      mirror::Field* field = instance_fields->Get(i);
3579      if (field->GetOffset().Uint32Value() == field_offset) {
3580        return field;
3581      }
3582    }
3583  }
3584  // We did not find field in class: look into superclass.
3585  if (klass->GetSuperClass() != NULL) {
3586    return FindInstanceFieldWithOffset(klass->GetSuperClass(), field_offset);
3587  } else {
3588    return NULL;
3589  }
3590}
3591
3592// Returns the access field of a quick field access (iget/iput-quick) or NULL
3593// if it cannot be found.
3594mirror::Field* MethodVerifier::GetQuickFieldAccess(const Instruction* inst,
3595                                                   RegisterLine* reg_line) {
3596  DCHECK(inst->Opcode() == Instruction::IGET_QUICK ||
3597         inst->Opcode() == Instruction::IGET_WIDE_QUICK ||
3598         inst->Opcode() == Instruction::IGET_OBJECT_QUICK ||
3599         inst->Opcode() == Instruction::IPUT_QUICK ||
3600         inst->Opcode() == Instruction::IPUT_WIDE_QUICK ||
3601         inst->Opcode() == Instruction::IPUT_OBJECT_QUICK);
3602  const RegType& object_type = reg_line->GetRegisterType(inst->VRegB_22c());
3603  mirror::Class* object_class = NULL;
3604  if (!object_type.IsUnresolvedTypes()) {
3605    object_class = object_type.GetClass();
3606  } else {
3607    // We need to resolve the class from its descriptor.
3608    const std::string& descriptor(object_type.GetDescriptor());
3609    ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
3610    object_class = class_linker->FindClass(descriptor.c_str(), class_loader_);
3611    if (object_class == NULL) {
3612      Thread::Current()->ClearException();
3613      // Look for a system class
3614      object_class = class_linker->FindClass(descriptor.c_str(), NULL);
3615    }
3616  }
3617  if (object_class == NULL) {
3618    // Failed to get the Class* from reg type.
3619    LOG(WARNING) << "Failed to get Class* from " << object_type;
3620    return NULL;
3621  }
3622  uint32_t field_offset = static_cast<uint32_t>(inst->VRegC_22c());
3623  return FindInstanceFieldWithOffset(object_class, field_offset);
3624}
3625
3626void MethodVerifier::VerifyIGetQuick(const Instruction* inst, const RegType& insn_type,
3627                                     bool is_primitive) {
3628  DCHECK(Runtime::Current()->IsStarted());
3629  mirror::Field* field = GetQuickFieldAccess(inst, work_line_.get());
3630  if (field == NULL) {
3631    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Cannot infer field from " << inst->Name();
3632    return;
3633  }
3634  const char* descriptor = FieldHelper(field).GetTypeDescriptor();
3635  mirror::ClassLoader* loader = field->GetDeclaringClass()->GetClassLoader();
3636  const RegType& field_type = reg_types_.FromDescriptor(loader, descriptor, false);
3637  const uint32_t vregA = inst->VRegA_22c();
3638  if (is_primitive) {
3639    if (field_type.Equals(insn_type) ||
3640        (field_type.IsFloat() && insn_type.IsIntegralTypes()) ||
3641        (field_type.IsDouble() && insn_type.IsLongTypes())) {
3642      // expected that read is of the correct primitive type or that int reads are reading
3643      // floats or long reads are reading doubles
3644    } else {
3645      // This is a global failure rather than a class change failure as the instructions and
3646      // the descriptors for the type should have been consistent within the same file at
3647      // compile time
3648      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected field " << PrettyField(field)
3649                                        << " to be of type '" << insn_type
3650                                        << "' but found type '" << field_type << "' in get";
3651      return;
3652    }
3653  } else {
3654    if (!insn_type.IsAssignableFrom(field_type)) {
3655      Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "expected field " << PrettyField(field)
3656                                        << " to be compatible with type '" << insn_type
3657                                        << "' but found type '" << field_type
3658                                        << "' in get-object";
3659      work_line_->SetRegisterType(vregA, reg_types_.Conflict());
3660      return;
3661    }
3662  }
3663  if (!field_type.IsLowHalf()) {
3664    work_line_->SetRegisterType(vregA, field_type);
3665  } else {
3666    work_line_->SetRegisterTypeWide(vregA, field_type, field_type.HighHalf(&reg_types_));
3667  }
3668}
3669
3670void MethodVerifier::VerifyIPutQuick(const Instruction* inst, const RegType& insn_type,
3671                                     bool is_primitive) {
3672  DCHECK(Runtime::Current()->IsStarted());
3673  mirror::Field* field = GetQuickFieldAccess(inst, work_line_.get());
3674  if (field == NULL) {
3675    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Cannot infer field from " << inst->Name();
3676    return;
3677  }
3678  const char* descriptor = FieldHelper(field).GetTypeDescriptor();
3679  mirror::ClassLoader* loader = field->GetDeclaringClass()->GetClassLoader();
3680  const RegType& field_type = reg_types_.FromDescriptor(loader, descriptor, false);
3681  if (field != NULL) {
3682    if (field->IsFinal() && field->GetDeclaringClass() != GetDeclaringClass().GetClass()) {
3683      Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot modify final field " << PrettyField(field)
3684                                      << " from other class " << GetDeclaringClass();
3685      return;
3686    }
3687  }
3688  const uint32_t vregA = inst->VRegA_22c();
3689  if (is_primitive) {
3690    // Primitive field assignability rules are weaker than regular assignability rules
3691    bool instruction_compatible;
3692    bool value_compatible;
3693    const RegType& value_type = work_line_->GetRegisterType(vregA);
3694    if (field_type.IsIntegralTypes()) {
3695      instruction_compatible = insn_type.IsIntegralTypes();
3696      value_compatible = value_type.IsIntegralTypes();
3697    } else if (field_type.IsFloat()) {
3698      instruction_compatible = insn_type.IsInteger();  // no [is]put-float, so expect [is]put-int
3699      value_compatible = value_type.IsFloatTypes();
3700    } else if (field_type.IsLong()) {
3701      instruction_compatible = insn_type.IsLong();
3702      value_compatible = value_type.IsLongTypes();
3703    } else if (field_type.IsDouble()) {
3704      instruction_compatible = insn_type.IsLong();  // no [is]put-double, so expect [is]put-long
3705      value_compatible = value_type.IsDoubleTypes();
3706    } else {
3707      instruction_compatible = false;  // reference field with primitive store
3708      value_compatible = false;  // unused
3709    }
3710    if (!instruction_compatible) {
3711      // This is a global failure rather than a class change failure as the instructions and
3712      // the descriptors for the type should have been consistent within the same file at
3713      // compile time
3714      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected field " << PrettyField(field)
3715                                        << " to be of type '" << insn_type
3716                                        << "' but found type '" << field_type
3717                                        << "' in put";
3718      return;
3719    }
3720    if (!value_compatible) {
3721      Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected value in v" << vregA
3722          << " of type " << value_type
3723          << " but expected " << field_type
3724          << " for store to " << PrettyField(field) << " in put";
3725      return;
3726    }
3727  } else {
3728    if (!insn_type.IsAssignableFrom(field_type)) {
3729      Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "expected field " << PrettyField(field)
3730                                        << " to be compatible with type '" << insn_type
3731                                        << "' but found type '" << field_type
3732                                        << "' in put-object";
3733      return;
3734    }
3735    work_line_->VerifyRegisterType(vregA, field_type);
3736  }
3737}
3738
3739bool MethodVerifier::CheckNotMoveException(const uint16_t* insns, int insn_idx) {
3740  if ((insns[insn_idx] & 0xff) == Instruction::MOVE_EXCEPTION) {
3741    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid use of move-exception";
3742    return false;
3743  }
3744  return true;
3745}
3746
3747bool MethodVerifier::UpdateRegisters(uint32_t next_insn, const RegisterLine* merge_line) {
3748  bool changed = true;
3749  RegisterLine* target_line = reg_table_.GetLine(next_insn);
3750  if (!insn_flags_[next_insn].IsVisitedOrChanged()) {
3751    /*
3752     * We haven't processed this instruction before, and we haven't touched the registers here, so
3753     * there's nothing to "merge". Copy the registers over and mark it as changed. (This is the
3754     * only way a register can transition out of "unknown", so this is not just an optimization.)
3755     */
3756    if (!insn_flags_[next_insn].IsReturn()) {
3757      target_line->CopyFromLine(merge_line);
3758    } else {
3759      // For returns we only care about the operand to the return, all other registers are dead.
3760      // Initialize them as conflicts so they don't add to GC and deoptimization information.
3761      const Instruction* ret_inst = Instruction::At(code_item_->insns_ + next_insn);
3762      Instruction::Code opcode = ret_inst->Opcode();
3763      if ((opcode == Instruction::RETURN_VOID) || (opcode == Instruction::RETURN_VOID_BARRIER)) {
3764        target_line->MarkAllRegistersAsConflicts();
3765      } else {
3766        target_line->CopyFromLine(merge_line);
3767        if (opcode == Instruction::RETURN_WIDE) {
3768          target_line->MarkAllRegistersAsConflictsExceptWide(ret_inst->VRegA_11x());
3769        } else {
3770          target_line->MarkAllRegistersAsConflictsExcept(ret_inst->VRegA_11x());
3771        }
3772      }
3773    }
3774  } else {
3775    UniquePtr<RegisterLine> copy(gDebugVerify ?
3776                                 new RegisterLine(target_line->NumRegs(), this) :
3777                                 NULL);
3778    if (gDebugVerify) {
3779      copy->CopyFromLine(target_line);
3780    }
3781    changed = target_line->MergeRegisters(merge_line);
3782    if (have_pending_hard_failure_) {
3783      return false;
3784    }
3785    if (gDebugVerify && changed) {
3786      LogVerifyInfo() << "Merging at [" << reinterpret_cast<void*>(work_insn_idx_) << "]"
3787                      << " to [" << reinterpret_cast<void*>(next_insn) << "]: " << "\n"
3788                      << *copy.get() << "  MERGE\n"
3789                      << *merge_line << "  ==\n"
3790                      << *target_line << "\n";
3791    }
3792  }
3793  if (changed) {
3794    insn_flags_[next_insn].SetChanged();
3795  }
3796  return true;
3797}
3798
3799InstructionFlags* MethodVerifier::CurrentInsnFlags() {
3800  return &insn_flags_[work_insn_idx_];
3801}
3802
3803const RegType& MethodVerifier::GetMethodReturnType() {
3804  const DexFile::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx_);
3805  const DexFile::ProtoId& proto_id = dex_file_->GetMethodPrototype(method_id);
3806  uint16_t return_type_idx = proto_id.return_type_idx_;
3807  const char* descriptor = dex_file_->GetTypeDescriptor(dex_file_->GetTypeId(return_type_idx));
3808  return reg_types_.FromDescriptor(class_loader_, descriptor, false);
3809}
3810
3811const RegType& MethodVerifier::GetDeclaringClass() {
3812  if (declaring_class_ == NULL) {
3813    const DexFile::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx_);
3814    const char* descriptor
3815        = dex_file_->GetTypeDescriptor(dex_file_->GetTypeId(method_id.class_idx_));
3816    if (mirror_method_ != NULL) {
3817      mirror::Class* klass = mirror_method_->GetDeclaringClass();
3818      declaring_class_ = &reg_types_.FromClass(descriptor, klass,
3819                                               klass->CannotBeAssignedFromOtherTypes());
3820    } else {
3821      declaring_class_ = &reg_types_.FromDescriptor(class_loader_, descriptor, false);
3822    }
3823  }
3824  return *declaring_class_;
3825}
3826
3827void MethodVerifier::ComputeGcMapSizes(size_t* gc_points, size_t* ref_bitmap_bits,
3828                                       size_t* log2_max_gc_pc) {
3829  size_t local_gc_points = 0;
3830  size_t max_insn = 0;
3831  size_t max_ref_reg = -1;
3832  for (size_t i = 0; i < code_item_->insns_size_in_code_units_; i++) {
3833    if (insn_flags_[i].IsCompileTimeInfoPoint()) {
3834      local_gc_points++;
3835      max_insn = i;
3836      RegisterLine* line = reg_table_.GetLine(i);
3837      max_ref_reg = line->GetMaxNonZeroReferenceReg(max_ref_reg);
3838    }
3839  }
3840  *gc_points = local_gc_points;
3841  *ref_bitmap_bits = max_ref_reg + 1;  // if max register is 0 we need 1 bit to encode (ie +1)
3842  size_t i = 0;
3843  while ((1U << i) <= max_insn) {
3844    i++;
3845  }
3846  *log2_max_gc_pc = i;
3847}
3848
3849MethodVerifier::MethodSafeCastSet* MethodVerifier::GenerateSafeCastSet() {
3850  /*
3851   * Walks over the method code and adds any cast instructions in which
3852   * the type cast is implicit to a set, which is used in the code generation
3853   * to elide these casts.
3854   */
3855  if (!failure_messages_.empty()) {
3856    return NULL;
3857  }
3858  UniquePtr<MethodSafeCastSet> mscs;
3859  const Instruction* inst = Instruction::At(code_item_->insns_);
3860  const Instruction* end = Instruction::At(code_item_->insns_ +
3861                                           code_item_->insns_size_in_code_units_);
3862
3863  for (; inst < end; inst = inst->Next()) {
3864    if (Instruction::CHECK_CAST != inst->Opcode()) {
3865      continue;
3866    }
3867    uint32_t dex_pc = inst->GetDexPc(code_item_->insns_);
3868    RegisterLine* line = reg_table_.GetLine(dex_pc);
3869    const RegType& reg_type(line->GetRegisterType(inst->VRegA_21c()));
3870    const RegType& cast_type = ResolveClassAndCheckAccess(inst->VRegB_21c());
3871    if (cast_type.IsStrictlyAssignableFrom(reg_type)) {
3872      if (mscs.get() == NULL) {
3873        mscs.reset(new MethodSafeCastSet());
3874      }
3875      mscs->insert(dex_pc);
3876    }
3877  }
3878  return mscs.release();
3879}
3880
3881MethodVerifier::PcToConcreteMethodMap* MethodVerifier::GenerateDevirtMap() {
3882  // It is risky to rely on reg_types for sharpening in cases of soft
3883  // verification, we might end up sharpening to a wrong implementation. Just abort.
3884  if (!failure_messages_.empty()) {
3885    return NULL;
3886  }
3887
3888  UniquePtr<PcToConcreteMethodMap> pc_to_concrete_method_map;
3889  const uint16_t* insns = code_item_->insns_;
3890  const Instruction* inst = Instruction::At(insns);
3891  const Instruction* end = Instruction::At(insns + code_item_->insns_size_in_code_units_);
3892
3893  for (; inst < end; inst = inst->Next()) {
3894    bool is_virtual   = (inst->Opcode() == Instruction::INVOKE_VIRTUAL) ||
3895        (inst->Opcode() ==  Instruction::INVOKE_VIRTUAL_RANGE);
3896    bool is_interface = (inst->Opcode() == Instruction::INVOKE_INTERFACE) ||
3897        (inst->Opcode() == Instruction::INVOKE_INTERFACE_RANGE);
3898
3899    if (!is_interface && !is_virtual) {
3900      continue;
3901    }
3902    // Get reg type for register holding the reference to the object that will be dispatched upon.
3903    uint32_t dex_pc = inst->GetDexPc(insns);
3904    RegisterLine* line = reg_table_.GetLine(dex_pc);
3905    bool is_range = (inst->Opcode() ==  Instruction::INVOKE_VIRTUAL_RANGE) ||
3906        (inst->Opcode() ==  Instruction::INVOKE_INTERFACE_RANGE);
3907    const RegType&
3908        reg_type(line->GetRegisterType(is_range ? inst->VRegC_3rc() : inst->VRegC_35c()));
3909
3910    if (!reg_type.HasClass()) {
3911      // We will compute devirtualization information only when we know the Class of the reg type.
3912      continue;
3913    }
3914    mirror::Class* reg_class = reg_type.GetClass();
3915    if (reg_class->IsInterface()) {
3916      // We can't devirtualize when the known type of the register is an interface.
3917      continue;
3918    }
3919    if (reg_class->IsAbstract() && !reg_class->IsArrayClass()) {
3920      // We can't devirtualize abstract classes except on arrays of abstract classes.
3921      continue;
3922    }
3923    mirror::AbstractMethod* abstract_method =
3924        dex_cache_->GetResolvedMethod(is_range ? inst->VRegB_3rc() : inst->VRegB_35c());
3925    if (abstract_method == NULL) {
3926      // If the method is not found in the cache this means that it was never found
3927      // by ResolveMethodAndCheckAccess() called when verifying invoke_*.
3928      continue;
3929    }
3930    // Find the concrete method.
3931    mirror::AbstractMethod* concrete_method = NULL;
3932    if (is_interface) {
3933      concrete_method = reg_type.GetClass()->FindVirtualMethodForInterface(abstract_method);
3934    }
3935    if (is_virtual) {
3936      concrete_method = reg_type.GetClass()->FindVirtualMethodForVirtual(abstract_method);
3937    }
3938    if (concrete_method == NULL || concrete_method->IsAbstract()) {
3939      // In cases where concrete_method is not found, or is abstract, continue to the next invoke.
3940      continue;
3941    }
3942    if (reg_type.IsPreciseReference() || concrete_method->IsFinal() ||
3943        concrete_method->GetDeclaringClass()->IsFinal()) {
3944      // If we knew exactly the class being dispatched upon, or if the target method cannot be
3945      // overridden record the target to be used in the compiler driver.
3946      if (pc_to_concrete_method_map.get() == NULL) {
3947        pc_to_concrete_method_map.reset(new PcToConcreteMethodMap());
3948      }
3949      MethodReference concrete_ref(
3950          concrete_method->GetDeclaringClass()->GetDexCache()->GetDexFile(),
3951          concrete_method->GetDexMethodIndex());
3952      pc_to_concrete_method_map->Put(dex_pc, concrete_ref);
3953    }
3954  }
3955  return pc_to_concrete_method_map.release();
3956}
3957
3958const std::vector<uint8_t>* MethodVerifier::GenerateGcMap() {
3959  size_t num_entries, ref_bitmap_bits, pc_bits;
3960  ComputeGcMapSizes(&num_entries, &ref_bitmap_bits, &pc_bits);
3961  // There's a single byte to encode the size of each bitmap
3962  if (ref_bitmap_bits >= (8 /* bits per byte */ * 8192 /* 13-bit size */ )) {
3963    // TODO: either a better GC map format or per method failures
3964    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Cannot encode GC map for method with "
3965       << ref_bitmap_bits << " registers";
3966    return NULL;
3967  }
3968  size_t ref_bitmap_bytes = (ref_bitmap_bits + 7) / 8;
3969  // There are 2 bytes to encode the number of entries
3970  if (num_entries >= 65536) {
3971    // TODO: either a better GC map format or per method failures
3972    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Cannot encode GC map for method with "
3973       << num_entries << " entries";
3974    return NULL;
3975  }
3976  size_t pc_bytes;
3977  RegisterMapFormat format;
3978  if (pc_bits <= 8) {
3979    format = kRegMapFormatCompact8;
3980    pc_bytes = 1;
3981  } else if (pc_bits <= 16) {
3982    format = kRegMapFormatCompact16;
3983    pc_bytes = 2;
3984  } else {
3985    // TODO: either a better GC map format or per method failures
3986    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Cannot encode GC map for method with "
3987       << (1 << pc_bits) << " instructions (number is rounded up to nearest power of 2)";
3988    return NULL;
3989  }
3990  size_t table_size = ((pc_bytes + ref_bitmap_bytes) * num_entries) + 4;
3991  std::vector<uint8_t>* table = new std::vector<uint8_t>;
3992  if (table == NULL) {
3993    Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Failed to encode GC map (size=" << table_size << ")";
3994    return NULL;
3995  }
3996  table->reserve(table_size);
3997  // Write table header
3998  table->push_back(format | ((ref_bitmap_bytes >> DexPcToReferenceMap::kRegMapFormatShift) &
3999                             ~DexPcToReferenceMap::kRegMapFormatMask));
4000  table->push_back(ref_bitmap_bytes & 0xFF);
4001  table->push_back(num_entries & 0xFF);
4002  table->push_back((num_entries >> 8) & 0xFF);
4003  // Write table data
4004  for (size_t i = 0; i < code_item_->insns_size_in_code_units_; i++) {
4005    if (insn_flags_[i].IsCompileTimeInfoPoint()) {
4006      table->push_back(i & 0xFF);
4007      if (pc_bytes == 2) {
4008        table->push_back((i >> 8) & 0xFF);
4009      }
4010      RegisterLine* line = reg_table_.GetLine(i);
4011      line->WriteReferenceBitMap(*table, ref_bitmap_bytes);
4012    }
4013  }
4014  DCHECK_EQ(table->size(), table_size);
4015  return table;
4016}
4017
4018void MethodVerifier::VerifyGcMap(const std::vector<uint8_t>& data) {
4019  // Check that for every GC point there is a map entry, there aren't entries for non-GC points,
4020  // that the table data is well formed and all references are marked (or not) in the bitmap
4021  DexPcToReferenceMap map(&data[0], data.size());
4022  size_t map_index = 0;
4023  for (size_t i = 0; i < code_item_->insns_size_in_code_units_; i++) {
4024    const uint8_t* reg_bitmap = map.FindBitMap(i, false);
4025    if (insn_flags_[i].IsCompileTimeInfoPoint()) {
4026      CHECK_LT(map_index, map.NumEntries());
4027      CHECK_EQ(map.GetDexPc(map_index), i);
4028      CHECK_EQ(map.GetBitMap(map_index), reg_bitmap);
4029      map_index++;
4030      RegisterLine* line = reg_table_.GetLine(i);
4031      for (size_t j = 0; j < code_item_->registers_size_; j++) {
4032        if (line->GetRegisterType(j).IsNonZeroReferenceTypes()) {
4033          CHECK_LT(j / 8, map.RegWidth());
4034          CHECK_EQ((reg_bitmap[j / 8] >> (j % 8)) & 1, 1);
4035        } else if ((j / 8) < map.RegWidth()) {
4036          CHECK_EQ((reg_bitmap[j / 8] >> (j % 8)) & 1, 0);
4037        } else {
4038          // If a register doesn't contain a reference then the bitmap may be shorter than the line
4039        }
4040      }
4041    } else {
4042      CHECK(reg_bitmap == NULL);
4043    }
4044  }
4045}
4046
4047void MethodVerifier::SetDexGcMap(MethodReference ref, const std::vector<uint8_t>& gc_map) {
4048  DCHECK(Runtime::Current()->IsCompiler());
4049  {
4050    WriterMutexLock mu(Thread::Current(), *dex_gc_maps_lock_);
4051    DexGcMapTable::iterator it = dex_gc_maps_->find(ref);
4052    if (it != dex_gc_maps_->end()) {
4053      delete it->second;
4054      dex_gc_maps_->erase(it);
4055    }
4056    dex_gc_maps_->Put(ref, &gc_map);
4057  }
4058  DCHECK(GetDexGcMap(ref) != NULL);
4059}
4060
4061
4062void  MethodVerifier::SetSafeCastMap(MethodReference ref, const MethodSafeCastSet* cast_set) {
4063  DCHECK(Runtime::Current()->IsCompiler());
4064  MutexLock mu(Thread::Current(), *safecast_map_lock_);
4065  SafeCastMap::iterator it = safecast_map_->find(ref);
4066  if (it != safecast_map_->end()) {
4067    delete it->second;
4068    safecast_map_->erase(it);
4069  }
4070
4071  safecast_map_->Put(ref, cast_set);
4072  DCHECK(safecast_map_->find(ref) != safecast_map_->end());
4073}
4074
4075bool MethodVerifier::IsSafeCast(MethodReference ref, uint32_t pc) {
4076  DCHECK(Runtime::Current()->IsCompiler());
4077  MutexLock mu(Thread::Current(), *safecast_map_lock_);
4078  SafeCastMap::const_iterator it = safecast_map_->find(ref);
4079  if (it == safecast_map_->end()) {
4080    return false;
4081  }
4082
4083  // Look up the cast address in the set of safe casts
4084  MethodVerifier::MethodSafeCastSet::const_iterator cast_it = it->second->find(pc);
4085  return cast_it != it->second->end();
4086}
4087
4088const std::vector<uint8_t>* MethodVerifier::GetDexGcMap(MethodReference ref) {
4089  DCHECK(Runtime::Current()->IsCompiler());
4090  ReaderMutexLock mu(Thread::Current(), *dex_gc_maps_lock_);
4091  DexGcMapTable::const_iterator it = dex_gc_maps_->find(ref);
4092  if (it == dex_gc_maps_->end()) {
4093    LOG(WARNING) << "Didn't find GC map for: " << PrettyMethod(ref.dex_method_index, *ref.dex_file);
4094    return NULL;
4095  }
4096  CHECK(it->second != NULL);
4097  return it->second;
4098}
4099
4100void  MethodVerifier::SetDevirtMap(MethodReference ref,
4101                                   const PcToConcreteMethodMap* devirt_map) {
4102  DCHECK(Runtime::Current()->IsCompiler());
4103  WriterMutexLock mu(Thread::Current(), *devirt_maps_lock_);
4104  DevirtualizationMapTable::iterator it = devirt_maps_->find(ref);
4105  if (it != devirt_maps_->end()) {
4106    delete it->second;
4107    devirt_maps_->erase(it);
4108  }
4109
4110  devirt_maps_->Put(ref, devirt_map);
4111  DCHECK(devirt_maps_->find(ref) != devirt_maps_->end());
4112}
4113
4114const MethodReference* MethodVerifier::GetDevirtMap(const MethodReference& ref,
4115                                                                    uint32_t dex_pc) {
4116  DCHECK(Runtime::Current()->IsCompiler());
4117  ReaderMutexLock mu(Thread::Current(), *devirt_maps_lock_);
4118  DevirtualizationMapTable::const_iterator it = devirt_maps_->find(ref);
4119  if (it == devirt_maps_->end()) {
4120    return NULL;
4121  }
4122
4123  // Look up the PC in the map, get the concrete method to execute and return its reference.
4124  MethodVerifier::PcToConcreteMethodMap::const_iterator pc_to_concrete_method
4125      = it->second->find(dex_pc);
4126  if (pc_to_concrete_method != it->second->end()) {
4127    return &(pc_to_concrete_method->second);
4128  } else {
4129    return NULL;
4130  }
4131}
4132
4133std::vector<int32_t> MethodVerifier::DescribeVRegs(uint32_t dex_pc) {
4134  RegisterLine* line = reg_table_.GetLine(dex_pc);
4135  std::vector<int32_t> result;
4136  for (size_t i = 0; i < line->NumRegs(); ++i) {
4137    const RegType& type = line->GetRegisterType(i);
4138    if (type.IsConstant()) {
4139      result.push_back(type.IsPreciseConstant() ? kConstant : kImpreciseConstant);
4140      result.push_back(type.ConstantValue());
4141    } else if (type.IsConstantLo()) {
4142      result.push_back(type.IsPreciseConstantLo() ? kConstant : kImpreciseConstant);
4143      result.push_back(type.ConstantValueLo());
4144    } else if (type.IsConstantHi()) {
4145      result.push_back(type.IsPreciseConstantHi() ? kConstant : kImpreciseConstant);
4146      result.push_back(type.ConstantValueHi());
4147    } else if (type.IsIntegralTypes()) {
4148      result.push_back(kIntVReg);
4149      result.push_back(0);
4150    } else if (type.IsFloat()) {
4151      result.push_back(kFloatVReg);
4152      result.push_back(0);
4153    } else if (type.IsLong()) {
4154      result.push_back(kLongLoVReg);
4155      result.push_back(0);
4156      result.push_back(kLongHiVReg);
4157      result.push_back(0);
4158      ++i;
4159    } else if (type.IsDouble()) {
4160      result.push_back(kDoubleLoVReg);
4161      result.push_back(0);
4162      result.push_back(kDoubleHiVReg);
4163      result.push_back(0);
4164      ++i;
4165    } else if (type.IsUndefined() || type.IsConflict() || type.IsHighHalf()) {
4166      result.push_back(kUndefined);
4167      result.push_back(0);
4168    } else {
4169      CHECK(type.IsNonZeroReferenceTypes());
4170      result.push_back(kReferenceVReg);
4171      result.push_back(0);
4172    }
4173  }
4174  return result;
4175}
4176
4177bool MethodVerifier::IsCandidateForCompilation(const DexFile::CodeItem* code_item,
4178                                               const uint32_t access_flags) {
4179  // Don't compile class initializers, ever.
4180  if (((access_flags & kAccConstructor) != 0) && ((access_flags & kAccStatic) != 0)) {
4181    return false;
4182  }
4183
4184  const Runtime* runtime = Runtime::Current();
4185  if (runtime->IsSmallMode() && runtime->UseCompileTimeClassPath()) {
4186    // In Small mode, we only compile small methods.
4187    const uint32_t code_size = code_item->insns_size_in_code_units_;
4188    return (code_size < runtime->GetSmallModeMethodDexSizeLimit());
4189  } else {
4190    // In normal mode, we compile everything.
4191    return true;
4192  }
4193}
4194
4195ReaderWriterMutex* MethodVerifier::dex_gc_maps_lock_ = NULL;
4196MethodVerifier::DexGcMapTable* MethodVerifier::dex_gc_maps_ = NULL;
4197
4198Mutex* MethodVerifier::safecast_map_lock_ = NULL;
4199MethodVerifier::SafeCastMap* MethodVerifier::safecast_map_ = NULL;
4200
4201ReaderWriterMutex* MethodVerifier::devirt_maps_lock_ = NULL;
4202MethodVerifier::DevirtualizationMapTable* MethodVerifier::devirt_maps_ = NULL;
4203
4204Mutex* MethodVerifier::rejected_classes_lock_ = NULL;
4205MethodVerifier::RejectedClassesTable* MethodVerifier::rejected_classes_ = NULL;
4206
4207void MethodVerifier::Init() {
4208  if (Runtime::Current()->IsCompiler()) {
4209    dex_gc_maps_lock_ = new ReaderWriterMutex("verifier GC maps lock");
4210    Thread* self = Thread::Current();
4211    {
4212      WriterMutexLock mu(self, *dex_gc_maps_lock_);
4213      dex_gc_maps_ = new MethodVerifier::DexGcMapTable;
4214    }
4215
4216    safecast_map_lock_ = new Mutex("verifier Cast Elision lock");
4217    {
4218      MutexLock mu(self, *safecast_map_lock_);
4219      safecast_map_ = new MethodVerifier::SafeCastMap();
4220    }
4221
4222    devirt_maps_lock_ = new ReaderWriterMutex("verifier Devirtualization lock");
4223
4224    {
4225      WriterMutexLock mu(self, *devirt_maps_lock_);
4226      devirt_maps_ = new MethodVerifier::DevirtualizationMapTable();
4227    }
4228
4229    rejected_classes_lock_ = new Mutex("verifier rejected classes lock");
4230    {
4231      MutexLock mu(self, *rejected_classes_lock_);
4232      rejected_classes_ = new MethodVerifier::RejectedClassesTable;
4233    }
4234  }
4235  art::verifier::RegTypeCache::Init();
4236}
4237
4238void MethodVerifier::Shutdown() {
4239  if (Runtime::Current()->IsCompiler()) {
4240    Thread* self = Thread::Current();
4241    {
4242      WriterMutexLock mu(self, *dex_gc_maps_lock_);
4243      STLDeleteValues(dex_gc_maps_);
4244      delete dex_gc_maps_;
4245      dex_gc_maps_ = NULL;
4246    }
4247    delete dex_gc_maps_lock_;
4248    dex_gc_maps_lock_ = NULL;
4249
4250    {
4251      MutexLock mu(self, *safecast_map_lock_);
4252      STLDeleteValues(safecast_map_);
4253      delete safecast_map_;
4254      safecast_map_ = NULL;
4255    }
4256    delete safecast_map_lock_;
4257    safecast_map_lock_ = NULL;
4258
4259    {
4260      WriterMutexLock mu(self, *devirt_maps_lock_);
4261      STLDeleteValues(devirt_maps_);
4262      delete devirt_maps_;
4263      devirt_maps_ = NULL;
4264    }
4265    delete devirt_maps_lock_;
4266    devirt_maps_lock_ = NULL;
4267
4268    {
4269      MutexLock mu(self, *rejected_classes_lock_);
4270      delete rejected_classes_;
4271      rejected_classes_ = NULL;
4272    }
4273    delete rejected_classes_lock_;
4274    rejected_classes_lock_ = NULL;
4275  }
4276  verifier::RegTypeCache::ShutDown();
4277}
4278
4279void MethodVerifier::AddRejectedClass(ClassReference ref) {
4280  DCHECK(Runtime::Current()->IsCompiler());
4281  {
4282    MutexLock mu(Thread::Current(), *rejected_classes_lock_);
4283    rejected_classes_->insert(ref);
4284  }
4285  CHECK(IsClassRejected(ref));
4286}
4287
4288bool MethodVerifier::IsClassRejected(ClassReference ref) {
4289  DCHECK(Runtime::Current()->IsCompiler());
4290  MutexLock mu(Thread::Current(), *rejected_classes_lock_);
4291  return (rejected_classes_->find(ref) != rejected_classes_->end());
4292}
4293
4294}  // namespace verifier
4295}  // namespace art
4296