method_verifier.h revision 98be1a9d7280f82e533bc02d2df564da4c8f73a0
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 "reg_type_cache.h"
34#include "register_line.h"
35#include "verifier_enums.h"
36
37namespace art {
38
39class ClassLinker;
40class CompilerCallbacks;
41class Instruction;
42struct ReferenceMap2Visitor;
43class Thread;
44class VariableIndentationOutputStream;
45
46namespace mirror {
47class DexCache;
48}  // namespace mirror
49
50namespace verifier {
51
52class MethodVerifier;
53class RegisterLine;
54using RegisterLineArenaUniquePtr = std::unique_ptr<RegisterLine, RegisterLineArenaDelete>;
55class 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).
60enum 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.
68class 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
90class 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  enum class CheckAccess {  // private.
580    kYes,
581    kNo,
582  };
583  // Resolves a class based on an index and, if C is kYes, performs access checks to ensure
584  // the referrer can access the resolved class.
585  template <CheckAccess C>
586  const RegType& ResolveClass(dex::TypeIndex class_idx)
587      REQUIRES_SHARED(Locks::mutator_lock_);
588
589  /*
590   * For the "move-exception" instruction at "work_insn_idx_", which must be at an exception handler
591   * address, determine the Join of all exceptions that can land here. Fails if no matching
592   * exception handler can be found or if the Join of exception types fails.
593   */
594  const RegType& GetCaughtExceptionType()
595      REQUIRES_SHARED(Locks::mutator_lock_);
596
597  /*
598   * Resolves a method based on an index and performs access checks to ensure
599   * the referrer can access the resolved method.
600   * Does not throw exceptions.
601   */
602  ArtMethod* ResolveMethodAndCheckAccess(uint32_t method_idx, MethodType method_type)
603      REQUIRES_SHARED(Locks::mutator_lock_);
604
605  /*
606   * Verify the arguments to a method. We're executing in "method", making
607   * a call to the method reference in vB.
608   *
609   * If this is a "direct" invoke, we allow calls to <init>. For calls to
610   * <init>, the first argument may be an uninitialized reference. Otherwise,
611   * calls to anything starting with '<' will be rejected, as will any
612   * uninitialized reference arguments.
613   *
614   * For non-static method calls, this will verify that the method call is
615   * appropriate for the "this" argument.
616   *
617   * The method reference is in vBBBB. The "is_range" parameter determines
618   * whether we use 0-4 "args" values or a range of registers defined by
619   * vAA and vCCCC.
620   *
621   * Widening conversions on integers and references are allowed, but
622   * narrowing conversions are not.
623   *
624   * Returns the resolved method on success, null on failure (with *failure
625   * set appropriately).
626   */
627  ArtMethod* VerifyInvocationArgs(const Instruction* inst, MethodType method_type, bool is_range)
628      REQUIRES_SHARED(Locks::mutator_lock_);
629
630  // Similar checks to the above, but on the proto. Will be used when the method cannot be
631  // resolved.
632  void VerifyInvocationArgsUnresolvedMethod(const Instruction* inst, MethodType method_type,
633                                            bool is_range)
634      REQUIRES_SHARED(Locks::mutator_lock_);
635
636  template <class T>
637  ArtMethod* VerifyInvocationArgsFromIterator(T* it, const Instruction* inst,
638                                                      MethodType method_type, bool is_range,
639                                                      ArtMethod* res_method)
640      REQUIRES_SHARED(Locks::mutator_lock_);
641
642  ArtMethod* VerifyInvokeVirtualQuickArgs(const Instruction* inst, bool is_range)
643  REQUIRES_SHARED(Locks::mutator_lock_);
644
645  /*
646   * Verify the arguments present for a call site. Returns "true" if all is well, "false" otherwise.
647   */
648  bool CheckCallSite(uint32_t call_site_idx);
649
650  /*
651   * Verify that the target instruction is not "move-exception". It's important that the only way
652   * to execute a move-exception is as the first instruction of an exception handler.
653   * Returns "true" if all is well, "false" if the target instruction is move-exception.
654   */
655  bool CheckNotMoveException(const uint16_t* insns, int insn_idx);
656
657  /*
658   * Verify that the target instruction is not "move-result". It is important that we cannot
659   * branch to move-result instructions, but we have to make this a distinct check instead of
660   * adding it to CheckNotMoveException, because it is legal to continue into "move-result"
661   * instructions - as long as the previous instruction was an invoke, which is checked elsewhere.
662   */
663  bool CheckNotMoveResult(const uint16_t* insns, int insn_idx);
664
665  /*
666   * Verify that the target instruction is not "move-result" or "move-exception". This is to
667   * be used when checking branch and switch instructions, but not instructions that can
668   * continue.
669   */
670  bool CheckNotMoveExceptionOrMoveResult(const uint16_t* insns, int insn_idx);
671
672  /*
673  * Control can transfer to "next_insn". Merge the registers from merge_line into the table at
674  * next_insn, and set the changed flag on the target address if any of the registers were changed.
675  * In the case of fall-through, update the merge line on a change as its the working line for the
676  * next instruction.
677  * Returns "false" if an error is encountered.
678  */
679  bool UpdateRegisters(uint32_t next_insn, RegisterLine* merge_line, bool update_merge_line)
680      REQUIRES_SHARED(Locks::mutator_lock_);
681
682  // Return the register type for the method.
683  const RegType& GetMethodReturnType() REQUIRES_SHARED(Locks::mutator_lock_);
684
685  // Get a type representing the declaring class of the method.
686  const RegType& GetDeclaringClass() REQUIRES_SHARED(Locks::mutator_lock_);
687
688  InstructionFlags* CurrentInsnFlags();
689
690  const RegType& DetermineCat1Constant(int32_t value, bool precise)
691      REQUIRES_SHARED(Locks::mutator_lock_);
692
693  // Try to create a register type from the given class. In case a precise type is requested, but
694  // the class is not instantiable, a soft error (of type NO_CLASS) will be enqueued and a
695  // non-precise reference will be returned.
696  // Note: we reuse NO_CLASS as this will throw an exception at runtime, when the failing class is
697  //       actually touched.
698  const RegType& FromClass(const char* descriptor, mirror::Class* klass, bool precise)
699      REQUIRES_SHARED(Locks::mutator_lock_);
700
701  // The thread we're verifying on.
702  Thread* const self_;
703
704  // Arena allocator.
705  ArenaStack arena_stack_;
706  ScopedArenaAllocator arena_;
707
708  RegTypeCache reg_types_;
709
710  PcToRegisterLineTable reg_table_;
711
712  // Storage for the register status we're currently working on.
713  RegisterLineArenaUniquePtr work_line_;
714
715  // The address of the instruction we're currently working on, note that this is in 2 byte
716  // quantities
717  uint32_t work_insn_idx_;
718
719  // Storage for the register status we're saving for later.
720  RegisterLineArenaUniquePtr saved_line_;
721
722  const uint32_t dex_method_idx_;  // The method we're working on.
723  // Its object representation if known.
724  ArtMethod* mirror_method_ GUARDED_BY(Locks::mutator_lock_);
725  const uint32_t method_access_flags_;  // Method's access flags.
726  const RegType* return_type_;  // Lazily computed return type of the method.
727  const DexFile* const dex_file_;  // The dex file containing the method.
728  // The dex_cache for the declaring class of the method.
729  Handle<mirror::DexCache> dex_cache_ GUARDED_BY(Locks::mutator_lock_);
730  // The class loader for the declaring class of the method.
731  Handle<mirror::ClassLoader> class_loader_ GUARDED_BY(Locks::mutator_lock_);
732  const DexFile::ClassDef& class_def_;  // The class def of the declaring class of the method.
733  const DexFile::CodeItem* const code_item_;  // The code item containing the code for the method.
734  const RegType* declaring_class_;  // Lazily computed reg type of the method's declaring class.
735  // Instruction widths and flags, one entry per code unit.
736  // Owned, but not unique_ptr since insn_flags_ are allocated in arenas.
737  ArenaUniquePtr<InstructionFlags[]> insn_flags_;
738  // The dex PC of a FindLocksAtDexPc request, -1 otherwise.
739  uint32_t interesting_dex_pc_;
740  // The container into which FindLocksAtDexPc should write the registers containing held locks,
741  // null if we're not doing FindLocksAtDexPc.
742  std::vector<uint32_t>* monitor_enter_dex_pcs_;
743
744  // The types of any error that occurs.
745  std::vector<VerifyError> failures_;
746  // Error messages associated with failures.
747  std::vector<std::ostringstream*> failure_messages_;
748  // Is there a pending hard failure?
749  bool have_pending_hard_failure_;
750  // Is there a pending runtime throw failure? A runtime throw failure is when an instruction
751  // would fail at runtime throwing an exception. Such an instruction causes the following code
752  // to be unreachable. This is set by Fail and used to ensure we don't process unreachable
753  // instructions that would hard fail the verification.
754  // Note: this flag is reset after processing each instruction.
755  bool have_pending_runtime_throw_failure_;
756  // Is there a pending experimental failure?
757  bool have_pending_experimental_failure_;
758
759  // A version of the above that is not reset and thus captures if there were *any* throw failures.
760  bool have_any_pending_runtime_throw_failure_;
761
762  // Info message log use primarily for verifier diagnostics.
763  std::ostringstream info_messages_;
764
765  // The number of occurrences of specific opcodes.
766  size_t new_instance_count_;
767  size_t monitor_enter_count_;
768
769  // Bitset of the encountered failure types. Bits are according to the values in VerifyError.
770  uint32_t encountered_failure_types_;
771
772  const bool can_load_classes_;
773
774  // Converts soft failures to hard failures when false. Only false when the compiler isn't
775  // running and the verifier is called from the class linker.
776  const bool allow_soft_failures_;
777
778  // An optimization where instead of generating unique RegTypes for constants we use imprecise
779  // constants that cover a range of constants. This isn't good enough for deoptimization that
780  // avoids loading from registers in the case of a constant as the dex instruction set lost the
781  // notion of whether a value should be in a floating point or general purpose register file.
782  const bool need_precise_constants_;
783
784  // Indicates the method being verified contains at least one check-cast or aput-object
785  // instruction. Aput-object operations implicitly check for array-store exceptions, similar to
786  // check-cast.
787  bool has_check_casts_;
788
789  // Indicates the method being verified contains at least one invoke-virtual/range
790  // or invoke-interface/range.
791  bool has_virtual_or_interface_invokes_;
792
793  // Indicates whether we verify to dump the info. In that case we accept quickened instructions
794  // even though we might detect to be a compiler. Should only be set when running
795  // VerifyMethodAndDump.
796  const bool verify_to_dump_;
797
798  // Whether or not we call AllowThreadSuspension periodically, we want a way to disable this for
799  // thread dumping checkpoints since we may get thread suspension at an inopportune time due to
800  // FindLocksAtDexPC, resulting in deadlocks.
801  const bool allow_thread_suspension_;
802
803  // Whether the method seems to be a constructor. Note that this field exists as we can't trust
804  // the flags in the dex file. Some older code does not mark methods named "<init>" and "<clinit>"
805  // correctly.
806  //
807  // Note: this flag is only valid once Verify() has started.
808  bool is_constructor_;
809
810  // Link, for the method verifier root linked list.
811  MethodVerifier* link_;
812
813  friend class art::Thread;
814  friend class VerifierDepsTest;
815
816  DISALLOW_COPY_AND_ASSIGN(MethodVerifier);
817};
818
819}  // namespace verifier
820}  // namespace art
821
822#endif  // ART_RUNTIME_VERIFIER_METHOD_VERIFIER_H_
823