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