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