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