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 #ifndef ART_RUNTIME_VERIFIER_METHOD_VERIFIER_H_
18 #define ART_RUNTIME_VERIFIER_METHOD_VERIFIER_H_
19 
20 #include <memory>
21 #include <set>
22 #include <vector>
23 
24 #include "base/casts.h"
25 #include "base/macros.h"
26 #include "base/stl_util.h"
27 #include "class_reference.h"
28 #include "dex_file.h"
29 #include "dex_instruction.h"
30 #include "instruction_flags.h"
31 #include "method_reference.h"
32 #include "reg_type.h"
33 #include "reg_type_cache.h"
34 #include "register_line.h"
35 #include "safe_map.h"
36 
37 namespace art {
38 
39 struct ReferenceMap2Visitor;
40 template<class T> class Handle;
41 
42 namespace verifier {
43 
44 class MethodVerifier;
45 class DexPcToReferenceMap;
46 
47 /*
48  * "Direct" and "virtual" methods are stored independently. The type of call used to invoke the
49  * method determines which list we search, and whether we travel up into superclasses.
50  *
51  * (<clinit>, <init>, and methods declared "private" or "static" are stored in the "direct" list.
52  * All others are stored in the "virtual" list.)
53  */
54 enum MethodType {
55   METHOD_UNKNOWN  = 0,
56   METHOD_DIRECT,      // <init>, private
57   METHOD_STATIC,      // static
58   METHOD_VIRTUAL,     // virtual, super
59   METHOD_INTERFACE    // interface
60 };
61 std::ostream& operator<<(std::ostream& os, const MethodType& rhs);
62 
63 /*
64  * An enumeration of problems that can turn up during verification.
65  * Both VERIFY_ERROR_BAD_CLASS_SOFT and VERIFY_ERROR_BAD_CLASS_HARD denote failures that cause
66  * the entire class to be rejected. However, VERIFY_ERROR_BAD_CLASS_SOFT denotes a soft failure
67  * that can potentially be corrected, and the verifier will try again at runtime.
68  * VERIFY_ERROR_BAD_CLASS_HARD denotes a hard failure that can't be corrected, and will cause
69  * the class to remain uncompiled. Other errors denote verification errors that cause bytecode
70  * to be rewritten to fail at runtime.
71  */
72 enum VerifyError {
73   VERIFY_ERROR_BAD_CLASS_HARD,  // VerifyError; hard error that skips compilation.
74   VERIFY_ERROR_BAD_CLASS_SOFT,  // VerifyError; soft error that verifies again at runtime.
75 
76   VERIFY_ERROR_NO_CLASS,        // NoClassDefFoundError.
77   VERIFY_ERROR_NO_FIELD,        // NoSuchFieldError.
78   VERIFY_ERROR_NO_METHOD,       // NoSuchMethodError.
79   VERIFY_ERROR_ACCESS_CLASS,    // IllegalAccessError.
80   VERIFY_ERROR_ACCESS_FIELD,    // IllegalAccessError.
81   VERIFY_ERROR_ACCESS_METHOD,   // IllegalAccessError.
82   VERIFY_ERROR_CLASS_CHANGE,    // IncompatibleClassChangeError.
83   VERIFY_ERROR_INSTANTIATION,   // InstantiationError.
84 };
85 std::ostream& operator<<(std::ostream& os, const VerifyError& rhs);
86 
87 /*
88  * Identifies the type of reference in the instruction that generated the verify error
89  * (e.g. VERIFY_ERROR_ACCESS_CLASS could come from a method, field, or class reference).
90  *
91  * This must fit in two bits.
92  */
93 enum VerifyErrorRefType {
94   VERIFY_ERROR_REF_CLASS  = 0,
95   VERIFY_ERROR_REF_FIELD  = 1,
96   VERIFY_ERROR_REF_METHOD = 2,
97 };
98 const int kVerifyErrorRefTypeShift = 6;
99 
100 // We don't need to store the register data for many instructions, because we either only need
101 // it at branch points (for verification) or GC points and branches (for verification +
102 // type-precise register analysis).
103 enum RegisterTrackingMode {
104   kTrackRegsBranches,
105   kTrackCompilerInterestPoints,
106   kTrackRegsAll,
107 };
108 
109 // A mapping from a dex pc to the register line statuses as they are immediately prior to the
110 // execution of that instruction.
111 class PcToRegisterLineTable {
112  public:
PcToRegisterLineTable()113   PcToRegisterLineTable() : size_(0) {}
114   ~PcToRegisterLineTable();
115 
116   // Initialize the RegisterTable. Every instruction address can have a different set of information
117   // about what's in which register, but for verification purposes we only need to store it at
118   // branch target addresses (because we merge into that).
119   void Init(RegisterTrackingMode mode, InstructionFlags* flags, uint32_t insns_size,
120             uint16_t registers_size, MethodVerifier* verifier);
121 
GetLine(size_t idx)122   RegisterLine* GetLine(size_t idx) {
123     DCHECK_LT(idx, size_);
124     return register_lines_[idx];
125   }
126 
127  private:
128   std::unique_ptr<RegisterLine*[]> register_lines_;
129   size_t size_;
130 };
131 
132 // The verifier
133 class MethodVerifier {
134  public:
135   enum FailureKind {
136     kNoFailure,
137     kSoftFailure,
138     kHardFailure,
139   };
140 
141   /* Verify a class. Returns "kNoFailure" on success. */
142   static FailureKind VerifyClass(mirror::Class* klass, bool allow_soft_failures, std::string* error)
143       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
144   static FailureKind VerifyClass(const DexFile* dex_file, Handle<mirror::DexCache> dex_cache,
145                                  Handle<mirror::ClassLoader> class_loader,
146                                  const DexFile::ClassDef* class_def,
147                                  bool allow_soft_failures, std::string* error)
148       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
149 
150   static MethodVerifier* VerifyMethodAndDump(std::ostream& os, uint32_t method_idx,
151                                              const DexFile* dex_file,
152                                              Handle<mirror::DexCache> dex_cache,
153                                              Handle<mirror::ClassLoader> class_loader,
154                                              const DexFile::ClassDef* class_def,
155                                              const DexFile::CodeItem* code_item,
156                                              mirror::ArtMethod* method,
157                                              uint32_t method_access_flags)
158       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
159 
160   uint8_t EncodePcToReferenceMapData() const;
161 
DexFileVersion()162   uint32_t DexFileVersion() const {
163     return dex_file_->GetVersion();
164   }
165 
GetRegTypeCache()166   RegTypeCache* GetRegTypeCache() {
167     return &reg_types_;
168   }
169 
170   // Log a verification failure.
171   std::ostream& Fail(VerifyError error);
172 
173   // Log for verification information.
174   std::ostream& LogVerifyInfo();
175 
176   // Dump the failures encountered by the verifier.
177   std::ostream& DumpFailures(std::ostream& os);
178 
179   // Dump the state of the verifier, namely each instruction, what flags are set on it, register
180   // information
181   void Dump(std::ostream& os) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
182 
183   // Fills 'monitor_enter_dex_pcs' with the dex pcs of the monitor-enter instructions corresponding
184   // to the locks held at 'dex_pc' in method 'm'.
185   static void FindLocksAtDexPc(mirror::ArtMethod* m, uint32_t dex_pc,
186                                std::vector<uint32_t>* monitor_enter_dex_pcs)
187       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
188 
189   // Returns the accessed field corresponding to the quick instruction's field
190   // offset at 'dex_pc' in method 'm'.
191   static mirror::ArtField* FindAccessedFieldAtDexPc(mirror::ArtMethod* m, uint32_t dex_pc)
192       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
193 
194   // Returns the invoked method corresponding to the quick instruction's vtable
195   // index at 'dex_pc' in method 'm'.
196   static mirror::ArtMethod* FindInvokedMethodAtDexPc(mirror::ArtMethod* m, uint32_t dex_pc)
197       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
198 
199   static void Init() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
200   static void Shutdown();
201 
CanLoadClasses()202   bool CanLoadClasses() const {
203     return can_load_classes_;
204   }
205 
MethodVerifier(const DexFile * dex_file,Handle<mirror::DexCache> * dex_cache,Handle<mirror::ClassLoader> * class_loader,const DexFile::ClassDef * class_def,const DexFile::CodeItem * code_item,uint32_t method_idx,mirror::ArtMethod * method,uint32_t access_flags,bool can_load_classes,bool allow_soft_failures,bool need_precise_constants)206   MethodVerifier(const DexFile* dex_file, Handle<mirror::DexCache>* dex_cache,
207                  Handle<mirror::ClassLoader>* class_loader, const DexFile::ClassDef* class_def,
208                  const DexFile::CodeItem* code_item, uint32_t method_idx, mirror::ArtMethod* method,
209                  uint32_t access_flags, bool can_load_classes, bool allow_soft_failures,
210                  bool need_precise_constants) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
211       : MethodVerifier(dex_file, dex_cache, class_loader, class_def, code_item, method_idx, method,
212                        access_flags, can_load_classes, allow_soft_failures, need_precise_constants,
213                        false) {}
214 
215   ~MethodVerifier();
216 
217   // Run verification on the method. Returns true if verification completes and false if the input
218   // has an irrecoverable corruption.
219   bool Verify() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
220 
221   // Describe VRegs at the given dex pc.
222   std::vector<int32_t> DescribeVRegs(uint32_t dex_pc);
223 
224   static void VisitStaticRoots(RootCallback* callback, void* arg)
225       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
226   void VisitRoots(RootCallback* callback, void* arg) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
227 
228   // Accessors used by the compiler via CompilerCallback
229   const DexFile::CodeItem* CodeItem() const;
230   RegisterLine* GetRegLine(uint32_t dex_pc);
231   const InstructionFlags& GetInstructionFlags(size_t index) const;
232   mirror::ClassLoader* GetClassLoader() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
233   mirror::DexCache* GetDexCache() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
234   MethodReference GetMethodReference() const;
235   uint32_t GetAccessFlags() const;
236   bool HasCheckCasts() const;
237   bool HasVirtualOrInterfaceInvokes() const;
238   bool HasFailures() const;
239   RegType& ResolveCheckedClass(uint32_t class_idx)
240       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
241 
242  private:
243   // Private constructor for dumping.
244   MethodVerifier(const DexFile* dex_file, Handle<mirror::DexCache>* dex_cache,
245                  Handle<mirror::ClassLoader>* class_loader, const DexFile::ClassDef* class_def,
246                  const DexFile::CodeItem* code_item, uint32_t method_idx, mirror::ArtMethod* method,
247                  uint32_t access_flags, bool can_load_classes, bool allow_soft_failures,
248                  bool need_precise_constants, bool verify_to_dump)
249       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
250 
251   // Adds the given string to the beginning of the last failure message.
252   void PrependToLastFailMessage(std::string);
253 
254   // Adds the given string to the end of the last failure message.
255   void AppendToLastFailMessage(std::string);
256 
257   /*
258    * Perform verification on a single method.
259    *
260    * We do this in three passes:
261    *  (1) Walk through all code units, determining instruction locations,
262    *      widths, and other characteristics.
263    *  (2) Walk through all code units, performing static checks on
264    *      operands.
265    *  (3) Iterate through the method, checking type safety and looking
266    *      for code flow problems.
267    */
268   static FailureKind VerifyMethod(uint32_t method_idx, const DexFile* dex_file,
269                                   Handle<mirror::DexCache> dex_cache,
270                                   Handle<mirror::ClassLoader> class_loader,
271                                   const DexFile::ClassDef* class_def_idx,
272                                   const DexFile::CodeItem* code_item,
273                                   mirror::ArtMethod* method, uint32_t method_access_flags,
274                                   bool allow_soft_failures, bool need_precise_constants)
275       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
276 
277   void FindLocksAtDexPc() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
278 
279   mirror::ArtField* FindAccessedFieldAtDexPc(uint32_t dex_pc)
280       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
281 
282   mirror::ArtMethod* FindInvokedMethodAtDexPc(uint32_t dex_pc)
283       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
284 
285   /*
286    * Compute the width of the instruction at each address in the instruction stream, and store it in
287    * insn_flags_. Addresses that are in the middle of an instruction, or that are part of switch
288    * table data, are not touched (so the caller should probably initialize "insn_flags" to zero).
289    *
290    * The "new_instance_count_" and "monitor_enter_count_" fields in vdata are also set.
291    *
292    * Performs some static checks, notably:
293    * - opcode of first instruction begins at index 0
294    * - only documented instructions may appear
295    * - each instruction follows the last
296    * - last byte of last instruction is at (code_length-1)
297    *
298    * Logs an error and returns "false" on failure.
299    */
300   bool ComputeWidthsAndCountOps();
301 
302   /*
303    * Set the "in try" flags for all instructions protected by "try" statements. Also sets the
304    * "branch target" flags for exception handlers.
305    *
306    * Call this after widths have been set in "insn_flags".
307    *
308    * Returns "false" if something in the exception table looks fishy, but we're expecting the
309    * exception table to be somewhat sane.
310    */
311   bool ScanTryCatchBlocks() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
312 
313   /*
314    * Perform static verification on all instructions in a method.
315    *
316    * Walks through instructions in a method calling VerifyInstruction on each.
317    */
318   bool VerifyInstructions();
319 
320   /*
321    * Perform static verification on an instruction.
322    *
323    * As a side effect, this sets the "branch target" flags in InsnFlags.
324    *
325    * "(CF)" items are handled during code-flow analysis.
326    *
327    * v3 4.10.1
328    * - target of each jump and branch instruction must be valid
329    * - targets of switch statements must be valid
330    * - operands referencing constant pool entries must be valid
331    * - (CF) operands of getfield, putfield, getstatic, putstatic must be valid
332    * - (CF) operands of method invocation instructions must be valid
333    * - (CF) only invoke-direct can call a method starting with '<'
334    * - (CF) <clinit> must never be called explicitly
335    * - operands of instanceof, checkcast, new (and variants) must be valid
336    * - new-array[-type] limited to 255 dimensions
337    * - can't use "new" on an array class
338    * - (?) limit dimensions in multi-array creation
339    * - local variable load/store register values must be in valid range
340    *
341    * v3 4.11.1.2
342    * - branches must be within the bounds of the code array
343    * - targets of all control-flow instructions are the start of an instruction
344    * - register accesses fall within range of allocated registers
345    * - (N/A) access to constant pool must be of appropriate type
346    * - code does not end in the middle of an instruction
347    * - execution cannot fall off the end of the code
348    * - (earlier) for each exception handler, the "try" area must begin and
349    *   end at the start of an instruction (end can be at the end of the code)
350    * - (earlier) for each exception handler, the handler must start at a valid
351    *   instruction
352    */
353   bool VerifyInstruction(const Instruction* inst, uint32_t code_offset);
354 
355   /* Ensure that the register index is valid for this code item. */
356   bool CheckRegisterIndex(uint32_t idx);
357 
358   /* Ensure that the wide register index is valid for this code item. */
359   bool CheckWideRegisterIndex(uint32_t idx);
360 
361   // Perform static checks on a field Get or set instruction. All we do here is ensure that the
362   // field index is in the valid range.
363   bool CheckFieldIndex(uint32_t idx);
364 
365   // Perform static checks on a method invocation instruction. All we do here is ensure that the
366   // method index is in the valid range.
367   bool CheckMethodIndex(uint32_t idx);
368 
369   // Perform static checks on a "new-instance" instruction. Specifically, make sure the class
370   // reference isn't for an array class.
371   bool CheckNewInstance(uint32_t idx);
372 
373   /* Ensure that the string index is in the valid range. */
374   bool CheckStringIndex(uint32_t idx);
375 
376   // Perform static checks on an instruction that takes a class constant. Ensure that the class
377   // index is in the valid range.
378   bool CheckTypeIndex(uint32_t idx);
379 
380   // Perform static checks on a "new-array" instruction. Specifically, make sure they aren't
381   // creating an array of arrays that causes the number of dimensions to exceed 255.
382   bool CheckNewArray(uint32_t idx);
383 
384   // Verify an array data table. "cur_offset" is the offset of the fill-array-data instruction.
385   bool CheckArrayData(uint32_t cur_offset);
386 
387   // Verify that the target of a branch instruction is valid. We don't expect code to jump directly
388   // into an exception handler, but it's valid to do so as long as the target isn't a
389   // "move-exception" instruction. We verify that in a later stage.
390   // The dex format forbids certain instructions from branching to themselves.
391   // Updates "insn_flags_", setting the "branch target" flag.
392   bool CheckBranchTarget(uint32_t cur_offset);
393 
394   // Verify a switch table. "cur_offset" is the offset of the switch instruction.
395   // Updates "insn_flags_", setting the "branch target" flag.
396   bool CheckSwitchTargets(uint32_t cur_offset);
397 
398   // Check the register indices used in a "vararg" instruction, such as invoke-virtual or
399   // filled-new-array.
400   // - vA holds word count (0-5), args[] have values.
401   // There are some tests we don't do here, e.g. we don't try to verify that invoking a method that
402   // takes a double is done with consecutive registers. This requires parsing the target method
403   // signature, which we will be doing later on during the code flow analysis.
404   bool CheckVarArgRegs(uint32_t vA, uint32_t arg[]);
405 
406   // Check the register indices used in a "vararg/range" instruction, such as invoke-virtual/range
407   // or filled-new-array/range.
408   // - vA holds word count, vC holds index of first reg.
409   bool CheckVarArgRangeRegs(uint32_t vA, uint32_t vC);
410 
411   // Extract the relative offset from a branch instruction.
412   // Returns "false" on failure (e.g. this isn't a branch instruction).
413   bool GetBranchOffset(uint32_t cur_offset, int32_t* pOffset, bool* pConditional,
414                        bool* selfOkay);
415 
416   /* Perform detailed code-flow analysis on a single method. */
417   bool VerifyCodeFlow() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
418 
419   // Set the register types for the first instruction in the method based on the method signature.
420   // This has the side-effect of validating the signature.
421   bool SetTypesFromSignature() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
422 
423   /*
424    * Perform code flow on a method.
425    *
426    * The basic strategy is as outlined in v3 4.11.1.2: set the "changed" bit on the first
427    * instruction, process it (setting additional "changed" bits), and repeat until there are no
428    * more.
429    *
430    * v3 4.11.1.1
431    * - (N/A) operand stack is always the same size
432    * - operand stack [registers] contain the correct types of values
433    * - local variables [registers] contain the correct types of values
434    * - methods are invoked with the appropriate arguments
435    * - fields are assigned using values of appropriate types
436    * - opcodes have the correct type values in operand registers
437    * - there is never an uninitialized class instance in a local variable in code protected by an
438    *   exception handler (operand stack is okay, because the operand stack is discarded when an
439    *   exception is thrown) [can't know what's a local var w/o the debug info -- should fall out of
440    *   register typing]
441    *
442    * v3 4.11.1.2
443    * - execution cannot fall off the end of the code
444    *
445    * (We also do many of the items described in the "static checks" sections, because it's easier to
446    * do them here.)
447    *
448    * We need an array of RegType values, one per register, for every instruction. If the method uses
449    * monitor-enter, we need extra data for every register, and a stack for every "interesting"
450    * instruction. In theory this could become quite large -- up to several megabytes for a monster
451    * function.
452    *
453    * NOTE:
454    * The spec forbids backward branches when there's an uninitialized reference in a register. The
455    * idea is to prevent something like this:
456    *   loop:
457    *     move r1, r0
458    *     new-instance r0, MyClass
459    *     ...
460    *     if-eq rN, loop  // once
461    *   initialize r0
462    *
463    * This leaves us with two different instances, both allocated by the same instruction, but only
464    * one is initialized. The scheme outlined in v3 4.11.1.4 wouldn't catch this, so they work around
465    * it by preventing backward branches. We achieve identical results without restricting code
466    * reordering by specifying that you can't execute the new-instance instruction if a register
467    * contains an uninitialized instance created by that same instruction.
468    */
469   bool CodeFlowVerifyMethod() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
470 
471   /*
472    * Perform verification for a single instruction.
473    *
474    * This requires fully decoding the instruction to determine the effect it has on registers.
475    *
476    * Finds zero or more following instructions and sets the "changed" flag if execution at that
477    * point needs to be (re-)evaluated. Register changes are merged into "reg_types_" at the target
478    * addresses. Does not set or clear any other flags in "insn_flags_".
479    */
480   bool CodeFlowVerifyInstruction(uint32_t* start_guess)
481       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
482 
483   // Perform verification of a new array instruction
484   void VerifyNewArray(const Instruction* inst, bool is_filled, bool is_range)
485       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
486 
487   // Helper to perform verification on puts of primitive type.
488   void VerifyPrimitivePut(RegType& target_type, RegType& insn_type,
489                           const uint32_t vregA) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
490 
491   // Perform verification of an aget instruction. The destination register's type will be set to
492   // be that of component type of the array unless the array type is unknown, in which case a
493   // bottom type inferred from the type of instruction is used. is_primitive is false for an
494   // aget-object.
495   void VerifyAGet(const Instruction* inst, RegType& insn_type,
496                   bool is_primitive) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
497 
498   // Perform verification of an aput instruction.
499   void VerifyAPut(const Instruction* inst, RegType& insn_type,
500                   bool is_primitive) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
501 
502   // Lookup instance field and fail for resolution violations
503   mirror::ArtField* GetInstanceField(RegType& obj_type, int field_idx)
504       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
505 
506   // Lookup static field and fail for resolution violations
507   mirror::ArtField* GetStaticField(int field_idx) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
508 
509   // Perform verification of an iget/sget/iput/sput instruction.
510   enum class FieldAccessType {  // private
511     kAccGet,
512     kAccPut
513   };
514   template <FieldAccessType kAccType>
515   void VerifyISFieldAccess(const Instruction* inst, RegType& insn_type,
516                            bool is_primitive, bool is_static)
517       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
518 
519   // Returns the access field of a quick field access (iget/iput-quick) or nullptr
520   // if it cannot be found.
521   mirror::ArtField* GetQuickFieldAccess(const Instruction* inst, RegisterLine* reg_line)
522       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
523 
524   template <FieldAccessType kAccType>
525   void VerifyQuickFieldAccess(const Instruction* inst, RegType& insn_type, bool is_primitive)
526       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
527 
528   // Resolves a class based on an index and performs access checks to ensure the referrer can
529   // access the resolved class.
530   RegType& ResolveClassAndCheckAccess(uint32_t class_idx)
531       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
532 
533   /*
534    * For the "move-exception" instruction at "work_insn_idx_", which must be at an exception handler
535    * address, determine the Join of all exceptions that can land here. Fails if no matching
536    * exception handler can be found or if the Join of exception types fails.
537    */
538   RegType& GetCaughtExceptionType()
539       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
540 
541   /*
542    * Resolves a method based on an index and performs access checks to ensure
543    * the referrer can access the resolved method.
544    * Does not throw exceptions.
545    */
546   mirror::ArtMethod* ResolveMethodAndCheckAccess(uint32_t method_idx, MethodType method_type)
547       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
548 
549   /*
550    * Verify the arguments to a method. We're executing in "method", making
551    * a call to the method reference in vB.
552    *
553    * If this is a "direct" invoke, we allow calls to <init>. For calls to
554    * <init>, the first argument may be an uninitialized reference. Otherwise,
555    * calls to anything starting with '<' will be rejected, as will any
556    * uninitialized reference arguments.
557    *
558    * For non-static method calls, this will verify that the method call is
559    * appropriate for the "this" argument.
560    *
561    * The method reference is in vBBBB. The "is_range" parameter determines
562    * whether we use 0-4 "args" values or a range of registers defined by
563    * vAA and vCCCC.
564    *
565    * Widening conversions on integers and references are allowed, but
566    * narrowing conversions are not.
567    *
568    * Returns the resolved method on success, nullptr on failure (with *failure
569    * set appropriately).
570    */
571   mirror::ArtMethod* VerifyInvocationArgs(const Instruction* inst,
572                                           MethodType method_type,
573                                           bool is_range, bool is_super)
574       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
575 
576   // Similar checks to the above, but on the proto. Will be used when the method cannot be
577   // resolved.
578   void VerifyInvocationArgsUnresolvedMethod(const Instruction* inst, MethodType method_type,
579                                             bool is_range)
580       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
581 
582   template <class T>
583   mirror::ArtMethod* VerifyInvocationArgsFromIterator(T* it, const Instruction* inst,
584                                                       MethodType method_type, bool is_range,
585                                                       mirror::ArtMethod* res_method)
586       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
587 
588   mirror::ArtMethod* GetQuickInvokedMethod(const Instruction* inst,
589                                            RegisterLine* reg_line,
590                                            bool is_range)
591       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
592 
593   mirror::ArtMethod* VerifyInvokeVirtualQuickArgs(const Instruction* inst, bool is_range)
594   SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
595 
596   /*
597    * Verify that the target instruction is not "move-exception". It's important that the only way
598    * to execute a move-exception is as the first instruction of an exception handler.
599    * Returns "true" if all is well, "false" if the target instruction is move-exception.
600    */
601   bool CheckNotMoveException(const uint16_t* insns, int insn_idx);
602 
603   /*
604   * Control can transfer to "next_insn". Merge the registers from merge_line into the table at
605   * next_insn, and set the changed flag on the target address if any of the registers were changed.
606   * In the case of fall-through, update the merge line on a change as its the working line for the
607   * next instruction.
608   * Returns "false" if an error is encountered.
609   */
610   bool UpdateRegisters(uint32_t next_insn, RegisterLine* merge_line, bool update_merge_line)
611       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
612 
613   // Is the method being verified a constructor?
IsConstructor()614   bool IsConstructor() const {
615     return (method_access_flags_ & kAccConstructor) != 0;
616   }
617 
618   // Is the method verified static?
IsStatic()619   bool IsStatic() const {
620     return (method_access_flags_ & kAccStatic) != 0;
621   }
622 
623   // Return the register type for the method.
624   RegType& GetMethodReturnType() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
625 
626   // Get a type representing the declaring class of the method.
627   RegType& GetDeclaringClass() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
628 
629   InstructionFlags* CurrentInsnFlags();
630 
631   RegType& DetermineCat1Constant(int32_t value, bool precise)
632       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
633 
634   RegTypeCache reg_types_;
635 
636   PcToRegisterLineTable reg_table_;
637 
638   // Storage for the register status we're currently working on.
639   std::unique_ptr<RegisterLine> work_line_;
640 
641   // The address of the instruction we're currently working on, note that this is in 2 byte
642   // quantities
643   uint32_t work_insn_idx_;
644 
645   // Storage for the register status we're saving for later.
646   std::unique_ptr<RegisterLine> saved_line_;
647 
648   const uint32_t dex_method_idx_;  // The method we're working on.
649   // Its object representation if known.
650   mirror::ArtMethod* mirror_method_ GUARDED_BY(Locks::mutator_lock_);
651   const uint32_t method_access_flags_;  // Method's access flags.
652   RegType* return_type_;  // Lazily computed return type of the method.
653   const DexFile* const dex_file_;  // The dex file containing the method.
654   // The dex_cache for the declaring class of the method.
655   Handle<mirror::DexCache>* dex_cache_ GUARDED_BY(Locks::mutator_lock_);
656   // The class loader for the declaring class of the method.
657   Handle<mirror::ClassLoader>* class_loader_ GUARDED_BY(Locks::mutator_lock_);
658   const DexFile::ClassDef* const class_def_;  // The class def of the declaring class of the method.
659   const DexFile::CodeItem* const code_item_;  // The code item containing the code for the method.
660   RegType* declaring_class_;  // Lazily computed reg type of the method's declaring class.
661   // Instruction widths and flags, one entry per code unit.
662   std::unique_ptr<InstructionFlags[]> insn_flags_;
663   // The dex PC of a FindLocksAtDexPc request, -1 otherwise.
664   uint32_t interesting_dex_pc_;
665   // The container into which FindLocksAtDexPc should write the registers containing held locks,
666   // nullptr if we're not doing FindLocksAtDexPc.
667   std::vector<uint32_t>* monitor_enter_dex_pcs_;
668 
669   // The types of any error that occurs.
670   std::vector<VerifyError> failures_;
671   // Error messages associated with failures.
672   std::vector<std::ostringstream*> failure_messages_;
673   // Is there a pending hard failure?
674   bool have_pending_hard_failure_;
675   // Is there a pending runtime throw failure? A runtime throw failure is when an instruction
676   // would fail at runtime throwing an exception. Such an instruction causes the following code
677   // to be unreachable. This is set by Fail and used to ensure we don't process unreachable
678   // instructions that would hard fail the verification.
679   bool have_pending_runtime_throw_failure_;
680 
681   // Info message log use primarily for verifier diagnostics.
682   std::ostringstream info_messages_;
683 
684   // The number of occurrences of specific opcodes.
685   size_t new_instance_count_;
686   size_t monitor_enter_count_;
687 
688   const bool can_load_classes_;
689 
690   // Converts soft failures to hard failures when false. Only false when the compiler isn't
691   // running and the verifier is called from the class linker.
692   const bool allow_soft_failures_;
693 
694   // An optimization where instead of generating unique RegTypes for constants we use imprecise
695   // constants that cover a range of constants. This isn't good enough for deoptimization that
696   // avoids loading from registers in the case of a constant as the dex instruction set lost the
697   // notion of whether a value should be in a floating point or general purpose register file.
698   const bool need_precise_constants_;
699 
700   // Indicates the method being verified contains at least one check-cast or aput-object
701   // instruction. Aput-object operations implicitly check for array-store exceptions, similar to
702   // check-cast.
703   bool has_check_casts_;
704 
705   // Indicates the method being verified contains at least one invoke-virtual/range
706   // or invoke-interface/range.
707   bool has_virtual_or_interface_invokes_;
708 
709   // Indicates whether we verify to dump the info. In that case we accept quickened instructions
710   // even though we might detect to be a compiler. Should only be set when running
711   // VerifyMethodAndDump.
712   const bool verify_to_dump_;
713 };
714 std::ostream& operator<<(std::ostream& os, const MethodVerifier::FailureKind& rhs);
715 
716 }  // namespace verifier
717 }  // namespace art
718 
719 #endif  // ART_RUNTIME_VERIFIER_METHOD_VERIFIER_H_
720