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