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