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