Home | History | Annotate | Download | only in verifier
      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 <sstream>
     22 #include <vector>
     23 
     24 #include "base/arena_allocator.h"
     25 #include "base/macros.h"
     26 #include "base/scoped_arena_containers.h"
     27 #include "base/value_object.h"
     28 #include "dex/code_item_accessors.h"
     29 #include "dex/dex_file.h"
     30 #include "dex/dex_file_types.h"
     31 #include "dex/method_reference.h"
     32 #include "handle.h"
     33 #include "instruction_flags.h"
     34 #include "reg_type_cache.h"
     35 #include "register_line.h"
     36 #include "verifier_enums.h"
     37 
     38 namespace art {
     39 
     40 class ClassLinker;
     41 class CompilerCallbacks;
     42 class Instruction;
     43 struct ReferenceMap2Visitor;
     44 class Thread;
     45 class VariableIndentationOutputStream;
     46 
     47 namespace mirror {
     48 class DexCache;
     49 }  // namespace mirror
     50 
     51 namespace verifier {
     52 
     53 class MethodVerifier;
     54 class RegisterLine;
     55 using RegisterLineArenaUniquePtr = std::unique_ptr<RegisterLine, RegisterLineArenaDelete>;
     56 class RegType;
     57 
     58 // We don't need to store the register data for many instructions, because we either only need
     59 // it at branch points (for verification) or GC points and branches (for verification +
     60 // type-precise register analysis).
     61 enum RegisterTrackingMode {
     62   kTrackRegsBranches,
     63   kTrackCompilerInterestPoints,
     64   kTrackRegsAll,
     65 };
     66 
     67 // A mapping from a dex pc to the register line statuses as they are immediately prior to the
     68 // execution of that instruction.
     69 class PcToRegisterLineTable {
     70  public:
     71   explicit PcToRegisterLineTable(ScopedArenaAllocator& allocator);
     72   ~PcToRegisterLineTable();
     73 
     74   // Initialize the RegisterTable. Every instruction address can have a different set of information
     75   // about what's in which register, but for verification purposes we only need to store it at
     76   // branch target addresses (because we merge into that).
     77   void Init(RegisterTrackingMode mode, InstructionFlags* flags, uint32_t insns_size,
     78             uint16_t registers_size, MethodVerifier* verifier);
     79 
     80   bool IsInitialized() const {
     81     return !register_lines_.empty();
     82   }
     83 
     84   RegisterLine* GetLine(size_t idx) const {
     85     return register_lines_[idx].get();
     86   }
     87 
     88  private:
     89   ScopedArenaVector<RegisterLineArenaUniquePtr> register_lines_;
     90 
     91   DISALLOW_COPY_AND_ASSIGN(PcToRegisterLineTable);
     92 };
     93 
     94 // The verifier
     95 class MethodVerifier {
     96  public:
     97   // Verify a class. Returns "kNoFailure" on success.
     98   static FailureKind VerifyClass(Thread* self,
     99                                  mirror::Class* klass,
    100                                  CompilerCallbacks* callbacks,
    101                                  bool allow_soft_failures,
    102                                  HardFailLogMode log_level,
    103                                  std::string* error)
    104       REQUIRES_SHARED(Locks::mutator_lock_);
    105   static FailureKind VerifyClass(Thread* self,
    106                                  const DexFile* dex_file,
    107                                  Handle<mirror::DexCache> dex_cache,
    108                                  Handle<mirror::ClassLoader> class_loader,
    109                                  const DexFile::ClassDef& class_def,
    110                                  CompilerCallbacks* callbacks,
    111                                  bool allow_soft_failures,
    112                                  HardFailLogMode log_level,
    113                                  std::string* error)
    114       REQUIRES_SHARED(Locks::mutator_lock_);
    115 
    116   static MethodVerifier* VerifyMethodAndDump(Thread* self,
    117                                              VariableIndentationOutputStream* vios,
    118                                              uint32_t method_idx,
    119                                              const DexFile* dex_file,
    120                                              Handle<mirror::DexCache> dex_cache,
    121                                              Handle<mirror::ClassLoader> class_loader,
    122                                              const DexFile::ClassDef& class_def,
    123                                              const DexFile::CodeItem* code_item, ArtMethod* method,
    124                                              uint32_t method_access_flags)
    125       REQUIRES_SHARED(Locks::mutator_lock_);
    126 
    127   uint8_t EncodePcToReferenceMapData() const;
    128 
    129   const DexFile& GetDexFile() const {
    130     DCHECK(dex_file_ != nullptr);
    131     return *dex_file_;
    132   }
    133 
    134   RegTypeCache* GetRegTypeCache() {
    135     return &reg_types_;
    136   }
    137 
    138   // Log a verification failure.
    139   std::ostream& Fail(VerifyError error);
    140 
    141   // Log for verification information.
    142   std::ostream& LogVerifyInfo();
    143 
    144   // Dump the failures encountered by the verifier.
    145   std::ostream& DumpFailures(std::ostream& os);
    146 
    147   // Dump the state of the verifier, namely each instruction, what flags are set on it, register
    148   // information
    149   void Dump(std::ostream& os) REQUIRES_SHARED(Locks::mutator_lock_);
    150   void Dump(VariableIndentationOutputStream* vios) REQUIRES_SHARED(Locks::mutator_lock_);
    151 
    152   // Information structure for a lock held at a certain point in time.
    153   struct DexLockInfo {
    154     // The registers aliasing the lock.
    155     std::set<uint32_t> dex_registers;
    156     // The dex PC of the monitor-enter instruction.
    157     uint32_t dex_pc;
    158 
    159     explicit DexLockInfo(uint32_t dex_pc_in) {
    160       dex_pc = dex_pc_in;
    161     }
    162   };
    163   // Fills 'monitor_enter_dex_pcs' with the dex pcs of the monitor-enter instructions corresponding
    164   // to the locks held at 'dex_pc' in method 'm'.
    165   // Note: this is the only situation where the verifier will visit quickened instructions.
    166   static void FindLocksAtDexPc(ArtMethod* m, uint32_t dex_pc,
    167                                std::vector<DexLockInfo>* monitor_enter_dex_pcs)
    168       REQUIRES_SHARED(Locks::mutator_lock_);
    169 
    170   static void Init() REQUIRES_SHARED(Locks::mutator_lock_);
    171   static void Shutdown();
    172 
    173   bool CanLoadClasses() const {
    174     return can_load_classes_;
    175   }
    176 
    177   ~MethodVerifier();
    178 
    179   // Run verification on the method. Returns true if verification completes and false if the input
    180   // has an irrecoverable corruption.
    181   bool Verify() REQUIRES_SHARED(Locks::mutator_lock_);
    182 
    183   // Describe VRegs at the given dex pc.
    184   std::vector<int32_t> DescribeVRegs(uint32_t dex_pc);
    185 
    186   static void VisitStaticRoots(RootVisitor* visitor)
    187       REQUIRES_SHARED(Locks::mutator_lock_);
    188   void VisitRoots(RootVisitor* visitor, const RootInfo& roots)
    189       REQUIRES_SHARED(Locks::mutator_lock_);
    190 
    191   // Accessors used by the compiler via CompilerCallback
    192   const CodeItemDataAccessor& CodeItem() const {
    193     return code_item_accessor_;
    194   }
    195   RegisterLine* GetRegLine(uint32_t dex_pc);
    196   ALWAYS_INLINE const InstructionFlags& GetInstructionFlags(size_t index) const;
    197   ALWAYS_INLINE InstructionFlags& GetInstructionFlags(size_t index);
    198   mirror::ClassLoader* GetClassLoader() REQUIRES_SHARED(Locks::mutator_lock_);
    199   mirror::DexCache* GetDexCache() REQUIRES_SHARED(Locks::mutator_lock_);
    200   ArtMethod* GetMethod() const;
    201   MethodReference GetMethodReference() const;
    202   uint32_t GetAccessFlags() const;
    203   bool HasCheckCasts() const;
    204   bool HasVirtualOrInterfaceInvokes() const;
    205   bool HasFailures() const;
    206   bool HasInstructionThatWillThrow() const {
    207     return have_any_pending_runtime_throw_failure_;
    208   }
    209 
    210   const RegType& ResolveCheckedClass(dex::TypeIndex class_idx)
    211       REQUIRES_SHARED(Locks::mutator_lock_);
    212   // Returns the method index of an invoke instruction.
    213   uint16_t GetMethodIdxOfInvoke(const Instruction* inst)
    214       REQUIRES_SHARED(Locks::mutator_lock_);
    215   // Returns the field index of a field access instruction.
    216   uint16_t GetFieldIdxOfFieldAccess(const Instruction* inst, bool is_static)
    217       REQUIRES_SHARED(Locks::mutator_lock_);
    218 
    219   uint32_t GetEncounteredFailureTypes() {
    220     return encountered_failure_types_;
    221   }
    222 
    223   bool IsInstanceConstructor() const {
    224     return IsConstructor() && !IsStatic();
    225   }
    226 
    227   ScopedArenaAllocator& GetScopedAllocator() {
    228     return allocator_;
    229   }
    230 
    231  private:
    232   MethodVerifier(Thread* self,
    233                  const DexFile* dex_file,
    234                  Handle<mirror::DexCache> dex_cache,
    235                  Handle<mirror::ClassLoader> class_loader,
    236                  const DexFile::ClassDef& class_def,
    237                  const DexFile::CodeItem* code_item,
    238                  uint32_t method_idx,
    239                  ArtMethod* method,
    240                  uint32_t access_flags,
    241                  bool can_load_classes,
    242                  bool allow_soft_failures,
    243                  bool need_precise_constants,
    244                  bool verify_to_dump,
    245                  bool allow_thread_suspension)
    246       REQUIRES_SHARED(Locks::mutator_lock_);
    247 
    248   void UninstantiableError(const char* descriptor);
    249   static bool IsInstantiableOrPrimitive(ObjPtr<mirror::Class> klass)
    250       REQUIRES_SHARED(Locks::mutator_lock_);
    251 
    252   // Is the method being verified a constructor? See the comment on the field.
    253   bool IsConstructor() const {
    254     return is_constructor_;
    255   }
    256 
    257   // Is the method verified static?
    258   bool IsStatic() const {
    259     return (method_access_flags_ & kAccStatic) != 0;
    260   }
    261 
    262   // Adds the given string to the beginning of the last failure message.
    263   void PrependToLastFailMessage(std::string);
    264 
    265   // Adds the given string to the end of the last failure message.
    266   void AppendToLastFailMessage(const std::string& append);
    267 
    268   // Verification result for method(s). Includes a (maximum) failure kind, and (the union of)
    269   // all failure types.
    270   struct FailureData : ValueObject {
    271     FailureKind kind = FailureKind::kNoFailure;
    272     uint32_t types = 0U;
    273 
    274     // Merge src into this. Uses the most severe failure kind, and the union of types.
    275     void Merge(const FailureData& src);
    276   };
    277 
    278   // Verify all direct or virtual methods of a class. The method assumes that the iterator is
    279   // positioned correctly, and the iterator will be updated.
    280   template <bool kDirect>
    281   static FailureData VerifyMethods(Thread* self,
    282                                    ClassLinker* linker,
    283                                    const DexFile* dex_file,
    284                                    const DexFile::ClassDef& class_def,
    285                                    ClassDataItemIterator* it,
    286                                    Handle<mirror::DexCache> dex_cache,
    287                                    Handle<mirror::ClassLoader> class_loader,
    288                                    CompilerCallbacks* callbacks,
    289                                    bool allow_soft_failures,
    290                                    HardFailLogMode log_level,
    291                                    bool need_precise_constants,
    292                                    std::string* error_string)
    293       REQUIRES_SHARED(Locks::mutator_lock_);
    294 
    295   /*
    296    * Perform verification on a single method.
    297    *
    298    * We do this in three passes:
    299    *  (1) Walk through all code units, determining instruction locations,
    300    *      widths, and other characteristics.
    301    *  (2) Walk through all code units, performing static checks on
    302    *      operands.
    303    *  (3) Iterate through the method, checking type safety and looking
    304    *      for code flow problems.
    305    */
    306   static FailureData VerifyMethod(Thread* self,
    307                                   uint32_t method_idx,
    308                                   const DexFile* dex_file,
    309                                   Handle<mirror::DexCache> dex_cache,
    310                                   Handle<mirror::ClassLoader> class_loader,
    311                                   const DexFile::ClassDef& class_def_idx,
    312                                   const DexFile::CodeItem* code_item,
    313                                   ArtMethod* method,
    314                                   uint32_t method_access_flags,
    315                                   CompilerCallbacks* callbacks,
    316                                   bool allow_soft_failures,
    317                                   HardFailLogMode log_level,
    318                                   bool need_precise_constants,
    319                                   std::string* hard_failure_msg)
    320       REQUIRES_SHARED(Locks::mutator_lock_);
    321 
    322   void FindLocksAtDexPc() REQUIRES_SHARED(Locks::mutator_lock_);
    323 
    324   /*
    325    * Compute the width of the instruction at each address in the instruction stream, and store it in
    326    * insn_flags_. Addresses that are in the middle of an instruction, or that are part of switch
    327    * table data, are not touched (so the caller should probably initialize "insn_flags" to zero).
    328    *
    329    * The "new_instance_count_" and "monitor_enter_count_" fields in vdata are also set.
    330    *
    331    * Performs some static checks, notably:
    332    * - opcode of first instruction begins at index 0
    333    * - only documented instructions may appear
    334    * - each instruction follows the last
    335    * - last byte of last instruction is at (code_length-1)
    336    *
    337    * Logs an error and returns "false" on failure.
    338    */
    339   bool ComputeWidthsAndCountOps();
    340 
    341   /*
    342    * Set the "in try" flags for all instructions protected by "try" statements. Also sets the
    343    * "branch target" flags for exception handlers.
    344    *
    345    * Call this after widths have been set in "insn_flags".
    346    *
    347    * Returns "false" if something in the exception table looks fishy, but we're expecting the
    348    * exception table to be somewhat sane.
    349    */
    350   bool ScanTryCatchBlocks() REQUIRES_SHARED(Locks::mutator_lock_);
    351 
    352   /*
    353    * Perform static verification on all instructions in a method.
    354    *
    355    * Walks through instructions in a method calling VerifyInstruction on each.
    356    */
    357   template <bool kAllowRuntimeOnlyInstructions>
    358   bool VerifyInstructions();
    359 
    360   /*
    361    * Perform static verification on an instruction.
    362    *
    363    * As a side effect, this sets the "branch target" flags in InsnFlags.
    364    *
    365    * "(CF)" items are handled during code-flow analysis.
    366    *
    367    * v3 4.10.1
    368    * - target of each jump and branch instruction must be valid
    369    * - targets of switch statements must be valid
    370    * - operands referencing constant pool entries must be valid
    371    * - (CF) operands of getfield, putfield, getstatic, putstatic must be valid
    372    * - (CF) operands of method invocation instructions must be valid
    373    * - (CF) only invoke-direct can call a method starting with '<'
    374    * - (CF) <clinit> must never be called explicitly
    375    * - operands of instanceof, checkcast, new (and variants) must be valid
    376    * - new-array[-type] limited to 255 dimensions
    377    * - can't use "new" on an array class
    378    * - (?) limit dimensions in multi-array creation
    379    * - local variable load/store register values must be in valid range
    380    *
    381    * v3 4.11.1.2
    382    * - branches must be within the bounds of the code array
    383    * - targets of all control-flow instructions are the start of an instruction
    384    * - register accesses fall within range of allocated registers
    385    * - (N/A) access to constant pool must be of appropriate type
    386    * - code does not end in the middle of an instruction
    387    * - execution cannot fall off the end of the code
    388    * - (earlier) for each exception handler, the "try" area must begin and
    389    *   end at the start of an instruction (end can be at the end of the code)
    390    * - (earlier) for each exception handler, the handler must start at a valid
    391    *   instruction
    392    */
    393   template <bool kAllowRuntimeOnlyInstructions>
    394   bool VerifyInstruction(const Instruction* inst, uint32_t code_offset);
    395 
    396   /* Ensure that the register index is valid for this code item. */
    397   bool CheckRegisterIndex(uint32_t idx);
    398 
    399   /* Ensure that the wide register index is valid for this code item. */
    400   bool CheckWideRegisterIndex(uint32_t idx);
    401 
    402   // Perform static checks on an instruction referencing a CallSite. All we do here is ensure that
    403   // the call site index is in the valid range.
    404   bool CheckCallSiteIndex(uint32_t idx);
    405 
    406   // Perform static checks on a field Get or set instruction. All we do here is ensure that the
    407   // field index is in the valid range.
    408   bool CheckFieldIndex(uint32_t idx);
    409 
    410   // Perform static checks on a method invocation instruction. All we do here is ensure that the
    411   // method index is in the valid range.
    412   bool CheckMethodIndex(uint32_t idx);
    413 
    414   // Perform static checks on an instruction referencing a constant method handle. All we do here
    415   // is ensure that the method index is in the valid range.
    416   bool CheckMethodHandleIndex(uint32_t idx);
    417 
    418   // Perform static checks on a "new-instance" instruction. Specifically, make sure the class
    419   // reference isn't for an array class.
    420   bool CheckNewInstance(dex::TypeIndex idx);
    421 
    422   // Perform static checks on a prototype indexing instruction. All we do here is ensure that the
    423   // prototype index is in the valid range.
    424   bool CheckPrototypeIndex(uint32_t idx);
    425 
    426   /* Ensure that the string index is in the valid range. */
    427   bool CheckStringIndex(uint32_t idx);
    428 
    429   // Perform static checks on an instruction that takes a class constant. Ensure that the class
    430   // index is in the valid range.
    431   bool CheckTypeIndex(dex::TypeIndex idx);
    432 
    433   // Perform static checks on a "new-array" instruction. Specifically, make sure they aren't
    434   // creating an array of arrays that causes the number of dimensions to exceed 255.
    435   bool CheckNewArray(dex::TypeIndex idx);
    436 
    437   // Verify an array data table. "cur_offset" is the offset of the fill-array-data instruction.
    438   bool CheckArrayData(uint32_t cur_offset);
    439 
    440   // Verify that the target of a branch instruction is valid. We don't expect code to jump directly
    441   // into an exception handler, but it's valid to do so as long as the target isn't a
    442   // "move-exception" instruction. We verify that in a later stage.
    443   // The dex format forbids certain instructions from branching to themselves.
    444   // Updates "insn_flags_", setting the "branch target" flag.
    445   bool CheckBranchTarget(uint32_t cur_offset);
    446 
    447   // Verify a switch table. "cur_offset" is the offset of the switch instruction.
    448   // Updates "insn_flags_", setting the "branch target" flag.
    449   bool CheckSwitchTargets(uint32_t cur_offset);
    450 
    451   // Check the register indices used in a "vararg" instruction, such as invoke-virtual or
    452   // filled-new-array.
    453   // - vA holds word count (0-5), args[] have values.
    454   // There are some tests we don't do here, e.g. we don't try to verify that invoking a method that
    455   // takes a double is done with consecutive registers. This requires parsing the target method
    456   // signature, which we will be doing later on during the code flow analysis.
    457   bool CheckVarArgRegs(uint32_t vA, uint32_t arg[]);
    458 
    459   // Check the register indices used in a "vararg/range" instruction, such as invoke-virtual/range
    460   // or filled-new-array/range.
    461   // - vA holds word count, vC holds index of first reg.
    462   bool CheckVarArgRangeRegs(uint32_t vA, uint32_t vC);
    463 
    464   // Checks the method matches the expectations required to be signature polymorphic.
    465   bool CheckSignaturePolymorphicMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_);
    466 
    467   // Checks the invoked receiver matches the expectations for signature polymorphic methods.
    468   bool CheckSignaturePolymorphicReceiver(const Instruction* inst) REQUIRES_SHARED(Locks::mutator_lock_);
    469 
    470   // Extract the relative offset from a branch instruction.
    471   // Returns "false" on failure (e.g. this isn't a branch instruction).
    472   bool GetBranchOffset(uint32_t cur_offset, int32_t* pOffset, bool* pConditional,
    473                        bool* selfOkay);
    474 
    475   /* Perform detailed code-flow analysis on a single method. */
    476   bool VerifyCodeFlow() REQUIRES_SHARED(Locks::mutator_lock_);
    477 
    478   // Set the register types for the first instruction in the method based on the method signature.
    479   // This has the side-effect of validating the signature.
    480   bool SetTypesFromSignature() REQUIRES_SHARED(Locks::mutator_lock_);
    481 
    482   /*
    483    * Perform code flow on a method.
    484    *
    485    * The basic strategy is as outlined in v3 4.11.1.2: set the "changed" bit on the first
    486    * instruction, process it (setting additional "changed" bits), and repeat until there are no
    487    * more.
    488    *
    489    * v3 4.11.1.1
    490    * - (N/A) operand stack is always the same size
    491    * - operand stack [registers] contain the correct types of values
    492    * - local variables [registers] contain the correct types of values
    493    * - methods are invoked with the appropriate arguments
    494    * - fields are assigned using values of appropriate types
    495    * - opcodes have the correct type values in operand registers
    496    * - there is never an uninitialized class instance in a local variable in code protected by an
    497    *   exception handler (operand stack is okay, because the operand stack is discarded when an
    498    *   exception is thrown) [can't know what's a local var w/o the debug info -- should fall out of
    499    *   register typing]
    500    *
    501    * v3 4.11.1.2
    502    * - execution cannot fall off the end of the code
    503    *
    504    * (We also do many of the items described in the "static checks" sections, because it's easier to
    505    * do them here.)
    506    *
    507    * We need an array of RegType values, one per register, for every instruction. If the method uses
    508    * monitor-enter, we need extra data for every register, and a stack for every "interesting"
    509    * instruction. In theory this could become quite large -- up to several megabytes for a monster
    510    * function.
    511    *
    512    * NOTE:
    513    * The spec forbids backward branches when there's an uninitialized reference in a register. The
    514    * idea is to prevent something like this:
    515    *   loop:
    516    *     move r1, r0
    517    *     new-instance r0, MyClass
    518    *     ...
    519    *     if-eq rN, loop  // once
    520    *   initialize r0
    521    *
    522    * This leaves us with two different instances, both allocated by the same instruction, but only
    523    * one is initialized. The scheme outlined in v3 4.11.1.4 wouldn't catch this, so they work around
    524    * it by preventing backward branches. We achieve identical results without restricting code
    525    * reordering by specifying that you can't execute the new-instance instruction if a register
    526    * contains an uninitialized instance created by that same instruction.
    527    */
    528   bool CodeFlowVerifyMethod() REQUIRES_SHARED(Locks::mutator_lock_);
    529 
    530   /*
    531    * Perform verification for a single instruction.
    532    *
    533    * This requires fully decoding the instruction to determine the effect it has on registers.
    534    *
    535    * Finds zero or more following instructions and sets the "changed" flag if execution at that
    536    * point needs to be (re-)evaluated. Register changes are merged into "reg_types_" at the target
    537    * addresses. Does not set or clear any other flags in "insn_flags_".
    538    */
    539   bool CodeFlowVerifyInstruction(uint32_t* start_guess)
    540       REQUIRES_SHARED(Locks::mutator_lock_);
    541 
    542   // Perform verification of a new array instruction
    543   void VerifyNewArray(const Instruction* inst, bool is_filled, bool is_range)
    544       REQUIRES_SHARED(Locks::mutator_lock_);
    545 
    546   // Helper to perform verification on puts of primitive type.
    547   void VerifyPrimitivePut(const RegType& target_type, const RegType& insn_type,
    548                           const uint32_t vregA) REQUIRES_SHARED(Locks::mutator_lock_);
    549 
    550   // Perform verification of an aget instruction. The destination register's type will be set to
    551   // be that of component type of the array unless the array type is unknown, in which case a
    552   // bottom type inferred from the type of instruction is used. is_primitive is false for an
    553   // aget-object.
    554   void VerifyAGet(const Instruction* inst, const RegType& insn_type,
    555                   bool is_primitive) REQUIRES_SHARED(Locks::mutator_lock_);
    556 
    557   // Perform verification of an aput instruction.
    558   void VerifyAPut(const Instruction* inst, const RegType& insn_type,
    559                   bool is_primitive) REQUIRES_SHARED(Locks::mutator_lock_);
    560 
    561   // Lookup instance field and fail for resolution violations
    562   ArtField* GetInstanceField(const RegType& obj_type, int field_idx)
    563       REQUIRES_SHARED(Locks::mutator_lock_);
    564 
    565   // Lookup static field and fail for resolution violations
    566   ArtField* GetStaticField(int field_idx) REQUIRES_SHARED(Locks::mutator_lock_);
    567 
    568   // Perform verification of an iget/sget/iput/sput instruction.
    569   enum class FieldAccessType {  // private
    570     kAccGet,
    571     kAccPut
    572   };
    573   template <FieldAccessType kAccType>
    574   void VerifyISFieldAccess(const Instruction* inst, const RegType& insn_type,
    575                            bool is_primitive, bool is_static)
    576       REQUIRES_SHARED(Locks::mutator_lock_);
    577 
    578   enum class CheckAccess {  // private.
    579     kYes,
    580     kNo,
    581   };
    582   // Resolves a class based on an index and, if C is kYes, performs access checks to ensure
    583   // the referrer can access the resolved class.
    584   template <CheckAccess C>
    585   const RegType& ResolveClass(dex::TypeIndex class_idx)
    586       REQUIRES_SHARED(Locks::mutator_lock_);
    587 
    588   /*
    589    * For the "move-exception" instruction at "work_insn_idx_", which must be at an exception handler
    590    * address, determine the Join of all exceptions that can land here. Fails if no matching
    591    * exception handler can be found or if the Join of exception types fails.
    592    */
    593   const RegType& GetCaughtExceptionType()
    594       REQUIRES_SHARED(Locks::mutator_lock_);
    595 
    596   /*
    597    * Resolves a method based on an index and performs access checks to ensure
    598    * the referrer can access the resolved method.
    599    * Does not throw exceptions.
    600    */
    601   ArtMethod* ResolveMethodAndCheckAccess(uint32_t method_idx, MethodType method_type)
    602       REQUIRES_SHARED(Locks::mutator_lock_);
    603 
    604   /*
    605    * Verify the arguments to a method. We're executing in "method", making
    606    * a call to the method reference in vB.
    607    *
    608    * If this is a "direct" invoke, we allow calls to <init>. For calls to
    609    * <init>, the first argument may be an uninitialized reference. Otherwise,
    610    * calls to anything starting with '<' will be rejected, as will any
    611    * uninitialized reference arguments.
    612    *
    613    * For non-static method calls, this will verify that the method call is
    614    * appropriate for the "this" argument.
    615    *
    616    * The method reference is in vBBBB. The "is_range" parameter determines
    617    * whether we use 0-4 "args" values or a range of registers defined by
    618    * vAA and vCCCC.
    619    *
    620    * Widening conversions on integers and references are allowed, but
    621    * narrowing conversions are not.
    622    *
    623    * Returns the resolved method on success, null on failure (with *failure
    624    * set appropriately).
    625    */
    626   ArtMethod* VerifyInvocationArgs(const Instruction* inst, MethodType method_type, bool is_range)
    627       REQUIRES_SHARED(Locks::mutator_lock_);
    628 
    629   // Similar checks to the above, but on the proto. Will be used when the method cannot be
    630   // resolved.
    631   void VerifyInvocationArgsUnresolvedMethod(const Instruction* inst, MethodType method_type,
    632                                             bool is_range)
    633       REQUIRES_SHARED(Locks::mutator_lock_);
    634 
    635   template <class T>
    636   ArtMethod* VerifyInvocationArgsFromIterator(T* it, const Instruction* inst,
    637                                                       MethodType method_type, bool is_range,
    638                                                       ArtMethod* res_method)
    639       REQUIRES_SHARED(Locks::mutator_lock_);
    640 
    641   /*
    642    * Verify the arguments present for a call site. Returns "true" if all is well, "false" otherwise.
    643    */
    644   bool CheckCallSite(uint32_t call_site_idx);
    645 
    646   /*
    647    * Verify that the target instruction is not "move-exception". It's important that the only way
    648    * to execute a move-exception is as the first instruction of an exception handler.
    649    * Returns "true" if all is well, "false" if the target instruction is move-exception.
    650    */
    651   bool CheckNotMoveException(const uint16_t* insns, int insn_idx);
    652 
    653   /*
    654    * Verify that the target instruction is not "move-result". It is important that we cannot
    655    * branch to move-result instructions, but we have to make this a distinct check instead of
    656    * adding it to CheckNotMoveException, because it is legal to continue into "move-result"
    657    * instructions - as long as the previous instruction was an invoke, which is checked elsewhere.
    658    */
    659   bool CheckNotMoveResult(const uint16_t* insns, int insn_idx);
    660 
    661   /*
    662    * Verify that the target instruction is not "move-result" or "move-exception". This is to
    663    * be used when checking branch and switch instructions, but not instructions that can
    664    * continue.
    665    */
    666   bool CheckNotMoveExceptionOrMoveResult(const uint16_t* insns, int insn_idx);
    667 
    668   /*
    669   * Control can transfer to "next_insn". Merge the registers from merge_line into the table at
    670   * next_insn, and set the changed flag on the target address if any of the registers were changed.
    671   * In the case of fall-through, update the merge line on a change as its the working line for the
    672   * next instruction.
    673   * Returns "false" if an error is encountered.
    674   */
    675   bool UpdateRegisters(uint32_t next_insn, RegisterLine* merge_line, bool update_merge_line)
    676       REQUIRES_SHARED(Locks::mutator_lock_);
    677 
    678   // Return the register type for the method.
    679   const RegType& GetMethodReturnType() REQUIRES_SHARED(Locks::mutator_lock_);
    680 
    681   // Get a type representing the declaring class of the method.
    682   const RegType& GetDeclaringClass() REQUIRES_SHARED(Locks::mutator_lock_);
    683 
    684   InstructionFlags* CurrentInsnFlags();
    685 
    686   const RegType& DetermineCat1Constant(int32_t value, bool precise)
    687       REQUIRES_SHARED(Locks::mutator_lock_);
    688 
    689   // Try to create a register type from the given class. In case a precise type is requested, but
    690   // the class is not instantiable, a soft error (of type NO_CLASS) will be enqueued and a
    691   // non-precise reference will be returned.
    692   // Note: we reuse NO_CLASS as this will throw an exception at runtime, when the failing class is
    693   //       actually touched.
    694   const RegType& FromClass(const char* descriptor, mirror::Class* klass, bool precise)
    695       REQUIRES_SHARED(Locks::mutator_lock_);
    696 
    697   ALWAYS_INLINE bool FailOrAbort(bool condition, const char* error_msg, uint32_t work_insn_idx);
    698 
    699   // The thread we're verifying on.
    700   Thread* const self_;
    701 
    702   // Arena allocator.
    703   ArenaStack arena_stack_;
    704   ScopedArenaAllocator allocator_;
    705 
    706   RegTypeCache reg_types_;
    707 
    708   PcToRegisterLineTable reg_table_;
    709 
    710   // Storage for the register status we're currently working on.
    711   RegisterLineArenaUniquePtr work_line_;
    712 
    713   // The address of the instruction we're currently working on, note that this is in 2 byte
    714   // quantities
    715   uint32_t work_insn_idx_;
    716 
    717   // Storage for the register status we're saving for later.
    718   RegisterLineArenaUniquePtr saved_line_;
    719 
    720   const uint32_t dex_method_idx_;  // The method we're working on.
    721   ArtMethod* method_being_verified_;  // Its ArtMethod representation if known.
    722   const uint32_t method_access_flags_;  // Method's access flags.
    723   const RegType* return_type_;  // Lazily computed return type of the method.
    724   const DexFile* const dex_file_;  // The dex file containing the method.
    725   // The dex_cache for the declaring class of the method.
    726   Handle<mirror::DexCache> dex_cache_ GUARDED_BY(Locks::mutator_lock_);
    727   // The class loader for the declaring class of the method.
    728   Handle<mirror::ClassLoader> class_loader_ GUARDED_BY(Locks::mutator_lock_);
    729   const DexFile::ClassDef& class_def_;  // The class def of the declaring class of the method.
    730   const CodeItemDataAccessor code_item_accessor_;
    731   const RegType* declaring_class_;  // Lazily computed reg type of the method's declaring class.
    732   // Instruction widths and flags, one entry per code unit.
    733   // Owned, but not unique_ptr since insn_flags_ are allocated in arenas.
    734   ArenaUniquePtr<InstructionFlags[]> insn_flags_;
    735   // The dex PC of a FindLocksAtDexPc request, -1 otherwise.
    736   uint32_t interesting_dex_pc_;
    737   // The container into which FindLocksAtDexPc should write the registers containing held locks,
    738   // null if we're not doing FindLocksAtDexPc.
    739   std::vector<DexLockInfo>* monitor_enter_dex_pcs_;
    740 
    741   // The types of any error that occurs.
    742   std::vector<VerifyError> failures_;
    743   // Error messages associated with failures.
    744   std::vector<std::ostringstream*> failure_messages_;
    745   // Is there a pending hard failure?
    746   bool have_pending_hard_failure_;
    747   // Is there a pending runtime throw failure? A runtime throw failure is when an instruction
    748   // would fail at runtime throwing an exception. Such an instruction causes the following code
    749   // to be unreachable. This is set by Fail and used to ensure we don't process unreachable
    750   // instructions that would hard fail the verification.
    751   // Note: this flag is reset after processing each instruction.
    752   bool have_pending_runtime_throw_failure_;
    753   // Is there a pending experimental failure?
    754   bool have_pending_experimental_failure_;
    755 
    756   // A version of the above that is not reset and thus captures if there were *any* throw failures.
    757   bool have_any_pending_runtime_throw_failure_;
    758 
    759   // Info message log use primarily for verifier diagnostics.
    760   std::ostringstream info_messages_;
    761 
    762   // The number of occurrences of specific opcodes.
    763   size_t new_instance_count_;
    764   size_t monitor_enter_count_;
    765 
    766   // Bitset of the encountered failure types. Bits are according to the values in VerifyError.
    767   uint32_t encountered_failure_types_;
    768 
    769   const bool can_load_classes_;
    770 
    771   // Converts soft failures to hard failures when false. Only false when the compiler isn't
    772   // running and the verifier is called from the class linker.
    773   const bool allow_soft_failures_;
    774 
    775   // An optimization where instead of generating unique RegTypes for constants we use imprecise
    776   // constants that cover a range of constants. This isn't good enough for deoptimization that
    777   // avoids loading from registers in the case of a constant as the dex instruction set lost the
    778   // notion of whether a value should be in a floating point or general purpose register file.
    779   const bool need_precise_constants_;
    780 
    781   // Indicates the method being verified contains at least one check-cast or aput-object
    782   // instruction. Aput-object operations implicitly check for array-store exceptions, similar to
    783   // check-cast.
    784   bool has_check_casts_;
    785 
    786   // Indicates the method being verified contains at least one invoke-virtual/range
    787   // or invoke-interface/range.
    788   bool has_virtual_or_interface_invokes_;
    789 
    790   // Indicates whether we verify to dump the info. In that case we accept quickened instructions
    791   // even though we might detect to be a compiler. Should only be set when running
    792   // VerifyMethodAndDump.
    793   const bool verify_to_dump_;
    794 
    795   // Whether or not we call AllowThreadSuspension periodically, we want a way to disable this for
    796   // thread dumping checkpoints since we may get thread suspension at an inopportune time due to
    797   // FindLocksAtDexPC, resulting in deadlocks.
    798   const bool allow_thread_suspension_;
    799 
    800   // Whether the method seems to be a constructor. Note that this field exists as we can't trust
    801   // the flags in the dex file. Some older code does not mark methods named "<init>" and "<clinit>"
    802   // correctly.
    803   //
    804   // Note: this flag is only valid once Verify() has started.
    805   bool is_constructor_;
    806 
    807   // Link, for the method verifier root linked list.
    808   MethodVerifier* link_;
    809 
    810   friend class art::Thread;
    811   friend class VerifierDepsTest;
    812 
    813   DISALLOW_COPY_AND_ASSIGN(MethodVerifier);
    814 };
    815 
    816 }  // namespace verifier
    817 }  // namespace art
    818 
    819 #endif  // ART_RUNTIME_VERIFIER_METHOD_VERIFIER_H_
    820