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