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 <ostream>
20 
21 #include "android-base/stringprintf.h"
22 
23 #include "art_field-inl.h"
24 #include "art_method-inl.h"
25 #include "base/aborting.h"
26 #include "base/enums.h"
27 #include "base/leb128.h"
28 #include "base/indenter.h"
29 #include "base/logging.h"  // For VLOG.
30 #include "base/mutex-inl.h"
31 #include "base/sdk_version.h"
32 #include "base/stl_util.h"
33 #include "base/systrace.h"
34 #include "base/time_utils.h"
35 #include "base/utils.h"
36 #include "class_linker.h"
37 #include "class_root-inl.h"
38 #include "compiler_callbacks.h"
39 #include "dex/class_accessor-inl.h"
40 #include "dex/descriptors_names.h"
41 #include "dex/dex_file-inl.h"
42 #include "dex/dex_file_exception_helpers.h"
43 #include "dex/dex_instruction-inl.h"
44 #include "dex/dex_instruction_utils.h"
45 #include "experimental_flags.h"
46 #include "gc/accounting/card_table-inl.h"
47 #include "handle_scope-inl.h"
48 #include "intern_table.h"
49 #include "mirror/class-inl.h"
50 #include "mirror/class.h"
51 #include "mirror/class_loader.h"
52 #include "mirror/dex_cache-inl.h"
53 #include "mirror/method_handle_impl.h"
54 #include "mirror/method_type.h"
55 #include "mirror/object-inl.h"
56 #include "mirror/object_array-inl.h"
57 #include "mirror/var_handle.h"
58 #include "obj_ptr-inl.h"
59 #include "reg_type-inl.h"
60 #include "register_line-inl.h"
61 #include "runtime.h"
62 #include "scoped_newline.h"
63 #include "scoped_thread_state_change-inl.h"
64 #include "stack.h"
65 #include "vdex_file.h"
66 #include "verifier/method_verifier.h"
67 #include "verifier_compiler_binding.h"
68 #include "verifier_deps.h"
69 
70 namespace art {
71 namespace verifier {
72 
73 using android::base::StringPrintf;
74 
75 static constexpr bool kTimeVerifyMethod = !kIsDebugBuild;
76 
PcToRegisterLineTable(ScopedArenaAllocator & allocator)77 PcToRegisterLineTable::PcToRegisterLineTable(ScopedArenaAllocator& allocator)
78     : register_lines_(allocator.Adapter(kArenaAllocVerifier)) {}
79 
Init(RegisterTrackingMode mode,InstructionFlags * flags,uint32_t insns_size,uint16_t registers_size,ScopedArenaAllocator & allocator,RegTypeCache * reg_types)80 void PcToRegisterLineTable::Init(RegisterTrackingMode mode,
81                                  InstructionFlags* flags,
82                                  uint32_t insns_size,
83                                  uint16_t registers_size,
84                                  ScopedArenaAllocator& allocator,
85                                  RegTypeCache* reg_types) {
86   DCHECK_GT(insns_size, 0U);
87   register_lines_.resize(insns_size);
88   for (uint32_t i = 0; i < insns_size; i++) {
89     bool interesting = false;
90     switch (mode) {
91       case kTrackRegsAll:
92         interesting = flags[i].IsOpcode();
93         break;
94       case kTrackCompilerInterestPoints:
95         interesting = flags[i].IsCompileTimeInfoPoint() || flags[i].IsBranchTarget();
96         break;
97       case kTrackRegsBranches:
98         interesting = flags[i].IsBranchTarget();
99         break;
100     }
101     if (interesting) {
102       register_lines_[i].reset(RegisterLine::Create(registers_size, allocator, reg_types));
103     }
104   }
105 }
106 
~PcToRegisterLineTable()107 PcToRegisterLineTable::~PcToRegisterLineTable() {}
108 
109 namespace impl {
110 namespace {
111 
112 enum class CheckAccess {
113   kNo,
114   kOnResolvedClass,
115   kYes,
116 };
117 
118 enum class FieldAccessType {
119   kAccGet,
120   kAccPut
121 };
122 
123 // Instruction types that are not marked as throwing (because they normally would not), but for
124 // historical reasons may do so. These instructions cannot be marked kThrow as that would introduce
125 // a general flow that is unwanted.
126 //
127 // Note: Not implemented as Instruction::Flags value as that set is full and we'd need to increase
128 //       the struct size (making it a non-power-of-two) for a single element.
129 //
130 // Note: This should eventually be removed.
IsCompatThrow(Instruction::Code opcode)131 constexpr bool IsCompatThrow(Instruction::Code opcode) {
132   return opcode == Instruction::Code::RETURN_OBJECT || opcode == Instruction::Code::MOVE_EXCEPTION;
133 }
134 
135 template <bool kVerifierDebug>
136 class MethodVerifier final : public ::art::verifier::MethodVerifier {
137  public:
IsInstanceConstructor() const138   bool IsInstanceConstructor() const {
139     return IsConstructor() && !IsStatic();
140   }
141 
ResolveCheckedClass(dex::TypeIndex class_idx)142   const RegType& ResolveCheckedClass(dex::TypeIndex class_idx) override
143       REQUIRES_SHARED(Locks::mutator_lock_) {
144     DCHECK(!HasFailures());
145     const RegType& result = ResolveClass<CheckAccess::kYes>(class_idx);
146     DCHECK(!HasFailures());
147     return result;
148   }
149 
150   void FindLocksAtDexPc() REQUIRES_SHARED(Locks::mutator_lock_);
151 
152  private:
MethodVerifier(Thread * self,ClassLinker * class_linker,ArenaPool * arena_pool,const DexFile * dex_file,const dex::CodeItem * code_item,uint32_t method_idx,bool can_load_classes,bool allow_thread_suspension,bool allow_soft_failures,bool aot_mode,Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader,const dex::ClassDef & class_def,ArtMethod * method,uint32_t access_flags,bool need_precise_constants,bool verify_to_dump,bool fill_register_lines,uint32_t api_level)153   MethodVerifier(Thread* self,
154                  ClassLinker* class_linker,
155                  ArenaPool* arena_pool,
156                  const DexFile* dex_file,
157                  const dex::CodeItem* code_item,
158                  uint32_t method_idx,
159                  bool can_load_classes,
160                  bool allow_thread_suspension,
161                  bool allow_soft_failures,
162                  bool aot_mode,
163                  Handle<mirror::DexCache> dex_cache,
164                  Handle<mirror::ClassLoader> class_loader,
165                  const dex::ClassDef& class_def,
166                  ArtMethod* method,
167                  uint32_t access_flags,
168                  bool need_precise_constants,
169                  bool verify_to_dump,
170                  bool fill_register_lines,
171                  uint32_t api_level) REQUIRES_SHARED(Locks::mutator_lock_)
172      : art::verifier::MethodVerifier(self,
173                                      class_linker,
174                                      arena_pool,
175                                      dex_file,
176                                      code_item,
177                                      method_idx,
178                                      can_load_classes,
179                                      allow_thread_suspension,
180                                      allow_soft_failures,
181                                      aot_mode),
182        method_being_verified_(method),
183        method_access_flags_(access_flags),
184        return_type_(nullptr),
185        dex_cache_(dex_cache),
186        class_loader_(class_loader),
187        class_def_(class_def),
188        declaring_class_(nullptr),
189        interesting_dex_pc_(-1),
190        monitor_enter_dex_pcs_(nullptr),
191        need_precise_constants_(need_precise_constants),
192        verify_to_dump_(verify_to_dump),
193        allow_thread_suspension_(allow_thread_suspension),
194        is_constructor_(false),
195        fill_register_lines_(fill_register_lines),
196        api_level_(api_level == 0 ? std::numeric_limits<uint32_t>::max() : api_level) {
197   }
198 
UninstantiableError(const char * descriptor)199   void UninstantiableError(const char* descriptor) {
200     Fail(VerifyError::VERIFY_ERROR_NO_CLASS) << "Could not create precise reference for "
201                                              << "non-instantiable klass " << descriptor;
202   }
IsInstantiableOrPrimitive(ObjPtr<mirror::Class> klass)203   static bool IsInstantiableOrPrimitive(ObjPtr<mirror::Class> klass)
204       REQUIRES_SHARED(Locks::mutator_lock_) {
205     return klass->IsInstantiable() || klass->IsPrimitive();
206   }
207 
208   // Is the method being verified a constructor? See the comment on the field.
IsConstructor() const209   bool IsConstructor() const {
210     return is_constructor_;
211   }
212 
213   // Is the method verified static?
IsStatic() const214   bool IsStatic() const {
215     return (method_access_flags_ & kAccStatic) != 0;
216   }
217 
218   // Adds the given string to the beginning of the last failure message.
PrependToLastFailMessage(std::string prepend)219   void PrependToLastFailMessage(std::string prepend) {
220     size_t failure_num = failure_messages_.size();
221     DCHECK_NE(failure_num, 0U);
222     std::ostringstream* last_fail_message = failure_messages_[failure_num - 1];
223     prepend += last_fail_message->str();
224     failure_messages_[failure_num - 1] = new std::ostringstream(prepend, std::ostringstream::ate);
225     delete last_fail_message;
226   }
227 
228   // Adds the given string to the end of the last failure message.
AppendToLastFailMessage(const std::string & append)229   void AppendToLastFailMessage(const std::string& append) {
230     size_t failure_num = failure_messages_.size();
231     DCHECK_NE(failure_num, 0U);
232     std::ostringstream* last_fail_message = failure_messages_[failure_num - 1];
233     (*last_fail_message) << append;
234   }
235 
236   /*
237    * Compute the width of the instruction at each address in the instruction stream, and store it in
238    * insn_flags_. Addresses that are in the middle of an instruction, or that are part of switch
239    * table data, are not touched (so the caller should probably initialize "insn_flags" to zero).
240    *
241    * The "new_instance_count_" and "monitor_enter_count_" fields in vdata are also set.
242    *
243    * Performs some static checks, notably:
244    * - opcode of first instruction begins at index 0
245    * - only documented instructions may appear
246    * - each instruction follows the last
247    * - last byte of last instruction is at (code_length-1)
248    *
249    * Logs an error and returns "false" on failure.
250    */
251   bool ComputeWidthsAndCountOps();
252 
253   /*
254    * Set the "in try" flags for all instructions protected by "try" statements. Also sets the
255    * "branch target" flags for exception handlers.
256    *
257    * Call this after widths have been set in "insn_flags".
258    *
259    * Returns "false" if something in the exception table looks fishy, but we're expecting the
260    * exception table to be valid.
261    */
262   bool ScanTryCatchBlocks() REQUIRES_SHARED(Locks::mutator_lock_);
263 
264   /*
265    * Perform static verification on all instructions in a method.
266    *
267    * Walks through instructions in a method calling VerifyInstruction on each.
268    */
269   template <bool kAllowRuntimeOnlyInstructions>
270   bool VerifyInstructions();
271 
272   /*
273    * Perform static verification on an instruction.
274    *
275    * As a side effect, this sets the "branch target" flags in InsnFlags.
276    *
277    * "(CF)" items are handled during code-flow analysis.
278    *
279    * v3 4.10.1
280    * - target of each jump and branch instruction must be valid
281    * - targets of switch statements must be valid
282    * - operands referencing constant pool entries must be valid
283    * - (CF) operands of getfield, putfield, getstatic, putstatic must be valid
284    * - (CF) operands of method invocation instructions must be valid
285    * - (CF) only invoke-direct can call a method starting with '<'
286    * - (CF) <clinit> must never be called explicitly
287    * - operands of instanceof, checkcast, new (and variants) must be valid
288    * - new-array[-type] limited to 255 dimensions
289    * - can't use "new" on an array class
290    * - (?) limit dimensions in multi-array creation
291    * - local variable load/store register values must be in valid range
292    *
293    * v3 4.11.1.2
294    * - branches must be within the bounds of the code array
295    * - targets of all control-flow instructions are the start of an instruction
296    * - register accesses fall within range of allocated registers
297    * - (N/A) access to constant pool must be of appropriate type
298    * - code does not end in the middle of an instruction
299    * - execution cannot fall off the end of the code
300    * - (earlier) for each exception handler, the "try" area must begin and
301    *   end at the start of an instruction (end can be at the end of the code)
302    * - (earlier) for each exception handler, the handler must start at a valid
303    *   instruction
304    */
305   template <bool kAllowRuntimeOnlyInstructions>
306   bool VerifyInstruction(const Instruction* inst, uint32_t code_offset);
307 
308   /* Ensure that the register index is valid for this code item. */
CheckRegisterIndex(uint32_t idx)309   bool CheckRegisterIndex(uint32_t idx) {
310     if (UNLIKELY(idx >= code_item_accessor_.RegistersSize())) {
311       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "register index out of range (" << idx << " >= "
312                                         << code_item_accessor_.RegistersSize() << ")";
313       return false;
314     }
315     return true;
316   }
317 
318   /* Ensure that the wide register index is valid for this code item. */
CheckWideRegisterIndex(uint32_t idx)319   bool CheckWideRegisterIndex(uint32_t idx) {
320     if (UNLIKELY(idx + 1 >= code_item_accessor_.RegistersSize())) {
321       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "wide register index out of range (" << idx
322                                         << "+1 >= " << code_item_accessor_.RegistersSize() << ")";
323       return false;
324     }
325     return true;
326   }
327 
328   // Perform static checks on an instruction referencing a CallSite. All we do here is ensure that
329   // the call site index is in the valid range.
CheckCallSiteIndex(uint32_t idx)330   bool CheckCallSiteIndex(uint32_t idx) {
331     uint32_t limit = dex_file_->NumCallSiteIds();
332     if (UNLIKELY(idx >= limit)) {
333       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad call site index " << idx << " (max "
334                                         << limit << ")";
335       return false;
336     }
337     return true;
338   }
339 
340   // Perform static checks on a field Get or set instruction. All we do here is ensure that the
341   // field index is in the valid range.
CheckFieldIndex(uint32_t idx)342   bool CheckFieldIndex(uint32_t idx) {
343     if (UNLIKELY(idx >= dex_file_->GetHeader().field_ids_size_)) {
344       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad field index " << idx << " (max "
345                                         << dex_file_->GetHeader().field_ids_size_ << ")";
346       return false;
347     }
348     return true;
349   }
350 
351   // Perform static checks on a method invocation instruction. All we do here is ensure that the
352   // method index is in the valid range.
CheckMethodIndex(uint32_t idx)353   bool CheckMethodIndex(uint32_t idx) {
354     if (UNLIKELY(idx >= dex_file_->GetHeader().method_ids_size_)) {
355       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad method index " << idx << " (max "
356                                         << dex_file_->GetHeader().method_ids_size_ << ")";
357       return false;
358     }
359     return true;
360   }
361 
362   // Perform static checks on an instruction referencing a constant method handle. All we do here
363   // is ensure that the method index is in the valid range.
CheckMethodHandleIndex(uint32_t idx)364   bool CheckMethodHandleIndex(uint32_t idx) {
365     uint32_t limit = dex_file_->NumMethodHandles();
366     if (UNLIKELY(idx >= limit)) {
367       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad method handle index " << idx << " (max "
368                                         << limit << ")";
369       return false;
370     }
371     return true;
372   }
373 
374   // Perform static checks on a "new-instance" instruction. Specifically, make sure the class
375   // reference isn't for an array class.
376   bool CheckNewInstance(dex::TypeIndex idx);
377 
378   // Perform static checks on a prototype indexing instruction. All we do here is ensure that the
379   // prototype index is in the valid range.
CheckPrototypeIndex(uint32_t idx)380   bool CheckPrototypeIndex(uint32_t idx) {
381     if (UNLIKELY(idx >= dex_file_->GetHeader().proto_ids_size_)) {
382       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad prototype index " << idx << " (max "
383                                         << dex_file_->GetHeader().proto_ids_size_ << ")";
384       return false;
385     }
386     return true;
387   }
388 
389   /* Ensure that the string index is in the valid range. */
CheckStringIndex(uint32_t idx)390   bool CheckStringIndex(uint32_t idx) {
391     if (UNLIKELY(idx >= dex_file_->GetHeader().string_ids_size_)) {
392       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad string index " << idx << " (max "
393                                         << dex_file_->GetHeader().string_ids_size_ << ")";
394       return false;
395     }
396     return true;
397   }
398 
399   // Perform static checks on an instruction that takes a class constant. Ensure that the class
400   // index is in the valid range.
CheckTypeIndex(dex::TypeIndex idx)401   bool CheckTypeIndex(dex::TypeIndex idx) {
402     if (UNLIKELY(idx.index_ >= dex_file_->GetHeader().type_ids_size_)) {
403       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad type index " << idx.index_ << " (max "
404                                         << dex_file_->GetHeader().type_ids_size_ << ")";
405       return false;
406     }
407     return true;
408   }
409 
410   // Perform static checks on a "new-array" instruction. Specifically, make sure they aren't
411   // creating an array of arrays that causes the number of dimensions to exceed 255.
412   bool CheckNewArray(dex::TypeIndex idx);
413 
414   // Verify an array data table. "cur_offset" is the offset of the fill-array-data instruction.
415   bool CheckArrayData(uint32_t cur_offset);
416 
417   // Verify that the target of a branch instruction is valid. We don't expect code to jump directly
418   // into an exception handler, but it's valid to do so as long as the target isn't a
419   // "move-exception" instruction. We verify that in a later stage.
420   // The dex format forbids certain instructions from branching to themselves.
421   // Updates "insn_flags_", setting the "branch target" flag.
422   bool CheckBranchTarget(uint32_t cur_offset);
423 
424   // Verify a switch table. "cur_offset" is the offset of the switch instruction.
425   // Updates "insn_flags_", setting the "branch target" flag.
426   bool CheckSwitchTargets(uint32_t cur_offset);
427 
428   // Check the register indices used in a "vararg" instruction, such as invoke-virtual or
429   // filled-new-array.
430   // - vA holds word count (0-5), args[] have values.
431   // There are some tests we don't do here, e.g. we don't try to verify that invoking a method that
432   // takes a double is done with consecutive registers. This requires parsing the target method
433   // signature, which we will be doing later on during the code flow analysis.
CheckVarArgRegs(uint32_t vA,uint32_t arg[])434   bool CheckVarArgRegs(uint32_t vA, uint32_t arg[]) {
435     uint16_t registers_size = code_item_accessor_.RegistersSize();
436     for (uint32_t idx = 0; idx < vA; idx++) {
437       if (UNLIKELY(arg[idx] >= registers_size)) {
438         Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid reg index (" << arg[idx]
439                                           << ") in non-range invoke (>= " << registers_size << ")";
440         return false;
441       }
442     }
443 
444     return true;
445   }
446 
447   // Check the register indices used in a "vararg/range" instruction, such as invoke-virtual/range
448   // or filled-new-array/range.
449   // - vA holds word count, vC holds index of first reg.
CheckVarArgRangeRegs(uint32_t vA,uint32_t vC)450   bool CheckVarArgRangeRegs(uint32_t vA, uint32_t vC) {
451     uint16_t registers_size = code_item_accessor_.RegistersSize();
452     // vA/vC are unsigned 8-bit/16-bit quantities for /range instructions, so there's no risk of
453     // integer overflow when adding them here.
454     if (UNLIKELY(vA + vC > registers_size)) {
455       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid reg index " << vA << "+" << vC
456                                         << " in range invoke (> " << registers_size << ")";
457       return false;
458     }
459     return true;
460   }
461 
462   // Checks the method matches the expectations required to be signature polymorphic.
463   bool CheckSignaturePolymorphicMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_);
464 
465   // Checks the invoked receiver matches the expectations for signature polymorphic methods.
466   bool CheckSignaturePolymorphicReceiver(const Instruction* inst) REQUIRES_SHARED(Locks::mutator_lock_);
467 
468   // Extract the relative offset from a branch instruction.
469   // Returns "false" on failure (e.g. this isn't a branch instruction).
470   bool GetBranchOffset(uint32_t cur_offset, int32_t* pOffset, bool* pConditional,
471                        bool* selfOkay);
472 
473   /* Perform detailed code-flow analysis on a single method. */
474   bool VerifyCodeFlow() REQUIRES_SHARED(Locks::mutator_lock_);
475 
476   // Set the register types for the first instruction in the method based on the method signature.
477   // This has the side-effect of validating the signature.
478   bool SetTypesFromSignature() REQUIRES_SHARED(Locks::mutator_lock_);
479 
480   /*
481    * Perform code flow on a method.
482    *
483    * The basic strategy is as outlined in v3 4.11.1.2: set the "changed" bit on the first
484    * instruction, process it (setting additional "changed" bits), and repeat until there are no
485    * more.
486    *
487    * v3 4.11.1.1
488    * - (N/A) operand stack is always the same size
489    * - operand stack [registers] contain the correct types of values
490    * - local variables [registers] contain the correct types of values
491    * - methods are invoked with the appropriate arguments
492    * - fields are assigned using values of appropriate types
493    * - opcodes have the correct type values in operand registers
494    * - there is never an uninitialized class instance in a local variable in code protected by an
495    *   exception handler (operand stack is okay, because the operand stack is discarded when an
496    *   exception is thrown) [can't know what's a local var w/o the debug info -- should fall out of
497    *   register typing]
498    *
499    * v3 4.11.1.2
500    * - execution cannot fall off the end of the code
501    *
502    * (We also do many of the items described in the "static checks" sections, because it's easier to
503    * do them here.)
504    *
505    * We need an array of RegType values, one per register, for every instruction. If the method uses
506    * monitor-enter, we need extra data for every register, and a stack for every "interesting"
507    * instruction. In theory this could become quite large -- up to several megabytes for a monster
508    * function.
509    *
510    * NOTE:
511    * The spec forbids backward branches when there's an uninitialized reference in a register. The
512    * idea is to prevent something like this:
513    *   loop:
514    *     move r1, r0
515    *     new-instance r0, MyClass
516    *     ...
517    *     if-eq rN, loop  // once
518    *   initialize r0
519    *
520    * This leaves us with two different instances, both allocated by the same instruction, but only
521    * one is initialized. The scheme outlined in v3 4.11.1.4 wouldn't catch this, so they work around
522    * it by preventing backward branches. We achieve identical results without restricting code
523    * reordering by specifying that you can't execute the new-instance instruction if a register
524    * contains an uninitialized instance created by that same instruction.
525    */
526   template <bool kMonitorDexPCs>
527   bool CodeFlowVerifyMethod() REQUIRES_SHARED(Locks::mutator_lock_);
528 
529   /*
530    * Perform verification for a single instruction.
531    *
532    * This requires fully decoding the instruction to determine the effect it has on registers.
533    *
534    * Finds zero or more following instructions and sets the "changed" flag if execution at that
535    * point needs to be (re-)evaluated. Register changes are merged into "reg_types_" at the target
536    * addresses. Does not set or clear any other flags in "insn_flags_".
537    */
538   bool CodeFlowVerifyInstruction(uint32_t* start_guess)
539       REQUIRES_SHARED(Locks::mutator_lock_);
540 
541   // Perform verification of a new array instruction
542   void VerifyNewArray(const Instruction* inst, bool is_filled, bool is_range)
543       REQUIRES_SHARED(Locks::mutator_lock_);
544 
545   // Helper to perform verification on puts of primitive type.
546   void VerifyPrimitivePut(const RegType& target_type, const RegType& insn_type,
547                           const uint32_t vregA) REQUIRES_SHARED(Locks::mutator_lock_);
548 
549   // Perform verification of an aget instruction. The destination register's type will be set to
550   // be that of component type of the array unless the array type is unknown, in which case a
551   // bottom type inferred from the type of instruction is used. is_primitive is false for an
552   // aget-object.
553   void VerifyAGet(const Instruction* inst, const RegType& insn_type,
554                   bool is_primitive) REQUIRES_SHARED(Locks::mutator_lock_);
555 
556   // Perform verification of an aput instruction.
557   void VerifyAPut(const Instruction* inst, const RegType& insn_type,
558                   bool is_primitive) REQUIRES_SHARED(Locks::mutator_lock_);
559 
560   // Lookup instance field and fail for resolution violations
561   ArtField* GetInstanceField(const RegType& obj_type, int field_idx)
562       REQUIRES_SHARED(Locks::mutator_lock_);
563 
564   // Lookup static field and fail for resolution violations
565   ArtField* GetStaticField(int field_idx) REQUIRES_SHARED(Locks::mutator_lock_);
566 
567   // Perform verification of an iget/sget/iput/sput instruction.
568   template <FieldAccessType kAccType>
569   void VerifyISFieldAccess(const Instruction* inst, const RegType& insn_type,
570                            bool is_primitive, bool is_static)
571       REQUIRES_SHARED(Locks::mutator_lock_);
572 
573   // Resolves a class based on an index and, if C is kYes, performs access checks to ensure
574   // the referrer can access the resolved class.
575   template <CheckAccess C>
576   const RegType& ResolveClass(dex::TypeIndex class_idx)
577       REQUIRES_SHARED(Locks::mutator_lock_);
578 
579   /*
580    * For the "move-exception" instruction at "work_insn_idx_", which must be at an exception handler
581    * address, determine the Join of all exceptions that can land here. Fails if no matching
582    * exception handler can be found or if the Join of exception types fails.
583    */
584   const RegType& GetCaughtExceptionType()
585       REQUIRES_SHARED(Locks::mutator_lock_);
586 
587   /*
588    * Resolves a method based on an index and performs access checks to ensure
589    * the referrer can access the resolved method.
590    * Does not throw exceptions.
591    */
592   ArtMethod* ResolveMethodAndCheckAccess(uint32_t method_idx, MethodType method_type)
593       REQUIRES_SHARED(Locks::mutator_lock_);
594 
595   /*
596    * Verify the arguments to a method. We're executing in "method", making
597    * a call to the method reference in vB.
598    *
599    * If this is a "direct" invoke, we allow calls to <init>. For calls to
600    * <init>, the first argument may be an uninitialized reference. Otherwise,
601    * calls to anything starting with '<' will be rejected, as will any
602    * uninitialized reference arguments.
603    *
604    * For non-static method calls, this will verify that the method call is
605    * appropriate for the "this" argument.
606    *
607    * The method reference is in vBBBB. The "is_range" parameter determines
608    * whether we use 0-4 "args" values or a range of registers defined by
609    * vAA and vCCCC.
610    *
611    * Widening conversions on integers and references are allowed, but
612    * narrowing conversions are not.
613    *
614    * Returns the resolved method on success, null on failure (with *failure
615    * set appropriately).
616    */
617   ArtMethod* VerifyInvocationArgs(const Instruction* inst, MethodType method_type, bool is_range)
618       REQUIRES_SHARED(Locks::mutator_lock_);
619 
620   // Similar checks to the above, but on the proto. Will be used when the method cannot be
621   // resolved.
622   void VerifyInvocationArgsUnresolvedMethod(const Instruction* inst, MethodType method_type,
623                                             bool is_range)
624       REQUIRES_SHARED(Locks::mutator_lock_);
625 
626   template <class T>
627   ArtMethod* VerifyInvocationArgsFromIterator(T* it, const Instruction* inst,
628                                                       MethodType method_type, bool is_range,
629                                                       ArtMethod* res_method)
630       REQUIRES_SHARED(Locks::mutator_lock_);
631 
632   /*
633    * Verify the arguments present for a call site. Returns "true" if all is well, "false" otherwise.
634    */
635   bool CheckCallSite(uint32_t call_site_idx);
636 
637   /*
638    * Verify that the target instruction is not "move-exception". It's important that the only way
639    * to execute a move-exception is as the first instruction of an exception handler.
640    * Returns "true" if all is well, "false" if the target instruction is move-exception.
641    */
CheckNotMoveException(const uint16_t * insns,int insn_idx)642   bool CheckNotMoveException(const uint16_t* insns, int insn_idx) {
643     if ((insns[insn_idx] & 0xff) == Instruction::MOVE_EXCEPTION) {
644       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid use of move-exception";
645       return false;
646     }
647     return true;
648   }
649 
650   /*
651    * Verify that the target instruction is not "move-result". It is important that we cannot
652    * branch to move-result instructions, but we have to make this a distinct check instead of
653    * adding it to CheckNotMoveException, because it is legal to continue into "move-result"
654    * instructions - as long as the previous instruction was an invoke, which is checked elsewhere.
655    */
CheckNotMoveResult(const uint16_t * insns,int insn_idx)656   bool CheckNotMoveResult(const uint16_t* insns, int insn_idx) {
657     if (((insns[insn_idx] & 0xff) >= Instruction::MOVE_RESULT) &&
658         ((insns[insn_idx] & 0xff) <= Instruction::MOVE_RESULT_OBJECT)) {
659       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid use of move-result*";
660       return false;
661     }
662     return true;
663   }
664 
665   /*
666    * Verify that the target instruction is not "move-result" or "move-exception". This is to
667    * be used when checking branch and switch instructions, but not instructions that can
668    * continue.
669    */
CheckNotMoveExceptionOrMoveResult(const uint16_t * insns,int insn_idx)670   bool CheckNotMoveExceptionOrMoveResult(const uint16_t* insns, int insn_idx) {
671     return (CheckNotMoveException(insns, insn_idx) && CheckNotMoveResult(insns, insn_idx));
672   }
673 
674   /*
675   * Control can transfer to "next_insn". Merge the registers from merge_line into the table at
676   * next_insn, and set the changed flag on the target address if any of the registers were changed.
677   * In the case of fall-through, update the merge line on a change as its the working line for the
678   * next instruction.
679   * Returns "false" if an error is encountered.
680   */
681   bool UpdateRegisters(uint32_t next_insn, RegisterLine* merge_line, bool update_merge_line)
682       REQUIRES_SHARED(Locks::mutator_lock_);
683 
684   // Return the register type for the method.
685   const RegType& GetMethodReturnType() REQUIRES_SHARED(Locks::mutator_lock_);
686 
687   // Get a type representing the declaring class of the method.
GetDeclaringClass()688   const RegType& GetDeclaringClass() REQUIRES_SHARED(Locks::mutator_lock_) {
689     if (declaring_class_ == nullptr) {
690       const dex::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx_);
691       const char* descriptor
692           = dex_file_->GetTypeDescriptor(dex_file_->GetTypeId(method_id.class_idx_));
693       if (method_being_verified_ != nullptr) {
694         ObjPtr<mirror::Class> klass = method_being_verified_->GetDeclaringClass();
695         declaring_class_ = &FromClass(descriptor, klass, klass->CannotBeAssignedFromOtherTypes());
696       } else {
697         declaring_class_ = &reg_types_.FromDescriptor(class_loader_.Get(), descriptor, false);
698       }
699     }
700     return *declaring_class_;
701   }
702 
CurrentInsnFlags()703   InstructionFlags* CurrentInsnFlags() {
704     return &GetModifiableInstructionFlags(work_insn_idx_);
705   }
706 
707   const RegType& DetermineCat1Constant(int32_t value, bool precise)
708       REQUIRES_SHARED(Locks::mutator_lock_);
709 
710   // Try to create a register type from the given class. In case a precise type is requested, but
711   // the class is not instantiable, a soft error (of type NO_CLASS) will be enqueued and a
712   // non-precise reference will be returned.
713   // Note: we reuse NO_CLASS as this will throw an exception at runtime, when the failing class is
714   //       actually touched.
FromClass(const char * descriptor,ObjPtr<mirror::Class> klass,bool precise)715   const RegType& FromClass(const char* descriptor, ObjPtr<mirror::Class> klass, bool precise)
716       REQUIRES_SHARED(Locks::mutator_lock_) {
717     DCHECK(klass != nullptr);
718     if (precise && !klass->IsInstantiable() && !klass->IsPrimitive()) {
719       Fail(VerifyError::VERIFY_ERROR_NO_CLASS) << "Could not create precise reference for "
720           << "non-instantiable klass " << descriptor;
721       precise = false;
722     }
723     return reg_types_.FromClass(descriptor, klass, precise);
724   }
725 
726   ALWAYS_INLINE bool FailOrAbort(bool condition, const char* error_msg, uint32_t work_insn_idx);
727 
GetModifiableInstructionFlags(size_t index)728   ALWAYS_INLINE InstructionFlags& GetModifiableInstructionFlags(size_t index) {
729     return insn_flags_[index];
730   }
731 
732   // Returns the method index of an invoke instruction.
GetMethodIdxOfInvoke(const Instruction * inst)733   uint16_t GetMethodIdxOfInvoke(const Instruction* inst)
734       REQUIRES_SHARED(Locks::mutator_lock_) {
735     switch (inst->Opcode()) {
736       case Instruction::INVOKE_VIRTUAL_RANGE_QUICK:
737       case Instruction::INVOKE_VIRTUAL_QUICK: {
738         DCHECK(Runtime::Current()->IsStarted() || verify_to_dump_)
739             << dex_file_->PrettyMethod(dex_method_idx_, true) << "@" << work_insn_idx_;
740         DCHECK(method_being_verified_ != nullptr);
741         uint16_t method_idx = method_being_verified_->GetIndexFromQuickening(work_insn_idx_);
742         CHECK_NE(method_idx, DexFile::kDexNoIndex16);
743         return method_idx;
744       }
745       default: {
746         return inst->VRegB();
747       }
748     }
749   }
750   // Returns the field index of a field access instruction.
GetFieldIdxOfFieldAccess(const Instruction * inst,bool is_static)751   uint16_t GetFieldIdxOfFieldAccess(const Instruction* inst, bool is_static)
752       REQUIRES_SHARED(Locks::mutator_lock_) {
753     if (is_static) {
754       return inst->VRegB_21c();
755     } else if (inst->IsQuickened()) {
756       DCHECK(Runtime::Current()->IsStarted() || verify_to_dump_);
757       DCHECK(method_being_verified_ != nullptr);
758       uint16_t field_idx = method_being_verified_->GetIndexFromQuickening(work_insn_idx_);
759       CHECK_NE(field_idx, DexFile::kDexNoIndex16);
760       return field_idx;
761     } else {
762       return inst->VRegC_22c();
763     }
764   }
765 
766   // Run verification on the method. Returns true if verification completes and false if the input
767   // has an irrecoverable corruption.
768   bool Verify() override REQUIRES_SHARED(Locks::mutator_lock_);
769 
770   // Dump the failures encountered by the verifier.
DumpFailures(std::ostream & os)771   std::ostream& DumpFailures(std::ostream& os) {
772     DCHECK_EQ(failures_.size(), failure_messages_.size());
773     for (const auto* stream : failure_messages_) {
774         os << stream->str() << "\n";
775     }
776     return os;
777   }
778 
779   // Dump the state of the verifier, namely each instruction, what flags are set on it, register
780   // information
Dump(std::ostream & os)781   void Dump(std::ostream& os) REQUIRES_SHARED(Locks::mutator_lock_) {
782     VariableIndentationOutputStream vios(&os);
783     Dump(&vios);
784   }
785   void Dump(VariableIndentationOutputStream* vios) REQUIRES_SHARED(Locks::mutator_lock_);
786 
787   bool HandleMoveException(const Instruction* inst) REQUIRES_SHARED(Locks::mutator_lock_);
788 
789   ArtMethod* method_being_verified_;  // Its ArtMethod representation if known.
790   const uint32_t method_access_flags_;  // Method's access flags.
791   const RegType* return_type_;  // Lazily computed return type of the method.
792   // The dex_cache for the declaring class of the method.
793   Handle<mirror::DexCache> dex_cache_ GUARDED_BY(Locks::mutator_lock_);
794   // The class loader for the declaring class of the method.
795   Handle<mirror::ClassLoader> class_loader_ GUARDED_BY(Locks::mutator_lock_);
796   const dex::ClassDef& class_def_;  // The class def of the declaring class of the method.
797   const RegType* declaring_class_;  // Lazily computed reg type of the method's declaring class.
798 
799   // The dex PC of a FindLocksAtDexPc request, -1 otherwise.
800   uint32_t interesting_dex_pc_;
801   // The container into which FindLocksAtDexPc should write the registers containing held locks,
802   // null if we're not doing FindLocksAtDexPc.
803   std::vector<DexLockInfo>* monitor_enter_dex_pcs_;
804 
805 
806   // An optimization where instead of generating unique RegTypes for constants we use imprecise
807   // constants that cover a range of constants. This isn't good enough for deoptimization that
808   // avoids loading from registers in the case of a constant as the dex instruction set lost the
809   // notion of whether a value should be in a floating point or general purpose register file.
810   const bool need_precise_constants_;
811 
812   // Indicates whether we verify to dump the info. In that case we accept quickened instructions
813   // even though we might detect to be a compiler. Should only be set when running
814   // VerifyMethodAndDump.
815   const bool verify_to_dump_;
816 
817   // Whether or not we call AllowThreadSuspension periodically, we want a way to disable this for
818   // thread dumping checkpoints since we may get thread suspension at an inopportune time due to
819   // FindLocksAtDexPC, resulting in deadlocks.
820   const bool allow_thread_suspension_;
821 
822   // Whether the method seems to be a constructor. Note that this field exists as we can't trust
823   // the flags in the dex file. Some older code does not mark methods named "<init>" and "<clinit>"
824   // correctly.
825   //
826   // Note: this flag is only valid once Verify() has started.
827   bool is_constructor_;
828 
829   // Whether to attempt to fill all register lines for (ex) debugger use.
830   bool fill_register_lines_;
831 
832   // API level, for dependent checks. Note: we do not use '0' for unset here, to simplify checks.
833   // Instead, unset level should correspond to max().
834   const uint32_t api_level_;
835 
836   friend class ::art::verifier::MethodVerifier;
837 
838   DISALLOW_COPY_AND_ASSIGN(MethodVerifier);
839 };
840 
841 // Note: returns true on failure.
842 template <bool kVerifierDebug>
FailOrAbort(bool condition,const char * error_msg,uint32_t work_insn_idx)843 inline bool MethodVerifier<kVerifierDebug>::FailOrAbort(bool condition,
844                                                         const char* error_msg,
845                                                         uint32_t work_insn_idx) {
846   if (kIsDebugBuild) {
847     // In a debug build, abort if the error condition is wrong. Only warn if
848     // we are already aborting (as this verification is likely run to print
849     // lock information).
850     if (LIKELY(gAborting == 0)) {
851       DCHECK(condition) << error_msg << work_insn_idx << " "
852                         << dex_file_->PrettyMethod(dex_method_idx_);
853     } else {
854       if (!condition) {
855         LOG(ERROR) << error_msg << work_insn_idx;
856         Fail(VERIFY_ERROR_BAD_CLASS_HARD) << error_msg << work_insn_idx;
857         return true;
858       }
859     }
860   } else {
861     // In a non-debug build, just fail the class.
862     if (!condition) {
863       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << error_msg << work_insn_idx;
864       return true;
865     }
866   }
867 
868   return false;
869 }
870 
IsLargeMethod(const CodeItemDataAccessor & accessor)871 static bool IsLargeMethod(const CodeItemDataAccessor& accessor) {
872   if (!accessor.HasCodeItem()) {
873     return false;
874   }
875 
876   uint16_t registers_size = accessor.RegistersSize();
877   uint32_t insns_size = accessor.InsnsSizeInCodeUnits();
878 
879   return registers_size * insns_size > 4*1024*1024;
880 }
881 
882 template <bool kVerifierDebug>
FindLocksAtDexPc()883 void MethodVerifier<kVerifierDebug>::FindLocksAtDexPc() {
884   CHECK(monitor_enter_dex_pcs_ != nullptr);
885   CHECK(code_item_accessor_.HasCodeItem());  // This only makes sense for methods with code.
886 
887   // Quick check whether there are any monitor_enter instructions before verifying.
888   for (const DexInstructionPcPair& inst : code_item_accessor_) {
889     if (inst->Opcode() == Instruction::MONITOR_ENTER) {
890       // Strictly speaking, we ought to be able to get away with doing a subset of the full method
891       // verification. In practice, the phase we want relies on data structures set up by all the
892       // earlier passes, so we just run the full method verification and bail out early when we've
893       // got what we wanted.
894       Verify();
895       return;
896     }
897   }
898 }
899 
900 template <bool kVerifierDebug>
Verify()901 bool MethodVerifier<kVerifierDebug>::Verify() {
902   // Some older code doesn't correctly mark constructors as such. Test for this case by looking at
903   // the name.
904   const dex::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx_);
905   const char* method_name = dex_file_->StringDataByIdx(method_id.name_idx_);
906   bool instance_constructor_by_name = strcmp("<init>", method_name) == 0;
907   bool static_constructor_by_name = strcmp("<clinit>", method_name) == 0;
908   bool constructor_by_name = instance_constructor_by_name || static_constructor_by_name;
909   // Check that only constructors are tagged, and check for bad code that doesn't tag constructors.
910   if ((method_access_flags_ & kAccConstructor) != 0) {
911     if (!constructor_by_name) {
912       Fail(VERIFY_ERROR_BAD_CLASS_HARD)
913             << "method is marked as constructor, but not named accordingly";
914       return false;
915     }
916     is_constructor_ = true;
917   } else if (constructor_by_name) {
918     LOG(WARNING) << "Method " << dex_file_->PrettyMethod(dex_method_idx_)
919                  << " not marked as constructor.";
920     is_constructor_ = true;
921   }
922   // If it's a constructor, check whether IsStatic() matches the name.
923   // This should have been rejected by the dex file verifier. Only do in debug build.
924   if (kIsDebugBuild) {
925     if (IsConstructor()) {
926       if (IsStatic() ^ static_constructor_by_name) {
927         Fail(VERIFY_ERROR_BAD_CLASS_HARD)
928               << "constructor name doesn't match static flag";
929         return false;
930       }
931     }
932   }
933 
934   // Methods may only have one of public/protected/private.
935   // This should have been rejected by the dex file verifier. Only do in debug build.
936   if (kIsDebugBuild) {
937     size_t access_mod_count =
938         (((method_access_flags_ & kAccPublic) == 0) ? 0 : 1) +
939         (((method_access_flags_ & kAccProtected) == 0) ? 0 : 1) +
940         (((method_access_flags_ & kAccPrivate) == 0) ? 0 : 1);
941     if (access_mod_count > 1) {
942       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "method has more than one of public/protected/private";
943       return false;
944     }
945   }
946 
947   // If there aren't any instructions, make sure that's expected, then exit successfully.
948   if (!code_item_accessor_.HasCodeItem()) {
949     // Only native or abstract methods may not have code.
950     if ((method_access_flags_ & (kAccNative | kAccAbstract)) == 0) {
951       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "zero-length code in concrete non-native method";
952       return false;
953     }
954 
955     // This should have been rejected by the dex file verifier. Only do in debug build.
956     // Note: the above will also be rejected in the dex file verifier, starting in dex version 37.
957     if (kIsDebugBuild) {
958       if ((method_access_flags_ & kAccAbstract) != 0) {
959         // Abstract methods are not allowed to have the following flags.
960         static constexpr uint32_t kForbidden =
961             kAccPrivate |
962             kAccStatic |
963             kAccFinal |
964             kAccNative |
965             kAccStrict |
966             kAccSynchronized;
967         if ((method_access_flags_ & kForbidden) != 0) {
968           Fail(VERIFY_ERROR_BAD_CLASS_HARD)
969                 << "method can't be abstract and private/static/final/native/strict/synchronized";
970           return false;
971         }
972       }
973       if ((class_def_.GetJavaAccessFlags() & kAccInterface) != 0) {
974         // Interface methods must be public and abstract (if default methods are disabled).
975         uint32_t kRequired = kAccPublic;
976         if ((method_access_flags_ & kRequired) != kRequired) {
977           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "interface methods must be public";
978           return false;
979         }
980         // In addition to the above, interface methods must not be protected.
981         static constexpr uint32_t kForbidden = kAccProtected;
982         if ((method_access_flags_ & kForbidden) != 0) {
983           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "interface methods can't be protected";
984           return false;
985         }
986       }
987       // We also don't allow constructors to be abstract or native.
988       if (IsConstructor()) {
989         Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "constructors can't be abstract or native";
990         return false;
991       }
992     }
993     return true;
994   }
995 
996   // This should have been rejected by the dex file verifier. Only do in debug build.
997   if (kIsDebugBuild) {
998     // When there's code, the method must not be native or abstract.
999     if ((method_access_flags_ & (kAccNative | kAccAbstract)) != 0) {
1000       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "non-zero-length code in abstract or native method";
1001       return false;
1002     }
1003 
1004     if ((class_def_.GetJavaAccessFlags() & kAccInterface) != 0) {
1005       // Interfaces may always have static initializers for their fields. If we are running with
1006       // default methods enabled we also allow other public, static, non-final methods to have code.
1007       // Otherwise that is the only type of method allowed.
1008       if (!(IsConstructor() && IsStatic())) {
1009         if (IsInstanceConstructor()) {
1010           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "interfaces may not have non-static constructor";
1011           return false;
1012         } else if (method_access_flags_ & kAccFinal) {
1013           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "interfaces may not have final methods";
1014           return false;
1015         } else {
1016           uint32_t access_flag_options = kAccPublic;
1017           if (dex_file_->SupportsDefaultMethods()) {
1018             access_flag_options |= kAccPrivate;
1019           }
1020           if (!(method_access_flags_ & access_flag_options)) {
1021             Fail(VERIFY_ERROR_BAD_CLASS_HARD)
1022                 << "interfaces may not have protected or package-private members";
1023             return false;
1024           }
1025         }
1026       }
1027     }
1028 
1029     // Instance constructors must not be synchronized.
1030     if (IsInstanceConstructor()) {
1031       static constexpr uint32_t kForbidden = kAccSynchronized;
1032       if ((method_access_flags_ & kForbidden) != 0) {
1033         Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "constructors can't be synchronized";
1034         return false;
1035       }
1036     }
1037   }
1038 
1039   // Consistency-check of the register counts.
1040   // ins + locals = registers, so make sure that ins <= registers.
1041   if (code_item_accessor_.InsSize() > code_item_accessor_.RegistersSize()) {
1042     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad register counts (ins="
1043                                       << code_item_accessor_.InsSize()
1044                                       << " regs=" << code_item_accessor_.RegistersSize();
1045     return false;
1046   }
1047 
1048   // Allocate and initialize an array to hold instruction data.
1049   insn_flags_.reset(allocator_.AllocArray<InstructionFlags>(
1050       code_item_accessor_.InsnsSizeInCodeUnits()));
1051   DCHECK(insn_flags_ != nullptr);
1052   std::uninitialized_fill_n(insn_flags_.get(),
1053                             code_item_accessor_.InsnsSizeInCodeUnits(),
1054                             InstructionFlags());
1055   // Run through the instructions and see if the width checks out.
1056   bool result = ComputeWidthsAndCountOps();
1057   bool allow_runtime_only_instructions = !IsAotMode() || verify_to_dump_;
1058   // Flag instructions guarded by a "try" block and check exception handlers.
1059   result = result && ScanTryCatchBlocks();
1060   // Perform static instruction verification.
1061   result = result && (allow_runtime_only_instructions
1062                           ? VerifyInstructions<true>()
1063                           : VerifyInstructions<false>());
1064   // Perform code-flow analysis and return.
1065   result = result && VerifyCodeFlow();
1066 
1067   return result;
1068 }
1069 
1070 template <bool kVerifierDebug>
ComputeWidthsAndCountOps()1071 bool MethodVerifier<kVerifierDebug>::ComputeWidthsAndCountOps() {
1072   // We can't assume the instruction is well formed, handle the case where calculating the size
1073   // goes past the end of the code item.
1074   SafeDexInstructionIterator it(code_item_accessor_.begin(), code_item_accessor_.end());
1075   for ( ; !it.IsErrorState() && it < code_item_accessor_.end(); ++it) {
1076     // In case the instruction goes past the end of the code item, make sure to not process it.
1077     SafeDexInstructionIterator next = it;
1078     ++next;
1079     if (next.IsErrorState()) {
1080       break;
1081     }
1082     Instruction::Code opcode = it->Opcode();
1083     switch (opcode) {
1084       case Instruction::APUT_OBJECT:
1085       case Instruction::CHECK_CAST:
1086         has_check_casts_ = true;
1087         break;
1088       default:
1089         break;
1090     }
1091     GetModifiableInstructionFlags(it.DexPc()).SetIsOpcode();
1092   }
1093 
1094   if (it != code_item_accessor_.end()) {
1095     const size_t insns_size = code_item_accessor_.InsnsSizeInCodeUnits();
1096     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "code did not end where expected ("
1097                                       << it.DexPc() << " vs. " << insns_size << ")";
1098     return false;
1099   }
1100   DCHECK(GetInstructionFlags(0).IsOpcode());
1101 
1102   return true;
1103 }
1104 
1105 template <bool kVerifierDebug>
ScanTryCatchBlocks()1106 bool MethodVerifier<kVerifierDebug>::ScanTryCatchBlocks() {
1107   const uint32_t tries_size = code_item_accessor_.TriesSize();
1108   if (tries_size == 0) {
1109     return true;
1110   }
1111   const uint32_t insns_size = code_item_accessor_.InsnsSizeInCodeUnits();
1112   for (const dex::TryItem& try_item : code_item_accessor_.TryItems()) {
1113     const uint32_t start = try_item.start_addr_;
1114     const uint32_t end = start + try_item.insn_count_;
1115     if ((start >= end) || (start >= insns_size) || (end > insns_size)) {
1116       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad exception entry: startAddr=" << start
1117                                         << " endAddr=" << end << " (size=" << insns_size << ")";
1118       return false;
1119     }
1120     if (!GetInstructionFlags(start).IsOpcode()) {
1121       Fail(VERIFY_ERROR_BAD_CLASS_HARD)
1122           << "'try' block starts inside an instruction (" << start << ")";
1123       return false;
1124     }
1125     DexInstructionIterator end_it(code_item_accessor_.Insns(), end);
1126     for (DexInstructionIterator it(code_item_accessor_.Insns(), start); it < end_it; ++it) {
1127       GetModifiableInstructionFlags(it.DexPc()).SetInTry();
1128     }
1129   }
1130   // Iterate over each of the handlers to verify target addresses.
1131   const uint8_t* handlers_ptr = code_item_accessor_.GetCatchHandlerData();
1132   const uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
1133   ClassLinker* linker = GetClassLinker();
1134   for (uint32_t idx = 0; idx < handlers_size; idx++) {
1135     CatchHandlerIterator iterator(handlers_ptr);
1136     for (; iterator.HasNext(); iterator.Next()) {
1137       uint32_t dex_pc = iterator.GetHandlerAddress();
1138       if (!GetInstructionFlags(dex_pc).IsOpcode()) {
1139         Fail(VERIFY_ERROR_BAD_CLASS_HARD)
1140             << "exception handler starts at bad address (" << dex_pc << ")";
1141         return false;
1142       }
1143       if (!CheckNotMoveResult(code_item_accessor_.Insns(), dex_pc)) {
1144         Fail(VERIFY_ERROR_BAD_CLASS_HARD)
1145             << "exception handler begins with move-result* (" << dex_pc << ")";
1146         return false;
1147       }
1148       GetModifiableInstructionFlags(dex_pc).SetBranchTarget();
1149       // Ensure exception types are resolved so that they don't need resolution to be delivered,
1150       // unresolved exception types will be ignored by exception delivery
1151       if (iterator.GetHandlerTypeIndex().IsValid()) {
1152         ObjPtr<mirror::Class> exception_type =
1153             linker->ResolveType(iterator.GetHandlerTypeIndex(), dex_cache_, class_loader_);
1154         if (exception_type == nullptr) {
1155           DCHECK(self_->IsExceptionPending());
1156           self_->ClearException();
1157         }
1158       }
1159     }
1160     handlers_ptr = iterator.EndDataPointer();
1161   }
1162   return true;
1163 }
1164 
1165 template <bool kVerifierDebug>
1166 template <bool kAllowRuntimeOnlyInstructions>
VerifyInstructions()1167 bool MethodVerifier<kVerifierDebug>::VerifyInstructions() {
1168   // Flag the start of the method as a branch target.
1169   GetModifiableInstructionFlags(0).SetBranchTarget();
1170   for (const DexInstructionPcPair& inst : code_item_accessor_) {
1171     const uint32_t dex_pc = inst.DexPc();
1172     if (!VerifyInstruction<kAllowRuntimeOnlyInstructions>(&inst.Inst(), dex_pc)) {
1173       DCHECK_NE(failures_.size(), 0U);
1174       return false;
1175     }
1176     // Flag some interesting instructions.
1177     if (inst->IsReturn()) {
1178       GetModifiableInstructionFlags(dex_pc).SetReturn();
1179     } else if (inst->Opcode() == Instruction::CHECK_CAST) {
1180       // The dex-to-dex compiler wants type information to elide check-casts.
1181       GetModifiableInstructionFlags(dex_pc).SetCompileTimeInfoPoint();
1182     }
1183   }
1184   return true;
1185 }
1186 
1187 template <bool kVerifierDebug>
1188 template <bool kAllowRuntimeOnlyInstructions>
VerifyInstruction(const Instruction * inst,uint32_t code_offset)1189 bool MethodVerifier<kVerifierDebug>::VerifyInstruction(const Instruction* inst,
1190                                                        uint32_t code_offset) {
1191   if (Instruction::kHaveExperimentalInstructions && UNLIKELY(inst->IsExperimental())) {
1192     // Experimental instructions don't yet have verifier support implementation.
1193     // While it is possible to use them by themselves, when we try to use stable instructions
1194     // with a virtual register that was created by an experimental instruction,
1195     // the data flow analysis will fail.
1196     Fail(VERIFY_ERROR_FORCE_INTERPRETER)
1197         << "experimental instruction is not supported by verifier; skipping verification";
1198     flags_.have_pending_experimental_failure_ = true;
1199     return false;
1200   }
1201 
1202   bool result = true;
1203   switch (inst->GetVerifyTypeArgumentA()) {
1204     case Instruction::kVerifyRegA:
1205       result = result && CheckRegisterIndex(inst->VRegA());
1206       break;
1207     case Instruction::kVerifyRegAWide:
1208       result = result && CheckWideRegisterIndex(inst->VRegA());
1209       break;
1210   }
1211   switch (inst->GetVerifyTypeArgumentB()) {
1212     case Instruction::kVerifyRegB:
1213       result = result && CheckRegisterIndex(inst->VRegB());
1214       break;
1215     case Instruction::kVerifyRegBField:
1216       result = result && CheckFieldIndex(inst->VRegB());
1217       break;
1218     case Instruction::kVerifyRegBMethod:
1219       result = result && CheckMethodIndex(inst->VRegB());
1220       break;
1221     case Instruction::kVerifyRegBNewInstance:
1222       result = result && CheckNewInstance(dex::TypeIndex(inst->VRegB()));
1223       break;
1224     case Instruction::kVerifyRegBString:
1225       result = result && CheckStringIndex(inst->VRegB());
1226       break;
1227     case Instruction::kVerifyRegBType:
1228       result = result && CheckTypeIndex(dex::TypeIndex(inst->VRegB()));
1229       break;
1230     case Instruction::kVerifyRegBWide:
1231       result = result && CheckWideRegisterIndex(inst->VRegB());
1232       break;
1233     case Instruction::kVerifyRegBCallSite:
1234       result = result && CheckCallSiteIndex(inst->VRegB());
1235       break;
1236     case Instruction::kVerifyRegBMethodHandle:
1237       result = result && CheckMethodHandleIndex(inst->VRegB());
1238       break;
1239     case Instruction::kVerifyRegBPrototype:
1240       result = result && CheckPrototypeIndex(inst->VRegB());
1241       break;
1242   }
1243   switch (inst->GetVerifyTypeArgumentC()) {
1244     case Instruction::kVerifyRegC:
1245       result = result && CheckRegisterIndex(inst->VRegC());
1246       break;
1247     case Instruction::kVerifyRegCField:
1248       result = result && CheckFieldIndex(inst->VRegC());
1249       break;
1250     case Instruction::kVerifyRegCNewArray:
1251       result = result && CheckNewArray(dex::TypeIndex(inst->VRegC()));
1252       break;
1253     case Instruction::kVerifyRegCType:
1254       result = result && CheckTypeIndex(dex::TypeIndex(inst->VRegC()));
1255       break;
1256     case Instruction::kVerifyRegCWide:
1257       result = result && CheckWideRegisterIndex(inst->VRegC());
1258       break;
1259   }
1260   switch (inst->GetVerifyTypeArgumentH()) {
1261     case Instruction::kVerifyRegHPrototype:
1262       result = result && CheckPrototypeIndex(inst->VRegH());
1263       break;
1264   }
1265   switch (inst->GetVerifyExtraFlags()) {
1266     case Instruction::kVerifyArrayData:
1267       result = result && CheckArrayData(code_offset);
1268       break;
1269     case Instruction::kVerifyBranchTarget:
1270       result = result && CheckBranchTarget(code_offset);
1271       break;
1272     case Instruction::kVerifySwitchTargets:
1273       result = result && CheckSwitchTargets(code_offset);
1274       break;
1275     case Instruction::kVerifyVarArgNonZero:
1276       // Fall-through.
1277     case Instruction::kVerifyVarArg: {
1278       // Instructions that can actually return a negative value shouldn't have this flag.
1279       uint32_t v_a = dchecked_integral_cast<uint32_t>(inst->VRegA());
1280       if ((inst->GetVerifyExtraFlags() == Instruction::kVerifyVarArgNonZero && v_a == 0) ||
1281           v_a > Instruction::kMaxVarArgRegs) {
1282         Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid arg count (" << v_a << ") in "
1283                                              "non-range invoke";
1284         return false;
1285       }
1286 
1287       uint32_t args[Instruction::kMaxVarArgRegs];
1288       inst->GetVarArgs(args);
1289       result = result && CheckVarArgRegs(v_a, args);
1290       break;
1291     }
1292     case Instruction::kVerifyVarArgRangeNonZero:
1293       // Fall-through.
1294     case Instruction::kVerifyVarArgRange:
1295       if (inst->GetVerifyExtraFlags() == Instruction::kVerifyVarArgRangeNonZero &&
1296           inst->VRegA() <= 0) {
1297         Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid arg count (" << inst->VRegA() << ") in "
1298                                              "range invoke";
1299         return false;
1300       }
1301       result = result && CheckVarArgRangeRegs(inst->VRegA(), inst->VRegC());
1302       break;
1303     case Instruction::kVerifyError:
1304       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected opcode " << inst->Name();
1305       result = false;
1306       break;
1307   }
1308   if (!kAllowRuntimeOnlyInstructions && inst->GetVerifyIsRuntimeOnly()) {
1309     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "opcode only expected at runtime " << inst->Name();
1310     result = false;
1311   }
1312   return result;
1313 }
1314 
1315 template <bool kVerifierDebug>
CheckNewInstance(dex::TypeIndex idx)1316 inline bool MethodVerifier<kVerifierDebug>::CheckNewInstance(dex::TypeIndex idx) {
1317   if (UNLIKELY(idx.index_ >= dex_file_->GetHeader().type_ids_size_)) {
1318     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad type index " << idx.index_ << " (max "
1319                                       << dex_file_->GetHeader().type_ids_size_ << ")";
1320     return false;
1321   }
1322   // We don't need the actual class, just a pointer to the class name.
1323   const char* descriptor = dex_file_->StringByTypeIdx(idx);
1324   if (UNLIKELY(descriptor[0] != 'L')) {
1325     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "can't call new-instance on type '" << descriptor << "'";
1326     return false;
1327   } else if (UNLIKELY(strcmp(descriptor, "Ljava/lang/Class;") == 0)) {
1328     // An unlikely new instance on Class is not allowed. Fall back to interpreter to ensure an
1329     // exception is thrown when this statement is executed (compiled code would not do that).
1330     Fail(VERIFY_ERROR_INSTANTIATION);
1331   }
1332   return true;
1333 }
1334 
1335 template <bool kVerifierDebug>
CheckNewArray(dex::TypeIndex idx)1336 bool MethodVerifier<kVerifierDebug>::CheckNewArray(dex::TypeIndex idx) {
1337   if (UNLIKELY(idx.index_ >= dex_file_->GetHeader().type_ids_size_)) {
1338     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad type index " << idx.index_ << " (max "
1339                                       << dex_file_->GetHeader().type_ids_size_ << ")";
1340     return false;
1341   }
1342   int bracket_count = 0;
1343   const char* descriptor = dex_file_->StringByTypeIdx(idx);
1344   const char* cp = descriptor;
1345   while (*cp++ == '[') {
1346     bracket_count++;
1347   }
1348   if (UNLIKELY(bracket_count == 0)) {
1349     /* The given class must be an array type. */
1350     Fail(VERIFY_ERROR_BAD_CLASS_HARD)
1351         << "can't new-array class '" << descriptor << "' (not an array)";
1352     return false;
1353   } else if (UNLIKELY(bracket_count > 255)) {
1354     /* It is illegal to create an array of more than 255 dimensions. */
1355     Fail(VERIFY_ERROR_BAD_CLASS_HARD)
1356         << "can't new-array class '" << descriptor << "' (exceeds limit)";
1357     return false;
1358   }
1359   return true;
1360 }
1361 
1362 template <bool kVerifierDebug>
CheckArrayData(uint32_t cur_offset)1363 bool MethodVerifier<kVerifierDebug>::CheckArrayData(uint32_t cur_offset) {
1364   const uint32_t insn_count = code_item_accessor_.InsnsSizeInCodeUnits();
1365   const uint16_t* insns = code_item_accessor_.Insns() + cur_offset;
1366   const uint16_t* array_data;
1367   int32_t array_data_offset;
1368 
1369   DCHECK_LT(cur_offset, insn_count);
1370   /* make sure the start of the array data table is in range */
1371   array_data_offset = insns[1] | (static_cast<int32_t>(insns[2]) << 16);
1372   if (UNLIKELY(static_cast<int32_t>(cur_offset) + array_data_offset < 0 ||
1373                cur_offset + array_data_offset + 2 >= insn_count)) {
1374     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid array data start: at " << cur_offset
1375                                       << ", data offset " << array_data_offset
1376                                       << ", count " << insn_count;
1377     return false;
1378   }
1379   /* offset to array data table is a relative branch-style offset */
1380   array_data = insns + array_data_offset;
1381   // Make sure the table is at an even dex pc, that is, 32-bit aligned.
1382   if (UNLIKELY(!IsAligned<4>(array_data))) {
1383     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unaligned array data table: at " << cur_offset
1384                                       << ", data offset " << array_data_offset;
1385     return false;
1386   }
1387   // Make sure the array-data is marked as an opcode. This ensures that it was reached when
1388   // traversing the code item linearly. It is an approximation for a by-spec padding value.
1389   if (UNLIKELY(!GetInstructionFlags(cur_offset + array_data_offset).IsOpcode())) {
1390     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array data table at " << cur_offset
1391                                       << ", data offset " << array_data_offset
1392                                       << " not correctly visited, probably bad padding.";
1393     return false;
1394   }
1395 
1396   uint32_t value_width = array_data[1];
1397   uint32_t value_count = *reinterpret_cast<const uint32_t*>(&array_data[2]);
1398   uint32_t table_size = 4 + (value_width * value_count + 1) / 2;
1399   /* make sure the end of the switch is in range */
1400   if (UNLIKELY(cur_offset + array_data_offset + table_size > insn_count)) {
1401     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid array data end: at " << cur_offset
1402                                       << ", data offset " << array_data_offset << ", end "
1403                                       << cur_offset + array_data_offset + table_size
1404                                       << ", count " << insn_count;
1405     return false;
1406   }
1407   return true;
1408 }
1409 
1410 template <bool kVerifierDebug>
CheckBranchTarget(uint32_t cur_offset)1411 bool MethodVerifier<kVerifierDebug>::CheckBranchTarget(uint32_t cur_offset) {
1412   int32_t offset;
1413   bool isConditional, selfOkay;
1414   if (!GetBranchOffset(cur_offset, &offset, &isConditional, &selfOkay)) {
1415     return false;
1416   }
1417   if (UNLIKELY(!selfOkay && offset == 0)) {
1418     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "branch offset of zero not allowed at"
1419                                       << reinterpret_cast<void*>(cur_offset);
1420     return false;
1421   }
1422   // Check for 32-bit overflow. This isn't strictly necessary if we can depend on the runtime
1423   // to have identical "wrap-around" behavior, but it's unwise to depend on that.
1424   if (UNLIKELY(((int64_t) cur_offset + (int64_t) offset) != (int64_t) (cur_offset + offset))) {
1425     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "branch target overflow "
1426                                       << reinterpret_cast<void*>(cur_offset) << " +" << offset;
1427     return false;
1428   }
1429   int32_t abs_offset = cur_offset + offset;
1430   if (UNLIKELY(abs_offset < 0 ||
1431                (uint32_t) abs_offset >= code_item_accessor_.InsnsSizeInCodeUnits()  ||
1432                !GetInstructionFlags(abs_offset).IsOpcode())) {
1433     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid branch target " << offset << " (-> "
1434                                       << reinterpret_cast<void*>(abs_offset) << ") at "
1435                                       << reinterpret_cast<void*>(cur_offset);
1436     return false;
1437   }
1438   GetModifiableInstructionFlags(abs_offset).SetBranchTarget();
1439   return true;
1440 }
1441 
1442 template <bool kVerifierDebug>
GetBranchOffset(uint32_t cur_offset,int32_t * pOffset,bool * pConditional,bool * selfOkay)1443 bool MethodVerifier<kVerifierDebug>::GetBranchOffset(uint32_t cur_offset,
1444                                                      int32_t* pOffset,
1445                                                      bool* pConditional,
1446                                                      bool* selfOkay) {
1447   const uint16_t* insns = code_item_accessor_.Insns() + cur_offset;
1448   *pConditional = false;
1449   *selfOkay = false;
1450   switch (*insns & 0xff) {
1451     case Instruction::GOTO:
1452       *pOffset = ((int16_t) *insns) >> 8;
1453       break;
1454     case Instruction::GOTO_32:
1455       *pOffset = insns[1] | (((uint32_t) insns[2]) << 16);
1456       *selfOkay = true;
1457       break;
1458     case Instruction::GOTO_16:
1459       *pOffset = (int16_t) insns[1];
1460       break;
1461     case Instruction::IF_EQ:
1462     case Instruction::IF_NE:
1463     case Instruction::IF_LT:
1464     case Instruction::IF_GE:
1465     case Instruction::IF_GT:
1466     case Instruction::IF_LE:
1467     case Instruction::IF_EQZ:
1468     case Instruction::IF_NEZ:
1469     case Instruction::IF_LTZ:
1470     case Instruction::IF_GEZ:
1471     case Instruction::IF_GTZ:
1472     case Instruction::IF_LEZ:
1473       *pOffset = (int16_t) insns[1];
1474       *pConditional = true;
1475       break;
1476     default:
1477       return false;
1478   }
1479   return true;
1480 }
1481 
1482 template <bool kVerifierDebug>
CheckSwitchTargets(uint32_t cur_offset)1483 bool MethodVerifier<kVerifierDebug>::CheckSwitchTargets(uint32_t cur_offset) {
1484   const uint32_t insn_count = code_item_accessor_.InsnsSizeInCodeUnits();
1485   DCHECK_LT(cur_offset, insn_count);
1486   const uint16_t* insns = code_item_accessor_.Insns() + cur_offset;
1487   /* make sure the start of the switch is in range */
1488   int32_t switch_offset = insns[1] | (static_cast<int32_t>(insns[2]) << 16);
1489   if (UNLIKELY(static_cast<int32_t>(cur_offset) + switch_offset < 0 ||
1490                cur_offset + switch_offset + 2 > insn_count)) {
1491     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid switch start: at " << cur_offset
1492                                       << ", switch offset " << switch_offset
1493                                       << ", count " << insn_count;
1494     return false;
1495   }
1496   /* offset to switch table is a relative branch-style offset */
1497   const uint16_t* switch_insns = insns + switch_offset;
1498   // Make sure the table is at an even dex pc, that is, 32-bit aligned.
1499   if (UNLIKELY(!IsAligned<4>(switch_insns))) {
1500     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unaligned switch table: at " << cur_offset
1501                                       << ", switch offset " << switch_offset;
1502     return false;
1503   }
1504   // Make sure the switch data is marked as an opcode. This ensures that it was reached when
1505   // traversing the code item linearly. It is an approximation for a by-spec padding value.
1506   if (UNLIKELY(!GetInstructionFlags(cur_offset + switch_offset).IsOpcode())) {
1507     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "switch table at " << cur_offset
1508                                       << ", switch offset " << switch_offset
1509                                       << " not correctly visited, probably bad padding.";
1510     return false;
1511   }
1512 
1513   bool is_packed_switch = (*insns & 0xff) == Instruction::PACKED_SWITCH;
1514 
1515   uint32_t switch_count = switch_insns[1];
1516   int32_t targets_offset;
1517   uint16_t expected_signature;
1518   if (is_packed_switch) {
1519     /* 0=sig, 1=count, 2/3=firstKey */
1520     targets_offset = 4;
1521     expected_signature = Instruction::kPackedSwitchSignature;
1522   } else {
1523     /* 0=sig, 1=count, 2..count*2 = keys */
1524     targets_offset = 2 + 2 * switch_count;
1525     expected_signature = Instruction::kSparseSwitchSignature;
1526   }
1527   uint32_t table_size = targets_offset + switch_count * 2;
1528   if (UNLIKELY(switch_insns[0] != expected_signature)) {
1529     Fail(VERIFY_ERROR_BAD_CLASS_HARD)
1530         << StringPrintf("wrong signature for switch table (%x, wanted %x)",
1531                         switch_insns[0], expected_signature);
1532     return false;
1533   }
1534   /* make sure the end of the switch is in range */
1535   if (UNLIKELY(cur_offset + switch_offset + table_size > (uint32_t) insn_count)) {
1536     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid switch end: at " << cur_offset
1537                                       << ", switch offset " << switch_offset
1538                                       << ", end " << (cur_offset + switch_offset + table_size)
1539                                       << ", count " << insn_count;
1540     return false;
1541   }
1542 
1543   constexpr int32_t keys_offset = 2;
1544   if (switch_count > 1) {
1545     if (is_packed_switch) {
1546       /* for a packed switch, verify that keys do not overflow int32 */
1547       int32_t first_key = switch_insns[keys_offset] | (switch_insns[keys_offset + 1] << 16);
1548       int32_t max_first_key =
1549           std::numeric_limits<int32_t>::max() - (static_cast<int32_t>(switch_count) - 1);
1550       if (UNLIKELY(first_key > max_first_key)) {
1551         Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid packed switch: first_key=" << first_key
1552                                           << ", switch_count=" << switch_count;
1553         return false;
1554       }
1555     } else {
1556       /* for a sparse switch, verify the keys are in ascending order */
1557       int32_t last_key = switch_insns[keys_offset] | (switch_insns[keys_offset + 1] << 16);
1558       for (uint32_t targ = 1; targ < switch_count; targ++) {
1559         int32_t key =
1560             static_cast<int32_t>(switch_insns[keys_offset + targ * 2]) |
1561             static_cast<int32_t>(switch_insns[keys_offset + targ * 2 + 1] << 16);
1562         if (UNLIKELY(key <= last_key)) {
1563           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid sparse switch: last key=" << last_key
1564                                             << ", this=" << key;
1565           return false;
1566         }
1567         last_key = key;
1568       }
1569     }
1570   }
1571   /* verify each switch target */
1572   for (uint32_t targ = 0; targ < switch_count; targ++) {
1573     int32_t offset = static_cast<int32_t>(switch_insns[targets_offset + targ * 2]) |
1574                      static_cast<int32_t>(switch_insns[targets_offset + targ * 2 + 1] << 16);
1575     int32_t abs_offset = cur_offset + offset;
1576     if (UNLIKELY(abs_offset < 0 ||
1577                  abs_offset >= static_cast<int32_t>(insn_count) ||
1578                  !GetInstructionFlags(abs_offset).IsOpcode())) {
1579       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid switch target " << offset
1580                                         << " (-> " << reinterpret_cast<void*>(abs_offset) << ") at "
1581                                         << reinterpret_cast<void*>(cur_offset)
1582                                         << "[" << targ << "]";
1583       return false;
1584     }
1585     GetModifiableInstructionFlags(abs_offset).SetBranchTarget();
1586   }
1587   return true;
1588 }
1589 
1590 template <bool kVerifierDebug>
VerifyCodeFlow()1591 bool MethodVerifier<kVerifierDebug>::VerifyCodeFlow() {
1592   const uint16_t registers_size = code_item_accessor_.RegistersSize();
1593 
1594   /* Create and initialize table holding register status */
1595   RegisterTrackingMode base_mode = IsAotMode()
1596                                        ? kTrackCompilerInterestPoints
1597                                        : kTrackRegsBranches;
1598   reg_table_.Init(fill_register_lines_ ? kTrackRegsAll : base_mode,
1599                   insn_flags_.get(),
1600                   code_item_accessor_.InsnsSizeInCodeUnits(),
1601                   registers_size,
1602                   allocator_,
1603                   GetRegTypeCache());
1604 
1605   work_line_.reset(RegisterLine::Create(registers_size, allocator_, GetRegTypeCache()));
1606   saved_line_.reset(RegisterLine::Create(registers_size, allocator_, GetRegTypeCache()));
1607 
1608   /* Initialize register types of method arguments. */
1609   if (!SetTypesFromSignature()) {
1610     DCHECK_NE(failures_.size(), 0U);
1611     std::string prepend("Bad signature in ");
1612     prepend += dex_file_->PrettyMethod(dex_method_idx_);
1613     PrependToLastFailMessage(prepend);
1614     return false;
1615   }
1616   // We may have a runtime failure here, clear.
1617   flags_.have_pending_runtime_throw_failure_ = false;
1618 
1619   /* Perform code flow verification. */
1620   bool res = LIKELY(monitor_enter_dex_pcs_ == nullptr)
1621                  ? CodeFlowVerifyMethod</*kMonitorDexPCs=*/ false>()
1622                  : CodeFlowVerifyMethod</*kMonitorDexPCs=*/ true>();
1623   if (UNLIKELY(!res)) {
1624     DCHECK_NE(failures_.size(), 0U);
1625     return false;
1626   }
1627   return true;
1628 }
1629 
1630 template <bool kVerifierDebug>
Dump(VariableIndentationOutputStream * vios)1631 void MethodVerifier<kVerifierDebug>::Dump(VariableIndentationOutputStream* vios) {
1632   if (!code_item_accessor_.HasCodeItem()) {
1633     vios->Stream() << "Native method\n";
1634     return;
1635   }
1636   {
1637     vios->Stream() << "Register Types:\n";
1638     ScopedIndentation indent1(vios);
1639     reg_types_.Dump(vios->Stream());
1640   }
1641   vios->Stream() << "Dumping instructions and register lines:\n";
1642   ScopedIndentation indent1(vios);
1643 
1644   for (const DexInstructionPcPair& inst : code_item_accessor_) {
1645     const size_t dex_pc = inst.DexPc();
1646 
1647     // Might be asked to dump before the table is initialized.
1648     if (reg_table_.IsInitialized()) {
1649       RegisterLine* reg_line = reg_table_.GetLine(dex_pc);
1650       if (reg_line != nullptr) {
1651         vios->Stream() << reg_line->Dump(this) << "\n";
1652       }
1653     }
1654 
1655     vios->Stream()
1656         << StringPrintf("0x%04zx", dex_pc) << ": " << GetInstructionFlags(dex_pc).ToString() << " ";
1657     const bool kDumpHexOfInstruction = false;
1658     if (kDumpHexOfInstruction) {
1659       vios->Stream() << inst->DumpHex(5) << " ";
1660     }
1661     vios->Stream() << inst->DumpString(dex_file_) << "\n";
1662   }
1663 }
1664 
IsPrimitiveDescriptor(char descriptor)1665 static bool IsPrimitiveDescriptor(char descriptor) {
1666   switch (descriptor) {
1667     case 'I':
1668     case 'C':
1669     case 'S':
1670     case 'B':
1671     case 'Z':
1672     case 'F':
1673     case 'D':
1674     case 'J':
1675       return true;
1676     default:
1677       return false;
1678   }
1679 }
1680 
1681 template <bool kVerifierDebug>
SetTypesFromSignature()1682 bool MethodVerifier<kVerifierDebug>::SetTypesFromSignature() {
1683   RegisterLine* reg_line = reg_table_.GetLine(0);
1684 
1685   // Should have been verified earlier.
1686   DCHECK_GE(code_item_accessor_.RegistersSize(), code_item_accessor_.InsSize());
1687 
1688   uint32_t arg_start = code_item_accessor_.RegistersSize() - code_item_accessor_.InsSize();
1689   size_t expected_args = code_item_accessor_.InsSize();   /* long/double count as two */
1690 
1691   // Include the "this" pointer.
1692   size_t cur_arg = 0;
1693   if (!IsStatic()) {
1694     if (expected_args == 0) {
1695       // Expect at least a receiver.
1696       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected 0 args, but method is not static";
1697       return false;
1698     }
1699 
1700     // If this is a constructor for a class other than java.lang.Object, mark the first ("this")
1701     // argument as uninitialized. This restricts field access until the superclass constructor is
1702     // called.
1703     const RegType& declaring_class = GetDeclaringClass();
1704     if (IsConstructor()) {
1705       if (declaring_class.IsJavaLangObject()) {
1706         // "this" is implicitly initialized.
1707         reg_line->SetThisInitialized();
1708         reg_line->SetRegisterType<LockOp::kClear>(this, arg_start + cur_arg, declaring_class);
1709       } else {
1710         reg_line->SetRegisterType<LockOp::kClear>(
1711             this,
1712             arg_start + cur_arg,
1713             reg_types_.UninitializedThisArgument(declaring_class));
1714       }
1715     } else {
1716       reg_line->SetRegisterType<LockOp::kClear>(this, arg_start + cur_arg, declaring_class);
1717     }
1718     cur_arg++;
1719   }
1720 
1721   const dex::ProtoId& proto_id =
1722       dex_file_->GetMethodPrototype(dex_file_->GetMethodId(dex_method_idx_));
1723   DexFileParameterIterator iterator(*dex_file_, proto_id);
1724 
1725   for (; iterator.HasNext(); iterator.Next()) {
1726     const char* descriptor = iterator.GetDescriptor();
1727     if (descriptor == nullptr) {
1728       LOG(FATAL) << "Null descriptor";
1729     }
1730     if (cur_arg >= expected_args) {
1731       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected " << expected_args
1732                                         << " args, found more (" << descriptor << ")";
1733       return false;
1734     }
1735     switch (descriptor[0]) {
1736       case 'L':
1737       case '[':
1738         // We assume that reference arguments are initialized. The only way it could be otherwise
1739         // (assuming the caller was verified) is if the current method is <init>, but in that case
1740         // it's effectively considered initialized the instant we reach here (in the sense that we
1741         // can return without doing anything or call virtual methods).
1742         {
1743           // Note: don't check access. No error would be thrown for declaring or passing an
1744           //       inaccessible class. Only actual accesses to fields or methods will.
1745           const RegType& reg_type = ResolveClass<CheckAccess::kNo>(iterator.GetTypeIdx());
1746           if (!reg_type.IsNonZeroReferenceTypes()) {
1747             DCHECK(HasFailures());
1748             return false;
1749           }
1750           reg_line->SetRegisterType<LockOp::kClear>(this, arg_start + cur_arg, reg_type);
1751         }
1752         break;
1753       case 'Z':
1754         reg_line->SetRegisterType<LockOp::kClear>(this, arg_start + cur_arg, reg_types_.Boolean());
1755         break;
1756       case 'C':
1757         reg_line->SetRegisterType<LockOp::kClear>(this, arg_start + cur_arg, reg_types_.Char());
1758         break;
1759       case 'B':
1760         reg_line->SetRegisterType<LockOp::kClear>(this, arg_start + cur_arg, reg_types_.Byte());
1761         break;
1762       case 'I':
1763         reg_line->SetRegisterType<LockOp::kClear>(this, arg_start + cur_arg, reg_types_.Integer());
1764         break;
1765       case 'S':
1766         reg_line->SetRegisterType<LockOp::kClear>(this, arg_start + cur_arg, reg_types_.Short());
1767         break;
1768       case 'F':
1769         reg_line->SetRegisterType<LockOp::kClear>(this, arg_start + cur_arg, reg_types_.Float());
1770         break;
1771       case 'J':
1772       case 'D': {
1773         if (cur_arg + 1 >= expected_args) {
1774           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected " << expected_args
1775               << " args, found more (" << descriptor << ")";
1776           return false;
1777         }
1778 
1779         const RegType* lo_half;
1780         const RegType* hi_half;
1781         if (descriptor[0] == 'J') {
1782           lo_half = &reg_types_.LongLo();
1783           hi_half = &reg_types_.LongHi();
1784         } else {
1785           lo_half = &reg_types_.DoubleLo();
1786           hi_half = &reg_types_.DoubleHi();
1787         }
1788         reg_line->SetRegisterTypeWide(this, arg_start + cur_arg, *lo_half, *hi_half);
1789         cur_arg++;
1790         break;
1791       }
1792       default:
1793         Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected signature type char '"
1794                                           << descriptor << "'";
1795         return false;
1796     }
1797     cur_arg++;
1798   }
1799   if (cur_arg != expected_args) {
1800     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected " << expected_args
1801                                       << " arguments, found " << cur_arg;
1802     return false;
1803   }
1804   const char* descriptor = dex_file_->GetReturnTypeDescriptor(proto_id);
1805   // Validate return type. We don't do the type lookup; just want to make sure that it has the right
1806   // format. Only major difference from the method argument format is that 'V' is supported.
1807   bool result;
1808   if (IsPrimitiveDescriptor(descriptor[0]) || descriptor[0] == 'V') {
1809     result = descriptor[1] == '\0';
1810   } else if (descriptor[0] == '[') {  // single/multi-dimensional array of object/primitive
1811     size_t i = 0;
1812     do {
1813       i++;
1814     } while (descriptor[i] == '[');  // process leading [
1815     if (descriptor[i] == 'L') {  // object array
1816       do {
1817         i++;  // find closing ;
1818       } while (descriptor[i] != ';' && descriptor[i] != '\0');
1819       result = descriptor[i] == ';';
1820     } else {  // primitive array
1821       result = IsPrimitiveDescriptor(descriptor[i]) && descriptor[i + 1] == '\0';
1822     }
1823   } else if (descriptor[0] == 'L') {
1824     // could be more thorough here, but shouldn't be required
1825     size_t i = 0;
1826     do {
1827       i++;
1828     } while (descriptor[i] != ';' && descriptor[i] != '\0');
1829     result = descriptor[i] == ';';
1830   } else {
1831     result = false;
1832   }
1833   if (!result) {
1834     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected char in return type descriptor '"
1835                                       << descriptor << "'";
1836   }
1837   return result;
1838 }
1839 
1840 COLD_ATTR
HandleMonitorDexPcsWorkLine(std::vector<::art::verifier::MethodVerifier::DexLockInfo> * monitor_enter_dex_pcs,RegisterLine * work_line)1841 void HandleMonitorDexPcsWorkLine(
1842     std::vector<::art::verifier::MethodVerifier::DexLockInfo>* monitor_enter_dex_pcs,
1843     RegisterLine* work_line) {
1844   monitor_enter_dex_pcs->clear();  // The new work line is more accurate than the previous one.
1845 
1846   std::map<uint32_t, ::art::verifier::MethodVerifier::DexLockInfo> depth_to_lock_info;
1847   auto collector = [&](uint32_t dex_reg, uint32_t depth) {
1848     auto insert_pair = depth_to_lock_info.emplace(
1849         depth, ::art::verifier::MethodVerifier::DexLockInfo(depth));
1850     auto it = insert_pair.first;
1851     auto set_insert_pair = it->second.dex_registers.insert(dex_reg);
1852     DCHECK(set_insert_pair.second);
1853   };
1854   work_line->IterateRegToLockDepths(collector);
1855   for (auto& pair : depth_to_lock_info) {
1856     monitor_enter_dex_pcs->push_back(pair.second);
1857     // Map depth to dex PC.
1858     monitor_enter_dex_pcs->back().dex_pc = work_line->GetMonitorEnterDexPc(pair.second.dex_pc);
1859   }
1860 }
1861 
1862 template <bool kVerifierDebug>
1863 template <bool kMonitorDexPCs>
CodeFlowVerifyMethod()1864 bool MethodVerifier<kVerifierDebug>::CodeFlowVerifyMethod() {
1865   const uint16_t* insns = code_item_accessor_.Insns();
1866   const uint32_t insns_size = code_item_accessor_.InsnsSizeInCodeUnits();
1867 
1868   /* Begin by marking the first instruction as "changed". */
1869   GetModifiableInstructionFlags(0).SetChanged();
1870   uint32_t start_guess = 0;
1871 
1872   /* Continue until no instructions are marked "changed". */
1873   while (true) {
1874     if (allow_thread_suspension_) {
1875       self_->AllowThreadSuspension();
1876     }
1877     // Find the first marked one. Use "start_guess" as a way to find one quickly.
1878     uint32_t insn_idx = start_guess;
1879     for (; insn_idx < insns_size; insn_idx++) {
1880       if (GetInstructionFlags(insn_idx).IsChanged())
1881         break;
1882     }
1883     if (insn_idx == insns_size) {
1884       if (start_guess != 0) {
1885         /* try again, starting from the top */
1886         start_guess = 0;
1887         continue;
1888       } else {
1889         /* all flags are clear */
1890         break;
1891       }
1892     }
1893     // We carry the working set of registers from instruction to instruction. If this address can
1894     // be the target of a branch (or throw) instruction, or if we're skipping around chasing
1895     // "changed" flags, we need to load the set of registers from the table.
1896     // Because we always prefer to continue on to the next instruction, we should never have a
1897     // situation where we have a stray "changed" flag set on an instruction that isn't a branch
1898     // target.
1899     work_insn_idx_ = insn_idx;
1900     if (GetInstructionFlags(insn_idx).IsBranchTarget()) {
1901       work_line_->CopyFromLine(reg_table_.GetLine(insn_idx));
1902     } else if (kIsDebugBuild) {
1903       /*
1904        * Consistency check: retrieve the stored register line (assuming
1905        * a full table) and make sure it actually matches.
1906        */
1907       RegisterLine* register_line = reg_table_.GetLine(insn_idx);
1908       if (register_line != nullptr) {
1909         if (work_line_->CompareLine(register_line) != 0) {
1910           Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
1911           LOG(FATAL_WITHOUT_ABORT) << info_messages_.str();
1912           LOG(FATAL) << "work_line diverged in " << dex_file_->PrettyMethod(dex_method_idx_)
1913                      << "@" << reinterpret_cast<void*>(work_insn_idx_) << "\n"
1914                      << " work_line=" << work_line_->Dump(this) << "\n"
1915                      << "  expected=" << register_line->Dump(this);
1916         }
1917       }
1918     }
1919 
1920     // If we're doing FindLocksAtDexPc, check whether we're at the dex pc we care about.
1921     // We want the state _before_ the instruction, for the case where the dex pc we're
1922     // interested in is itself a monitor-enter instruction (which is a likely place
1923     // for a thread to be suspended).
1924     if (kMonitorDexPCs && UNLIKELY(work_insn_idx_ == interesting_dex_pc_)) {
1925       HandleMonitorDexPcsWorkLine(monitor_enter_dex_pcs_, work_line_.get());
1926     }
1927 
1928     if (!CodeFlowVerifyInstruction(&start_guess)) {
1929       std::string prepend(dex_file_->PrettyMethod(dex_method_idx_));
1930       prepend += " failed to verify: ";
1931       PrependToLastFailMessage(prepend);
1932       return false;
1933     }
1934     /* Clear "changed" and mark as visited. */
1935     GetModifiableInstructionFlags(insn_idx).SetVisited();
1936     GetModifiableInstructionFlags(insn_idx).ClearChanged();
1937   }
1938 
1939   if (kVerifierDebug) {
1940     /*
1941      * Scan for dead code. There's nothing "evil" about dead code
1942      * (besides the wasted space), but it indicates a flaw somewhere
1943      * down the line, possibly in the verifier.
1944      *
1945      * If we've substituted "always throw" instructions into the stream,
1946      * we are almost certainly going to have some dead code.
1947      */
1948     int dead_start = -1;
1949 
1950     for (const DexInstructionPcPair& inst : code_item_accessor_) {
1951       const uint32_t insn_idx = inst.DexPc();
1952       /*
1953        * Switch-statement data doesn't get "visited" by scanner. It
1954        * may or may not be preceded by a padding NOP (for alignment).
1955        */
1956       if (insns[insn_idx] == Instruction::kPackedSwitchSignature ||
1957           insns[insn_idx] == Instruction::kSparseSwitchSignature ||
1958           insns[insn_idx] == Instruction::kArrayDataSignature ||
1959           (insns[insn_idx] == Instruction::NOP && (insn_idx + 1 < insns_size) &&
1960            (insns[insn_idx + 1] == Instruction::kPackedSwitchSignature ||
1961             insns[insn_idx + 1] == Instruction::kSparseSwitchSignature ||
1962             insns[insn_idx + 1] == Instruction::kArrayDataSignature))) {
1963         GetModifiableInstructionFlags(insn_idx).SetVisited();
1964       }
1965 
1966       if (!GetInstructionFlags(insn_idx).IsVisited()) {
1967         if (dead_start < 0) {
1968           dead_start = insn_idx;
1969         }
1970       } else if (dead_start >= 0) {
1971         LogVerifyInfo() << "dead code " << reinterpret_cast<void*>(dead_start)
1972                         << "-" << reinterpret_cast<void*>(insn_idx - 1);
1973         dead_start = -1;
1974       }
1975     }
1976     if (dead_start >= 0) {
1977       LogVerifyInfo()
1978           << "dead code " << reinterpret_cast<void*>(dead_start)
1979           << "-" << reinterpret_cast<void*>(code_item_accessor_.InsnsSizeInCodeUnits() - 1);
1980     }
1981     // To dump the state of the verify after a method, do something like:
1982     // if (dex_file_->PrettyMethod(dex_method_idx_) ==
1983     //     "boolean java.lang.String.equals(java.lang.Object)") {
1984     //   LOG(INFO) << info_messages_.str();
1985     // }
1986   }
1987   return true;
1988 }
1989 
1990 // Returns the index of the first final instance field of the given class, or kDexNoIndex if there
1991 // is no such field.
GetFirstFinalInstanceFieldIndex(const DexFile & dex_file,dex::TypeIndex type_idx)1992 static uint32_t GetFirstFinalInstanceFieldIndex(const DexFile& dex_file, dex::TypeIndex type_idx) {
1993   const dex::ClassDef* class_def = dex_file.FindClassDef(type_idx);
1994   DCHECK(class_def != nullptr);
1995   ClassAccessor accessor(dex_file, *class_def);
1996   for (const ClassAccessor::Field& field : accessor.GetInstanceFields()) {
1997     if (field.IsFinal()) {
1998       return field.GetIndex();
1999     }
2000   }
2001   return dex::kDexNoIndex;
2002 }
2003 
2004 // Setup a register line for the given return instruction.
2005 template <bool kVerifierDebug>
AdjustReturnLine(MethodVerifier<kVerifierDebug> * verifier,const Instruction * ret_inst,RegisterLine * line)2006 static void AdjustReturnLine(MethodVerifier<kVerifierDebug>* verifier,
2007                              const Instruction* ret_inst,
2008                              RegisterLine* line) {
2009   Instruction::Code opcode = ret_inst->Opcode();
2010 
2011   switch (opcode) {
2012     case Instruction::RETURN_VOID:
2013     case Instruction::RETURN_VOID_NO_BARRIER:
2014       if (verifier->IsInstanceConstructor()) {
2015         // Before we mark all regs as conflicts, check that we don't have an uninitialized this.
2016         line->CheckConstructorReturn(verifier);
2017       }
2018       line->MarkAllRegistersAsConflicts(verifier);
2019       break;
2020 
2021     case Instruction::RETURN:
2022     case Instruction::RETURN_OBJECT:
2023       line->MarkAllRegistersAsConflictsExcept(verifier, ret_inst->VRegA_11x());
2024       break;
2025 
2026     case Instruction::RETURN_WIDE:
2027       line->MarkAllRegistersAsConflictsExceptWide(verifier, ret_inst->VRegA_11x());
2028       break;
2029 
2030     default:
2031       LOG(FATAL) << "Unknown return opcode " << opcode;
2032       UNREACHABLE();
2033   }
2034 }
2035 
2036 template <bool kVerifierDebug>
CodeFlowVerifyInstruction(uint32_t * start_guess)2037 bool MethodVerifier<kVerifierDebug>::CodeFlowVerifyInstruction(uint32_t* start_guess) {
2038   /*
2039    * Once we finish decoding the instruction, we need to figure out where
2040    * we can go from here. There are three possible ways to transfer
2041    * control to another statement:
2042    *
2043    * (1) Continue to the next instruction. Applies to all but
2044    *     unconditional branches, method returns, and exception throws.
2045    * (2) Branch to one or more possible locations. Applies to branches
2046    *     and switch statements.
2047    * (3) Exception handlers. Applies to any instruction that can
2048    *     throw an exception that is handled by an encompassing "try"
2049    *     block.
2050    *
2051    * We can also return, in which case there is no successor instruction
2052    * from this point.
2053    *
2054    * The behavior can be determined from the opcode flags.
2055    */
2056   const uint16_t* insns = code_item_accessor_.Insns() + work_insn_idx_;
2057   const Instruction* inst = Instruction::At(insns);
2058   int opcode_flags = Instruction::FlagsOf(inst->Opcode());
2059 
2060   int32_t branch_target = 0;
2061   bool just_set_result = false;
2062   if (kVerifierDebug) {
2063     // Generate processing back trace to debug verifier
2064     LogVerifyInfo() << "Processing " << inst->DumpString(dex_file_) << std::endl
2065                     << work_line_->Dump(this);
2066   }
2067 
2068   /*
2069    * Make a copy of the previous register state. If the instruction
2070    * can throw an exception, we will copy/merge this into the "catch"
2071    * address rather than work_line, because we don't want the result
2072    * from the "successful" code path (e.g. a check-cast that "improves"
2073    * a type) to be visible to the exception handler.
2074    */
2075   if (((opcode_flags & Instruction::kThrow) != 0 || IsCompatThrow(inst->Opcode())) &&
2076       CurrentInsnFlags()->IsInTry()) {
2077     saved_line_->CopyFromLine(work_line_.get());
2078   } else if (kIsDebugBuild) {
2079     saved_line_->FillWithGarbage();
2080   }
2081   // Per-instruction flag, should not be set here.
2082   DCHECK(!flags_.have_pending_runtime_throw_failure_);
2083   bool exc_handler_unreachable = false;
2084 
2085 
2086   // We need to ensure the work line is consistent while performing validation. When we spot a
2087   // peephole pattern we compute a new line for either the fallthrough instruction or the
2088   // branch target.
2089   RegisterLineArenaUniquePtr branch_line;
2090   RegisterLineArenaUniquePtr fallthrough_line;
2091 
2092   switch (inst->Opcode()) {
2093     case Instruction::NOP:
2094       /*
2095        * A "pure" NOP has no effect on anything. Data tables start with
2096        * a signature that looks like a NOP; if we see one of these in
2097        * the course of executing code then we have a problem.
2098        */
2099       if (inst->VRegA_10x() != 0) {
2100         Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "encountered data table in instruction stream";
2101       }
2102       break;
2103 
2104     case Instruction::MOVE:
2105       work_line_->CopyRegister1(this, inst->VRegA_12x(), inst->VRegB_12x(), kTypeCategory1nr);
2106       break;
2107     case Instruction::MOVE_FROM16:
2108       work_line_->CopyRegister1(this, inst->VRegA_22x(), inst->VRegB_22x(), kTypeCategory1nr);
2109       break;
2110     case Instruction::MOVE_16:
2111       work_line_->CopyRegister1(this, inst->VRegA_32x(), inst->VRegB_32x(), kTypeCategory1nr);
2112       break;
2113     case Instruction::MOVE_WIDE:
2114       work_line_->CopyRegister2(this, inst->VRegA_12x(), inst->VRegB_12x());
2115       break;
2116     case Instruction::MOVE_WIDE_FROM16:
2117       work_line_->CopyRegister2(this, inst->VRegA_22x(), inst->VRegB_22x());
2118       break;
2119     case Instruction::MOVE_WIDE_16:
2120       work_line_->CopyRegister2(this, inst->VRegA_32x(), inst->VRegB_32x());
2121       break;
2122     case Instruction::MOVE_OBJECT:
2123       work_line_->CopyRegister1(this, inst->VRegA_12x(), inst->VRegB_12x(), kTypeCategoryRef);
2124       break;
2125     case Instruction::MOVE_OBJECT_FROM16:
2126       work_line_->CopyRegister1(this, inst->VRegA_22x(), inst->VRegB_22x(), kTypeCategoryRef);
2127       break;
2128     case Instruction::MOVE_OBJECT_16:
2129       work_line_->CopyRegister1(this, inst->VRegA_32x(), inst->VRegB_32x(), kTypeCategoryRef);
2130       break;
2131 
2132     /*
2133      * The move-result instructions copy data out of a "pseudo-register"
2134      * with the results from the last method invocation. In practice we
2135      * might want to hold the result in an actual CPU register, so the
2136      * Dalvik spec requires that these only appear immediately after an
2137      * invoke or filled-new-array.
2138      *
2139      * These calls invalidate the "result" register. (This is now
2140      * redundant with the reset done below, but it can make the debug info
2141      * easier to read in some cases.)
2142      */
2143     case Instruction::MOVE_RESULT:
2144       work_line_->CopyResultRegister1(this, inst->VRegA_11x(), false);
2145       break;
2146     case Instruction::MOVE_RESULT_WIDE:
2147       work_line_->CopyResultRegister2(this, inst->VRegA_11x());
2148       break;
2149     case Instruction::MOVE_RESULT_OBJECT:
2150       work_line_->CopyResultRegister1(this, inst->VRegA_11x(), true);
2151       break;
2152 
2153     case Instruction::MOVE_EXCEPTION:
2154       if (!HandleMoveException(inst)) {
2155         exc_handler_unreachable = true;
2156       }
2157       break;
2158 
2159     case Instruction::RETURN_VOID:
2160       if (!IsInstanceConstructor() || work_line_->CheckConstructorReturn(this)) {
2161         if (!GetMethodReturnType().IsConflict()) {
2162           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-void not expected";
2163         }
2164       }
2165       break;
2166     case Instruction::RETURN:
2167       if (!IsInstanceConstructor() || work_line_->CheckConstructorReturn(this)) {
2168         /* check the method signature */
2169         const RegType& return_type = GetMethodReturnType();
2170         if (!return_type.IsCategory1Types()) {
2171           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected non-category 1 return type "
2172                                             << return_type;
2173         } else {
2174           // Compilers may generate synthetic functions that write byte values into boolean fields.
2175           // Also, it may use integer values for boolean, byte, short, and character return types.
2176           const uint32_t vregA = inst->VRegA_11x();
2177           const RegType& src_type = work_line_->GetRegisterType(this, vregA);
2178           bool use_src = ((return_type.IsBoolean() && src_type.IsByte()) ||
2179                           ((return_type.IsBoolean() || return_type.IsByte() ||
2180                            return_type.IsShort() || return_type.IsChar()) &&
2181                            src_type.IsInteger()));
2182           /* check the register contents */
2183           bool success =
2184               work_line_->VerifyRegisterType(this, vregA, use_src ? src_type : return_type);
2185           if (!success) {
2186             AppendToLastFailMessage(StringPrintf(" return-1nr on invalid register v%d", vregA));
2187           }
2188         }
2189       }
2190       break;
2191     case Instruction::RETURN_WIDE:
2192       if (!IsInstanceConstructor() || work_line_->CheckConstructorReturn(this)) {
2193         /* check the method signature */
2194         const RegType& return_type = GetMethodReturnType();
2195         if (!return_type.IsCategory2Types()) {
2196           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-wide not expected";
2197         } else {
2198           /* check the register contents */
2199           const uint32_t vregA = inst->VRegA_11x();
2200           bool success = work_line_->VerifyRegisterType(this, vregA, return_type);
2201           if (!success) {
2202             AppendToLastFailMessage(StringPrintf(" return-wide on invalid register v%d", vregA));
2203           }
2204         }
2205       }
2206       break;
2207     case Instruction::RETURN_OBJECT:
2208       if (!IsInstanceConstructor() || work_line_->CheckConstructorReturn(this)) {
2209         const RegType& return_type = GetMethodReturnType();
2210         if (!return_type.IsReferenceTypes()) {
2211           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-object not expected";
2212         } else {
2213           /* return_type is the *expected* return type, not register value */
2214           DCHECK(!return_type.IsZeroOrNull());
2215           DCHECK(!return_type.IsUninitializedReference());
2216           const uint32_t vregA = inst->VRegA_11x();
2217           const RegType& reg_type = work_line_->GetRegisterType(this, vregA);
2218           // Disallow returning undefined, conflict & uninitialized values and verify that the
2219           // reference in vAA is an instance of the "return_type."
2220           if (reg_type.IsUndefined()) {
2221             Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "returning undefined register";
2222           } else if (reg_type.IsConflict()) {
2223             Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "returning register with conflict";
2224           } else if (reg_type.IsUninitializedTypes()) {
2225             Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "returning uninitialized object '"
2226                                               << reg_type << "'";
2227           } else if (!reg_type.IsReferenceTypes()) {
2228             // We really do expect a reference here.
2229             Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-object returns a non-reference type "
2230                                               << reg_type;
2231           } else if (!return_type.IsAssignableFrom(reg_type, this)) {
2232             if (reg_type.IsUnresolvedTypes() || return_type.IsUnresolvedTypes()) {
2233               Fail(api_level_ > 29u ? VERIFY_ERROR_BAD_CLASS_SOFT : VERIFY_ERROR_NO_CLASS)
2234                   << " can't resolve returned type '" << return_type << "' or '" << reg_type << "'";
2235             } else {
2236               bool soft_error = false;
2237               // Check whether arrays are involved. They will show a valid class status, even
2238               // if their components are erroneous.
2239               if (reg_type.IsArrayTypes() && return_type.IsArrayTypes()) {
2240                 return_type.CanAssignArray(reg_type, reg_types_, class_loader_, this, &soft_error);
2241                 if (soft_error) {
2242                   Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "array with erroneous component type: "
2243                         << reg_type << " vs " << return_type;
2244                 }
2245               }
2246 
2247               if (!soft_error) {
2248                 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "returning '" << reg_type
2249                     << "', but expected from declaration '" << return_type << "'";
2250               }
2251             }
2252           }
2253         }
2254       }
2255       break;
2256 
2257       /* could be boolean, int, float, or a null reference */
2258     case Instruction::CONST_4: {
2259       int32_t val = static_cast<int32_t>(inst->VRegB_11n() << 28) >> 28;
2260       work_line_->SetRegisterType<LockOp::kClear>(
2261           this, inst->VRegA_11n(), DetermineCat1Constant(val, need_precise_constants_));
2262       break;
2263     }
2264     case Instruction::CONST_16: {
2265       int16_t val = static_cast<int16_t>(inst->VRegB_21s());
2266       work_line_->SetRegisterType<LockOp::kClear>(
2267           this, inst->VRegA_21s(), DetermineCat1Constant(val, need_precise_constants_));
2268       break;
2269     }
2270     case Instruction::CONST: {
2271       int32_t val = inst->VRegB_31i();
2272       work_line_->SetRegisterType<LockOp::kClear>(
2273           this, inst->VRegA_31i(), DetermineCat1Constant(val, need_precise_constants_));
2274       break;
2275     }
2276     case Instruction::CONST_HIGH16: {
2277       int32_t val = static_cast<int32_t>(inst->VRegB_21h() << 16);
2278       work_line_->SetRegisterType<LockOp::kClear>(
2279           this, inst->VRegA_21h(), DetermineCat1Constant(val, need_precise_constants_));
2280       break;
2281     }
2282       /* could be long or double; resolved upon use */
2283     case Instruction::CONST_WIDE_16: {
2284       int64_t val = static_cast<int16_t>(inst->VRegB_21s());
2285       const RegType& lo = reg_types_.FromCat2ConstLo(static_cast<int32_t>(val), true);
2286       const RegType& hi = reg_types_.FromCat2ConstHi(static_cast<int32_t>(val >> 32), true);
2287       work_line_->SetRegisterTypeWide(this, inst->VRegA_21s(), lo, hi);
2288       break;
2289     }
2290     case Instruction::CONST_WIDE_32: {
2291       int64_t val = static_cast<int32_t>(inst->VRegB_31i());
2292       const RegType& lo = reg_types_.FromCat2ConstLo(static_cast<int32_t>(val), true);
2293       const RegType& hi = reg_types_.FromCat2ConstHi(static_cast<int32_t>(val >> 32), true);
2294       work_line_->SetRegisterTypeWide(this, inst->VRegA_31i(), lo, hi);
2295       break;
2296     }
2297     case Instruction::CONST_WIDE: {
2298       int64_t val = inst->VRegB_51l();
2299       const RegType& lo = reg_types_.FromCat2ConstLo(static_cast<int32_t>(val), true);
2300       const RegType& hi = reg_types_.FromCat2ConstHi(static_cast<int32_t>(val >> 32), true);
2301       work_line_->SetRegisterTypeWide(this, inst->VRegA_51l(), lo, hi);
2302       break;
2303     }
2304     case Instruction::CONST_WIDE_HIGH16: {
2305       int64_t val = static_cast<uint64_t>(inst->VRegB_21h()) << 48;
2306       const RegType& lo = reg_types_.FromCat2ConstLo(static_cast<int32_t>(val), true);
2307       const RegType& hi = reg_types_.FromCat2ConstHi(static_cast<int32_t>(val >> 32), true);
2308       work_line_->SetRegisterTypeWide(this, inst->VRegA_21h(), lo, hi);
2309       break;
2310     }
2311     case Instruction::CONST_STRING:
2312       work_line_->SetRegisterType<LockOp::kClear>(
2313           this, inst->VRegA_21c(), reg_types_.JavaLangString());
2314       break;
2315     case Instruction::CONST_STRING_JUMBO:
2316       work_line_->SetRegisterType<LockOp::kClear>(
2317           this, inst->VRegA_31c(), reg_types_.JavaLangString());
2318       break;
2319     case Instruction::CONST_CLASS: {
2320       // Get type from instruction if unresolved then we need an access check
2321       // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved
2322       const RegType& res_type = ResolveClass<CheckAccess::kYes>(dex::TypeIndex(inst->VRegB_21c()));
2323       // Register holds class, ie its type is class, on error it will hold Conflict.
2324       work_line_->SetRegisterType<LockOp::kClear>(
2325           this, inst->VRegA_21c(), res_type.IsConflict() ? res_type
2326                                                          : reg_types_.JavaLangClass());
2327       break;
2328     }
2329     case Instruction::CONST_METHOD_HANDLE:
2330       work_line_->SetRegisterType<LockOp::kClear>(
2331           this, inst->VRegA_21c(), reg_types_.JavaLangInvokeMethodHandle());
2332       break;
2333     case Instruction::CONST_METHOD_TYPE:
2334       work_line_->SetRegisterType<LockOp::kClear>(
2335           this, inst->VRegA_21c(), reg_types_.JavaLangInvokeMethodType());
2336       break;
2337     case Instruction::MONITOR_ENTER:
2338       work_line_->PushMonitor(this, inst->VRegA_11x(), work_insn_idx_);
2339       // Check whether the previous instruction is a move-object with vAA as a source, creating
2340       // untracked lock aliasing.
2341       if (0 != work_insn_idx_ && !GetInstructionFlags(work_insn_idx_).IsBranchTarget()) {
2342         uint32_t prev_idx = work_insn_idx_ - 1;
2343         while (0 != prev_idx && !GetInstructionFlags(prev_idx).IsOpcode()) {
2344           prev_idx--;
2345         }
2346         const Instruction& prev_inst = code_item_accessor_.InstructionAt(prev_idx);
2347         switch (prev_inst.Opcode()) {
2348           case Instruction::MOVE_OBJECT:
2349           case Instruction::MOVE_OBJECT_16:
2350           case Instruction::MOVE_OBJECT_FROM16:
2351             if (prev_inst.VRegB() == inst->VRegA_11x()) {
2352               // Redo the copy. This won't change the register types, but update the lock status
2353               // for the aliased register.
2354               work_line_->CopyRegister1(this,
2355                                         prev_inst.VRegA(),
2356                                         prev_inst.VRegB(),
2357                                         kTypeCategoryRef);
2358             }
2359             break;
2360 
2361           // Catch a case of register aliasing when two registers are linked to the same
2362           // java.lang.Class object via two consequent const-class instructions immediately
2363           // preceding monitor-enter called on one of those registers.
2364           case Instruction::CONST_CLASS: {
2365             // Get the second previous instruction.
2366             if (prev_idx == 0 || GetInstructionFlags(prev_idx).IsBranchTarget()) {
2367               break;
2368             }
2369             prev_idx--;
2370             while (0 != prev_idx && !GetInstructionFlags(prev_idx).IsOpcode()) {
2371               prev_idx--;
2372             }
2373             const Instruction& prev2_inst = code_item_accessor_.InstructionAt(prev_idx);
2374 
2375             // Match the pattern "const-class; const-class; monitor-enter;"
2376             if (prev2_inst.Opcode() != Instruction::CONST_CLASS) {
2377               break;
2378             }
2379 
2380             // Ensure both const-classes are called for the same type_idx.
2381             if (prev_inst.VRegB_21c() != prev2_inst.VRegB_21c()) {
2382               break;
2383             }
2384 
2385             // Update the lock status for the aliased register.
2386             if (prev_inst.VRegA() == inst->VRegA_11x()) {
2387               work_line_->CopyRegister1(this,
2388                                         prev2_inst.VRegA(),
2389                                         inst->VRegA_11x(),
2390                                         kTypeCategoryRef);
2391             } else if (prev2_inst.VRegA() == inst->VRegA_11x()) {
2392               work_line_->CopyRegister1(this,
2393                                         prev_inst.VRegA(),
2394                                         inst->VRegA_11x(),
2395                                         kTypeCategoryRef);
2396             }
2397             break;
2398           }
2399 
2400           default:  // Other instruction types ignored.
2401             break;
2402         }
2403       }
2404       break;
2405     case Instruction::MONITOR_EXIT:
2406       /*
2407        * monitor-exit instructions are odd. They can throw exceptions,
2408        * but when they do they act as if they succeeded and the PC is
2409        * pointing to the following instruction. (This behavior goes back
2410        * to the need to handle asynchronous exceptions, a now-deprecated
2411        * feature that Dalvik doesn't support.)
2412        *
2413        * In practice we don't need to worry about this. The only
2414        * exceptions that can be thrown from monitor-exit are for a
2415        * null reference and -exit without a matching -enter. If the
2416        * structured locking checks are working, the former would have
2417        * failed on the -enter instruction, and the latter is impossible.
2418        *
2419        * This is fortunate, because issue 3221411 prevents us from
2420        * chasing the "can throw" path when monitor verification is
2421        * enabled. If we can fully verify the locking we can ignore
2422        * some catch blocks (which will show up as "dead" code when
2423        * we skip them here); if we can't, then the code path could be
2424        * "live" so we still need to check it.
2425        */
2426       opcode_flags &= ~Instruction::kThrow;
2427       work_line_->PopMonitor(this, inst->VRegA_11x());
2428       break;
2429     case Instruction::CHECK_CAST:
2430     case Instruction::INSTANCE_OF: {
2431       /*
2432        * If this instruction succeeds, we will "downcast" register vA to the type in vB. (This
2433        * could be a "upcast" -- not expected, so we don't try to address it.)
2434        *
2435        * If it fails, an exception is thrown, which we deal with later by ignoring the update to
2436        * dec_insn.vA when branching to a handler.
2437        */
2438       const bool is_checkcast = (inst->Opcode() == Instruction::CHECK_CAST);
2439       const dex::TypeIndex type_idx((is_checkcast) ? inst->VRegB_21c() : inst->VRegC_22c());
2440       const RegType& res_type = ResolveClass<CheckAccess::kYes>(type_idx);
2441       if (res_type.IsConflict()) {
2442         // If this is a primitive type, fail HARD.
2443         ObjPtr<mirror::Class> klass = GetClassLinker()->LookupResolvedType(
2444             type_idx, dex_cache_.Get(), class_loader_.Get());
2445         if (klass != nullptr && klass->IsPrimitive()) {
2446           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "using primitive type "
2447               << dex_file_->StringByTypeIdx(type_idx) << " in instanceof in "
2448               << GetDeclaringClass();
2449           break;
2450         }
2451 
2452         DCHECK_NE(failures_.size(), 0U);
2453         if (!is_checkcast) {
2454           work_line_->SetRegisterType<LockOp::kClear>(this,
2455                                                       inst->VRegA_22c(),
2456                                                       reg_types_.Boolean());
2457         }
2458         break;  // bad class
2459       }
2460       // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved
2461       uint32_t orig_type_reg = (is_checkcast) ? inst->VRegA_21c() : inst->VRegB_22c();
2462       const RegType& orig_type = work_line_->GetRegisterType(this, orig_type_reg);
2463       if (!res_type.IsNonZeroReferenceTypes()) {
2464         if (is_checkcast) {
2465           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "check-cast on unexpected class " << res_type;
2466         } else {
2467           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "instance-of on unexpected class " << res_type;
2468         }
2469       } else if (!orig_type.IsReferenceTypes()) {
2470         if (is_checkcast) {
2471           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "check-cast on non-reference in v" << orig_type_reg;
2472         } else {
2473           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "instance-of on non-reference in v" << orig_type_reg;
2474         }
2475       } else if (orig_type.IsUninitializedTypes()) {
2476         if (is_checkcast) {
2477           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "check-cast on uninitialized reference in v"
2478                                             << orig_type_reg;
2479         } else {
2480           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "instance-of on uninitialized reference in v"
2481                                             << orig_type_reg;
2482         }
2483       } else {
2484         if (is_checkcast) {
2485           work_line_->SetRegisterType<LockOp::kKeep>(this, inst->VRegA_21c(), res_type);
2486         } else {
2487           work_line_->SetRegisterType<LockOp::kClear>(this,
2488                                                       inst->VRegA_22c(),
2489                                                       reg_types_.Boolean());
2490         }
2491       }
2492       break;
2493     }
2494     case Instruction::ARRAY_LENGTH: {
2495       const RegType& res_type = work_line_->GetRegisterType(this, inst->VRegB_12x());
2496       if (res_type.IsReferenceTypes()) {
2497         if (!res_type.IsArrayTypes() && !res_type.IsZeroOrNull()) {
2498           // ie not an array or null
2499           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array-length on non-array " << res_type;
2500         } else {
2501           work_line_->SetRegisterType<LockOp::kClear>(this,
2502                                                       inst->VRegA_12x(),
2503                                                       reg_types_.Integer());
2504         }
2505       } else {
2506         Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array-length on non-array " << res_type;
2507       }
2508       break;
2509     }
2510     case Instruction::NEW_INSTANCE: {
2511       const RegType& res_type = ResolveClass<CheckAccess::kYes>(dex::TypeIndex(inst->VRegB_21c()));
2512       if (res_type.IsConflict()) {
2513         DCHECK_NE(failures_.size(), 0U);
2514         break;  // bad class
2515       }
2516       // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved
2517       // can't create an instance of an interface or abstract class */
2518       if (!res_type.IsInstantiableTypes()) {
2519         Fail(VERIFY_ERROR_INSTANTIATION)
2520             << "new-instance on primitive, interface or abstract class" << res_type;
2521         // Soft failure so carry on to set register type.
2522       }
2523       const RegType& uninit_type = reg_types_.Uninitialized(res_type, work_insn_idx_);
2524       // Any registers holding previous allocations from this address that have not yet been
2525       // initialized must be marked invalid.
2526       work_line_->MarkUninitRefsAsInvalid(this, uninit_type);
2527       // add the new uninitialized reference to the register state
2528       work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_21c(), uninit_type);
2529       break;
2530     }
2531     case Instruction::NEW_ARRAY:
2532       VerifyNewArray(inst, false, false);
2533       break;
2534     case Instruction::FILLED_NEW_ARRAY:
2535       VerifyNewArray(inst, true, false);
2536       just_set_result = true;  // Filled new array sets result register
2537       break;
2538     case Instruction::FILLED_NEW_ARRAY_RANGE:
2539       VerifyNewArray(inst, true, true);
2540       just_set_result = true;  // Filled new array range sets result register
2541       break;
2542     case Instruction::CMPL_FLOAT:
2543     case Instruction::CMPG_FLOAT:
2544       if (!work_line_->VerifyRegisterType(this, inst->VRegB_23x(), reg_types_.Float())) {
2545         break;
2546       }
2547       if (!work_line_->VerifyRegisterType(this, inst->VRegC_23x(), reg_types_.Float())) {
2548         break;
2549       }
2550       work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_23x(), reg_types_.Integer());
2551       break;
2552     case Instruction::CMPL_DOUBLE:
2553     case Instruction::CMPG_DOUBLE:
2554       if (!work_line_->VerifyRegisterTypeWide(this, inst->VRegB_23x(), reg_types_.DoubleLo(),
2555                                               reg_types_.DoubleHi())) {
2556         break;
2557       }
2558       if (!work_line_->VerifyRegisterTypeWide(this, inst->VRegC_23x(), reg_types_.DoubleLo(),
2559                                               reg_types_.DoubleHi())) {
2560         break;
2561       }
2562       work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_23x(), reg_types_.Integer());
2563       break;
2564     case Instruction::CMP_LONG:
2565       if (!work_line_->VerifyRegisterTypeWide(this, inst->VRegB_23x(), reg_types_.LongLo(),
2566                                               reg_types_.LongHi())) {
2567         break;
2568       }
2569       if (!work_line_->VerifyRegisterTypeWide(this, inst->VRegC_23x(), reg_types_.LongLo(),
2570                                               reg_types_.LongHi())) {
2571         break;
2572       }
2573       work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_23x(), reg_types_.Integer());
2574       break;
2575     case Instruction::THROW: {
2576       const RegType& res_type = work_line_->GetRegisterType(this, inst->VRegA_11x());
2577       if (!reg_types_.JavaLangThrowable(false).IsAssignableFrom(res_type, this)) {
2578         if (res_type.IsUninitializedTypes()) {
2579           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "thrown exception not initialized";
2580         } else if (!res_type.IsReferenceTypes()) {
2581           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "thrown value of non-reference type " << res_type;
2582         } else {
2583           Fail(res_type.IsUnresolvedTypes() ? VERIFY_ERROR_NO_CLASS : VERIFY_ERROR_BAD_CLASS_SOFT)
2584                 << "thrown class " << res_type << " not instanceof Throwable";
2585         }
2586       }
2587       break;
2588     }
2589     case Instruction::GOTO:
2590     case Instruction::GOTO_16:
2591     case Instruction::GOTO_32:
2592       /* no effect on or use of registers */
2593       break;
2594 
2595     case Instruction::PACKED_SWITCH:
2596     case Instruction::SPARSE_SWITCH:
2597       /* verify that vAA is an integer, or can be converted to one */
2598       work_line_->VerifyRegisterType(this, inst->VRegA_31t(), reg_types_.Integer());
2599       break;
2600 
2601     case Instruction::FILL_ARRAY_DATA: {
2602       /* Similar to the verification done for APUT */
2603       const RegType& array_type = work_line_->GetRegisterType(this, inst->VRegA_31t());
2604       /* array_type can be null if the reg type is Zero */
2605       if (!array_type.IsZeroOrNull()) {
2606         if (!array_type.IsArrayTypes()) {
2607           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid fill-array-data with array type "
2608                                             << array_type;
2609         } else if (array_type.IsUnresolvedTypes()) {
2610           // If it's an unresolved array type, it must be non-primitive.
2611           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid fill-array-data for array of type "
2612                                             << array_type;
2613         } else {
2614           const RegType& component_type = reg_types_.GetComponentType(array_type,
2615                                                                       class_loader_.Get());
2616           DCHECK(!component_type.IsConflict());
2617           if (component_type.IsNonZeroReferenceTypes()) {
2618             Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid fill-array-data with component type "
2619                                               << component_type;
2620           } else {
2621             // Now verify if the element width in the table matches the element width declared in
2622             // the array
2623             const uint16_t* array_data =
2624                 insns + (insns[1] | (static_cast<int32_t>(insns[2]) << 16));
2625             if (array_data[0] != Instruction::kArrayDataSignature) {
2626               Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid magic for array-data";
2627             } else {
2628               size_t elem_width = Primitive::ComponentSize(component_type.GetPrimitiveType());
2629               // Since we don't compress the data in Dex, expect to see equal width of data stored
2630               // in the table and expected from the array class.
2631               if (array_data[1] != elem_width) {
2632                 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array-data size mismatch (" << array_data[1]
2633                                                   << " vs " << elem_width << ")";
2634               }
2635             }
2636           }
2637         }
2638       }
2639       break;
2640     }
2641     case Instruction::IF_EQ:
2642     case Instruction::IF_NE: {
2643       const RegType& reg_type1 = work_line_->GetRegisterType(this, inst->VRegA_22t());
2644       const RegType& reg_type2 = work_line_->GetRegisterType(this, inst->VRegB_22t());
2645       bool mismatch = false;
2646       if (reg_type1.IsZeroOrNull()) {  // zero then integral or reference expected
2647         mismatch = !reg_type2.IsReferenceTypes() && !reg_type2.IsIntegralTypes();
2648       } else if (reg_type1.IsReferenceTypes()) {  // both references?
2649         mismatch = !reg_type2.IsReferenceTypes();
2650       } else {  // both integral?
2651         mismatch = !reg_type1.IsIntegralTypes() || !reg_type2.IsIntegralTypes();
2652       }
2653       if (mismatch) {
2654         Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "args to if-eq/if-ne (" << reg_type1 << ","
2655                                           << reg_type2 << ") must both be references or integral";
2656       }
2657       break;
2658     }
2659     case Instruction::IF_LT:
2660     case Instruction::IF_GE:
2661     case Instruction::IF_GT:
2662     case Instruction::IF_LE: {
2663       const RegType& reg_type1 = work_line_->GetRegisterType(this, inst->VRegA_22t());
2664       const RegType& reg_type2 = work_line_->GetRegisterType(this, inst->VRegB_22t());
2665       if (!reg_type1.IsIntegralTypes() || !reg_type2.IsIntegralTypes()) {
2666         Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "args to 'if' (" << reg_type1 << ","
2667                                           << reg_type2 << ") must be integral";
2668       }
2669       break;
2670     }
2671     case Instruction::IF_EQZ:
2672     case Instruction::IF_NEZ: {
2673       const RegType& reg_type = work_line_->GetRegisterType(this, inst->VRegA_21t());
2674       if (!reg_type.IsReferenceTypes() && !reg_type.IsIntegralTypes()) {
2675         Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "type " << reg_type
2676                                           << " unexpected as arg to if-eqz/if-nez";
2677       }
2678 
2679       // Find previous instruction - its existence is a precondition to peephole optimization.
2680       if (UNLIKELY(0 == work_insn_idx_)) {
2681         break;
2682       }
2683       uint32_t instance_of_idx = work_insn_idx_ - 1;
2684       while (0 != instance_of_idx && !GetInstructionFlags(instance_of_idx).IsOpcode()) {
2685         instance_of_idx--;
2686       }
2687       // Dex index 0 must be an opcode.
2688       DCHECK(GetInstructionFlags(instance_of_idx).IsOpcode());
2689 
2690       const Instruction& instance_of_inst = code_item_accessor_.InstructionAt(instance_of_idx);
2691 
2692       /* Check for peep-hole pattern of:
2693        *    ...;
2694        *    instance-of vX, vY, T;
2695        *    ifXXX vX, label ;
2696        *    ...;
2697        * label:
2698        *    ...;
2699        * and sharpen the type of vY to be type T.
2700        * Note, this pattern can't be if:
2701        *  - if there are other branches to this branch,
2702        *  - when vX == vY.
2703        */
2704       if (!CurrentInsnFlags()->IsBranchTarget() &&
2705           (Instruction::INSTANCE_OF == instance_of_inst.Opcode()) &&
2706           (inst->VRegA_21t() == instance_of_inst.VRegA_22c()) &&
2707           (instance_of_inst.VRegA_22c() != instance_of_inst.VRegB_22c())) {
2708         // Check the type of the instance-of is different than that of registers type, as if they
2709         // are the same there is no work to be done here. Check that the conversion is not to or
2710         // from an unresolved type as type information is imprecise. If the instance-of is to an
2711         // interface then ignore the type information as interfaces can only be treated as Objects
2712         // and we don't want to disallow field and other operations on the object. If the value
2713         // being instance-of checked against is known null (zero) then allow the optimization as
2714         // we didn't have type information. If the merge of the instance-of type with the original
2715         // type is assignable to the original then allow optimization. This check is performed to
2716         // ensure that subsequent merges don't lose type information - such as becoming an
2717         // interface from a class that would lose information relevant to field checks.
2718         //
2719         // Note: do not do an access check. This may mark this with a runtime throw that actually
2720         //       happens at the instanceof, not the branch (and branches aren't flagged to throw).
2721         const RegType& orig_type = work_line_->GetRegisterType(this, instance_of_inst.VRegB_22c());
2722         const RegType& cast_type = ResolveClass<CheckAccess::kNo>(
2723             dex::TypeIndex(instance_of_inst.VRegC_22c()));
2724 
2725         if (!orig_type.Equals(cast_type) &&
2726             !cast_type.IsUnresolvedTypes() && !orig_type.IsUnresolvedTypes() &&
2727             cast_type.HasClass() &&             // Could be conflict type, make sure it has a class.
2728             !cast_type.GetClass()->IsInterface() &&
2729             (orig_type.IsZeroOrNull() ||
2730                 orig_type.IsStrictlyAssignableFrom(
2731                     cast_type.Merge(orig_type, &reg_types_, this), this))) {
2732           RegisterLine* update_line = RegisterLine::Create(code_item_accessor_.RegistersSize(),
2733                                                            allocator_,
2734                                                            GetRegTypeCache());
2735           if (inst->Opcode() == Instruction::IF_EQZ) {
2736             fallthrough_line.reset(update_line);
2737           } else {
2738             branch_line.reset(update_line);
2739           }
2740           update_line->CopyFromLine(work_line_.get());
2741           update_line->SetRegisterType<LockOp::kKeep>(this,
2742                                                       instance_of_inst.VRegB_22c(),
2743                                                       cast_type);
2744           if (!GetInstructionFlags(instance_of_idx).IsBranchTarget() && 0 != instance_of_idx) {
2745             // See if instance-of was preceded by a move-object operation, common due to the small
2746             // register encoding space of instance-of, and propagate type information to the source
2747             // of the move-object.
2748             // Note: this is only valid if the move source was not clobbered.
2749             uint32_t move_idx = instance_of_idx - 1;
2750             while (0 != move_idx && !GetInstructionFlags(move_idx).IsOpcode()) {
2751               move_idx--;
2752             }
2753             DCHECK(GetInstructionFlags(move_idx).IsOpcode());
2754             auto maybe_update_fn = [&instance_of_inst, update_line, this, &cast_type](
2755                 uint16_t move_src,
2756                 uint16_t move_trg)
2757                 REQUIRES_SHARED(Locks::mutator_lock_) {
2758               if (move_trg == instance_of_inst.VRegB_22c() &&
2759                   move_src != instance_of_inst.VRegA_22c()) {
2760                 update_line->SetRegisterType<LockOp::kKeep>(this, move_src, cast_type);
2761               }
2762             };
2763             const Instruction& move_inst = code_item_accessor_.InstructionAt(move_idx);
2764             switch (move_inst.Opcode()) {
2765               case Instruction::MOVE_OBJECT:
2766                 maybe_update_fn(move_inst.VRegB_12x(), move_inst.VRegA_12x());
2767                 break;
2768               case Instruction::MOVE_OBJECT_FROM16:
2769                 maybe_update_fn(move_inst.VRegB_22x(), move_inst.VRegA_22x());
2770                 break;
2771               case Instruction::MOVE_OBJECT_16:
2772                 maybe_update_fn(move_inst.VRegB_32x(), move_inst.VRegA_32x());
2773                 break;
2774               default:
2775                 break;
2776             }
2777           }
2778         }
2779       }
2780 
2781       break;
2782     }
2783     case Instruction::IF_LTZ:
2784     case Instruction::IF_GEZ:
2785     case Instruction::IF_GTZ:
2786     case Instruction::IF_LEZ: {
2787       const RegType& reg_type = work_line_->GetRegisterType(this, inst->VRegA_21t());
2788       if (!reg_type.IsIntegralTypes()) {
2789         Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "type " << reg_type
2790                                           << " unexpected as arg to if-ltz/if-gez/if-gtz/if-lez";
2791       }
2792       break;
2793     }
2794     case Instruction::AGET_BOOLEAN:
2795       VerifyAGet(inst, reg_types_.Boolean(), true);
2796       break;
2797     case Instruction::AGET_BYTE:
2798       VerifyAGet(inst, reg_types_.Byte(), true);
2799       break;
2800     case Instruction::AGET_CHAR:
2801       VerifyAGet(inst, reg_types_.Char(), true);
2802       break;
2803     case Instruction::AGET_SHORT:
2804       VerifyAGet(inst, reg_types_.Short(), true);
2805       break;
2806     case Instruction::AGET:
2807       VerifyAGet(inst, reg_types_.Integer(), true);
2808       break;
2809     case Instruction::AGET_WIDE:
2810       VerifyAGet(inst, reg_types_.LongLo(), true);
2811       break;
2812     case Instruction::AGET_OBJECT:
2813       VerifyAGet(inst, reg_types_.JavaLangObject(false), false);
2814       break;
2815 
2816     case Instruction::APUT_BOOLEAN:
2817       VerifyAPut(inst, reg_types_.Boolean(), true);
2818       break;
2819     case Instruction::APUT_BYTE:
2820       VerifyAPut(inst, reg_types_.Byte(), true);
2821       break;
2822     case Instruction::APUT_CHAR:
2823       VerifyAPut(inst, reg_types_.Char(), true);
2824       break;
2825     case Instruction::APUT_SHORT:
2826       VerifyAPut(inst, reg_types_.Short(), true);
2827       break;
2828     case Instruction::APUT:
2829       VerifyAPut(inst, reg_types_.Integer(), true);
2830       break;
2831     case Instruction::APUT_WIDE:
2832       VerifyAPut(inst, reg_types_.LongLo(), true);
2833       break;
2834     case Instruction::APUT_OBJECT:
2835       VerifyAPut(inst, reg_types_.JavaLangObject(false), false);
2836       break;
2837 
2838     case Instruction::IGET_BOOLEAN:
2839     case Instruction::IGET_BOOLEAN_QUICK:
2840       VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Boolean(), true, false);
2841       break;
2842     case Instruction::IGET_BYTE:
2843     case Instruction::IGET_BYTE_QUICK:
2844       VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Byte(), true, false);
2845       break;
2846     case Instruction::IGET_CHAR:
2847     case Instruction::IGET_CHAR_QUICK:
2848       VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Char(), true, false);
2849       break;
2850     case Instruction::IGET_SHORT:
2851     case Instruction::IGET_SHORT_QUICK:
2852       VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Short(), true, false);
2853       break;
2854     case Instruction::IGET:
2855     case Instruction::IGET_QUICK:
2856       VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Integer(), true, false);
2857       break;
2858     case Instruction::IGET_WIDE:
2859     case Instruction::IGET_WIDE_QUICK:
2860       VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.LongLo(), true, false);
2861       break;
2862     case Instruction::IGET_OBJECT:
2863     case Instruction::IGET_OBJECT_QUICK:
2864       VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.JavaLangObject(false), false,
2865                                                     false);
2866       break;
2867 
2868     case Instruction::IPUT_BOOLEAN:
2869     case Instruction::IPUT_BOOLEAN_QUICK:
2870       VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Boolean(), true, false);
2871       break;
2872     case Instruction::IPUT_BYTE:
2873     case Instruction::IPUT_BYTE_QUICK:
2874       VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Byte(), true, false);
2875       break;
2876     case Instruction::IPUT_CHAR:
2877     case Instruction::IPUT_CHAR_QUICK:
2878       VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Char(), true, false);
2879       break;
2880     case Instruction::IPUT_SHORT:
2881     case Instruction::IPUT_SHORT_QUICK:
2882       VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Short(), true, false);
2883       break;
2884     case Instruction::IPUT:
2885     case Instruction::IPUT_QUICK:
2886       VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Integer(), true, false);
2887       break;
2888     case Instruction::IPUT_WIDE:
2889     case Instruction::IPUT_WIDE_QUICK:
2890       VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.LongLo(), true, false);
2891       break;
2892     case Instruction::IPUT_OBJECT:
2893     case Instruction::IPUT_OBJECT_QUICK:
2894       VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.JavaLangObject(false), false,
2895                                                     false);
2896       break;
2897 
2898     case Instruction::SGET_BOOLEAN:
2899       VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Boolean(), true, true);
2900       break;
2901     case Instruction::SGET_BYTE:
2902       VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Byte(), true, true);
2903       break;
2904     case Instruction::SGET_CHAR:
2905       VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Char(), true, true);
2906       break;
2907     case Instruction::SGET_SHORT:
2908       VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Short(), true, true);
2909       break;
2910     case Instruction::SGET:
2911       VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Integer(), true, true);
2912       break;
2913     case Instruction::SGET_WIDE:
2914       VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.LongLo(), true, true);
2915       break;
2916     case Instruction::SGET_OBJECT:
2917       VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.JavaLangObject(false), false,
2918                                                     true);
2919       break;
2920 
2921     case Instruction::SPUT_BOOLEAN:
2922       VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Boolean(), true, true);
2923       break;
2924     case Instruction::SPUT_BYTE:
2925       VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Byte(), true, true);
2926       break;
2927     case Instruction::SPUT_CHAR:
2928       VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Char(), true, true);
2929       break;
2930     case Instruction::SPUT_SHORT:
2931       VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Short(), true, true);
2932       break;
2933     case Instruction::SPUT:
2934       VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Integer(), true, true);
2935       break;
2936     case Instruction::SPUT_WIDE:
2937       VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.LongLo(), true, true);
2938       break;
2939     case Instruction::SPUT_OBJECT:
2940       VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.JavaLangObject(false), false,
2941                                                     true);
2942       break;
2943 
2944     case Instruction::INVOKE_VIRTUAL:
2945     case Instruction::INVOKE_VIRTUAL_RANGE:
2946     case Instruction::INVOKE_SUPER:
2947     case Instruction::INVOKE_SUPER_RANGE:
2948     case Instruction::INVOKE_VIRTUAL_QUICK:
2949     case Instruction::INVOKE_VIRTUAL_RANGE_QUICK: {
2950       bool is_range = (inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE ||
2951                        inst->Opcode() == Instruction::INVOKE_SUPER_RANGE ||
2952                        inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE_QUICK);
2953       bool is_super = (inst->Opcode() == Instruction::INVOKE_SUPER ||
2954                        inst->Opcode() == Instruction::INVOKE_SUPER_RANGE);
2955       MethodType type = is_super ? METHOD_SUPER : METHOD_VIRTUAL;
2956       ArtMethod* called_method = VerifyInvocationArgs(inst, type, is_range);
2957       const RegType* return_type = nullptr;
2958       if (called_method != nullptr) {
2959         ObjPtr<mirror::Class> return_type_class = can_load_classes_
2960             ? called_method->ResolveReturnType()
2961             : called_method->LookupResolvedReturnType();
2962         if (return_type_class != nullptr) {
2963           return_type = &FromClass(called_method->GetReturnTypeDescriptor(),
2964                                    return_type_class,
2965                                    return_type_class->CannotBeAssignedFromOtherTypes());
2966         } else {
2967           DCHECK(!can_load_classes_ || self_->IsExceptionPending());
2968           self_->ClearException();
2969         }
2970       }
2971       if (return_type == nullptr) {
2972         uint32_t method_idx = GetMethodIdxOfInvoke(inst);
2973         const dex::MethodId& method_id = dex_file_->GetMethodId(method_idx);
2974         dex::TypeIndex return_type_idx =
2975             dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_;
2976         const char* descriptor = dex_file_->StringByTypeIdx(return_type_idx);
2977         return_type = &reg_types_.FromDescriptor(class_loader_.Get(), descriptor, false);
2978       }
2979       if (!return_type->IsLowHalf()) {
2980         work_line_->SetResultRegisterType(this, *return_type);
2981       } else {
2982         work_line_->SetResultRegisterTypeWide(*return_type, return_type->HighHalf(&reg_types_));
2983       }
2984       just_set_result = true;
2985       break;
2986     }
2987     case Instruction::INVOKE_DIRECT:
2988     case Instruction::INVOKE_DIRECT_RANGE: {
2989       bool is_range = (inst->Opcode() == Instruction::INVOKE_DIRECT_RANGE);
2990       ArtMethod* called_method = VerifyInvocationArgs(inst, METHOD_DIRECT, is_range);
2991       const char* return_type_descriptor;
2992       bool is_constructor;
2993       const RegType* return_type = nullptr;
2994       if (called_method == nullptr) {
2995         uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c();
2996         const dex::MethodId& method_id = dex_file_->GetMethodId(method_idx);
2997         is_constructor = strcmp("<init>", dex_file_->StringDataByIdx(method_id.name_idx_)) == 0;
2998         dex::TypeIndex return_type_idx =
2999             dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_;
3000         return_type_descriptor =  dex_file_->StringByTypeIdx(return_type_idx);
3001       } else {
3002         is_constructor = called_method->IsConstructor();
3003         return_type_descriptor = called_method->GetReturnTypeDescriptor();
3004         ObjPtr<mirror::Class> return_type_class = can_load_classes_
3005             ? called_method->ResolveReturnType()
3006             : called_method->LookupResolvedReturnType();
3007         if (return_type_class != nullptr) {
3008           return_type = &FromClass(return_type_descriptor,
3009                                    return_type_class,
3010                                    return_type_class->CannotBeAssignedFromOtherTypes());
3011         } else {
3012           DCHECK(!can_load_classes_ || self_->IsExceptionPending());
3013           self_->ClearException();
3014         }
3015       }
3016       if (is_constructor) {
3017         /*
3018          * Some additional checks when calling a constructor. We know from the invocation arg check
3019          * that the "this" argument is an instance of called_method->klass. Now we further restrict
3020          * that to require that called_method->klass is the same as this->klass or this->super,
3021          * allowing the latter only if the "this" argument is the same as the "this" argument to
3022          * this method (which implies that we're in a constructor ourselves).
3023          */
3024         const RegType& this_type = work_line_->GetInvocationThis(this, inst);
3025         if (this_type.IsConflict())  // failure.
3026           break;
3027 
3028         /* no null refs allowed (?) */
3029         if (this_type.IsZeroOrNull()) {
3030           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unable to initialize null ref";
3031           break;
3032         }
3033 
3034         /* must be in same class or in superclass */
3035         // const RegType& this_super_klass = this_type.GetSuperClass(&reg_types_);
3036         // TODO: re-enable constructor type verification
3037         // if (this_super_klass.IsConflict()) {
3038           // Unknown super class, fail so we re-check at runtime.
3039           // Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "super class unknown for '" << this_type << "'";
3040           // break;
3041         // }
3042 
3043         /* arg must be an uninitialized reference */
3044         if (!this_type.IsUninitializedTypes()) {
3045           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Expected initialization on uninitialized reference "
3046               << this_type;
3047           break;
3048         }
3049 
3050         /*
3051          * Replace the uninitialized reference with an initialized one. We need to do this for all
3052          * registers that have the same object instance in them, not just the "this" register.
3053          */
3054         work_line_->MarkRefsAsInitialized(this, this_type);
3055       }
3056       if (return_type == nullptr) {
3057         return_type = &reg_types_.FromDescriptor(class_loader_.Get(),
3058                                                  return_type_descriptor,
3059                                                  false);
3060       }
3061       if (!return_type->IsLowHalf()) {
3062         work_line_->SetResultRegisterType(this, *return_type);
3063       } else {
3064         work_line_->SetResultRegisterTypeWide(*return_type, return_type->HighHalf(&reg_types_));
3065       }
3066       just_set_result = true;
3067       break;
3068     }
3069     case Instruction::INVOKE_STATIC:
3070     case Instruction::INVOKE_STATIC_RANGE: {
3071         bool is_range = (inst->Opcode() == Instruction::INVOKE_STATIC_RANGE);
3072         ArtMethod* called_method = VerifyInvocationArgs(inst, METHOD_STATIC, is_range);
3073         const char* descriptor;
3074         if (called_method == nullptr) {
3075           uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c();
3076           const dex::MethodId& method_id = dex_file_->GetMethodId(method_idx);
3077           dex::TypeIndex return_type_idx =
3078               dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_;
3079           descriptor = dex_file_->StringByTypeIdx(return_type_idx);
3080         } else {
3081           descriptor = called_method->GetReturnTypeDescriptor();
3082         }
3083         const RegType& return_type = reg_types_.FromDescriptor(class_loader_.Get(),
3084                                                                descriptor,
3085                                                                false);
3086         if (!return_type.IsLowHalf()) {
3087           work_line_->SetResultRegisterType(this, return_type);
3088         } else {
3089           work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(&reg_types_));
3090         }
3091         just_set_result = true;
3092       }
3093       break;
3094     case Instruction::INVOKE_INTERFACE:
3095     case Instruction::INVOKE_INTERFACE_RANGE: {
3096       bool is_range =  (inst->Opcode() == Instruction::INVOKE_INTERFACE_RANGE);
3097       ArtMethod* abs_method = VerifyInvocationArgs(inst, METHOD_INTERFACE, is_range);
3098       if (abs_method != nullptr) {
3099         ObjPtr<mirror::Class> called_interface = abs_method->GetDeclaringClass();
3100         if (!called_interface->IsInterface() && !called_interface->IsObjectClass()) {
3101           Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected interface class in invoke-interface '"
3102               << abs_method->PrettyMethod() << "'";
3103           break;
3104         }
3105       }
3106       /* Get the type of the "this" arg, which should either be a sub-interface of called
3107        * interface or Object (see comments in RegType::JoinClass).
3108        */
3109       const RegType& this_type = work_line_->GetInvocationThis(this, inst);
3110       if (this_type.IsZeroOrNull()) {
3111         /* null pointer always passes (and always fails at runtime) */
3112       } else {
3113         if (this_type.IsUninitializedTypes()) {
3114           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "interface call on uninitialized object "
3115               << this_type;
3116           break;
3117         }
3118         // In the past we have tried to assert that "called_interface" is assignable
3119         // from "this_type.GetClass()", however, as we do an imprecise Join
3120         // (RegType::JoinClass) we don't have full information on what interfaces are
3121         // implemented by "this_type". For example, two classes may implement the same
3122         // interfaces and have a common parent that doesn't implement the interface. The
3123         // join will set "this_type" to the parent class and a test that this implements
3124         // the interface will incorrectly fail.
3125       }
3126       /*
3127        * We don't have an object instance, so we can't find the concrete method. However, all of
3128        * the type information is in the abstract method, so we're good.
3129        */
3130       const char* descriptor;
3131       if (abs_method == nullptr) {
3132         uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c();
3133         const dex::MethodId& method_id = dex_file_->GetMethodId(method_idx);
3134         dex::TypeIndex return_type_idx =
3135             dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_;
3136         descriptor = dex_file_->StringByTypeIdx(return_type_idx);
3137       } else {
3138         descriptor = abs_method->GetReturnTypeDescriptor();
3139       }
3140       const RegType& return_type = reg_types_.FromDescriptor(class_loader_.Get(),
3141                                                              descriptor,
3142                                                              false);
3143       if (!return_type.IsLowHalf()) {
3144         work_line_->SetResultRegisterType(this, return_type);
3145       } else {
3146         work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(&reg_types_));
3147       }
3148       just_set_result = true;
3149       break;
3150     }
3151     case Instruction::INVOKE_POLYMORPHIC:
3152     case Instruction::INVOKE_POLYMORPHIC_RANGE: {
3153       bool is_range = (inst->Opcode() == Instruction::INVOKE_POLYMORPHIC_RANGE);
3154       ArtMethod* called_method = VerifyInvocationArgs(inst, METHOD_POLYMORPHIC, is_range);
3155       if (called_method == nullptr) {
3156         // Convert potential soft failures in VerifyInvocationArgs() to hard errors.
3157         if (failure_messages_.size() > 0) {
3158           std::string message = failure_messages_.back()->str();
3159           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << message;
3160         } else {
3161           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invoke-polymorphic verification failure.";
3162         }
3163         break;
3164       }
3165       if (!CheckSignaturePolymorphicMethod(called_method) ||
3166           !CheckSignaturePolymorphicReceiver(inst)) {
3167         DCHECK(HasFailures());
3168         break;
3169       }
3170       const uint16_t vRegH = (is_range) ? inst->VRegH_4rcc() : inst->VRegH_45cc();
3171       const dex::ProtoIndex proto_idx(vRegH);
3172       const char* return_descriptor =
3173           dex_file_->GetReturnTypeDescriptor(dex_file_->GetProtoId(proto_idx));
3174       const RegType& return_type =
3175           reg_types_.FromDescriptor(class_loader_.Get(), return_descriptor, false);
3176       if (!return_type.IsLowHalf()) {
3177         work_line_->SetResultRegisterType(this, return_type);
3178       } else {
3179         work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(&reg_types_));
3180       }
3181       just_set_result = true;
3182       break;
3183     }
3184     case Instruction::INVOKE_CUSTOM:
3185     case Instruction::INVOKE_CUSTOM_RANGE: {
3186       // Verify registers based on method_type in the call site.
3187       bool is_range = (inst->Opcode() == Instruction::INVOKE_CUSTOM_RANGE);
3188 
3189       // Step 1. Check the call site that produces the method handle for invocation
3190       const uint32_t call_site_idx = is_range ? inst->VRegB_3rc() : inst->VRegB_35c();
3191       if (!CheckCallSite(call_site_idx)) {
3192         DCHECK(HasFailures());
3193         break;
3194       }
3195 
3196       // Step 2. Check the register arguments correspond to the expected arguments for the
3197       // method handle produced by step 1. The dex file verifier has checked ranges for
3198       // the first three arguments and CheckCallSite has checked the method handle type.
3199       const dex::ProtoIndex proto_idx = dex_file_->GetProtoIndexForCallSite(call_site_idx);
3200       const dex::ProtoId& proto_id = dex_file_->GetProtoId(proto_idx);
3201       DexFileParameterIterator param_it(*dex_file_, proto_id);
3202       // Treat method as static as it has yet to be determined.
3203       VerifyInvocationArgsFromIterator(&param_it, inst, METHOD_STATIC, is_range, nullptr);
3204       const char* return_descriptor = dex_file_->GetReturnTypeDescriptor(proto_id);
3205 
3206       // Step 3. Propagate return type information
3207       const RegType& return_type =
3208           reg_types_.FromDescriptor(class_loader_.Get(), return_descriptor, false);
3209       if (!return_type.IsLowHalf()) {
3210         work_line_->SetResultRegisterType(this, return_type);
3211       } else {
3212         work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(&reg_types_));
3213       }
3214       just_set_result = true;
3215       break;
3216     }
3217     case Instruction::NEG_INT:
3218     case Instruction::NOT_INT:
3219       work_line_->CheckUnaryOp(this, inst, reg_types_.Integer(), reg_types_.Integer());
3220       break;
3221     case Instruction::NEG_LONG:
3222     case Instruction::NOT_LONG:
3223       work_line_->CheckUnaryOpWide(this, inst, reg_types_.LongLo(), reg_types_.LongHi(),
3224                                    reg_types_.LongLo(), reg_types_.LongHi());
3225       break;
3226     case Instruction::NEG_FLOAT:
3227       work_line_->CheckUnaryOp(this, inst, reg_types_.Float(), reg_types_.Float());
3228       break;
3229     case Instruction::NEG_DOUBLE:
3230       work_line_->CheckUnaryOpWide(this, inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(),
3231                                    reg_types_.DoubleLo(), reg_types_.DoubleHi());
3232       break;
3233     case Instruction::INT_TO_LONG:
3234       work_line_->CheckUnaryOpToWide(this, inst, reg_types_.LongLo(), reg_types_.LongHi(),
3235                                      reg_types_.Integer());
3236       break;
3237     case Instruction::INT_TO_FLOAT:
3238       work_line_->CheckUnaryOp(this, inst, reg_types_.Float(), reg_types_.Integer());
3239       break;
3240     case Instruction::INT_TO_DOUBLE:
3241       work_line_->CheckUnaryOpToWide(this, inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(),
3242                                      reg_types_.Integer());
3243       break;
3244     case Instruction::LONG_TO_INT:
3245       work_line_->CheckUnaryOpFromWide(this, inst, reg_types_.Integer(),
3246                                        reg_types_.LongLo(), reg_types_.LongHi());
3247       break;
3248     case Instruction::LONG_TO_FLOAT:
3249       work_line_->CheckUnaryOpFromWide(this, inst, reg_types_.Float(),
3250                                        reg_types_.LongLo(), reg_types_.LongHi());
3251       break;
3252     case Instruction::LONG_TO_DOUBLE:
3253       work_line_->CheckUnaryOpWide(this, inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(),
3254                                    reg_types_.LongLo(), reg_types_.LongHi());
3255       break;
3256     case Instruction::FLOAT_TO_INT:
3257       work_line_->CheckUnaryOp(this, inst, reg_types_.Integer(), reg_types_.Float());
3258       break;
3259     case Instruction::FLOAT_TO_LONG:
3260       work_line_->CheckUnaryOpToWide(this, inst, reg_types_.LongLo(), reg_types_.LongHi(),
3261                                      reg_types_.Float());
3262       break;
3263     case Instruction::FLOAT_TO_DOUBLE:
3264       work_line_->CheckUnaryOpToWide(this, inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(),
3265                                      reg_types_.Float());
3266       break;
3267     case Instruction::DOUBLE_TO_INT:
3268       work_line_->CheckUnaryOpFromWide(this, inst, reg_types_.Integer(),
3269                                        reg_types_.DoubleLo(), reg_types_.DoubleHi());
3270       break;
3271     case Instruction::DOUBLE_TO_LONG:
3272       work_line_->CheckUnaryOpWide(this, inst, reg_types_.LongLo(), reg_types_.LongHi(),
3273                                    reg_types_.DoubleLo(), reg_types_.DoubleHi());
3274       break;
3275     case Instruction::DOUBLE_TO_FLOAT:
3276       work_line_->CheckUnaryOpFromWide(this, inst, reg_types_.Float(),
3277                                        reg_types_.DoubleLo(), reg_types_.DoubleHi());
3278       break;
3279     case Instruction::INT_TO_BYTE:
3280       work_line_->CheckUnaryOp(this, inst, reg_types_.Byte(), reg_types_.Integer());
3281       break;
3282     case Instruction::INT_TO_CHAR:
3283       work_line_->CheckUnaryOp(this, inst, reg_types_.Char(), reg_types_.Integer());
3284       break;
3285     case Instruction::INT_TO_SHORT:
3286       work_line_->CheckUnaryOp(this, inst, reg_types_.Short(), reg_types_.Integer());
3287       break;
3288 
3289     case Instruction::ADD_INT:
3290     case Instruction::SUB_INT:
3291     case Instruction::MUL_INT:
3292     case Instruction::REM_INT:
3293     case Instruction::DIV_INT:
3294     case Instruction::SHL_INT:
3295     case Instruction::SHR_INT:
3296     case Instruction::USHR_INT:
3297       work_line_->CheckBinaryOp(this, inst, reg_types_.Integer(), reg_types_.Integer(),
3298                                 reg_types_.Integer(), false);
3299       break;
3300     case Instruction::AND_INT:
3301     case Instruction::OR_INT:
3302     case Instruction::XOR_INT:
3303       work_line_->CheckBinaryOp(this, inst, reg_types_.Integer(), reg_types_.Integer(),
3304                                 reg_types_.Integer(), true);
3305       break;
3306     case Instruction::ADD_LONG:
3307     case Instruction::SUB_LONG:
3308     case Instruction::MUL_LONG:
3309     case Instruction::DIV_LONG:
3310     case Instruction::REM_LONG:
3311     case Instruction::AND_LONG:
3312     case Instruction::OR_LONG:
3313     case Instruction::XOR_LONG:
3314       work_line_->CheckBinaryOpWide(this, inst, reg_types_.LongLo(), reg_types_.LongHi(),
3315                                     reg_types_.LongLo(), reg_types_.LongHi(),
3316                                     reg_types_.LongLo(), reg_types_.LongHi());
3317       break;
3318     case Instruction::SHL_LONG:
3319     case Instruction::SHR_LONG:
3320     case Instruction::USHR_LONG:
3321       /* shift distance is Int, making these different from other binary operations */
3322       work_line_->CheckBinaryOpWideShift(this, inst, reg_types_.LongLo(), reg_types_.LongHi(),
3323                                          reg_types_.Integer());
3324       break;
3325     case Instruction::ADD_FLOAT:
3326     case Instruction::SUB_FLOAT:
3327     case Instruction::MUL_FLOAT:
3328     case Instruction::DIV_FLOAT:
3329     case Instruction::REM_FLOAT:
3330       work_line_->CheckBinaryOp(this, inst, reg_types_.Float(), reg_types_.Float(),
3331                                 reg_types_.Float(), false);
3332       break;
3333     case Instruction::ADD_DOUBLE:
3334     case Instruction::SUB_DOUBLE:
3335     case Instruction::MUL_DOUBLE:
3336     case Instruction::DIV_DOUBLE:
3337     case Instruction::REM_DOUBLE:
3338       work_line_->CheckBinaryOpWide(this, inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(),
3339                                     reg_types_.DoubleLo(), reg_types_.DoubleHi(),
3340                                     reg_types_.DoubleLo(), reg_types_.DoubleHi());
3341       break;
3342     case Instruction::ADD_INT_2ADDR:
3343     case Instruction::SUB_INT_2ADDR:
3344     case Instruction::MUL_INT_2ADDR:
3345     case Instruction::REM_INT_2ADDR:
3346     case Instruction::SHL_INT_2ADDR:
3347     case Instruction::SHR_INT_2ADDR:
3348     case Instruction::USHR_INT_2ADDR:
3349       work_line_->CheckBinaryOp2addr(this, inst, reg_types_.Integer(), reg_types_.Integer(),
3350                                      reg_types_.Integer(), false);
3351       break;
3352     case Instruction::AND_INT_2ADDR:
3353     case Instruction::OR_INT_2ADDR:
3354     case Instruction::XOR_INT_2ADDR:
3355       work_line_->CheckBinaryOp2addr(this, inst, reg_types_.Integer(), reg_types_.Integer(),
3356                                      reg_types_.Integer(), true);
3357       break;
3358     case Instruction::DIV_INT_2ADDR:
3359       work_line_->CheckBinaryOp2addr(this, inst, reg_types_.Integer(), reg_types_.Integer(),
3360                                      reg_types_.Integer(), false);
3361       break;
3362     case Instruction::ADD_LONG_2ADDR:
3363     case Instruction::SUB_LONG_2ADDR:
3364     case Instruction::MUL_LONG_2ADDR:
3365     case Instruction::DIV_LONG_2ADDR:
3366     case Instruction::REM_LONG_2ADDR:
3367     case Instruction::AND_LONG_2ADDR:
3368     case Instruction::OR_LONG_2ADDR:
3369     case Instruction::XOR_LONG_2ADDR:
3370       work_line_->CheckBinaryOp2addrWide(this, inst, reg_types_.LongLo(), reg_types_.LongHi(),
3371                                          reg_types_.LongLo(), reg_types_.LongHi(),
3372                                          reg_types_.LongLo(), reg_types_.LongHi());
3373       break;
3374     case Instruction::SHL_LONG_2ADDR:
3375     case Instruction::SHR_LONG_2ADDR:
3376     case Instruction::USHR_LONG_2ADDR:
3377       work_line_->CheckBinaryOp2addrWideShift(this, inst, reg_types_.LongLo(), reg_types_.LongHi(),
3378                                               reg_types_.Integer());
3379       break;
3380     case Instruction::ADD_FLOAT_2ADDR:
3381     case Instruction::SUB_FLOAT_2ADDR:
3382     case Instruction::MUL_FLOAT_2ADDR:
3383     case Instruction::DIV_FLOAT_2ADDR:
3384     case Instruction::REM_FLOAT_2ADDR:
3385       work_line_->CheckBinaryOp2addr(this, inst, reg_types_.Float(), reg_types_.Float(),
3386                                      reg_types_.Float(), false);
3387       break;
3388     case Instruction::ADD_DOUBLE_2ADDR:
3389     case Instruction::SUB_DOUBLE_2ADDR:
3390     case Instruction::MUL_DOUBLE_2ADDR:
3391     case Instruction::DIV_DOUBLE_2ADDR:
3392     case Instruction::REM_DOUBLE_2ADDR:
3393       work_line_->CheckBinaryOp2addrWide(this, inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(),
3394                                          reg_types_.DoubleLo(),  reg_types_.DoubleHi(),
3395                                          reg_types_.DoubleLo(), reg_types_.DoubleHi());
3396       break;
3397     case Instruction::ADD_INT_LIT16:
3398     case Instruction::RSUB_INT_LIT16:
3399     case Instruction::MUL_INT_LIT16:
3400     case Instruction::DIV_INT_LIT16:
3401     case Instruction::REM_INT_LIT16:
3402       work_line_->CheckLiteralOp(this, inst, reg_types_.Integer(), reg_types_.Integer(), false,
3403                                  true);
3404       break;
3405     case Instruction::AND_INT_LIT16:
3406     case Instruction::OR_INT_LIT16:
3407     case Instruction::XOR_INT_LIT16:
3408       work_line_->CheckLiteralOp(this, inst, reg_types_.Integer(), reg_types_.Integer(), true,
3409                                  true);
3410       break;
3411     case Instruction::ADD_INT_LIT8:
3412     case Instruction::RSUB_INT_LIT8:
3413     case Instruction::MUL_INT_LIT8:
3414     case Instruction::DIV_INT_LIT8:
3415     case Instruction::REM_INT_LIT8:
3416     case Instruction::SHL_INT_LIT8:
3417     case Instruction::SHR_INT_LIT8:
3418     case Instruction::USHR_INT_LIT8:
3419       work_line_->CheckLiteralOp(this, inst, reg_types_.Integer(), reg_types_.Integer(), false,
3420                                  false);
3421       break;
3422     case Instruction::AND_INT_LIT8:
3423     case Instruction::OR_INT_LIT8:
3424     case Instruction::XOR_INT_LIT8:
3425       work_line_->CheckLiteralOp(this, inst, reg_types_.Integer(), reg_types_.Integer(), true,
3426                                  false);
3427       break;
3428 
3429     // Special instructions.
3430     case Instruction::RETURN_VOID_NO_BARRIER:
3431       if (IsConstructor() && !IsStatic()) {
3432         const RegType& declaring_class = GetDeclaringClass();
3433         if (declaring_class.IsUnresolvedReference()) {
3434           // We must iterate over the fields, even if we cannot use mirror classes to do so. Do it
3435           // manually over the underlying dex file.
3436           uint32_t first_index = GetFirstFinalInstanceFieldIndex(*dex_file_,
3437               dex_file_->GetMethodId(dex_method_idx_).class_idx_);
3438           if (first_index != dex::kDexNoIndex) {
3439             Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-void-no-barrier not expected for field "
3440                               << first_index;
3441           }
3442           break;
3443         }
3444         ObjPtr<mirror::Class> klass = declaring_class.GetClass();
3445         for (uint32_t i = 0, num_fields = klass->NumInstanceFields(); i < num_fields; ++i) {
3446           if (klass->GetInstanceField(i)->IsFinal()) {
3447             Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-void-no-barrier not expected for "
3448                 << klass->GetInstanceField(i)->PrettyField();
3449             break;
3450           }
3451         }
3452       }
3453       // Handle this like a RETURN_VOID now. Code is duplicated to separate standard from
3454       // quickened opcodes (otherwise this could be a fall-through).
3455       if (!IsConstructor()) {
3456         if (!GetMethodReturnType().IsConflict()) {
3457           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-void not expected";
3458         }
3459       }
3460       break;
3461 
3462     /* These should never appear during verification. */
3463     case Instruction::UNUSED_3E ... Instruction::UNUSED_43:
3464     case Instruction::UNUSED_F3 ... Instruction::UNUSED_F9:
3465     case Instruction::UNUSED_79:
3466     case Instruction::UNUSED_7A:
3467       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Unexpected opcode " << inst->DumpString(dex_file_);
3468       break;
3469 
3470     /*
3471      * DO NOT add a "default" clause here. Without it the compiler will
3472      * complain if an instruction is missing (which is desirable).
3473      */
3474   }  // end - switch (dec_insn.opcode)
3475 
3476   if (flags_.have_pending_hard_failure_) {
3477     if (IsAotMode()) {
3478       /* When AOT compiling, check that the last failure is a hard failure */
3479       if (failures_[failures_.size() - 1] != VERIFY_ERROR_BAD_CLASS_HARD) {
3480         LOG(ERROR) << "Pending failures:";
3481         for (auto& error : failures_) {
3482           LOG(ERROR) << error;
3483         }
3484         for (auto& error_msg : failure_messages_) {
3485           LOG(ERROR) << error_msg->str();
3486         }
3487         LOG(FATAL) << "Pending hard failure, but last failure not hard.";
3488       }
3489     }
3490     /* immediate failure, reject class */
3491     info_messages_ << "Rejecting opcode " << inst->DumpString(dex_file_);
3492     return false;
3493   } else if (flags_.have_pending_runtime_throw_failure_) {
3494     LogVerifyInfo() << "Elevating opcode flags from " << opcode_flags << " to Throw";
3495     /* checking interpreter will throw, mark following code as unreachable */
3496     opcode_flags = Instruction::kThrow;
3497     // Note: the flag must be reset as it is only global to decouple Fail and is semantically per
3498     //       instruction. However, RETURN checking may throw LOCKING errors, so we clear at the
3499     //       very end.
3500   }
3501   /*
3502    * If we didn't just set the result register, clear it out. This ensures that you can only use
3503    * "move-result" immediately after the result is set. (We could check this statically, but it's
3504    * not expensive and it makes our debugging output cleaner.)
3505    */
3506   if (!just_set_result) {
3507     work_line_->SetResultTypeToUnknown(GetRegTypeCache());
3508   }
3509 
3510   /*
3511    * Handle "branch". Tag the branch target.
3512    *
3513    * NOTE: instructions like Instruction::EQZ provide information about the
3514    * state of the register when the branch is taken or not taken. For example,
3515    * somebody could get a reference field, check it for zero, and if the
3516    * branch is taken immediately store that register in a boolean field
3517    * since the value is known to be zero. We do not currently account for
3518    * that, and will reject the code.
3519    *
3520    * TODO: avoid re-fetching the branch target
3521    */
3522   if ((opcode_flags & Instruction::kBranch) != 0) {
3523     bool isConditional, selfOkay;
3524     if (!GetBranchOffset(work_insn_idx_, &branch_target, &isConditional, &selfOkay)) {
3525       /* should never happen after static verification */
3526       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad branch";
3527       return false;
3528     }
3529     DCHECK_EQ(isConditional, (opcode_flags & Instruction::kContinue) != 0);
3530     if (!CheckNotMoveExceptionOrMoveResult(code_item_accessor_.Insns(),
3531                                            work_insn_idx_ + branch_target)) {
3532       return false;
3533     }
3534     /* update branch target, set "changed" if appropriate */
3535     if (nullptr != branch_line) {
3536       if (!UpdateRegisters(work_insn_idx_ + branch_target, branch_line.get(), false)) {
3537         return false;
3538       }
3539     } else {
3540       if (!UpdateRegisters(work_insn_idx_ + branch_target, work_line_.get(), false)) {
3541         return false;
3542       }
3543     }
3544   }
3545 
3546   /*
3547    * Handle "switch". Tag all possible branch targets.
3548    *
3549    * We've already verified that the table is structurally sound, so we
3550    * just need to walk through and tag the targets.
3551    */
3552   if ((opcode_flags & Instruction::kSwitch) != 0) {
3553     int offset_to_switch = insns[1] | (static_cast<int32_t>(insns[2]) << 16);
3554     const uint16_t* switch_insns = insns + offset_to_switch;
3555     int switch_count = switch_insns[1];
3556     int offset_to_targets, targ;
3557 
3558     if ((*insns & 0xff) == Instruction::PACKED_SWITCH) {
3559       /* 0 = sig, 1 = count, 2/3 = first key */
3560       offset_to_targets = 4;
3561     } else {
3562       /* 0 = sig, 1 = count, 2..count * 2 = keys */
3563       DCHECK((*insns & 0xff) == Instruction::SPARSE_SWITCH);
3564       offset_to_targets = 2 + 2 * switch_count;
3565     }
3566 
3567     /* verify each switch target */
3568     for (targ = 0; targ < switch_count; targ++) {
3569       int offset;
3570       uint32_t abs_offset;
3571 
3572       /* offsets are 32-bit, and only partly endian-swapped */
3573       offset = switch_insns[offset_to_targets + targ * 2] |
3574          (static_cast<int32_t>(switch_insns[offset_to_targets + targ * 2 + 1]) << 16);
3575       abs_offset = work_insn_idx_ + offset;
3576       DCHECK_LT(abs_offset, code_item_accessor_.InsnsSizeInCodeUnits());
3577       if (!CheckNotMoveExceptionOrMoveResult(code_item_accessor_.Insns(), abs_offset)) {
3578         return false;
3579       }
3580       if (!UpdateRegisters(abs_offset, work_line_.get(), false)) {
3581         return false;
3582       }
3583     }
3584   }
3585 
3586   /*
3587    * Handle instructions that can throw and that are sitting in a "try" block. (If they're not in a
3588    * "try" block when they throw, control transfers out of the method.)
3589    */
3590   if ((opcode_flags & Instruction::kThrow) != 0 && GetInstructionFlags(work_insn_idx_).IsInTry()) {
3591     bool has_catch_all_handler = false;
3592     const dex::TryItem* try_item = code_item_accessor_.FindTryItem(work_insn_idx_);
3593     CHECK(try_item != nullptr);
3594     CatchHandlerIterator iterator(code_item_accessor_, *try_item);
3595 
3596     // Need the linker to try and resolve the handled class to check if it's Throwable.
3597     ClassLinker* linker = GetClassLinker();
3598 
3599     for (; iterator.HasNext(); iterator.Next()) {
3600       dex::TypeIndex handler_type_idx = iterator.GetHandlerTypeIndex();
3601       if (!handler_type_idx.IsValid()) {
3602         has_catch_all_handler = true;
3603       } else {
3604         // It is also a catch-all if it is java.lang.Throwable.
3605         ObjPtr<mirror::Class> klass =
3606             linker->ResolveType(handler_type_idx, dex_cache_, class_loader_);
3607         if (klass != nullptr) {
3608           if (klass == GetClassRoot<mirror::Throwable>()) {
3609             has_catch_all_handler = true;
3610           }
3611         } else {
3612           // Clear exception.
3613           DCHECK(self_->IsExceptionPending());
3614           self_->ClearException();
3615         }
3616       }
3617       /*
3618        * Merge registers into the "catch" block. We want to use the "savedRegs" rather than
3619        * "work_regs", because at runtime the exception will be thrown before the instruction
3620        * modifies any registers.
3621        */
3622       if (kVerifierDebug) {
3623         LogVerifyInfo() << "Updating exception handler 0x"
3624                         << std::hex << iterator.GetHandlerAddress();
3625       }
3626       if (!UpdateRegisters(iterator.GetHandlerAddress(), saved_line_.get(), false)) {
3627         return false;
3628       }
3629     }
3630 
3631     /*
3632      * If the monitor stack depth is nonzero, there must be a "catch all" handler for this
3633      * instruction. This does apply to monitor-exit because of async exception handling.
3634      */
3635     if (work_line_->MonitorStackDepth() > 0 && !has_catch_all_handler) {
3636       /*
3637        * The state in work_line reflects the post-execution state. If the current instruction is a
3638        * monitor-enter and the monitor stack was empty, we don't need a catch-all (if it throws,
3639        * it will do so before grabbing the lock).
3640        */
3641       if (inst->Opcode() != Instruction::MONITOR_ENTER || work_line_->MonitorStackDepth() != 1) {
3642         Fail(VERIFY_ERROR_BAD_CLASS_HARD)
3643             << "expected to be within a catch-all for an instruction where a monitor is held";
3644         return false;
3645       }
3646     }
3647   }
3648 
3649   /* Handle "continue". Tag the next consecutive instruction.
3650    *  Note: Keep the code handling "continue" case below the "branch" and "switch" cases,
3651    *        because it changes work_line_ when performing peephole optimization
3652    *        and this change should not be used in those cases.
3653    */
3654   if ((opcode_flags & Instruction::kContinue) != 0 && !exc_handler_unreachable) {
3655     DCHECK_EQ(&code_item_accessor_.InstructionAt(work_insn_idx_), inst);
3656     uint32_t next_insn_idx = work_insn_idx_ + inst->SizeInCodeUnits();
3657     if (next_insn_idx >= code_item_accessor_.InsnsSizeInCodeUnits()) {
3658       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Execution can walk off end of code area";
3659       return false;
3660     }
3661     // The only way to get to a move-exception instruction is to get thrown there. Make sure the
3662     // next instruction isn't one.
3663     if (!CheckNotMoveException(code_item_accessor_.Insns(), next_insn_idx)) {
3664       return false;
3665     }
3666     if (nullptr != fallthrough_line) {
3667       // Make workline consistent with fallthrough computed from peephole optimization.
3668       work_line_->CopyFromLine(fallthrough_line.get());
3669     }
3670     if (GetInstructionFlags(next_insn_idx).IsReturn()) {
3671       // For returns we only care about the operand to the return, all other registers are dead.
3672       const Instruction* ret_inst = &code_item_accessor_.InstructionAt(next_insn_idx);
3673       AdjustReturnLine(this, ret_inst, work_line_.get());
3674     }
3675     RegisterLine* next_line = reg_table_.GetLine(next_insn_idx);
3676     if (next_line != nullptr) {
3677       // Merge registers into what we have for the next instruction, and set the "changed" flag if
3678       // needed. If the merge changes the state of the registers then the work line will be
3679       // updated.
3680       if (!UpdateRegisters(next_insn_idx, work_line_.get(), true)) {
3681         return false;
3682       }
3683     } else {
3684       /*
3685        * We're not recording register data for the next instruction, so we don't know what the
3686        * prior state was. We have to assume that something has changed and re-evaluate it.
3687        */
3688       GetModifiableInstructionFlags(next_insn_idx).SetChanged();
3689     }
3690   }
3691 
3692   /* If we're returning from the method, make sure monitor stack is empty. */
3693   if ((opcode_flags & Instruction::kReturn) != 0) {
3694     work_line_->VerifyMonitorStackEmpty(this);
3695   }
3696 
3697   /*
3698    * Update start_guess. Advance to the next instruction of that's
3699    * possible, otherwise use the branch target if one was found. If
3700    * neither of those exists we're in a return or throw; leave start_guess
3701    * alone and let the caller sort it out.
3702    */
3703   if ((opcode_flags & Instruction::kContinue) != 0) {
3704     DCHECK_EQ(&code_item_accessor_.InstructionAt(work_insn_idx_), inst);
3705     *start_guess = work_insn_idx_ + inst->SizeInCodeUnits();
3706   } else if ((opcode_flags & Instruction::kBranch) != 0) {
3707     /* we're still okay if branch_target is zero */
3708     *start_guess = work_insn_idx_ + branch_target;
3709   }
3710 
3711   DCHECK_LT(*start_guess, code_item_accessor_.InsnsSizeInCodeUnits());
3712   DCHECK(GetInstructionFlags(*start_guess).IsOpcode());
3713 
3714   if (flags_.have_pending_runtime_throw_failure_) {
3715     flags_.have_any_pending_runtime_throw_failure_ = true;
3716     // Reset the pending_runtime_throw flag now.
3717     flags_.have_pending_runtime_throw_failure_ = false;
3718   }
3719 
3720   return true;
3721 }  // NOLINT(readability/fn_size)
3722 
3723 template <bool kVerifierDebug>
3724 template <CheckAccess C>
ResolveClass(dex::TypeIndex class_idx)3725 const RegType& MethodVerifier<kVerifierDebug>::ResolveClass(dex::TypeIndex class_idx) {
3726   ClassLinker* linker = GetClassLinker();
3727   ObjPtr<mirror::Class> klass = can_load_classes_
3728       ? linker->ResolveType(class_idx, dex_cache_, class_loader_)
3729       : linker->LookupResolvedType(class_idx, dex_cache_.Get(), class_loader_.Get());
3730   if (can_load_classes_ && klass == nullptr) {
3731     DCHECK(self_->IsExceptionPending());
3732     self_->ClearException();
3733   }
3734   const RegType* result = nullptr;
3735   if (klass != nullptr) {
3736     bool precise = klass->CannotBeAssignedFromOtherTypes();
3737     if (precise && !IsInstantiableOrPrimitive(klass)) {
3738       const char* descriptor = dex_file_->StringByTypeIdx(class_idx);
3739       UninstantiableError(descriptor);
3740       precise = false;
3741     }
3742     result = reg_types_.FindClass(klass, precise);
3743     if (result == nullptr) {
3744       const char* descriptor = dex_file_->StringByTypeIdx(class_idx);
3745       result = reg_types_.InsertClass(descriptor, klass, precise);
3746     }
3747   } else {
3748     const char* descriptor = dex_file_->StringByTypeIdx(class_idx);
3749     result = &reg_types_.FromDescriptor(class_loader_.Get(), descriptor, false);
3750   }
3751   DCHECK(result != nullptr);
3752   if (result->IsConflict()) {
3753     const char* descriptor = dex_file_->StringByTypeIdx(class_idx);
3754     Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "accessing broken descriptor '" << descriptor
3755         << "' in " << GetDeclaringClass();
3756     return *result;
3757   }
3758 
3759   // Record result of class resolution attempt.
3760   VerifierDeps::MaybeRecordClassResolution(*dex_file_, class_idx, klass);
3761 
3762   // If requested, check if access is allowed. Unresolved types are included in this check, as the
3763   // interpreter only tests whether access is allowed when a class is not pre-verified and runs in
3764   // the access-checks interpreter. If result is primitive, skip the access check.
3765   //
3766   // Note: we do this for unresolved classes to trigger re-verification at runtime.
3767   if (C != CheckAccess::kNo &&
3768       result->IsNonZeroReferenceTypes() &&
3769       ((C == CheckAccess::kYes && IsSdkVersionSetAndAtLeast(api_level_, SdkVersion::kP))
3770           || !result->IsUnresolvedTypes())) {
3771     const RegType& referrer = GetDeclaringClass();
3772     if ((IsSdkVersionSetAndAtLeast(api_level_, SdkVersion::kP) || !referrer.IsUnresolvedTypes()) &&
3773         !referrer.CanAccess(*result)) {
3774       Fail(VERIFY_ERROR_ACCESS_CLASS) << "(possibly) illegal class access: '"
3775                                       << referrer << "' -> '" << *result << "'";
3776     }
3777   }
3778   return *result;
3779 }
3780 
3781 template <bool kVerifierDebug>
HandleMoveException(const Instruction * inst)3782 bool MethodVerifier<kVerifierDebug>::HandleMoveException(const Instruction* inst)  {
3783   // We do not allow MOVE_EXCEPTION as the first instruction in a method. This is a simple case
3784   // where one entrypoint to the catch block is not actually an exception path.
3785   if (work_insn_idx_ == 0) {
3786     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "move-exception at pc 0x0";
3787     return true;
3788   }
3789   /*
3790    * This statement can only appear as the first instruction in an exception handler. We verify
3791    * that as part of extracting the exception type from the catch block list.
3792    */
3793   auto caught_exc_type_fn = [&]() REQUIRES_SHARED(Locks::mutator_lock_) ->
3794       std::pair<bool, const RegType*> {
3795     const RegType* common_super = nullptr;
3796     if (code_item_accessor_.TriesSize() != 0) {
3797       const uint8_t* handlers_ptr = code_item_accessor_.GetCatchHandlerData();
3798       uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3799       const RegType* unresolved = nullptr;
3800       for (uint32_t i = 0; i < handlers_size; i++) {
3801         CatchHandlerIterator iterator(handlers_ptr);
3802         for (; iterator.HasNext(); iterator.Next()) {
3803           if (iterator.GetHandlerAddress() == (uint32_t) work_insn_idx_) {
3804             if (!iterator.GetHandlerTypeIndex().IsValid()) {
3805               common_super = &reg_types_.JavaLangThrowable(false);
3806             } else {
3807               // Do access checks only on resolved exception classes.
3808               const RegType& exception =
3809                   ResolveClass<CheckAccess::kOnResolvedClass>(iterator.GetHandlerTypeIndex());
3810               if (!reg_types_.JavaLangThrowable(false).IsAssignableFrom(exception, this)) {
3811                 DCHECK(!exception.IsUninitializedTypes());  // Comes from dex, shouldn't be uninit.
3812                 if (exception.IsUnresolvedTypes()) {
3813                   if (unresolved == nullptr) {
3814                     unresolved = &exception;
3815                   } else {
3816                     unresolved = &unresolved->SafeMerge(exception, &reg_types_, this);
3817                   }
3818                 } else {
3819                   Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "unexpected non-exception class "
3820                                                     << exception;
3821                   return std::make_pair(true, &reg_types_.Conflict());
3822                 }
3823               } else if (common_super == nullptr) {
3824                 common_super = &exception;
3825               } else if (common_super->Equals(exception)) {
3826                 // odd case, but nothing to do
3827               } else {
3828                 common_super = &common_super->Merge(exception, &reg_types_, this);
3829                 if (FailOrAbort(reg_types_.JavaLangThrowable(false).IsAssignableFrom(
3830                     *common_super, this),
3831                     "java.lang.Throwable is not assignable-from common_super at ",
3832                     work_insn_idx_)) {
3833                   break;
3834                 }
3835               }
3836             }
3837           }
3838         }
3839         handlers_ptr = iterator.EndDataPointer();
3840       }
3841       if (unresolved != nullptr) {
3842         if (!IsAotMode() && common_super == nullptr) {
3843           // This is an unreachable handler.
3844 
3845           // We need to post a failure. The compiler currently does not handle unreachable
3846           // code correctly.
3847           Fail(VERIFY_ERROR_SKIP_COMPILER, /*pending_exc=*/ false)
3848               << "Unresolved catch handler, fail for compiler";
3849 
3850           return std::make_pair(false, unresolved);
3851         }
3852         // Soft-fail, but do not handle this with a synthetic throw.
3853         Fail(VERIFY_ERROR_NO_CLASS, /*pending_exc=*/ false) << "Unresolved catch handler";
3854         if (common_super != nullptr) {
3855           unresolved = &unresolved->Merge(*common_super, &reg_types_, this);
3856         }
3857         return std::make_pair(true, unresolved);
3858       }
3859     }
3860     if (common_super == nullptr) {
3861       /* no catch blocks, or no catches with classes we can find */
3862       Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "unable to find exception handler";
3863       return std::make_pair(true, &reg_types_.Conflict());
3864     }
3865     return std::make_pair(true, common_super);
3866   };
3867   auto result = caught_exc_type_fn();
3868   work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_11x(), *result.second);
3869   return result.first;
3870 }
3871 
3872 template <bool kVerifierDebug>
ResolveMethodAndCheckAccess(uint32_t dex_method_idx,MethodType method_type)3873 ArtMethod* MethodVerifier<kVerifierDebug>::ResolveMethodAndCheckAccess(
3874     uint32_t dex_method_idx, MethodType method_type) {
3875   const dex::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx);
3876   const RegType& klass_type = ResolveClass<CheckAccess::kYes>(method_id.class_idx_);
3877   if (klass_type.IsConflict()) {
3878     std::string append(" in attempt to access method ");
3879     append += dex_file_->GetMethodName(method_id);
3880     AppendToLastFailMessage(append);
3881     return nullptr;
3882   }
3883   if (klass_type.IsUnresolvedTypes()) {
3884     return nullptr;  // Can't resolve Class so no more to do here
3885   }
3886   ObjPtr<mirror::Class> klass = klass_type.GetClass();
3887   const RegType& referrer = GetDeclaringClass();
3888   ClassLinker* class_linker = GetClassLinker();
3889   PointerSize pointer_size = class_linker->GetImagePointerSize();
3890 
3891   ArtMethod* res_method = dex_cache_->GetResolvedMethod(dex_method_idx, pointer_size);
3892   if (res_method == nullptr) {
3893     res_method = class_linker->FindResolvedMethod(
3894         klass, dex_cache_.Get(), class_loader_.Get(), dex_method_idx);
3895   }
3896 
3897   // Record result of method resolution attempt. The klass resolution has recorded whether
3898   // the class is an interface or not and therefore the type of the lookup performed above.
3899   // TODO: Maybe we should not record dependency if the invoke type does not match the lookup type.
3900   VerifierDeps::MaybeRecordMethodResolution(*dex_file_, dex_method_idx, res_method);
3901 
3902   bool must_fail = false;
3903   // This is traditional and helps with screwy bytecode. It will tell you that, yes, a method
3904   // exists, but that it's called incorrectly. This significantly helps debugging, as locally it's
3905   // hard to see the differences.
3906   // If we don't have res_method here we must fail. Just use this bool to make sure of that with a
3907   // DCHECK.
3908   if (res_method == nullptr) {
3909     must_fail = true;
3910     // Try to find the method also with the other type for better error reporting below
3911     // but do not store such bogus lookup result in the DexCache or VerifierDeps.
3912     res_method = class_linker->FindIncompatibleMethod(
3913         klass, dex_cache_.Get(), class_loader_.Get(), dex_method_idx);
3914   }
3915 
3916   if (res_method == nullptr) {
3917     Fail(VERIFY_ERROR_NO_METHOD) << "couldn't find method "
3918                                  << klass->PrettyDescriptor() << "."
3919                                  << dex_file_->GetMethodName(method_id) << " "
3920                                  << dex_file_->GetMethodSignature(method_id);
3921     return nullptr;
3922   }
3923 
3924   // Make sure calls to constructors are "direct". There are additional restrictions but we don't
3925   // enforce them here.
3926   if (res_method->IsConstructor() && method_type != METHOD_DIRECT) {
3927     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "rejecting non-direct call to constructor "
3928                                       << res_method->PrettyMethod();
3929     return nullptr;
3930   }
3931   // Disallow any calls to class initializers.
3932   if (res_method->IsClassInitializer()) {
3933     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "rejecting call to class initializer "
3934                                       << res_method->PrettyMethod();
3935     return nullptr;
3936   }
3937 
3938   // Check that interface methods are static or match interface classes.
3939   // We only allow statics if we don't have default methods enabled.
3940   //
3941   // Note: this check must be after the initializer check, as those are required to fail a class,
3942   //       while this check implies an IncompatibleClassChangeError.
3943   if (klass->IsInterface()) {
3944     // methods called on interfaces should be invoke-interface, invoke-super, invoke-direct (if
3945     // default methods are supported for the dex file), or invoke-static.
3946     if (method_type != METHOD_INTERFACE &&
3947         method_type != METHOD_STATIC &&
3948         (!dex_file_->SupportsDefaultMethods() ||
3949          method_type != METHOD_DIRECT) &&
3950         method_type != METHOD_SUPER) {
3951       Fail(VERIFY_ERROR_CLASS_CHANGE)
3952           << "non-interface method " << dex_file_->PrettyMethod(dex_method_idx)
3953           << " is in an interface class " << klass->PrettyClass();
3954       return nullptr;
3955     }
3956   } else {
3957     if (method_type == METHOD_INTERFACE) {
3958       Fail(VERIFY_ERROR_CLASS_CHANGE)
3959           << "interface method " << dex_file_->PrettyMethod(dex_method_idx)
3960           << " is in a non-interface class " << klass->PrettyClass();
3961       return nullptr;
3962     }
3963   }
3964 
3965   // Check specifically for non-public object methods being provided for interface dispatch. This
3966   // can occur if we failed to find a method with FindInterfaceMethod but later find one with
3967   // FindClassMethod for error message use.
3968   if (method_type == METHOD_INTERFACE &&
3969       res_method->GetDeclaringClass()->IsObjectClass() &&
3970       !res_method->IsPublic()) {
3971     Fail(VERIFY_ERROR_NO_METHOD) << "invoke-interface " << klass->PrettyDescriptor() << "."
3972                                  << dex_file_->GetMethodName(method_id) << " "
3973                                  << dex_file_->GetMethodSignature(method_id) << " resolved to "
3974                                  << "non-public object method " << res_method->PrettyMethod() << " "
3975                                  << "but non-public Object methods are excluded from interface "
3976                                  << "method resolution.";
3977     return nullptr;
3978   }
3979   // Check if access is allowed.
3980   if (!referrer.CanAccessMember(res_method->GetDeclaringClass(), res_method->GetAccessFlags())) {
3981     Fail(VERIFY_ERROR_ACCESS_METHOD) << "illegal method access (call "
3982                                      << res_method->PrettyMethod()
3983                                      << " from " << referrer << ")";
3984     return res_method;
3985   }
3986   // Check that invoke-virtual and invoke-super are not used on private methods of the same class.
3987   if (res_method->IsPrivate() && (method_type == METHOD_VIRTUAL || method_type == METHOD_SUPER)) {
3988     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invoke-super/virtual can't be used on private method "
3989                                       << res_method->PrettyMethod();
3990     return nullptr;
3991   }
3992   // See if the method type implied by the invoke instruction matches the access flags for the
3993   // target method. The flags for METHOD_POLYMORPHIC are based on there being precisely two
3994   // signature polymorphic methods supported by the run-time which are native methods with variable
3995   // arguments.
3996   if ((method_type == METHOD_DIRECT && (!res_method->IsDirect() || res_method->IsStatic())) ||
3997       (method_type == METHOD_STATIC && !res_method->IsStatic()) ||
3998       ((method_type == METHOD_SUPER ||
3999         method_type == METHOD_VIRTUAL ||
4000         method_type == METHOD_INTERFACE) && res_method->IsDirect()) ||
4001       ((method_type == METHOD_POLYMORPHIC) &&
4002        (!res_method->IsNative() || !res_method->IsVarargs()))) {
4003     Fail(VERIFY_ERROR_CLASS_CHANGE) << "invoke type (" << method_type << ") does not match method "
4004                                        "type of " << res_method->PrettyMethod();
4005     return nullptr;
4006   }
4007   // Make sure we weren't expecting to fail.
4008   DCHECK(!must_fail) << "invoke type (" << method_type << ")"
4009                      << klass->PrettyDescriptor() << "."
4010                      << dex_file_->GetMethodName(method_id) << " "
4011                      << dex_file_->GetMethodSignature(method_id) << " unexpectedly resolved to "
4012                      << res_method->PrettyMethod() << " without error. Initially this method was "
4013                      << "not found so we were expecting to fail for some reason.";
4014   return res_method;
4015 }
4016 
4017 template <bool kVerifierDebug>
4018 template <class T>
VerifyInvocationArgsFromIterator(T * it,const Instruction * inst,MethodType method_type,bool is_range,ArtMethod * res_method)4019 ArtMethod* MethodVerifier<kVerifierDebug>::VerifyInvocationArgsFromIterator(
4020     T* it, const Instruction* inst, MethodType method_type, bool is_range, ArtMethod* res_method) {
4021   DCHECK_EQ(!is_range, inst->HasVarArgs());
4022 
4023   // We use vAA as our expected arg count, rather than res_method->insSize, because we need to
4024   // match the call to the signature. Also, we might be calling through an abstract method
4025   // definition (which doesn't have register count values).
4026   const size_t expected_args = inst->VRegA();
4027   /* caught by static verifier */
4028   DCHECK(is_range || expected_args <= 5);
4029 
4030   if (expected_args > code_item_accessor_.OutsSize()) {
4031     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid argument count (" << expected_args
4032                                       << ") exceeds outsSize ("
4033                                       << code_item_accessor_.OutsSize() << ")";
4034     return nullptr;
4035   }
4036 
4037   /*
4038    * Check the "this" argument, which must be an instance of the class that declared the method.
4039    * For an interface class, we don't do the full interface merge (see JoinClass), so we can't do a
4040    * rigorous check here (which is okay since we have to do it at runtime).
4041    */
4042   if (method_type != METHOD_STATIC) {
4043     const RegType& actual_arg_type = work_line_->GetInvocationThis(this, inst);
4044     if (actual_arg_type.IsConflict()) {  // GetInvocationThis failed.
4045       CHECK(flags_.have_pending_hard_failure_);
4046       return nullptr;
4047     }
4048     bool is_init = false;
4049     if (actual_arg_type.IsUninitializedTypes()) {
4050       if (res_method) {
4051         if (!res_method->IsConstructor()) {
4052           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "'this' arg must be initialized";
4053           return nullptr;
4054         }
4055       } else {
4056         // Check whether the name of the called method is "<init>"
4057         const uint32_t method_idx = GetMethodIdxOfInvoke(inst);
4058         if (strcmp(dex_file_->GetMethodName(dex_file_->GetMethodId(method_idx)), "<init>") != 0) {
4059           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "'this' arg must be initialized";
4060           return nullptr;
4061         }
4062       }
4063       is_init = true;
4064     }
4065     const RegType& adjusted_type = is_init
4066                                        ? GetRegTypeCache()->FromUninitialized(actual_arg_type)
4067                                        : actual_arg_type;
4068     if (method_type != METHOD_INTERFACE && !adjusted_type.IsZeroOrNull()) {
4069       const RegType* res_method_class;
4070       // Miranda methods have the declaring interface as their declaring class, not the abstract
4071       // class. It would be wrong to use this for the type check (interface type checks are
4072       // postponed to runtime).
4073       if (res_method != nullptr && !res_method->IsMiranda()) {
4074         ObjPtr<mirror::Class> klass = res_method->GetDeclaringClass();
4075         std::string temp;
4076         res_method_class = &FromClass(klass->GetDescriptor(&temp), klass,
4077                                       klass->CannotBeAssignedFromOtherTypes());
4078       } else {
4079         const uint32_t method_idx = GetMethodIdxOfInvoke(inst);
4080         const dex::TypeIndex class_idx = dex_file_->GetMethodId(method_idx).class_idx_;
4081         res_method_class = &reg_types_.FromDescriptor(
4082             class_loader_.Get(),
4083             dex_file_->StringByTypeIdx(class_idx),
4084             false);
4085       }
4086       if (!res_method_class->IsAssignableFrom(adjusted_type, this)) {
4087         Fail(adjusted_type.IsUnresolvedTypes()
4088                  ? VERIFY_ERROR_NO_CLASS
4089                  : VERIFY_ERROR_BAD_CLASS_SOFT)
4090             << "'this' argument '" << actual_arg_type << "' not instance of '"
4091             << *res_method_class << "'";
4092         // Continue on soft failures. We need to find possible hard failures to avoid problems in
4093         // the compiler.
4094         if (flags_.have_pending_hard_failure_) {
4095           return nullptr;
4096         }
4097       }
4098     }
4099   }
4100 
4101   uint32_t arg[5];
4102   if (!is_range) {
4103     inst->GetVarArgs(arg);
4104   }
4105   uint32_t sig_registers = (method_type == METHOD_STATIC) ? 0 : 1;
4106   for ( ; it->HasNext(); it->Next()) {
4107     if (sig_registers >= expected_args) {
4108       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation, expected " << inst->VRegA() <<
4109           " argument registers, method signature has " << sig_registers + 1 << " or more";
4110       return nullptr;
4111     }
4112 
4113     const char* param_descriptor = it->GetDescriptor();
4114 
4115     if (param_descriptor == nullptr) {
4116       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation because of missing signature "
4117           "component";
4118       return nullptr;
4119     }
4120 
4121     const RegType& reg_type = reg_types_.FromDescriptor(class_loader_.Get(),
4122                                                         param_descriptor,
4123                                                         false);
4124     uint32_t get_reg = is_range ? inst->VRegC() + static_cast<uint32_t>(sig_registers) :
4125         arg[sig_registers];
4126     if (reg_type.IsIntegralTypes()) {
4127       const RegType& src_type = work_line_->GetRegisterType(this, get_reg);
4128       if (!src_type.IsIntegralTypes()) {
4129         Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "register v" << get_reg << " has type " << src_type
4130             << " but expected " << reg_type;
4131         return nullptr;
4132       }
4133     } else {
4134       if (!work_line_->VerifyRegisterType(this, get_reg, reg_type)) {
4135         // Continue on soft failures. We need to find possible hard failures to avoid problems in
4136         // the compiler.
4137         if (flags_.have_pending_hard_failure_) {
4138           return nullptr;
4139         }
4140       } else if (reg_type.IsLongOrDoubleTypes()) {
4141         // Check that registers are consecutive (for non-range invokes). Invokes are the only
4142         // instructions not specifying register pairs by the first component, but require them
4143         // nonetheless. Only check when there's an actual register in the parameters. If there's
4144         // none, this will fail below.
4145         if (!is_range && sig_registers + 1 < expected_args) {
4146           uint32_t second_reg = arg[sig_registers + 1];
4147           if (second_reg != get_reg + 1) {
4148             Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation, long or double parameter "
4149                 "at index " << sig_registers << " is not a pair: " << get_reg << " + "
4150                 << second_reg << ".";
4151             return nullptr;
4152           }
4153         }
4154       }
4155     }
4156     sig_registers += reg_type.IsLongOrDoubleTypes() ?  2 : 1;
4157   }
4158   if (expected_args != sig_registers) {
4159     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation, expected " << expected_args <<
4160         " argument registers, method signature has " << sig_registers;
4161     return nullptr;
4162   }
4163   return res_method;
4164 }
4165 
4166 template <bool kVerifierDebug>
VerifyInvocationArgsUnresolvedMethod(const Instruction * inst,MethodType method_type,bool is_range)4167 void MethodVerifier<kVerifierDebug>::VerifyInvocationArgsUnresolvedMethod(const Instruction* inst,
4168                                                                           MethodType method_type,
4169                                                                           bool is_range) {
4170   // As the method may not have been resolved, make this static check against what we expect.
4171   // The main reason for this code block is to fail hard when we find an illegal use, e.g.,
4172   // wrong number of arguments or wrong primitive types, even if the method could not be resolved.
4173   const uint32_t method_idx = GetMethodIdxOfInvoke(inst);
4174   DexFileParameterIterator it(*dex_file_,
4175                               dex_file_->GetProtoId(dex_file_->GetMethodId(method_idx).proto_idx_));
4176   VerifyInvocationArgsFromIterator(&it, inst, method_type, is_range, nullptr);
4177 }
4178 
4179 template <bool kVerifierDebug>
CheckCallSite(uint32_t call_site_idx)4180 bool MethodVerifier<kVerifierDebug>::CheckCallSite(uint32_t call_site_idx) {
4181   if (call_site_idx >= dex_file_->NumCallSiteIds()) {
4182     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Bad call site id #" << call_site_idx
4183                                       << " >= " << dex_file_->NumCallSiteIds();
4184     return false;
4185   }
4186 
4187   CallSiteArrayValueIterator it(*dex_file_, dex_file_->GetCallSiteId(call_site_idx));
4188   // Check essential arguments are provided. The dex file verifier has verified indices of the
4189   // main values (method handle, name, method_type).
4190   static const size_t kRequiredArguments = 3;
4191   if (it.Size() < kRequiredArguments) {
4192     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Call site #" << call_site_idx
4193                                       << " has too few arguments: "
4194                                       << it.Size() << " < " << kRequiredArguments;
4195     return false;
4196   }
4197 
4198   std::pair<const EncodedArrayValueIterator::ValueType, size_t> type_and_max[kRequiredArguments] =
4199       { { EncodedArrayValueIterator::ValueType::kMethodHandle, dex_file_->NumMethodHandles() },
4200         { EncodedArrayValueIterator::ValueType::kString, dex_file_->NumStringIds() },
4201         { EncodedArrayValueIterator::ValueType::kMethodType, dex_file_->NumProtoIds() }
4202       };
4203   uint32_t index[kRequiredArguments];
4204 
4205   // Check arguments have expected types and are within permitted ranges.
4206   for (size_t i = 0; i < kRequiredArguments; ++i) {
4207     if (it.GetValueType() != type_and_max[i].first) {
4208       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Call site id #" << call_site_idx
4209                                         << " argument " << i << " has wrong type "
4210                                         << it.GetValueType() << "!=" << type_and_max[i].first;
4211       return false;
4212     }
4213     index[i] = static_cast<uint32_t>(it.GetJavaValue().i);
4214     if (index[i] >= type_and_max[i].second) {
4215       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Call site id #" << call_site_idx
4216                                         << " argument " << i << " bad index "
4217                                         << index[i] << " >= " << type_and_max[i].second;
4218       return false;
4219     }
4220     it.Next();
4221   }
4222 
4223   // Check method handle kind is valid.
4224   const dex::MethodHandleItem& mh = dex_file_->GetMethodHandle(index[0]);
4225   if (mh.method_handle_type_ != static_cast<uint16_t>(DexFile::MethodHandleType::kInvokeStatic)) {
4226     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Call site #" << call_site_idx
4227                                       << " argument 0 method handle type is not InvokeStatic: "
4228                                       << mh.method_handle_type_;
4229     return false;
4230   }
4231   return true;
4232 }
4233 
4234 class MethodParamListDescriptorIterator {
4235  public:
MethodParamListDescriptorIterator(ArtMethod * res_method)4236   explicit MethodParamListDescriptorIterator(ArtMethod* res_method) :
4237       res_method_(res_method), pos_(0), params_(res_method->GetParameterTypeList()),
4238       params_size_(params_ == nullptr ? 0 : params_->Size()) {
4239   }
4240 
HasNext()4241   bool HasNext() {
4242     return pos_ < params_size_;
4243   }
4244 
Next()4245   void Next() {
4246     ++pos_;
4247   }
4248 
GetDescriptor()4249   const char* GetDescriptor() REQUIRES_SHARED(Locks::mutator_lock_) {
4250     return res_method_->GetTypeDescriptorFromTypeIdx(params_->GetTypeItem(pos_).type_idx_);
4251   }
4252 
4253  private:
4254   ArtMethod* res_method_;
4255   size_t pos_;
4256   const dex::TypeList* params_;
4257   const size_t params_size_;
4258 };
4259 
4260 template <bool kVerifierDebug>
VerifyInvocationArgs(const Instruction * inst,MethodType method_type,bool is_range)4261 ArtMethod* MethodVerifier<kVerifierDebug>::VerifyInvocationArgs(
4262     const Instruction* inst, MethodType method_type, bool is_range) {
4263   // Resolve the method. This could be an abstract or concrete method depending on what sort of call
4264   // we're making.
4265   const uint32_t method_idx = GetMethodIdxOfInvoke(inst);
4266   ArtMethod* res_method = ResolveMethodAndCheckAccess(method_idx, method_type);
4267   if (res_method == nullptr) {  // error or class is unresolved
4268     // Check what we can statically.
4269     if (!flags_.have_pending_hard_failure_) {
4270       VerifyInvocationArgsUnresolvedMethod(inst, method_type, is_range);
4271     }
4272     return nullptr;
4273   }
4274 
4275   // If we're using invoke-super(method), make sure that the executing method's class' superclass
4276   // has a vtable entry for the target method. Or the target is on a interface.
4277   if (method_type == METHOD_SUPER) {
4278     dex::TypeIndex class_idx = dex_file_->GetMethodId(method_idx).class_idx_;
4279     const RegType& reference_type = reg_types_.FromDescriptor(
4280         class_loader_.Get(),
4281         dex_file_->StringByTypeIdx(class_idx),
4282         false);
4283     if (reference_type.IsUnresolvedTypes()) {
4284       Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "Unable to find referenced class from invoke-super";
4285       return nullptr;
4286     }
4287     if (reference_type.GetClass()->IsInterface()) {
4288       if (!GetDeclaringClass().HasClass()) {
4289         Fail(VERIFY_ERROR_NO_CLASS) << "Unable to resolve the full class of 'this' used in an"
4290                                     << "interface invoke-super";
4291         return nullptr;
4292       } else if (!reference_type.IsStrictlyAssignableFrom(GetDeclaringClass(), this)) {
4293         Fail(VERIFY_ERROR_CLASS_CHANGE)
4294             << "invoke-super in " << mirror::Class::PrettyClass(GetDeclaringClass().GetClass())
4295             << " in method "
4296             << dex_file_->PrettyMethod(dex_method_idx_) << " to method "
4297             << dex_file_->PrettyMethod(method_idx) << " references "
4298             << "non-super-interface type " << mirror::Class::PrettyClass(reference_type.GetClass());
4299         return nullptr;
4300       }
4301     } else {
4302       const RegType& super = GetDeclaringClass().GetSuperClass(&reg_types_);
4303       if (super.IsUnresolvedTypes()) {
4304         Fail(VERIFY_ERROR_NO_METHOD) << "unknown super class in invoke-super from "
4305                                     << dex_file_->PrettyMethod(dex_method_idx_)
4306                                     << " to super " << res_method->PrettyMethod();
4307         return nullptr;
4308       }
4309       if (!reference_type.IsStrictlyAssignableFrom(GetDeclaringClass(), this) ||
4310           (res_method->GetMethodIndex() >= super.GetClass()->GetVTableLength())) {
4311         Fail(VERIFY_ERROR_NO_METHOD) << "invalid invoke-super from "
4312                                     << dex_file_->PrettyMethod(dex_method_idx_)
4313                                     << " to super " << super
4314                                     << "." << res_method->GetName()
4315                                     << res_method->GetSignature();
4316         return nullptr;
4317       }
4318     }
4319   }
4320 
4321   if (UNLIKELY(method_type == METHOD_POLYMORPHIC)) {
4322     // Process the signature of the calling site that is invoking the method handle.
4323     dex::ProtoIndex proto_idx(inst->VRegH());
4324     DexFileParameterIterator it(*dex_file_, dex_file_->GetProtoId(proto_idx));
4325     return VerifyInvocationArgsFromIterator(&it, inst, method_type, is_range, res_method);
4326   } else {
4327     // Process the target method's signature.
4328     MethodParamListDescriptorIterator it(res_method);
4329     return VerifyInvocationArgsFromIterator(&it, inst, method_type, is_range, res_method);
4330   }
4331 }
4332 
4333 template <bool kVerifierDebug>
CheckSignaturePolymorphicMethod(ArtMethod * method)4334 bool MethodVerifier<kVerifierDebug>::CheckSignaturePolymorphicMethod(ArtMethod* method) {
4335   ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
4336   const char* method_name = method->GetName();
4337 
4338   const char* expected_return_descriptor;
4339   ObjPtr<mirror::ObjectArray<mirror::Class>> class_roots = GetClassLinker()->GetClassRoots();
4340   if (klass == GetClassRoot<mirror::MethodHandle>(class_roots)) {
4341     expected_return_descriptor = mirror::MethodHandle::GetReturnTypeDescriptor(method_name);
4342   } else if (klass == GetClassRoot<mirror::VarHandle>(class_roots)) {
4343     expected_return_descriptor = mirror::VarHandle::GetReturnTypeDescriptor(method_name);
4344   } else {
4345     Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4346         << "Signature polymorphic method in unsuppported class: " << klass->PrettyDescriptor();
4347     return false;
4348   }
4349 
4350   if (expected_return_descriptor == nullptr) {
4351     Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4352         << "Signature polymorphic method name invalid: " << method_name;
4353     return false;
4354   }
4355 
4356   const dex::TypeList* types = method->GetParameterTypeList();
4357   if (types->Size() != 1) {
4358     Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4359         << "Signature polymorphic method has too many arguments " << types->Size() << " != 1";
4360     return false;
4361   }
4362 
4363   const dex::TypeIndex argument_type_index = types->GetTypeItem(0).type_idx_;
4364   const char* argument_descriptor = method->GetTypeDescriptorFromTypeIdx(argument_type_index);
4365   if (strcmp(argument_descriptor, "[Ljava/lang/Object;") != 0) {
4366     Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4367         << "Signature polymorphic method has unexpected argument type: " << argument_descriptor;
4368     return false;
4369   }
4370 
4371   const char* return_descriptor = method->GetReturnTypeDescriptor();
4372   if (strcmp(return_descriptor, expected_return_descriptor) != 0) {
4373     Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4374         << "Signature polymorphic method has unexpected return type: " << return_descriptor
4375         << " != " << expected_return_descriptor;
4376     return false;
4377   }
4378 
4379   return true;
4380 }
4381 
4382 template <bool kVerifierDebug>
CheckSignaturePolymorphicReceiver(const Instruction * inst)4383 bool MethodVerifier<kVerifierDebug>::CheckSignaturePolymorphicReceiver(const Instruction* inst) {
4384   const RegType& this_type = work_line_->GetInvocationThis(this, inst);
4385   if (this_type.IsZeroOrNull()) {
4386     /* null pointer always passes (and always fails at run time) */
4387     return true;
4388   } else if (!this_type.IsNonZeroReferenceTypes()) {
4389     Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4390         << "invoke-polymorphic receiver is not a reference: "
4391         << this_type;
4392     return false;
4393   } else if (this_type.IsUninitializedReference()) {
4394     Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4395         << "invoke-polymorphic receiver is uninitialized: "
4396         << this_type;
4397     return false;
4398   } else if (!this_type.HasClass()) {
4399     Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4400         << "invoke-polymorphic receiver has no class: "
4401         << this_type;
4402     return false;
4403   } else {
4404     ObjPtr<mirror::ObjectArray<mirror::Class>> class_roots = GetClassLinker()->GetClassRoots();
4405     if (!this_type.GetClass()->IsSubClass(GetClassRoot<mirror::MethodHandle>(class_roots)) &&
4406         !this_type.GetClass()->IsSubClass(GetClassRoot<mirror::VarHandle>(class_roots))) {
4407       Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4408           << "invoke-polymorphic receiver is not a subclass of MethodHandle or VarHandle: "
4409           << this_type;
4410       return false;
4411     }
4412   }
4413   return true;
4414 }
4415 
4416 template <bool kVerifierDebug>
VerifyNewArray(const Instruction * inst,bool is_filled,bool is_range)4417 void MethodVerifier<kVerifierDebug>::VerifyNewArray(const Instruction* inst,
4418                                                     bool is_filled,
4419                                                     bool is_range) {
4420   dex::TypeIndex type_idx;
4421   if (!is_filled) {
4422     DCHECK_EQ(inst->Opcode(), Instruction::NEW_ARRAY);
4423     type_idx = dex::TypeIndex(inst->VRegC_22c());
4424   } else if (!is_range) {
4425     DCHECK_EQ(inst->Opcode(), Instruction::FILLED_NEW_ARRAY);
4426     type_idx = dex::TypeIndex(inst->VRegB_35c());
4427   } else {
4428     DCHECK_EQ(inst->Opcode(), Instruction::FILLED_NEW_ARRAY_RANGE);
4429     type_idx = dex::TypeIndex(inst->VRegB_3rc());
4430   }
4431   const RegType& res_type = ResolveClass<CheckAccess::kYes>(type_idx);
4432   if (res_type.IsConflict()) {  // bad class
4433     DCHECK_NE(failures_.size(), 0U);
4434   } else {
4435     // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved
4436     if (!res_type.IsArrayTypes()) {
4437       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "new-array on non-array class " << res_type;
4438     } else if (!is_filled) {
4439       /* make sure "size" register is valid type */
4440       work_line_->VerifyRegisterType(this, inst->VRegB_22c(), reg_types_.Integer());
4441       /* set register type to array class */
4442       const RegType& precise_type = reg_types_.FromUninitialized(res_type);
4443       work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_22c(), precise_type);
4444     } else {
4445       DCHECK(!res_type.IsUnresolvedMergedReference());
4446       // Verify each register. If "arg_count" is bad, VerifyRegisterType() will run off the end of
4447       // the list and fail. It's legal, if silly, for arg_count to be zero.
4448       const RegType& expected_type = reg_types_.GetComponentType(res_type, class_loader_.Get());
4449       uint32_t arg_count = (is_range) ? inst->VRegA_3rc() : inst->VRegA_35c();
4450       uint32_t arg[5];
4451       if (!is_range) {
4452         inst->GetVarArgs(arg);
4453       }
4454       for (size_t ui = 0; ui < arg_count; ui++) {
4455         uint32_t get_reg = is_range ? inst->VRegC_3rc() + ui : arg[ui];
4456         if (!work_line_->VerifyRegisterType(this, get_reg, expected_type)) {
4457           work_line_->SetResultRegisterType(this, reg_types_.Conflict());
4458           return;
4459         }
4460       }
4461       // filled-array result goes into "result" register
4462       const RegType& precise_type = reg_types_.FromUninitialized(res_type);
4463       work_line_->SetResultRegisterType(this, precise_type);
4464     }
4465   }
4466 }
4467 
4468 template <bool kVerifierDebug>
VerifyAGet(const Instruction * inst,const RegType & insn_type,bool is_primitive)4469 void MethodVerifier<kVerifierDebug>::VerifyAGet(const Instruction* inst,
4470                                                 const RegType& insn_type,
4471                                                 bool is_primitive) {
4472   const RegType& index_type = work_line_->GetRegisterType(this, inst->VRegC_23x());
4473   if (!index_type.IsArrayIndexTypes()) {
4474     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Invalid reg type for array index (" << index_type << ")";
4475   } else {
4476     const RegType& array_type = work_line_->GetRegisterType(this, inst->VRegB_23x());
4477     if (array_type.IsZeroOrNull()) {
4478       // Null array class; this code path will fail at runtime. Infer a merge-able type from the
4479       // instruction type.
4480       if (!is_primitive) {
4481         work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_23x(), reg_types_.Null());
4482       } else if (insn_type.IsInteger()) {
4483         // Pick a non-zero constant (to distinguish with null) that can fit in any primitive.
4484         // We cannot use 'insn_type' as it could be a float array or an int array.
4485         work_line_->SetRegisterType<LockOp::kClear>(
4486             this, inst->VRegA_23x(), DetermineCat1Constant(1, need_precise_constants_));
4487       } else if (insn_type.IsCategory1Types()) {
4488         // Category 1
4489         // The 'insn_type' is exactly the type we need.
4490         work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_23x(), insn_type);
4491       } else {
4492         // Category 2
4493         work_line_->SetRegisterTypeWide(this, inst->VRegA_23x(),
4494                                         reg_types_.FromCat2ConstLo(0, false),
4495                                         reg_types_.FromCat2ConstHi(0, false));
4496       }
4497     } else if (!array_type.IsArrayTypes()) {
4498       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "not array type " << array_type << " with aget";
4499     } else if (array_type.IsUnresolvedMergedReference()) {
4500       // Unresolved array types must be reference array types.
4501       if (is_primitive) {
4502         Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "reference array type " << array_type
4503                     << " source for category 1 aget";
4504       } else {
4505         Fail(VERIFY_ERROR_NO_CLASS) << "cannot verify aget for " << array_type
4506             << " because of missing class";
4507         // Approximate with java.lang.Object[].
4508         work_line_->SetRegisterType<LockOp::kClear>(this,
4509                                                     inst->VRegA_23x(),
4510                                                     reg_types_.JavaLangObject(false));
4511       }
4512     } else {
4513       /* verify the class */
4514       const RegType& component_type = reg_types_.GetComponentType(array_type, class_loader_.Get());
4515       if (!component_type.IsReferenceTypes() && !is_primitive) {
4516         Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "primitive array type " << array_type
4517             << " source for aget-object";
4518       } else if (component_type.IsNonZeroReferenceTypes() && is_primitive) {
4519         Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "reference array type " << array_type
4520             << " source for category 1 aget";
4521       } else if (is_primitive && !insn_type.Equals(component_type) &&
4522                  !((insn_type.IsInteger() && component_type.IsFloat()) ||
4523                  (insn_type.IsLong() && component_type.IsDouble()))) {
4524         Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array type " << array_type
4525             << " incompatible with aget of type " << insn_type;
4526       } else {
4527         // Use knowledge of the field type which is stronger than the type inferred from the
4528         // instruction, which can't differentiate object types and ints from floats, longs from
4529         // doubles.
4530         if (!component_type.IsLowHalf()) {
4531           work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_23x(), component_type);
4532         } else {
4533           work_line_->SetRegisterTypeWide(this, inst->VRegA_23x(), component_type,
4534                                           component_type.HighHalf(&reg_types_));
4535         }
4536       }
4537     }
4538   }
4539 }
4540 
4541 template <bool kVerifierDebug>
VerifyPrimitivePut(const RegType & target_type,const RegType & insn_type,const uint32_t vregA)4542 void MethodVerifier<kVerifierDebug>::VerifyPrimitivePut(const RegType& target_type,
4543                                                         const RegType& insn_type,
4544                                                         const uint32_t vregA) {
4545   // Primitive assignability rules are weaker than regular assignability rules.
4546   bool instruction_compatible;
4547   bool value_compatible;
4548   const RegType& value_type = work_line_->GetRegisterType(this, vregA);
4549   if (target_type.IsIntegralTypes()) {
4550     instruction_compatible = target_type.Equals(insn_type);
4551     value_compatible = value_type.IsIntegralTypes();
4552   } else if (target_type.IsFloat()) {
4553     instruction_compatible = insn_type.IsInteger();  // no put-float, so expect put-int
4554     value_compatible = value_type.IsFloatTypes();
4555   } else if (target_type.IsLong()) {
4556     instruction_compatible = insn_type.IsLong();
4557     // Additional register check: this is not checked statically (as part of VerifyInstructions),
4558     // as target_type depends on the resolved type of the field.
4559     if (instruction_compatible && work_line_->NumRegs() > vregA + 1) {
4560       const RegType& value_type_hi = work_line_->GetRegisterType(this, vregA + 1);
4561       value_compatible = value_type.IsLongTypes() && value_type.CheckWidePair(value_type_hi);
4562     } else {
4563       value_compatible = false;
4564     }
4565   } else if (target_type.IsDouble()) {
4566     instruction_compatible = insn_type.IsLong();  // no put-double, so expect put-long
4567     // Additional register check: this is not checked statically (as part of VerifyInstructions),
4568     // as target_type depends on the resolved type of the field.
4569     if (instruction_compatible && work_line_->NumRegs() > vregA + 1) {
4570       const RegType& value_type_hi = work_line_->GetRegisterType(this, vregA + 1);
4571       value_compatible = value_type.IsDoubleTypes() && value_type.CheckWidePair(value_type_hi);
4572     } else {
4573       value_compatible = false;
4574     }
4575   } else {
4576     instruction_compatible = false;  // reference with primitive store
4577     value_compatible = false;  // unused
4578   }
4579   if (!instruction_compatible) {
4580     // This is a global failure rather than a class change failure as the instructions and
4581     // the descriptors for the type should have been consistent within the same file at
4582     // compile time.
4583     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "put insn has type '" << insn_type
4584         << "' but expected type '" << target_type << "'";
4585     return;
4586   }
4587   if (!value_compatible) {
4588     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected value in v" << vregA
4589         << " of type " << value_type << " but expected " << target_type << " for put";
4590     return;
4591   }
4592 }
4593 
4594 template <bool kVerifierDebug>
VerifyAPut(const Instruction * inst,const RegType & insn_type,bool is_primitive)4595 void MethodVerifier<kVerifierDebug>::VerifyAPut(const Instruction* inst,
4596                                                 const RegType& insn_type,
4597                                                 bool is_primitive) {
4598   const RegType& index_type = work_line_->GetRegisterType(this, inst->VRegC_23x());
4599   if (!index_type.IsArrayIndexTypes()) {
4600     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Invalid reg type for array index (" << index_type << ")";
4601   } else {
4602     const RegType& array_type = work_line_->GetRegisterType(this, inst->VRegB_23x());
4603     if (array_type.IsZeroOrNull()) {
4604       // Null array type; this code path will fail at runtime.
4605       // Still check that the given value matches the instruction's type.
4606       // Note: this is, as usual, complicated by the fact the the instruction isn't fully typed
4607       //       and fits multiple register types.
4608       const RegType* modified_reg_type = &insn_type;
4609       if ((modified_reg_type == &reg_types_.Integer()) ||
4610           (modified_reg_type == &reg_types_.LongLo())) {
4611         // May be integer or float | long or double. Overwrite insn_type accordingly.
4612         const RegType& value_type = work_line_->GetRegisterType(this, inst->VRegA_23x());
4613         if (modified_reg_type == &reg_types_.Integer()) {
4614           if (&value_type == &reg_types_.Float()) {
4615             modified_reg_type = &value_type;
4616           }
4617         } else {
4618           if (&value_type == &reg_types_.DoubleLo()) {
4619             modified_reg_type = &value_type;
4620           }
4621         }
4622       }
4623       work_line_->VerifyRegisterType(this, inst->VRegA_23x(), *modified_reg_type);
4624     } else if (!array_type.IsArrayTypes()) {
4625       Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "not array type " << array_type << " with aput";
4626     } else if (array_type.IsUnresolvedMergedReference()) {
4627       // Unresolved array types must be reference array types.
4628       if (is_primitive) {
4629         Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "put insn has type '" << insn_type
4630                                           << "' but unresolved type '" << array_type << "'";
4631       } else {
4632         Fail(VERIFY_ERROR_NO_CLASS) << "cannot verify aput for " << array_type
4633                                     << " because of missing class";
4634       }
4635     } else {
4636       const RegType& component_type = reg_types_.GetComponentType(array_type, class_loader_.Get());
4637       const uint32_t vregA = inst->VRegA_23x();
4638       if (is_primitive) {
4639         VerifyPrimitivePut(component_type, insn_type, vregA);
4640       } else {
4641         if (!component_type.IsReferenceTypes()) {
4642           Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "primitive array type " << array_type
4643               << " source for aput-object";
4644         } else {
4645           // The instruction agrees with the type of array, confirm the value to be stored does too
4646           // Note: we use the instruction type (rather than the component type) for aput-object as
4647           // incompatible classes will be caught at runtime as an array store exception
4648           work_line_->VerifyRegisterType(this, vregA, insn_type);
4649         }
4650       }
4651     }
4652   }
4653 }
4654 
4655 template <bool kVerifierDebug>
GetStaticField(int field_idx)4656 ArtField* MethodVerifier<kVerifierDebug>::GetStaticField(int field_idx) {
4657   const dex::FieldId& field_id = dex_file_->GetFieldId(field_idx);
4658   // Check access to class
4659   const RegType& klass_type = ResolveClass<CheckAccess::kYes>(field_id.class_idx_);
4660   if (klass_type.IsConflict()) {  // bad class
4661     AppendToLastFailMessage(StringPrintf(" in attempt to access static field %d (%s) in %s",
4662                                          field_idx, dex_file_->GetFieldName(field_id),
4663                                          dex_file_->GetFieldDeclaringClassDescriptor(field_id)));
4664     return nullptr;
4665   }
4666   if (klass_type.IsUnresolvedTypes()) {
4667     // Accessibility checks depend on resolved fields.
4668     DCHECK(klass_type.Equals(GetDeclaringClass()) ||
4669            !failures_.empty() ||
4670            IsSdkVersionSetAndLessThan(api_level_, SdkVersion::kP));
4671 
4672     return nullptr;  // Can't resolve Class so no more to do here, will do checking at runtime.
4673   }
4674   ClassLinker* class_linker = GetClassLinker();
4675   ArtField* field = class_linker->ResolveFieldJLS(field_idx, dex_cache_, class_loader_);
4676 
4677   // Record result of the field resolution attempt.
4678   VerifierDeps::MaybeRecordFieldResolution(*dex_file_, field_idx, field);
4679 
4680   if (field == nullptr) {
4681     VLOG(verifier) << "Unable to resolve static field " << field_idx << " ("
4682               << dex_file_->GetFieldName(field_id) << ") in "
4683               << dex_file_->GetFieldDeclaringClassDescriptor(field_id);
4684     DCHECK(self_->IsExceptionPending());
4685     self_->ClearException();
4686     return nullptr;
4687   } else if (!GetDeclaringClass().CanAccessMember(field->GetDeclaringClass(),
4688                                                   field->GetAccessFlags())) {
4689     Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot access static field " << field->PrettyField()
4690                                     << " from " << GetDeclaringClass();
4691     return nullptr;
4692   } else if (!field->IsStatic()) {
4693     Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected field " << field->PrettyField() << " to be static";
4694     return nullptr;
4695   }
4696   return field;
4697 }
4698 
4699 template <bool kVerifierDebug>
GetInstanceField(const RegType & obj_type,int field_idx)4700 ArtField* MethodVerifier<kVerifierDebug>::GetInstanceField(const RegType& obj_type, int field_idx) {
4701   if (!obj_type.IsZeroOrNull() && !obj_type.IsReferenceTypes()) {
4702     // Trying to read a field from something that isn't a reference.
4703     Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "instance field access on object that has "
4704         << "non-reference type " << obj_type;
4705     return nullptr;
4706   }
4707   const dex::FieldId& field_id = dex_file_->GetFieldId(field_idx);
4708   // Check access to class.
4709   const RegType& klass_type = ResolveClass<CheckAccess::kYes>(field_id.class_idx_);
4710   if (klass_type.IsConflict()) {
4711     AppendToLastFailMessage(StringPrintf(" in attempt to access instance field %d (%s) in %s",
4712                                          field_idx, dex_file_->GetFieldName(field_id),
4713                                          dex_file_->GetFieldDeclaringClassDescriptor(field_id)));
4714     return nullptr;
4715   }
4716   if (klass_type.IsUnresolvedTypes()) {
4717     // Accessibility checks depend on resolved fields.
4718     DCHECK(klass_type.Equals(GetDeclaringClass()) ||
4719            !failures_.empty() ||
4720            IsSdkVersionSetAndLessThan(api_level_, SdkVersion::kP));
4721 
4722     return nullptr;  // Can't resolve Class so no more to do here
4723   }
4724   ClassLinker* class_linker = GetClassLinker();
4725   ArtField* field = class_linker->ResolveFieldJLS(field_idx, dex_cache_, class_loader_);
4726 
4727   // Record result of the field resolution attempt.
4728   VerifierDeps::MaybeRecordFieldResolution(*dex_file_, field_idx, field);
4729 
4730   if (field == nullptr) {
4731     VLOG(verifier) << "Unable to resolve instance field " << field_idx << " ("
4732               << dex_file_->GetFieldName(field_id) << ") in "
4733               << dex_file_->GetFieldDeclaringClassDescriptor(field_id);
4734     DCHECK(self_->IsExceptionPending());
4735     self_->ClearException();
4736     return nullptr;
4737   } else if (obj_type.IsZeroOrNull()) {
4738     // Cannot infer and check type, however, access will cause null pointer exception.
4739     // Fall through into a few last soft failure checks below.
4740   } else {
4741     std::string temp;
4742     ObjPtr<mirror::Class> klass = field->GetDeclaringClass();
4743     const RegType& field_klass =
4744         FromClass(klass->GetDescriptor(&temp), klass, klass->CannotBeAssignedFromOtherTypes());
4745     if (obj_type.IsUninitializedTypes()) {
4746       // Field accesses through uninitialized references are only allowable for constructors where
4747       // the field is declared in this class.
4748       // Note: this IsConstructor check is technically redundant, as UninitializedThis should only
4749       //       appear in constructors.
4750       if (!obj_type.IsUninitializedThisReference() ||
4751           !IsConstructor() ||
4752           !field_klass.Equals(GetDeclaringClass())) {
4753         Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "cannot access instance field " << field->PrettyField()
4754                                           << " of a not fully initialized object within the context"
4755                                           << " of " << dex_file_->PrettyMethod(dex_method_idx_);
4756         return nullptr;
4757       }
4758     } else if (!field_klass.IsAssignableFrom(obj_type, this)) {
4759       // Trying to access C1.field1 using reference of type C2, which is neither C1 or a sub-class
4760       // of C1. For resolution to occur the declared class of the field must be compatible with
4761       // obj_type, we've discovered this wasn't so, so report the field didn't exist.
4762       VerifyError type;
4763       bool is_aot = IsAotMode();
4764       if (is_aot && (field_klass.IsUnresolvedTypes() || obj_type.IsUnresolvedTypes())) {
4765         // Compiler & unresolved types involved, retry at runtime.
4766         type = VerifyError::VERIFY_ERROR_NO_CLASS;
4767       } else {
4768         // Classes known (resolved; and thus assignability check is precise), or we are at runtime
4769         // and still missing classes. This is a hard failure.
4770         type = VerifyError::VERIFY_ERROR_BAD_CLASS_HARD;
4771       }
4772       Fail(type) << "cannot access instance field " << field->PrettyField()
4773                  << " from object of type " << obj_type;
4774       return nullptr;
4775     }
4776   }
4777 
4778   // Few last soft failure checks.
4779   if (!GetDeclaringClass().CanAccessMember(field->GetDeclaringClass(),
4780                                            field->GetAccessFlags())) {
4781     Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot access instance field " << field->PrettyField()
4782                                     << " from " << GetDeclaringClass();
4783     return nullptr;
4784   } else if (field->IsStatic()) {
4785     Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected field " << field->PrettyField()
4786                                     << " to not be static";
4787     return nullptr;
4788   }
4789 
4790   return field;
4791 }
4792 
4793 template <bool kVerifierDebug>
4794 template <FieldAccessType kAccType>
VerifyISFieldAccess(const Instruction * inst,const RegType & insn_type,bool is_primitive,bool is_static)4795 void MethodVerifier<kVerifierDebug>::VerifyISFieldAccess(const Instruction* inst,
4796                                                          const RegType& insn_type,
4797                                                          bool is_primitive,
4798                                                          bool is_static) {
4799   uint32_t field_idx = GetFieldIdxOfFieldAccess(inst, is_static);
4800   ArtField* field;
4801   if (is_static) {
4802     field = GetStaticField(field_idx);
4803   } else {
4804     const RegType& object_type = work_line_->GetRegisterType(this, inst->VRegB_22c());
4805 
4806     // One is not allowed to access fields on uninitialized references, except to write to
4807     // fields in the constructor (before calling another constructor).
4808     // GetInstanceField does an assignability check which will fail for uninitialized types.
4809     // We thus modify the type if the uninitialized reference is a "this" reference (this also
4810     // checks at the same time that we're verifying a constructor).
4811     bool should_adjust = (kAccType == FieldAccessType::kAccPut) &&
4812                          object_type.IsUninitializedThisReference();
4813     const RegType& adjusted_type = should_adjust
4814                                        ? GetRegTypeCache()->FromUninitialized(object_type)
4815                                        : object_type;
4816     field = GetInstanceField(adjusted_type, field_idx);
4817     if (UNLIKELY(flags_.have_pending_hard_failure_)) {
4818       return;
4819     }
4820     if (should_adjust) {
4821       if (field == nullptr) {
4822         Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "Might be accessing a superclass instance field prior "
4823                                           << "to the superclass being initialized in "
4824                                           << dex_file_->PrettyMethod(dex_method_idx_);
4825       } else if (field->GetDeclaringClass() != GetDeclaringClass().GetClass()) {
4826         Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "cannot access superclass instance field "
4827                                           << field->PrettyField() << " of a not fully initialized "
4828                                           << "object within the context of "
4829                                           << dex_file_->PrettyMethod(dex_method_idx_);
4830         return;
4831       }
4832     }
4833   }
4834   const RegType* field_type = nullptr;
4835   if (field != nullptr) {
4836     if (kAccType == FieldAccessType::kAccPut) {
4837       if (field->IsFinal() && field->GetDeclaringClass() != GetDeclaringClass().GetClass()) {
4838         Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot modify final field " << field->PrettyField()
4839                                         << " from other class " << GetDeclaringClass();
4840         // Keep hunting for possible hard fails.
4841       }
4842     }
4843 
4844     ObjPtr<mirror::Class> field_type_class =
4845         can_load_classes_ ? field->ResolveType() : field->LookupResolvedType();
4846     if (field_type_class != nullptr) {
4847       field_type = &FromClass(field->GetTypeDescriptor(),
4848                               field_type_class,
4849                               field_type_class->CannotBeAssignedFromOtherTypes());
4850     } else {
4851       DCHECK(!can_load_classes_ || self_->IsExceptionPending());
4852       self_->ClearException();
4853     }
4854   } else if (IsSdkVersionSetAndAtLeast(api_level_, SdkVersion::kP)) {
4855     // If we don't have the field (it seems we failed resolution) and this is a PUT, we need to
4856     // redo verification at runtime as the field may be final, unless the field id shows it's in
4857     // the same class.
4858     //
4859     // For simplicity, it is OK to not distinguish compile-time vs runtime, and post this an
4860     // ACCESS_FIELD failure at runtime. This has the same effect as NO_FIELD - punting the class
4861     // to the access-checks interpreter.
4862     //
4863     // Note: see b/34966607. This and above may be changed in the future.
4864     if (kAccType == FieldAccessType::kAccPut) {
4865       const dex::FieldId& field_id = dex_file_->GetFieldId(field_idx);
4866       const char* field_class_descriptor = dex_file_->GetFieldDeclaringClassDescriptor(field_id);
4867       const RegType* field_class_type = &reg_types_.FromDescriptor(class_loader_.Get(),
4868                                                                    field_class_descriptor,
4869                                                                    false);
4870       if (!field_class_type->Equals(GetDeclaringClass())) {
4871         Fail(VERIFY_ERROR_ACCESS_FIELD) << "could not check field put for final field modify of "
4872                                         << field_class_descriptor
4873                                         << "."
4874                                         << dex_file_->GetFieldName(field_id)
4875                                         << " from other class "
4876                                         << GetDeclaringClass();
4877       }
4878     }
4879   }
4880   if (field_type == nullptr) {
4881     const dex::FieldId& field_id = dex_file_->GetFieldId(field_idx);
4882     const char* descriptor = dex_file_->GetFieldTypeDescriptor(field_id);
4883     field_type = &reg_types_.FromDescriptor(class_loader_.Get(), descriptor, false);
4884   }
4885   DCHECK(field_type != nullptr);
4886   const uint32_t vregA = (is_static) ? inst->VRegA_21c() : inst->VRegA_22c();
4887   static_assert(kAccType == FieldAccessType::kAccPut || kAccType == FieldAccessType::kAccGet,
4888                 "Unexpected third access type");
4889   if (kAccType == FieldAccessType::kAccPut) {
4890     // sput or iput.
4891     if (is_primitive) {
4892       VerifyPrimitivePut(*field_type, insn_type, vregA);
4893     } else {
4894       if (!insn_type.IsAssignableFrom(*field_type, this)) {
4895         // If the field type is not a reference, this is a global failure rather than
4896         // a class change failure as the instructions and the descriptors for the type
4897         // should have been consistent within the same file at compile time.
4898         VerifyError error = field_type->IsReferenceTypes() ? VERIFY_ERROR_BAD_CLASS_SOFT
4899                                                            : VERIFY_ERROR_BAD_CLASS_HARD;
4900         Fail(error) << "expected field " << ArtField::PrettyField(field)
4901                     << " to be compatible with type '" << insn_type
4902                     << "' but found type '" << *field_type
4903                     << "' in put-object";
4904         return;
4905       }
4906       work_line_->VerifyRegisterType(this, vregA, *field_type);
4907     }
4908   } else if (kAccType == FieldAccessType::kAccGet) {
4909     // sget or iget.
4910     if (is_primitive) {
4911       if (field_type->Equals(insn_type) ||
4912           (field_type->IsFloat() && insn_type.IsInteger()) ||
4913           (field_type->IsDouble() && insn_type.IsLong())) {
4914         // expected that read is of the correct primitive type or that int reads are reading
4915         // floats or long reads are reading doubles
4916       } else {
4917         // This is a global failure rather than a class change failure as the instructions and
4918         // the descriptors for the type should have been consistent within the same file at
4919         // compile time
4920         Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected field " << ArtField::PrettyField(field)
4921                                           << " to be of type '" << insn_type
4922                                           << "' but found type '" << *field_type << "' in get";
4923         return;
4924       }
4925     } else {
4926       if (!insn_type.IsAssignableFrom(*field_type, this)) {
4927         // If the field type is not a reference, this is a global failure rather than
4928         // a class change failure as the instructions and the descriptors for the type
4929         // should have been consistent within the same file at compile time.
4930         VerifyError error = field_type->IsReferenceTypes() ? VERIFY_ERROR_BAD_CLASS_SOFT
4931                                                            : VERIFY_ERROR_BAD_CLASS_HARD;
4932         Fail(error) << "expected field " << ArtField::PrettyField(field)
4933                     << " to be compatible with type '" << insn_type
4934                     << "' but found type '" << *field_type
4935                     << "' in get-object";
4936         if (error != VERIFY_ERROR_BAD_CLASS_HARD) {
4937           work_line_->SetRegisterType<LockOp::kClear>(this, vregA, reg_types_.Conflict());
4938         }
4939         return;
4940       }
4941     }
4942     if (!field_type->IsLowHalf()) {
4943       work_line_->SetRegisterType<LockOp::kClear>(this, vregA, *field_type);
4944     } else {
4945       work_line_->SetRegisterTypeWide(this, vregA, *field_type, field_type->HighHalf(&reg_types_));
4946     }
4947   } else {
4948     LOG(FATAL) << "Unexpected case.";
4949   }
4950 }
4951 
4952 template <bool kVerifierDebug>
UpdateRegisters(uint32_t next_insn,RegisterLine * merge_line,bool update_merge_line)4953 bool MethodVerifier<kVerifierDebug>::UpdateRegisters(uint32_t next_insn,
4954                                                      RegisterLine* merge_line,
4955                                                      bool update_merge_line) {
4956   bool changed = true;
4957   RegisterLine* target_line = reg_table_.GetLine(next_insn);
4958   if (!GetInstructionFlags(next_insn).IsVisitedOrChanged()) {
4959     /*
4960      * We haven't processed this instruction before, and we haven't touched the registers here, so
4961      * there's nothing to "merge". Copy the registers over and mark it as changed. (This is the
4962      * only way a register can transition out of "unknown", so this is not just an optimization.)
4963      */
4964     target_line->CopyFromLine(merge_line);
4965     if (GetInstructionFlags(next_insn).IsReturn()) {
4966       // Verify that the monitor stack is empty on return.
4967       merge_line->VerifyMonitorStackEmpty(this);
4968 
4969       // For returns we only care about the operand to the return, all other registers are dead.
4970       // Initialize them as conflicts so they don't add to GC and deoptimization information.
4971       const Instruction* ret_inst = &code_item_accessor_.InstructionAt(next_insn);
4972       AdjustReturnLine(this, ret_inst, target_line);
4973       // Directly bail if a hard failure was found.
4974       if (flags_.have_pending_hard_failure_) {
4975         return false;
4976       }
4977     }
4978   } else {
4979     RegisterLineArenaUniquePtr copy;
4980     if (kVerifierDebug) {
4981       copy.reset(RegisterLine::Create(target_line->NumRegs(), allocator_, GetRegTypeCache()));
4982       copy->CopyFromLine(target_line);
4983     }
4984     changed = target_line->MergeRegisters(this, merge_line);
4985     if (flags_.have_pending_hard_failure_) {
4986       return false;
4987     }
4988     if (kVerifierDebug && changed) {
4989       LogVerifyInfo() << "Merging at [" << reinterpret_cast<void*>(work_insn_idx_) << "]"
4990                       << " to [" << reinterpret_cast<void*>(next_insn) << "]: " << "\n"
4991                       << copy->Dump(this) << "  MERGE\n"
4992                       << merge_line->Dump(this) << "  ==\n"
4993                       << target_line->Dump(this);
4994     }
4995     if (update_merge_line && changed) {
4996       merge_line->CopyFromLine(target_line);
4997     }
4998   }
4999   if (changed) {
5000     GetModifiableInstructionFlags(next_insn).SetChanged();
5001   }
5002   return true;
5003 }
5004 
5005 template <bool kVerifierDebug>
GetMethodReturnType()5006 const RegType& MethodVerifier<kVerifierDebug>::GetMethodReturnType() {
5007   if (return_type_ == nullptr) {
5008     if (method_being_verified_ != nullptr) {
5009       ObjPtr<mirror::Class> return_type_class = can_load_classes_
5010           ? method_being_verified_->ResolveReturnType()
5011           : method_being_verified_->LookupResolvedReturnType();
5012       if (return_type_class != nullptr) {
5013         return_type_ = &FromClass(method_being_verified_->GetReturnTypeDescriptor(),
5014                                   return_type_class,
5015                                   return_type_class->CannotBeAssignedFromOtherTypes());
5016       } else {
5017         DCHECK(!can_load_classes_ || self_->IsExceptionPending());
5018         self_->ClearException();
5019       }
5020     }
5021     if (return_type_ == nullptr) {
5022       const dex::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx_);
5023       const dex::ProtoId& proto_id = dex_file_->GetMethodPrototype(method_id);
5024       dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
5025       const char* descriptor = dex_file_->GetTypeDescriptor(dex_file_->GetTypeId(return_type_idx));
5026       return_type_ = &reg_types_.FromDescriptor(class_loader_.Get(), descriptor, false);
5027     }
5028   }
5029   return *return_type_;
5030 }
5031 
5032 template <bool kVerifierDebug>
DetermineCat1Constant(int32_t value,bool precise)5033 const RegType& MethodVerifier<kVerifierDebug>::DetermineCat1Constant(int32_t value, bool precise) {
5034   if (precise) {
5035     // Precise constant type.
5036     return reg_types_.FromCat1Const(value, true);
5037   } else {
5038     // Imprecise constant type.
5039     if (value < -32768) {
5040       return reg_types_.IntConstant();
5041     } else if (value < -128) {
5042       return reg_types_.ShortConstant();
5043     } else if (value < 0) {
5044       return reg_types_.ByteConstant();
5045     } else if (value == 0) {
5046       return reg_types_.Zero();
5047     } else if (value == 1) {
5048       return reg_types_.One();
5049     } else if (value < 128) {
5050       return reg_types_.PosByteConstant();
5051     } else if (value < 32768) {
5052       return reg_types_.PosShortConstant();
5053     } else if (value < 65536) {
5054       return reg_types_.CharConstant();
5055     } else {
5056       return reg_types_.IntConstant();
5057     }
5058   }
5059 }
5060 
5061 }  // namespace
5062 }  // namespace impl
5063 
MethodVerifier(Thread * self,ClassLinker * class_linker,ArenaPool * arena_pool,const DexFile * dex_file,const dex::CodeItem * code_item,uint32_t dex_method_idx,bool can_load_classes,bool allow_thread_suspension,bool allow_soft_failures,bool aot_mode)5064 MethodVerifier::MethodVerifier(Thread* self,
5065                                ClassLinker* class_linker,
5066                                ArenaPool* arena_pool,
5067                                const DexFile* dex_file,
5068                                const dex::CodeItem* code_item,
5069                                uint32_t dex_method_idx,
5070                                bool can_load_classes,
5071                                bool allow_thread_suspension,
5072                                bool allow_soft_failures,
5073                                bool aot_mode)
5074     : self_(self),
5075       arena_stack_(arena_pool),
5076       allocator_(&arena_stack_),
5077       reg_types_(class_linker, can_load_classes, allocator_, allow_thread_suspension),
5078       reg_table_(allocator_),
5079       work_insn_idx_(dex::kDexNoIndex),
5080       dex_method_idx_(dex_method_idx),
5081       dex_file_(dex_file),
5082       code_item_accessor_(*dex_file, code_item),
5083       // TODO: make it designated initialization when we compile as C++20.
5084       flags_({false, false, false, false, aot_mode}),
5085       encountered_failure_types_(0),
5086       can_load_classes_(can_load_classes),
5087       allow_soft_failures_(allow_soft_failures),
5088       has_check_casts_(false),
5089       class_linker_(class_linker),
5090       link_(nullptr) {
5091   self->PushVerifier(this);
5092 }
5093 
~MethodVerifier()5094 MethodVerifier::~MethodVerifier() {
5095   Thread::Current()->PopVerifier(this);
5096   STLDeleteElements(&failure_messages_);
5097 }
5098 
VerifyMethod(Thread * self,ClassLinker * class_linker,ArenaPool * arena_pool,uint32_t method_idx,const DexFile * dex_file,Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader,const dex::ClassDef & class_def,const dex::CodeItem * code_item,ArtMethod * method,uint32_t method_access_flags,CompilerCallbacks * callbacks,VerifierCallback * verifier_callback,bool allow_soft_failures,HardFailLogMode log_level,bool need_precise_constants,uint32_t api_level,bool aot_mode,std::string * hard_failure_msg)5099 MethodVerifier::FailureData MethodVerifier::VerifyMethod(Thread* self,
5100                                                          ClassLinker* class_linker,
5101                                                          ArenaPool* arena_pool,
5102                                                          uint32_t method_idx,
5103                                                          const DexFile* dex_file,
5104                                                          Handle<mirror::DexCache> dex_cache,
5105                                                          Handle<mirror::ClassLoader> class_loader,
5106                                                          const dex::ClassDef& class_def,
5107                                                          const dex::CodeItem* code_item,
5108                                                          ArtMethod* method,
5109                                                          uint32_t method_access_flags,
5110                                                          CompilerCallbacks* callbacks,
5111                                                          VerifierCallback* verifier_callback,
5112                                                          bool allow_soft_failures,
5113                                                          HardFailLogMode log_level,
5114                                                          bool need_precise_constants,
5115                                                          uint32_t api_level,
5116                                                          bool aot_mode,
5117                                                          std::string* hard_failure_msg) {
5118   if (VLOG_IS_ON(verifier_debug)) {
5119     return VerifyMethod<true>(self,
5120                               class_linker,
5121                               arena_pool,
5122                               method_idx,
5123                               dex_file,
5124                               dex_cache,
5125                               class_loader,
5126                               class_def,
5127                               code_item,
5128                               method,
5129                               method_access_flags,
5130                               callbacks,
5131                               verifier_callback,
5132                               allow_soft_failures,
5133                               log_level,
5134                               need_precise_constants,
5135                               api_level,
5136                               aot_mode,
5137                               hard_failure_msg);
5138   } else {
5139     return VerifyMethod<false>(self,
5140                                class_linker,
5141                                arena_pool,
5142                                method_idx,
5143                                dex_file,
5144                                dex_cache,
5145                                class_loader,
5146                                class_def,
5147                                code_item,
5148                                method,
5149                                method_access_flags,
5150                                callbacks,
5151                                verifier_callback,
5152                                allow_soft_failures,
5153                                log_level,
5154                                need_precise_constants,
5155                                api_level,
5156                                aot_mode,
5157                                hard_failure_msg);
5158   }
5159 }
5160 
5161 // Return whether the runtime knows how to execute a method without needing to
5162 // re-verify it at runtime (and therefore save on first use of the class). We
5163 // currently only support it for access checks, where the runtime will mark the
5164 // methods as needing access checks and have the interpreter execute with them.
5165 // The AOT/JIT compiled code is not affected.
CanRuntimeHandleVerificationFailure(uint32_t encountered_failure_types)5166 static inline bool CanRuntimeHandleVerificationFailure(uint32_t encountered_failure_types) {
5167   constexpr uint32_t unresolved_mask =
5168       verifier::VerifyError::VERIFY_ERROR_ACCESS_CLASS |
5169       verifier::VerifyError::VERIFY_ERROR_ACCESS_FIELD |
5170       verifier::VerifyError::VERIFY_ERROR_ACCESS_METHOD;
5171   return (encountered_failure_types & (~unresolved_mask)) == 0;
5172 }
5173 
5174 template <bool kVerifierDebug>
VerifyMethod(Thread * self,ClassLinker * class_linker,ArenaPool * arena_pool,uint32_t method_idx,const DexFile * dex_file,Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader,const dex::ClassDef & class_def,const dex::CodeItem * code_item,ArtMethod * method,uint32_t method_access_flags,CompilerCallbacks * callbacks,VerifierCallback * verifier_callback,bool allow_soft_failures,HardFailLogMode log_level,bool need_precise_constants,uint32_t api_level,bool aot_mode,std::string * hard_failure_msg)5175 MethodVerifier::FailureData MethodVerifier::VerifyMethod(Thread* self,
5176                                                          ClassLinker* class_linker,
5177                                                          ArenaPool* arena_pool,
5178                                                          uint32_t method_idx,
5179                                                          const DexFile* dex_file,
5180                                                          Handle<mirror::DexCache> dex_cache,
5181                                                          Handle<mirror::ClassLoader> class_loader,
5182                                                          const dex::ClassDef& class_def,
5183                                                          const dex::CodeItem* code_item,
5184                                                          ArtMethod* method,
5185                                                          uint32_t method_access_flags,
5186                                                          CompilerCallbacks* callbacks,
5187                                                          VerifierCallback* verifier_callback,
5188                                                          bool allow_soft_failures,
5189                                                          HardFailLogMode log_level,
5190                                                          bool need_precise_constants,
5191                                                          uint32_t api_level,
5192                                                          bool aot_mode,
5193                                                          std::string* hard_failure_msg) {
5194   MethodVerifier::FailureData result;
5195   uint64_t start_ns = kTimeVerifyMethod ? NanoTime() : 0;
5196 
5197   impl::MethodVerifier<kVerifierDebug> verifier(self,
5198                                                 class_linker,
5199                                                 arena_pool,
5200                                                 dex_file,
5201                                                 code_item,
5202                                                 method_idx,
5203                                                 /* can_load_classes= */ true,
5204                                                 /* allow_thread_suspension= */ true,
5205                                                 allow_soft_failures,
5206                                                 aot_mode,
5207                                                 dex_cache,
5208                                                 class_loader,
5209                                                 class_def,
5210                                                 method,
5211                                                 method_access_flags,
5212                                                 need_precise_constants,
5213                                                 /* verify to dump */ false,
5214                                                 /* fill_register_lines= */ false,
5215                                                 api_level);
5216   if (verifier.Verify()) {
5217     // Verification completed, however failures may be pending that didn't cause the verification
5218     // to hard fail.
5219     CHECK(!verifier.flags_.have_pending_hard_failure_);
5220 
5221     if (code_item != nullptr && callbacks != nullptr) {
5222       // Let the interested party know that the method was verified.
5223       callbacks->MethodVerified(&verifier);
5224     }
5225 
5226     bool set_dont_compile = false;
5227     if (verifier.failures_.size() != 0) {
5228       if (VLOG_IS_ON(verifier)) {
5229         verifier.DumpFailures(VLOG_STREAM(verifier) << "Soft verification failures in "
5230                                                     << dex_file->PrettyMethod(method_idx) << "\n");
5231       }
5232       if (kVerifierDebug) {
5233         LOG(INFO) << verifier.info_messages_.str();
5234         verifier.Dump(LOG_STREAM(INFO));
5235       }
5236       if (CanRuntimeHandleVerificationFailure(verifier.encountered_failure_types_)) {
5237         result.kind = FailureKind::kAccessChecksFailure;
5238       } else {
5239         result.kind = FailureKind::kSoftFailure;
5240       }
5241       if (method != nullptr &&
5242           !CanCompilerHandleVerificationFailure(verifier.encountered_failure_types_)) {
5243         set_dont_compile = true;
5244       }
5245     }
5246     if (method != nullptr) {
5247       if (verifier.HasInstructionThatWillThrow()) {
5248         set_dont_compile = true;
5249         if (aot_mode && (callbacks != nullptr) && !callbacks->IsBootImage()) {
5250           // When compiling apps, make HasInstructionThatWillThrow a soft error to trigger
5251           // re-verification at runtime.
5252           // The dead code after the throw is not verified and might be invalid. This may cause
5253           // the JIT compiler to crash since it assumes that all the code is valid.
5254           //
5255           // There's a strong assumption that the entire boot image is verified and all its dex
5256           // code is valid (even the dead and unverified one). As such this is done only for apps.
5257           // (CompilerDriver DCHECKs in VerifyClassVisitor that methods from boot image are
5258           // fully verified).
5259           result.kind = FailureKind::kSoftFailure;
5260         }
5261       }
5262       bool must_count_locks = false;
5263       if ((verifier.encountered_failure_types_ & VerifyError::VERIFY_ERROR_LOCKING) != 0) {
5264         must_count_locks = true;
5265       }
5266       verifier_callback->SetDontCompile(method, set_dont_compile);
5267       verifier_callback->SetMustCountLocks(method, must_count_locks);
5268     }
5269   } else {
5270     // Bad method data.
5271     CHECK_NE(verifier.failures_.size(), 0U);
5272 
5273     if (UNLIKELY(verifier.flags_.have_pending_experimental_failure_)) {
5274       // Failed due to being forced into interpreter. This is ok because
5275       // we just want to skip verification.
5276       result.kind = FailureKind::kSoftFailure;
5277     } else {
5278       CHECK(verifier.flags_.have_pending_hard_failure_);
5279       if (VLOG_IS_ON(verifier)) {
5280         log_level = std::max(HardFailLogMode::kLogVerbose, log_level);
5281       }
5282       if (log_level >= HardFailLogMode::kLogVerbose) {
5283         LogSeverity severity;
5284         switch (log_level) {
5285           case HardFailLogMode::kLogVerbose:
5286             severity = LogSeverity::VERBOSE;
5287             break;
5288           case HardFailLogMode::kLogWarning:
5289             severity = LogSeverity::WARNING;
5290             break;
5291           case HardFailLogMode::kLogInternalFatal:
5292             severity = LogSeverity::FATAL_WITHOUT_ABORT;
5293             break;
5294           default:
5295             LOG(FATAL) << "Unsupported log-level " << static_cast<uint32_t>(log_level);
5296             UNREACHABLE();
5297         }
5298         verifier.DumpFailures(LOG_STREAM(severity) << "Verification error in "
5299                                                    << dex_file->PrettyMethod(method_idx)
5300                                                    << "\n");
5301       }
5302       if (hard_failure_msg != nullptr) {
5303         CHECK(!verifier.failure_messages_.empty());
5304         *hard_failure_msg =
5305             verifier.failure_messages_[verifier.failure_messages_.size() - 1]->str();
5306       }
5307       result.kind = FailureKind::kHardFailure;
5308 
5309       if (callbacks != nullptr) {
5310         // Let the interested party know that we failed the class.
5311         ClassReference ref(dex_file, dex_file->GetIndexForClassDef(class_def));
5312         callbacks->ClassRejected(ref);
5313       }
5314     }
5315     if (kVerifierDebug || VLOG_IS_ON(verifier)) {
5316       LOG(ERROR) << verifier.info_messages_.str();
5317       verifier.Dump(LOG_STREAM(ERROR));
5318     }
5319     // Under verifier-debug, dump the complete log into the error message.
5320     if (kVerifierDebug && hard_failure_msg != nullptr) {
5321       hard_failure_msg->append("\n");
5322       hard_failure_msg->append(verifier.info_messages_.str());
5323       hard_failure_msg->append("\n");
5324       std::ostringstream oss;
5325       verifier.Dump(oss);
5326       hard_failure_msg->append(oss.str());
5327     }
5328   }
5329   if (kTimeVerifyMethod) {
5330     uint64_t duration_ns = NanoTime() - start_ns;
5331     if (duration_ns > MsToNs(Runtime::Current()->GetVerifierLoggingThresholdMs())) {
5332       double bytecodes_per_second =
5333           verifier.code_item_accessor_.InsnsSizeInCodeUnits() / (duration_ns * 1e-9);
5334       LOG(WARNING) << "Verification of " << dex_file->PrettyMethod(method_idx)
5335                    << " took " << PrettyDuration(duration_ns)
5336                    << (impl::IsLargeMethod(verifier.CodeItem()) ? " (large method)" : "")
5337                    << " (" << StringPrintf("%.2f", bytecodes_per_second) << " bytecodes/s)"
5338                    << " (" << verifier.allocator_.ApproximatePeakBytes()
5339                    << "B approximate peak alloc)";
5340     }
5341   }
5342   result.types = verifier.encountered_failure_types_;
5343   return result;
5344 }
5345 
CalculateVerificationInfo(Thread * self,ArtMethod * method,Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader)5346 MethodVerifier* MethodVerifier::CalculateVerificationInfo(
5347       Thread* self,
5348       ArtMethod* method,
5349       Handle<mirror::DexCache> dex_cache,
5350       Handle<mirror::ClassLoader> class_loader) {
5351   std::unique_ptr<impl::MethodVerifier<false>> verifier(
5352       new impl::MethodVerifier<false>(self,
5353                                       Runtime::Current()->GetClassLinker(),
5354                                       Runtime::Current()->GetArenaPool(),
5355                                       method->GetDexFile(),
5356                                       method->GetCodeItem(),
5357                                       method->GetDexMethodIndex(),
5358                                       /* can_load_classes= */ false,
5359                                       /* allow_thread_suspension= */ false,
5360                                       /* allow_soft_failures= */ true,
5361                                       Runtime::Current()->IsAotCompiler(),
5362                                       dex_cache,
5363                                       class_loader,
5364                                       *method->GetDeclaringClass()->GetClassDef(),
5365                                       method,
5366                                       method->GetAccessFlags(),
5367                                       /* need_precise_constants= */ true,
5368                                       /* verify_to_dump= */ false,
5369                                       /* fill_register_lines= */ true,
5370                                       // Just use the verifier at the current skd-version.
5371                                       // This might affect what soft-verifier errors are reported.
5372                                       // Callers can then filter out relevant errors if needed.
5373                                       Runtime::Current()->GetTargetSdkVersion()));
5374   verifier->Verify();
5375   if (VLOG_IS_ON(verifier)) {
5376     verifier->DumpFailures(VLOG_STREAM(verifier));
5377     VLOG(verifier) << verifier->info_messages_.str();
5378     verifier->Dump(VLOG_STREAM(verifier));
5379   }
5380   if (verifier->flags_.have_pending_hard_failure_) {
5381     return nullptr;
5382   } else {
5383     return verifier.release();
5384   }
5385 }
5386 
VerifyMethodAndDump(Thread * self,VariableIndentationOutputStream * vios,uint32_t dex_method_idx,const DexFile * dex_file,Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader,const dex::ClassDef & class_def,const dex::CodeItem * code_item,ArtMethod * method,uint32_t method_access_flags,uint32_t api_level)5387 MethodVerifier* MethodVerifier::VerifyMethodAndDump(Thread* self,
5388                                                     VariableIndentationOutputStream* vios,
5389                                                     uint32_t dex_method_idx,
5390                                                     const DexFile* dex_file,
5391                                                     Handle<mirror::DexCache> dex_cache,
5392                                                     Handle<mirror::ClassLoader> class_loader,
5393                                                     const dex::ClassDef& class_def,
5394                                                     const dex::CodeItem* code_item,
5395                                                     ArtMethod* method,
5396                                                     uint32_t method_access_flags,
5397                                                     uint32_t api_level) {
5398   impl::MethodVerifier<false>* verifier = new impl::MethodVerifier<false>(
5399       self,
5400       Runtime::Current()->GetClassLinker(),
5401       Runtime::Current()->GetArenaPool(),
5402       dex_file,
5403       code_item,
5404       dex_method_idx,
5405       /* can_load_classes= */ true,
5406       /* allow_thread_suspension= */ true,
5407       /* allow_soft_failures= */ true,
5408       Runtime::Current()->IsAotCompiler(),
5409       dex_cache,
5410       class_loader,
5411       class_def,
5412       method,
5413       method_access_flags,
5414       /* need_precise_constants= */ true,
5415       /* verify_to_dump= */ true,
5416       /* fill_register_lines= */ false,
5417       api_level);
5418   verifier->Verify();
5419   verifier->DumpFailures(vios->Stream());
5420   vios->Stream() << verifier->info_messages_.str();
5421   // Only dump and return if no hard failures. Otherwise the verifier may be not fully initialized
5422   // and querying any info is dangerous/can abort.
5423   if (verifier->flags_.have_pending_hard_failure_) {
5424     delete verifier;
5425     return nullptr;
5426   } else {
5427     verifier->Dump(vios);
5428     return verifier;
5429   }
5430 }
5431 
FindLocksAtDexPc(ArtMethod * m,uint32_t dex_pc,std::vector<MethodVerifier::DexLockInfo> * monitor_enter_dex_pcs,uint32_t api_level)5432 void MethodVerifier::FindLocksAtDexPc(
5433     ArtMethod* m,
5434     uint32_t dex_pc,
5435     std::vector<MethodVerifier::DexLockInfo>* monitor_enter_dex_pcs,
5436     uint32_t api_level) {
5437   StackHandleScope<2> hs(Thread::Current());
5438   Handle<mirror::DexCache> dex_cache(hs.NewHandle(m->GetDexCache()));
5439   Handle<mirror::ClassLoader> class_loader(hs.NewHandle(m->GetClassLoader()));
5440   impl::MethodVerifier<false> verifier(hs.Self(),
5441                                        Runtime::Current()->GetClassLinker(),
5442                                        Runtime::Current()->GetArenaPool(),
5443                                        m->GetDexFile(),
5444                                        m->GetCodeItem(),
5445                                        m->GetDexMethodIndex(),
5446                                        /* can_load_classes= */ false,
5447                                        /* allow_thread_suspension= */ false,
5448                                        /* allow_soft_failures= */ true,
5449                                        Runtime::Current()->IsAotCompiler(),
5450                                        dex_cache,
5451                                        class_loader,
5452                                        m->GetClassDef(),
5453                                        m,
5454                                        m->GetAccessFlags(),
5455                                        /* need_precise_constants= */ false,
5456                                        /* verify_to_dump= */ false,
5457                                        /* fill_register_lines= */ false,
5458                                        api_level);
5459   verifier.interesting_dex_pc_ = dex_pc;
5460   verifier.monitor_enter_dex_pcs_ = monitor_enter_dex_pcs;
5461   verifier.FindLocksAtDexPc();
5462 }
5463 
CreateVerifier(Thread * self,const DexFile * dex_file,Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader,const dex::ClassDef & class_def,const dex::CodeItem * code_item,uint32_t method_idx,ArtMethod * method,uint32_t access_flags,bool can_load_classes,bool allow_soft_failures,bool need_precise_constants,bool verify_to_dump,bool allow_thread_suspension,uint32_t api_level)5464 MethodVerifier* MethodVerifier::CreateVerifier(Thread* self,
5465                                                const DexFile* dex_file,
5466                                                Handle<mirror::DexCache> dex_cache,
5467                                                Handle<mirror::ClassLoader> class_loader,
5468                                                const dex::ClassDef& class_def,
5469                                                const dex::CodeItem* code_item,
5470                                                uint32_t method_idx,
5471                                                ArtMethod* method,
5472                                                uint32_t access_flags,
5473                                                bool can_load_classes,
5474                                                bool allow_soft_failures,
5475                                                bool need_precise_constants,
5476                                                bool verify_to_dump,
5477                                                bool allow_thread_suspension,
5478                                                uint32_t api_level) {
5479   return new impl::MethodVerifier<false>(self,
5480                                          Runtime::Current()->GetClassLinker(),
5481                                          Runtime::Current()->GetArenaPool(),
5482                                          dex_file,
5483                                          code_item,
5484                                          method_idx,
5485                                          can_load_classes,
5486                                          allow_thread_suspension,
5487                                          allow_soft_failures,
5488                                          Runtime::Current()->IsAotCompiler(),
5489                                          dex_cache,
5490                                          class_loader,
5491                                          class_def,
5492                                          method,
5493                                          access_flags,
5494                                          need_precise_constants,
5495                                          verify_to_dump,
5496                                          /* fill_register_lines= */ false,
5497                                          api_level);
5498 }
5499 
Init(ClassLinker * class_linker)5500 void MethodVerifier::Init(ClassLinker* class_linker) {
5501   art::verifier::RegTypeCache::Init(class_linker);
5502 }
5503 
Shutdown()5504 void MethodVerifier::Shutdown() {
5505   verifier::RegTypeCache::ShutDown();
5506 }
5507 
VisitStaticRoots(RootVisitor * visitor)5508 void MethodVerifier::VisitStaticRoots(RootVisitor* visitor) {
5509   RegTypeCache::VisitStaticRoots(visitor);
5510 }
5511 
VisitRoots(RootVisitor * visitor,const RootInfo & root_info)5512 void MethodVerifier::VisitRoots(RootVisitor* visitor, const RootInfo& root_info) {
5513   reg_types_.VisitRoots(visitor, root_info);
5514 }
5515 
Fail(VerifyError error,bool pending_exc)5516 std::ostream& MethodVerifier::Fail(VerifyError error, bool pending_exc) {
5517   // Mark the error type as encountered.
5518   encountered_failure_types_ |= static_cast<uint32_t>(error);
5519 
5520   if (pending_exc) {
5521     switch (error) {
5522       case VERIFY_ERROR_NO_CLASS:
5523       case VERIFY_ERROR_NO_FIELD:
5524       case VERIFY_ERROR_NO_METHOD:
5525       case VERIFY_ERROR_ACCESS_CLASS:
5526       case VERIFY_ERROR_ACCESS_FIELD:
5527       case VERIFY_ERROR_ACCESS_METHOD:
5528       case VERIFY_ERROR_INSTANTIATION:
5529       case VERIFY_ERROR_CLASS_CHANGE:
5530       case VERIFY_ERROR_FORCE_INTERPRETER:
5531       case VERIFY_ERROR_LOCKING:
5532         if (IsAotMode() || !can_load_classes_) {
5533           if (error != VERIFY_ERROR_ACCESS_CLASS &&
5534               error != VERIFY_ERROR_ACCESS_FIELD &&
5535               error != VERIFY_ERROR_ACCESS_METHOD) {
5536             // If we're optimistically running verification at compile time, turn NO_xxx,
5537             // class change and instantiation errors into soft verification errors so that we
5538             // re-verify at runtime. We may fail to find or to agree on access because of not yet
5539             // available class loaders, or class loaders that will differ at runtime. In these
5540             // cases, we don't want to affect the soundness of the code being compiled. Instead, the
5541             // generated code runs "slow paths" that dynamically perform the verification and cause
5542             // the behavior to be that akin to an interpreter.
5543             error = VERIFY_ERROR_BAD_CLASS_SOFT;
5544           }
5545         } else {
5546           // If we fail again at runtime, mark that this instruction would throw and force this
5547           // method to be executed using the interpreter with checks.
5548           flags_.have_pending_runtime_throw_failure_ = true;
5549         }
5550         // How to handle runtime failures for instructions that are not flagged kThrow.
5551         //
5552         // The verifier may fail before we touch any instruction, for the signature of a method. So
5553         // add a check.
5554         if (work_insn_idx_ < dex::kDexNoIndex) {
5555           const Instruction& inst = code_item_accessor_.InstructionAt(work_insn_idx_);
5556           Instruction::Code opcode = inst.Opcode();
5557           if ((Instruction::FlagsOf(opcode) & Instruction::kThrow) == 0 &&
5558               !impl::IsCompatThrow(opcode) &&
5559               GetInstructionFlags(work_insn_idx_).IsInTry()) {
5560             if (Runtime::Current()->IsVerifierMissingKThrowFatal()) {
5561               LOG(FATAL) << "Unexpected throw: " << std::hex << work_insn_idx_ << " " << opcode;
5562               UNREACHABLE();
5563             }
5564             // We need to save the work_line if the instruction wasn't throwing before. Otherwise
5565             // we'll try to merge garbage.
5566             // Note: this assumes that Fail is called before we do any work_line modifications.
5567             saved_line_->CopyFromLine(work_line_.get());
5568           }
5569         }
5570         break;
5571 
5572         // Indication that verification should be retried at runtime.
5573       case VERIFY_ERROR_BAD_CLASS_SOFT:
5574         if (!allow_soft_failures_) {
5575           flags_.have_pending_hard_failure_ = true;
5576         }
5577         break;
5578 
5579         // Hard verification failures at compile time will still fail at runtime, so the class is
5580         // marked as rejected to prevent it from being compiled.
5581       case VERIFY_ERROR_BAD_CLASS_HARD: {
5582         flags_.have_pending_hard_failure_ = true;
5583         break;
5584       }
5585 
5586       case VERIFY_ERROR_SKIP_COMPILER:
5587         // Nothing to do, just remember the failure type.
5588         break;
5589     }
5590   } else if (kIsDebugBuild) {
5591     CHECK_NE(error, VERIFY_ERROR_BAD_CLASS_SOFT);
5592     CHECK_NE(error, VERIFY_ERROR_BAD_CLASS_HARD);
5593   }
5594 
5595   failures_.push_back(error);
5596   std::string location(StringPrintf("%s: [0x%X] ", dex_file_->PrettyMethod(dex_method_idx_).c_str(),
5597                                     work_insn_idx_));
5598   std::ostringstream* failure_message = new std::ostringstream(location, std::ostringstream::ate);
5599   failure_messages_.push_back(failure_message);
5600   return *failure_message;
5601 }
5602 
LogVerifyInfo()5603 ScopedNewLine MethodVerifier::LogVerifyInfo() {
5604   ScopedNewLine ret{info_messages_};
5605   ret << "VFY: " << dex_file_->PrettyMethod(dex_method_idx_)
5606       << '[' << reinterpret_cast<void*>(work_insn_idx_) << "] : ";
5607   return ret;
5608 }
5609 
FailureKindMax(FailureKind fk1,FailureKind fk2)5610 static FailureKind FailureKindMax(FailureKind fk1, FailureKind fk2) {
5611   static_assert(FailureKind::kNoFailure < FailureKind::kSoftFailure
5612                     && FailureKind::kSoftFailure < FailureKind::kHardFailure,
5613                 "Unexpected FailureKind order");
5614   return std::max(fk1, fk2);
5615 }
5616 
Merge(const MethodVerifier::FailureData & fd)5617 void MethodVerifier::FailureData::Merge(const MethodVerifier::FailureData& fd) {
5618   kind = FailureKindMax(kind, fd.kind);
5619   types |= fd.types;
5620 }
5621 
5622 }  // namespace verifier
5623 }  // namespace art
5624