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