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