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