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