blob: 41223b222b8664bc89b7631876226ef28b8fca0a [file] [log] [blame]
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001// Copyright 2011 Google Inc. All Rights Reserved.
2
3#ifndef ART_SRC_DEX_VERIFY_H_
4#define ART_SRC_DEX_VERIFY_H_
5
Elliott Hughes90a33692011-08-30 13:27:07 -07006#include "dex_file.h"
7#include "dex_instruction.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07008#include "macros.h"
9#include "object.h"
Elliott Hughes5fe594f2011-09-08 12:33:17 -070010#include "UniquePtr.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070011
12namespace art {
13
jeffhaobdb76512011-09-07 11:43:16 -070014#define kMaxMonitorStackDepth (sizeof(MonitorEntries) * 8)
15
16/*
jeffhaod1f0fde2011-09-08 17:25:33 -070017 * Set this to enable dead code scanning. This is not required, but it's
jeffhaobdb76512011-09-07 11:43:16 -070018 * very useful when testing changes to the verifier (to make sure we're not
19 * skipping over stuff). The only reason not to do it is that it slightly
20 * increases the time required to perform verification.
21 */
22#ifndef NDEBUG
23# define DEAD_CODE_SCAN true
24#else
25# define DEAD_CODE_SCAN false
26#endif
27
28/*
jeffhaod1f0fde2011-09-08 17:25:33 -070029 * We need an extra "pseudo register" to hold the return type briefly. It
jeffhaobdb76512011-09-07 11:43:16 -070030 * can be category 1 or 2, so we need two slots.
31 */
32#define kExtraRegs 2
33#define RESULT_REGISTER(_insnRegCount) (_insnRegCount)
34
35class DexVerifier {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070036 public:
jeffhao98eacac2011-09-14 16:11:53 -070037 /* Verify a class. Returns "true" on success. */
38 static bool VerifyClass(Class* klass);
39
40 private:
jeffhaobdb76512011-09-07 11:43:16 -070041 /*
42 * RegType holds information about the type of data held in a register.
jeffhaod1f0fde2011-09-08 17:25:33 -070043 * For most types it's a simple enum. For reference types it holds a
jeffhaobdb76512011-09-07 11:43:16 -070044 * pointer to the ClassObject, and for uninitialized references it holds
45 * an index into the UninitInstanceMap.
46 */
47 typedef uint32_t RegType;
48
49 /*
50 * A bit vector indicating which entries in the monitor stack are
jeffhaod1f0fde2011-09-08 17:25:33 -070051 * associated with this register. The low bit corresponds to the stack's
jeffhaobdb76512011-09-07 11:43:16 -070052 * bottom-most entry.
53 */
54 typedef uint32_t MonitorEntries;
55
56 /*
57 * InsnFlags is a 32-bit integer with the following layout:
58 * 0-15 instruction length (or 0 if this address doesn't hold an opcode)
59 * 16-31 single bit flags:
60 * InTry: in "try" block; exceptions thrown here may be caught locally
61 * BranchTarget: other instructions can branch to this instruction
62 * GcPoint: this instruction is a GC safe point
63 * Visited: verifier has examined this instruction at least once
64 * Changed: set/cleared as bytecode verifier runs
65 */
66 typedef uint32_t InsnFlags;
67
68 enum InsnFlag {
69 kInsnFlagWidthMask = 0x0000ffff,
70 kInsnFlagInTry = (1 << 16),
jeffhaoba5ebb92011-08-25 17:24:37 -070071 kInsnFlagBranchTarget = (1 << 17),
jeffhaobdb76512011-09-07 11:43:16 -070072 kInsnFlagGcPoint = (1 << 18),
73 kInsnFlagVisited = (1 << 30),
74 kInsnFlagChanged = (1 << 31),
jeffhaoba5ebb92011-08-25 17:24:37 -070075 };
76
jeffhaobdb76512011-09-07 11:43:16 -070077 /*
jeffhaod1f0fde2011-09-08 17:25:33 -070078 * "Direct" and "virtual" methods are stored independently. The type of call
jeffhaobdb76512011-09-07 11:43:16 -070079 * used to invoke the method determines which list we search, and whether
80 * we travel up into superclasses.
81 *
82 * (<clinit>, <init>, and methods declared "private" or "static" are stored
jeffhaod1f0fde2011-09-08 17:25:33 -070083 * in the "direct" list. All others are stored in the "virtual" list.)
jeffhaobdb76512011-09-07 11:43:16 -070084 */
85 enum MethodType {
86 METHOD_UNKNOWN = 0,
87 METHOD_DIRECT, // <init>, private
88 METHOD_STATIC, // static
89 METHOD_VIRTUAL, // virtual, super
90 METHOD_INTERFACE // interface
91 };
92
93 /*
94 * We don't need to store the register data for many instructions, because
95 * we either only need it at branch points (for verification) or GC points
96 * and branches (for verification + type-precise register analysis).
97 */
98 enum RegisterTrackingMode {
99 kTrackRegsBranches,
100 kTrackRegsGcPoints,
101 kTrackRegsAll,
102 };
103
104 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700105 * Enumeration for register type values. The "hi" piece of a 64-bit value
jeffhaobdb76512011-09-07 11:43:16 -0700106 * MUST immediately follow the "lo" piece in the enumeration, so we can check
107 * that hi==lo+1.
108 *
109 * Assignment of constants:
110 * [-MAXINT,-32768) : integer
111 * [-32768,-128) : short
112 * [-128,0) : byte
113 * 0 : zero
114 * 1 : one
115 * [2,128) : posbyte
116 * [128,32768) : posshort
117 * [32768,65536) : char
118 * [65536,MAXINT] : integer
119 *
120 * Allowed "implicit" widening conversions:
121 * zero -> boolean, posbyte, byte, posshort, short, char, integer, ref (null)
122 * one -> boolean, posbyte, byte, posshort, short, char, integer
123 * boolean -> posbyte, byte, posshort, short, char, integer
124 * posbyte -> posshort, short, integer, char
125 * byte -> short, integer
126 * posshort -> integer, char
127 * short -> integer
128 * char -> integer
129 *
130 * In addition, all of the above can convert to "float".
131 *
jeffhaod1f0fde2011-09-08 17:25:33 -0700132 * We're more careful with integer values than the spec requires. The
jeffhaobdb76512011-09-07 11:43:16 -0700133 * motivation is to restrict byte/char/short to the correct range of values.
134 * For example, if a method takes a byte argument, we don't want to allow
135 * the code to load the constant "1024" and pass it in.
136 */
137 enum {
138 kRegTypeUnknown = 0, /* initial state; use value=0 so calloc works */
139 kRegTypeUninit = 1, /* MUST be odd to distinguish from pointer */
140 kRegTypeConflict, /* merge clash makes this reg's type unknowable */
141
142 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700143 * Category-1nr types. The order of these is chiseled into a couple
jeffhaobdb76512011-09-07 11:43:16 -0700144 * of tables, so don't add, remove, or reorder if you can avoid it.
145 */
146#define kRegType1nrSTART kRegTypeZero
147 kRegTypeZero, /* 32-bit 0, could be Boolean, Int, Float, or Ref */
148 kRegTypeOne, /* 32-bit 1, could be Boolean, Int, Float */
149 kRegTypeBoolean, /* must be 0 or 1 */
150 kRegTypeConstPosByte, /* const derived byte, known positive */
151 kRegTypeConstByte, /* const derived byte */
152 kRegTypeConstPosShort, /* const derived short, known positive */
153 kRegTypeConstShort, /* const derived short */
154 kRegTypeConstChar, /* const derived char */
155 kRegTypeConstInteger, /* const derived integer */
156 kRegTypePosByte, /* byte, known positive (can become char) */
157 kRegTypeByte,
158 kRegTypePosShort, /* short, known positive (can become char) */
159 kRegTypeShort,
160 kRegTypeChar,
161 kRegTypeInteger,
162 kRegTypeFloat,
163#define kRegType1nrEND kRegTypeFloat
164 kRegTypeConstLo, /* const derived wide, lower half */
165 kRegTypeConstHi, /* const derived wide, upper half */
166 kRegTypeLongLo, /* lower-numbered register; endian-independent */
167 kRegTypeLongHi,
168 kRegTypeDoubleLo,
169 kRegTypeDoubleHi,
170
171 /*
172 * Enumeration max; this is used with "full" (32-bit) RegType values.
173 *
jeffhaod1f0fde2011-09-08 17:25:33 -0700174 * Anything larger than this is a ClassObject or uninit ref. Mask off
jeffhaobdb76512011-09-07 11:43:16 -0700175 * all but the low 8 bits; if you're left with kRegTypeUninit, pull
jeffhaod1f0fde2011-09-08 17:25:33 -0700176 * the uninit index out of the high 24. Because kRegTypeUninit has an
jeffhaobdb76512011-09-07 11:43:16 -0700177 * odd value, there is no risk of a particular ClassObject pointer bit
178 * pattern being confused for it (assuming our class object allocator
179 * uses word alignment).
180 */
181 kRegTypeMAX
182 };
183#define kRegTypeUninitMask 0xff
184#define kRegTypeUninitShift 8
185
186 /*
187 * Register type categories, for type checking.
188 *
189 * The spec says category 1 includes boolean, byte, char, short, int, float,
jeffhaod1f0fde2011-09-08 17:25:33 -0700190 * reference, and returnAddress. Category 2 includes long and double.
jeffhaobdb76512011-09-07 11:43:16 -0700191 *
jeffhaod1f0fde2011-09-08 17:25:33 -0700192 * We treat object references separately, so we have "category1nr". We
jeffhaobdb76512011-09-07 11:43:16 -0700193 * don't support jsr/ret, so there is no "returnAddress" type.
194 */
195 enum TypeCategory {
196 kTypeCategoryUnknown = 0,
197 kTypeCategory1nr = 1, // boolean, byte, char, short, int, float
198 kTypeCategory2 = 2, // long, double
199 kTypeCategoryRef = 3, // object reference
200 };
201
202 /* An enumeration of problems that can turn up during verification. */
203 enum VerifyError {
204 VERIFY_ERROR_NONE = 0, /* no error; must be zero */
205 VERIFY_ERROR_GENERIC, /* VerifyError */
206
207 VERIFY_ERROR_NO_CLASS, /* NoClassDefFoundError */
208 VERIFY_ERROR_NO_FIELD, /* NoSuchFieldError */
209 VERIFY_ERROR_NO_METHOD, /* NoSuchMethodError */
210 VERIFY_ERROR_ACCESS_CLASS, /* IllegalAccessError */
211 VERIFY_ERROR_ACCESS_FIELD, /* IllegalAccessError */
212 VERIFY_ERROR_ACCESS_METHOD, /* IllegalAccessError */
213 VERIFY_ERROR_CLASS_CHANGE, /* IncompatibleClassChangeError */
214 VERIFY_ERROR_INSTANTIATION, /* InstantiationError */
215 };
216
217 /*
218 * Identifies the type of reference in the instruction that generated the
219 * verify error (e.g. VERIFY_ERROR_ACCESS_CLASS could come from a method,
220 * field, or class reference).
221 *
222 * This must fit in two bits.
223 */
224 enum VerifyErrorRefType {
225 VERIFY_ERROR_REF_CLASS = 0,
226 VERIFY_ERROR_REF_FIELD = 1,
227 VERIFY_ERROR_REF_METHOD = 2,
228 };
229#define kVerifyErrorRefTypeShift 6
230
231 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700232 * Format enumeration for RegisterMap data area.
233 */
234 enum RegisterMapFormat {
235 kRegMapFormatUnknown = 0,
236 kRegMapFormatNone, /* indicates no map data follows */
237 kRegMapFormatCompact8, /* compact layout, 8-bit addresses */
238 kRegMapFormatCompact16, /* compact layout, 16-bit addresses */
239 kRegMapFormatDifferential, /* compressed, differential encoding */
240 };
241
242 /*
jeffhaobdb76512011-09-07 11:43:16 -0700243 * During verification, we associate one of these with every "interesting"
jeffhaod1f0fde2011-09-08 17:25:33 -0700244 * instruction. We track the status of all registers, and (if the method
jeffhaobdb76512011-09-07 11:43:16 -0700245 * has any monitor-enter instructions) maintain a stack of entered monitors
246 * (identified by code unit offset).
247 *
248 * If live-precise register maps are enabled, the "liveRegs" vector will
jeffhaod1f0fde2011-09-08 17:25:33 -0700249 * be populated. Unlike the other lists of registers here, we do not
jeffhaobdb76512011-09-07 11:43:16 -0700250 * track the liveness of the method result register (which is not visible
251 * to the GC).
252 */
253 struct RegisterLine {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700254 UniquePtr<RegType[]> reg_types_;
255 UniquePtr<MonitorEntries[]> monitor_entries_;
256 UniquePtr<uint32_t[]> monitor_stack_;
257 uint32_t monitor_stack_top_;
jeffhaobdb76512011-09-07 11:43:16 -0700258
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700259 RegisterLine()
jeffhaod1f0fde2011-09-08 17:25:33 -0700260 : reg_types_(NULL), monitor_entries_(NULL), monitor_stack_(NULL),
261 monitor_stack_top_(0) {
jeffhaobdb76512011-09-07 11:43:16 -0700262 }
263
264 /* Allocate space for the fields. */
265 void Alloc(size_t size, bool track_monitors) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700266 reg_types_.reset(new RegType[size]());
jeffhaobdb76512011-09-07 11:43:16 -0700267 if (track_monitors) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700268 monitor_entries_.reset(new MonitorEntries[size]);
269 monitor_stack_.reset(new uint32_t[kMaxMonitorStackDepth]);
jeffhaobdb76512011-09-07 11:43:16 -0700270 }
271 }
272 };
273
274 /* Big fat collection of register data. */
275 struct RegisterTable {
276 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700277 * Array of RegisterLine structs, one per address in the method. We only
jeffhaobdb76512011-09-07 11:43:16 -0700278 * set the pointers for certain addresses, based on instruction widths
279 * and what we're trying to accomplish.
280 */
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700281 UniquePtr<RegisterLine[]> register_lines_;
jeffhaobdb76512011-09-07 11:43:16 -0700282
283 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700284 * Number of registers we track for each instruction. This is equal
jeffhaobdb76512011-09-07 11:43:16 -0700285 * to the method's declared "registersSize" plus kExtraRegs (2).
286 */
287 size_t insn_reg_count_plus_;
288
289 /* Storage for a register line we're currently working on. */
290 RegisterLine work_line_;
291
292 /* Storage for a register line we're saving for later. */
293 RegisterLine saved_line_;
294
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700295 RegisterTable() : register_lines_(NULL), insn_reg_count_plus_(0) {
jeffhaobdb76512011-09-07 11:43:16 -0700296 }
297 };
298
299 /* Entries in the UninitInstanceMap. */
300 struct UninitInstanceMapEntry {
301 /* Code offset, or -1 for method arg ("this"). */
302 int addr_;
303
304 /* Class created at this address. */
305 Class* klass_;
306 };
307
308 /*
309 * Table that maps uninitialized instances to classes, based on the
jeffhaod1f0fde2011-09-08 17:25:33 -0700310 * address of the new-instance instruction. One per method.
jeffhaobdb76512011-09-07 11:43:16 -0700311 */
312 struct UninitInstanceMap {
313 int num_entries_;
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700314 UniquePtr<UninitInstanceMapEntry[]> map_;
jeffhaobdb76512011-09-07 11:43:16 -0700315
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700316 UninitInstanceMap(int num_entries)
317 : num_entries_(num_entries),
318 map_(new UninitInstanceMapEntry[num_entries]()) {
jeffhaobdb76512011-09-07 11:43:16 -0700319 }
320 };
321 #define kUninitThisArgAddr (-1)
322 #define kUninitThisArgSlot 0
323
324 /* Various bits of data used by the verifier and register map generator. */
325 struct VerifierData {
326 /* The method we're working on. */
327 Method* method_;
328
329 /* The dex file containing the method. */
330 const DexFile* dex_file_;
331
332 /* The code item containing the code for the method. */
333 const DexFile::CodeItem* code_item_;
334
335 /* Instruction widths and flags, one entry per code unit. */
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700336 UniquePtr<InsnFlags[]> insn_flags_;
jeffhaobdb76512011-09-07 11:43:16 -0700337
338 /*
339 * Uninitialized instance map, used for tracking the movement of
340 * objects that have been allocated but not initialized.
341 */
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700342 UniquePtr<UninitInstanceMap> uninit_map_;
jeffhaobdb76512011-09-07 11:43:16 -0700343
344 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700345 * Array of RegisterLine structs, one entry per code unit. We only need
jeffhaobdb76512011-09-07 11:43:16 -0700346 * entries for code units that hold the start of an "interesting"
jeffhaod1f0fde2011-09-08 17:25:33 -0700347 * instruction. For register map generation, we're only interested
jeffhaobdb76512011-09-07 11:43:16 -0700348 * in GC points.
349 */
350 RegisterLine* register_lines_;
351
352 /* The number of occurrences of specific opcodes. */
353 size_t new_instance_count_;
354 size_t monitor_enter_count_;
355
jeffhaobdb76512011-09-07 11:43:16 -0700356 VerifierData(Method* method, const DexFile* dex_file,
357 const DexFile::CodeItem* code_item)
358 : method_(method), dex_file_(dex_file), code_item_(code_item),
359 insn_flags_(NULL), uninit_map_(NULL), register_lines_(NULL),
jeffhaod1f0fde2011-09-08 17:25:33 -0700360 new_instance_count_(0), monitor_enter_count_(0) {
361 }
jeffhaobdb76512011-09-07 11:43:16 -0700362 };
363
364 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700365 * This is a single variable-size structure. It may be allocated on the
366 * heap or mapped out of a (post-dexopt) DEX file.
367 *
368 * 32-bit alignment of the structure is NOT guaranteed. This makes it a
369 * little awkward to deal with as a structure; to avoid accidents we use
370 * only byte types. Multi-byte values are little-endian.
371 *
372 * Size of (format==FormatNone): 1 byte
373 * Size of (format==FormatCompact8): 4 + (1 + reg_width) * num_entries
374 * Size of (format==FormatCompact16): 4 + (2 + reg_width) * num_entries
375 */
376 struct RegisterMap {
377 /* header */
378 uint8_t format_; /* enum RegisterMapFormat; MUST be first entry */
379 uint8_t reg_width_; /* bytes per register line, 1+ */
380 uint16_t num_entries_; /* number of entries */
381 bool format_on_heap_; /* indicates allocation on heap */
382
383 /* raw data starts here; need not be aligned */
384 UniquePtr<uint8_t[]> data_;
385
386 RegisterMap(uint8_t format, uint8_t reg_width, uint16_t num_entries,
387 bool format_on_heap, uint32_t data_size)
388 : format_(format), reg_width_(reg_width), num_entries_(num_entries),
389 format_on_heap_(format_on_heap), data_(new uint8_t[data_size]()) {
390 }
391 };
392
393 /*
394 * Merge result table for primitive values. The table is symmetric along
jeffhaobdb76512011-09-07 11:43:16 -0700395 * the diagonal.
396 *
jeffhaod1f0fde2011-09-08 17:25:33 -0700397 * Note that 32-bit int/float do not merge into 64-bit long/double. This
398 * is a register merge, not a widening conversion. Only the "implicit"
jeffhaobdb76512011-09-07 11:43:16 -0700399 * widening within a category, e.g. byte to short, is allowed.
400 *
401 * Dalvik does not draw a distinction between int and float, but we enforce
402 * that once a value is used as int, it can't be used as float, and vice
403 * versa. We do not allow free exchange between 32-bit int/float and 64-bit
404 * long/double.
405 *
jeffhaod1f0fde2011-09-08 17:25:33 -0700406 * Note that Uninit+Uninit=Uninit. This holds true because we only
jeffhaobdb76512011-09-07 11:43:16 -0700407 * use this when the RegType value is exactly equal to kRegTypeUninit, which
408 * can only happen for the zeroeth entry in the table.
409 *
jeffhaod1f0fde2011-09-08 17:25:33 -0700410 * "Unknown" never merges with anything known. The only time a register
jeffhaobdb76512011-09-07 11:43:16 -0700411 * transitions from "unknown" to "known" is when we're executing code
412 * for the first time, and we handle that with a simple copy.
413 */
414 static const char merge_table_[kRegTypeMAX][kRegTypeMAX];
415
416 /*
417 * Returns "true" if the flags indicate that this address holds the start
418 * of an instruction.
419 */
420 static inline bool InsnIsOpcode(const InsnFlags insn_flags[], int addr) {
421 return (insn_flags[addr] & kInsnFlagWidthMask) != 0;
422 }
423
424 /* Extract the unsigned 16-bit instruction width from "flags". */
425 static inline int InsnGetWidth(const InsnFlags insn_flags[], int addr) {
426 return insn_flags[addr] & kInsnFlagWidthMask;
427 }
428
429 /* Utilities to check and set kInsnFlagChanged. */
430 static inline bool InsnIsChanged(const InsnFlags insn_flags[], int addr) {
431 return (insn_flags[addr] & kInsnFlagChanged) != 0;
432 }
433 static inline void InsnSetChanged(InsnFlags insn_flags[], int addr,
434 bool changed) {
435 if (changed)
436 insn_flags[addr] |= kInsnFlagChanged;
437 else
438 insn_flags[addr] &= ~kInsnFlagChanged;
439 }
440
441 /* Utilities to check and set kInsnFlagVisited. */
442 static inline bool InsnIsVisited(const InsnFlags insn_flags[], int addr) {
443 return (insn_flags[addr] & kInsnFlagVisited) != 0;
444 }
445 static inline void InsnSetVisited(InsnFlags insn_flags[], int addr,
446 bool visited) {
447 if (visited)
448 insn_flags[addr] |= kInsnFlagVisited;
449 else
450 insn_flags[addr] &= ~kInsnFlagVisited;
451 }
452
453 static inline bool InsnIsVisitedOrChanged(const InsnFlags insn_flags[],
454 int addr) {
455 return (insn_flags[addr] & (kInsnFlagVisited |
456 kInsnFlagChanged)) != 0;
457 }
458
459 /* Utilities to check and set kInsnFlagInTry. */
460 static inline bool InsnIsInTry(const InsnFlags insn_flags[], int addr) {
461 return (insn_flags[addr] & kInsnFlagInTry) != 0;
462 }
463 static inline void InsnSetInTry(InsnFlags insn_flags[], int addr) {
464 insn_flags[addr] |= kInsnFlagInTry;
465 }
466
467 /* Utilities to check and set kInsnFlagBranchTarget. */
468 static inline bool InsnIsBranchTarget(const InsnFlags insn_flags[], int addr)
469 {
470 return (insn_flags[addr] & kInsnFlagBranchTarget) != 0;
471 }
472 static inline void InsnSetBranchTarget(InsnFlags insn_flags[], int addr) {
473 insn_flags[addr] |= kInsnFlagBranchTarget;
474 }
475
476 /* Utilities to check and set kInsnFlagGcPoint. */
477 static inline bool InsnIsGcPoint(const InsnFlags insn_flags[], int addr) {
478 return (insn_flags[addr] & kInsnFlagGcPoint) != 0;
479 }
480 static inline void InsnSetGcPoint(InsnFlags insn_flags[], int addr) {
481 insn_flags[addr] |= kInsnFlagGcPoint;
482 }
483
484 /* Get the class object at the specified index. */
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700485 static inline Class* GetUninitInstance(const UninitInstanceMap* uninit_map, int idx) {
486 DCHECK_GE(idx, 0);
487 DCHECK_LT(idx, uninit_map->num_entries_);
jeffhaobdb76512011-09-07 11:43:16 -0700488 return uninit_map->map_[idx].klass_;
489 }
490
491 /* Determine if "type" is actually an object reference (init/uninit/zero) */
492 static inline bool RegTypeIsReference(RegType type) {
493 return (type > kRegTypeMAX || type == kRegTypeUninit ||
494 type == kRegTypeZero);
495 }
496
497 /* Determine if "type" is an uninitialized object reference */
498 static inline bool RegTypeIsUninitReference(RegType type) {
499 return ((type & kRegTypeUninitMask) == kRegTypeUninit);
500 }
501
502 /*
503 * Convert the initialized reference "type" to a Class pointer
504 * (does not expect uninit ref types or "zero").
505 */
506 static Class* RegTypeInitializedReferenceToClass(RegType type) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700507 DCHECK(RegTypeIsReference(type) && type != kRegTypeZero);
jeffhaobdb76512011-09-07 11:43:16 -0700508 if ((type & 0x01) == 0) {
509 return (Class*) type;
510 } else {
511 LOG(ERROR) << "VFY: attempted to use uninitialized reference";
512 return NULL;
513 }
514 }
515
516 /* Extract the index into the uninitialized instance map table. */
517 static inline int RegTypeToUninitIndex(RegType type) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700518 DCHECK(RegTypeIsUninitReference(type));
jeffhaobdb76512011-09-07 11:43:16 -0700519 return (type & ~kRegTypeUninitMask) >> kRegTypeUninitShift;
520 }
521
522 /* Convert the reference "type" to a Class pointer. */
523 static Class* RegTypeReferenceToClass(RegType type,
524 const UninitInstanceMap* uninit_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700525 DCHECK(RegTypeIsReference(type) && type != kRegTypeZero);
jeffhaobdb76512011-09-07 11:43:16 -0700526 if (RegTypeIsUninitReference(type)) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700527 DCHECK(uninit_map != NULL);
jeffhaobdb76512011-09-07 11:43:16 -0700528 return GetUninitInstance(uninit_map, RegTypeToUninitIndex(type));
529 } else {
530 return (Class*) type;
531 }
532 }
533
534 /* Convert the ClassObject pointer to an (initialized) register type. */
535 static inline RegType RegTypeFromClass(Class* klass) {
536 return (uint32_t) klass;
537 }
538
539 /* Return the RegType for the uninitialized reference in slot "uidx". */
540 static inline RegType RegTypeFromUninitIndex(int uidx) {
541 return (uint32_t) (kRegTypeUninit | (uidx << kRegTypeUninitShift));
542 }
543
jeffhaobdb76512011-09-07 11:43:16 -0700544 /*
545 * Perform verification on a single method.
546 *
547 * We do this in three passes:
548 * (1) Walk through all code units, determining instruction locations,
549 * widths, and other characteristics.
550 * (2) Walk through all code units, performing static checks on
551 * operands.
552 * (3) Iterate through the method, checking type safety and looking
553 * for code flow problems.
554 *
jeffhaod1f0fde2011-09-08 17:25:33 -0700555 * Some checks may be bypassed depending on the verification mode. We can't
jeffhaobdb76512011-09-07 11:43:16 -0700556 * turn this stuff off completely if we want to do "exact" GC.
557 *
558 * Confirmed here:
559 * - code array must not be empty
560 * Confirmed by ComputeWidthsAndCountOps():
561 * - opcode of first instruction begins at index 0
562 * - only documented instructions may appear
563 * - each instruction follows the last
564 * - last byte of last instruction is at (code_length-1)
565 */
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700566 static bool VerifyMethod(Method* method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700567
jeffhaobdb76512011-09-07 11:43:16 -0700568 /*
569 * Perform static verification on all instructions in a method.
570 *
571 * Walks through instructions in a method calling VerifyInstruction on each.
572 */
573 static bool VerifyInstructions(VerifierData* vdata);
574
575 /*
576 * Perform static verification on an instruction.
577 *
578 * As a side effect, this sets the "branch target" flags in InsnFlags.
579 *
580 * "(CF)" items are handled during code-flow analysis.
581 *
582 * v3 4.10.1
583 * - target of each jump and branch instruction must be valid
584 * - targets of switch statements must be valid
585 * - operands referencing constant pool entries must be valid
586 * - (CF) operands of getfield, putfield, getstatic, putstatic must be valid
587 * - (CF) operands of method invocation instructions must be valid
588 * - (CF) only invoke-direct can call a method starting with '<'
589 * - (CF) <clinit> must never be called explicitly
590 * - operands of instanceof, checkcast, new (and variants) must be valid
591 * - new-array[-type] limited to 255 dimensions
592 * - can't use "new" on an array class
593 * - (?) limit dimensions in multi-array creation
594 * - local variable load/store register values must be in valid range
595 *
596 * v3 4.11.1.2
597 * - branches must be within the bounds of the code array
598 * - targets of all control-flow instructions are the start of an instruction
599 * - register accesses fall within range of allocated registers
600 * - (N/A) access to constant pool must be of appropriate type
601 * - code does not end in the middle of an instruction
602 * - execution cannot fall off the end of the code
603 * - (earlier) for each exception handler, the "try" area must begin and
604 * end at the start of an instruction (end can be at the end of the code)
605 * - (earlier) for each exception handler, the handler must start at a valid
606 * instruction
607 */
608 static bool VerifyInstruction(VerifierData* vdata,
609 const Instruction* inst, uint32_t code_offset);
610
611 /* Perform detailed code-flow analysis on a single method. */
612 static bool VerifyCodeFlow(VerifierData* vdata);
613
614 /*
615 * Compute the width of the instruction at each address in the instruction
jeffhaod1f0fde2011-09-08 17:25:33 -0700616 * stream, and store it in vdata->insn_flags. Addresses that are in the
jeffhaobdb76512011-09-07 11:43:16 -0700617 * middle of an instruction, or that are part of switch table data, are not
618 * touched (so the caller should probably initialize "insn_flags" to zero).
619 *
620 * The "new_instance_count_" and "monitor_enter_count_" fields in vdata are
621 * also set.
622 *
623 * Performs some static checks, notably:
624 * - opcode of first instruction begins at index 0
625 * - only documented instructions may appear
626 * - each instruction follows the last
627 * - last byte of last instruction is at (code_length-1)
628 *
629 * Logs an error and returns "false" on failure.
630 */
631 static bool ComputeWidthsAndCountOps(VerifierData* vdata);
632
633 /*
634 * Set the "in try" flags for all instructions protected by "try" statements.
635 * Also sets the "branch target" flags for exception handlers.
636 *
637 * Call this after widths have been set in "insn_flags".
638 *
639 * Returns "false" if something in the exception table looks fishy, but
640 * we're expecting the exception table to be somewhat sane.
641 */
642 static bool ScanTryCatchBlocks(VerifierData* vdata);
643
644 /*
645 * Extract the relative offset from a branch instruction.
646 *
647 * Returns "false" on failure (e.g. this isn't a branch instruction).
648 */
649 static bool GetBranchOffset(const DexFile::CodeItem* code_item,
650 const InsnFlags insn_flags[], uint32_t cur_offset, int32_t* pOffset,
651 bool* pConditional, bool* selfOkay);
652
653 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700654 * Verify an array data table. "cur_offset" is the offset of the
jeffhaobdb76512011-09-07 11:43:16 -0700655 * fill-array-data instruction.
656 */
657 static bool CheckArrayData(const DexFile::CodeItem* code_item,
658 uint32_t cur_offset);
659
660 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700661 * Perform static checks on a "new-instance" instruction. Specifically,
jeffhaobdb76512011-09-07 11:43:16 -0700662 * make sure the class reference isn't for an array class.
663 *
664 * We don't need the actual class, just a pointer to the class name.
665 */
666 static bool CheckNewInstance(const DexFile* dex_file, uint32_t idx);
667
668 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700669 * Perform static checks on a "new-array" instruction. Specifically, make
jeffhaobdb76512011-09-07 11:43:16 -0700670 * sure they aren't creating an array of arrays that causes the number of
671 * dimensions to exceed 255.
672 */
673 static bool CheckNewArray(const DexFile* dex_file, uint32_t idx);
674
675 /*
676 * Perform static checks on an instruction that takes a class constant.
677 * Ensure that the class index is in the valid range.
678 */
679 static bool CheckTypeIndex(const DexFile* dex_file, uint32_t idx);
680
681 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700682 * Perform static checks on a field get or set instruction. All we do
jeffhaobdb76512011-09-07 11:43:16 -0700683 * here is ensure that the field index is in the valid range.
684 */
685 static bool CheckFieldIndex(const DexFile* dex_file, uint32_t idx);
686
687 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700688 * Perform static checks on a method invocation instruction. All we do
jeffhaobdb76512011-09-07 11:43:16 -0700689 * here is ensure that the method index is in the valid range.
690 */
691 static bool CheckMethodIndex(const DexFile* dex_file, uint32_t idx);
692
693 /* Ensure that the string index is in the valid range. */
694 static bool CheckStringIndex(const DexFile* dex_file, uint32_t idx);
695
696 /* Ensure that the register index is valid for this code item. */
697 static bool CheckRegisterIndex(const DexFile::CodeItem* code_item,
698 uint32_t idx);
699
700 /* Ensure that the wide register index is valid for this code item. */
701 static bool CheckWideRegisterIndex(const DexFile::CodeItem* code_item,
702 uint32_t idx);
703
704 /*
705 * Check the register indices used in a "vararg" instruction, such as
706 * invoke-virtual or filled-new-array.
707 *
708 * vA holds word count (0-5), args[] have values.
709 *
710 * There are some tests we don't do here, e.g. we don't try to verify
711 * that invoking a method that takes a double is done with consecutive
jeffhaod1f0fde2011-09-08 17:25:33 -0700712 * registers. This requires parsing the target method signature, which
jeffhaobdb76512011-09-07 11:43:16 -0700713 * we will be doing later on during the code flow analysis.
714 */
715 static bool CheckVarArgRegs(const DexFile::CodeItem* code_item, uint32_t vA,
716 uint32_t arg[]);
717
718 /*
719 * Check the register indices used in a "vararg/range" instruction, such as
720 * invoke-virtual/range or filled-new-array/range.
721 *
722 * vA holds word count, vC holds index of first reg.
723 */
724 static bool CheckVarArgRangeRegs(const DexFile::CodeItem* code_item,
725 uint32_t vA, uint32_t vC);
726
727 /*
728 * Verify a switch table. "cur_offset" is the offset of the switch
729 * instruction.
730 *
731 * Updates "insnFlags", setting the "branch target" flag.
732 */
733 static bool CheckSwitchTargets(const DexFile::CodeItem* code_item,
734 InsnFlags insn_flags[], uint32_t cur_offset);
735
736 /*
737 * Verify that the target of a branch instruction is valid.
738 *
739 * We don't expect code to jump directly into an exception handler, but
740 * it's valid to do so as long as the target isn't a "move-exception"
jeffhaod1f0fde2011-09-08 17:25:33 -0700741 * instruction. We verify that in a later stage.
jeffhaobdb76512011-09-07 11:43:16 -0700742 *
743 * The dex format forbids certain instructions from branching to itself.
744 *
745 * Updates "insnFlags", setting the "branch target" flag.
746 */
747 static bool CheckBranchTarget(const DexFile::CodeItem* code_item,
748 InsnFlags insn_flags[], uint32_t cur_offset);
749
750 /*
751 * Initialize the RegisterTable.
752 *
753 * Every instruction address can have a different set of information about
754 * what's in which register, but for verification purposes we only need to
755 * store it at branch target addresses (because we merge into that).
756 *
757 * By zeroing out the regType storage we are effectively initializing the
758 * register information to kRegTypeUnknown.
759 *
760 * We jump through some hoops here to minimize the total number of
761 * allocations we have to perform per method verified.
762 */
763 static bool InitRegisterTable(VerifierData* vdata, RegisterTable* reg_table,
764 RegisterTrackingMode track_regs_for);
765
766 /* Get the register line for the given instruction in the current method. */
767 static inline RegisterLine* GetRegisterLine(const RegisterTable* reg_table,
768 int insn_idx) {
769 return &reg_table->register_lines_[insn_idx];
770 }
771
772 /* Copy a register line. */
773 static inline void CopyRegisterLine(RegisterLine* dst,
774 const RegisterLine* src, size_t num_regs) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700775 memcpy(dst->reg_types_.get(), src->reg_types_.get(), num_regs * sizeof(RegType));
jeffhaobdb76512011-09-07 11:43:16 -0700776
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700777 DCHECK((src->monitor_entries_.get() == NULL && dst->monitor_entries_.get() == NULL) ||
778 (src->monitor_entries_.get() != NULL && dst->monitor_entries_.get() != NULL));
779 if (dst->monitor_entries_.get() != NULL) {
780 DCHECK(dst->monitor_stack_.get() != NULL);
781 memcpy(dst->monitor_entries_.get(), src->monitor_entries_.get(),
jeffhaobdb76512011-09-07 11:43:16 -0700782 num_regs * sizeof(MonitorEntries));
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700783 memcpy(dst->monitor_stack_.get(), src->monitor_stack_.get(),
jeffhaobdb76512011-09-07 11:43:16 -0700784 kMaxMonitorStackDepth * sizeof(uint32_t));
785 dst->monitor_stack_top_ = src->monitor_stack_top_;
786 }
787 }
788
789 /* Copy a register line into the table. */
790 static inline void CopyLineToTable(RegisterTable* reg_table, int insn_idx,
791 const RegisterLine* src) {
792 RegisterLine* dst = GetRegisterLine(reg_table, insn_idx);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700793 DCHECK(dst->reg_types_.get() != NULL);
jeffhaobdb76512011-09-07 11:43:16 -0700794 CopyRegisterLine(dst, src, reg_table->insn_reg_count_plus_);
795 }
796
797 /* Copy a register line out of the table. */
798 static inline void CopyLineFromTable(RegisterLine* dst,
799 const RegisterTable* reg_table, int insn_idx) {
800 RegisterLine* src = GetRegisterLine(reg_table, insn_idx);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700801 DCHECK(src->reg_types_.get() != NULL);
jeffhaobdb76512011-09-07 11:43:16 -0700802 CopyRegisterLine(dst, src, reg_table->insn_reg_count_plus_);
803 }
804
805#ifndef NDEBUG
806 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700807 * Compare two register lines. Returns 0 if they match.
jeffhaobdb76512011-09-07 11:43:16 -0700808 *
809 * Using this for a sort is unwise, since the value can change based on
810 * machine endianness.
811 */
812 static inline int CompareLineToTable(const RegisterTable* reg_table,
813 int insn_idx, const RegisterLine* line2) {
814 const RegisterLine* line1 = GetRegisterLine(reg_table, insn_idx);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700815 if (line1->monitor_entries_.get() != NULL) {
jeffhaobdb76512011-09-07 11:43:16 -0700816 int result;
817
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700818 if (line2->monitor_entries_.get() == NULL)
jeffhaobdb76512011-09-07 11:43:16 -0700819 return 1;
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700820 result = memcmp(line1->monitor_entries_.get(), line2->monitor_entries_.get(),
jeffhaobdb76512011-09-07 11:43:16 -0700821 reg_table->insn_reg_count_plus_ * sizeof(MonitorEntries));
822 if (result != 0) {
823 LOG(ERROR) << "monitor_entries_ mismatch";
824 return result;
825 }
826 result = line1->monitor_stack_top_ - line2->monitor_stack_top_;
827 if (result != 0) {
828 LOG(ERROR) << "monitor_stack_top_ mismatch";
829 return result;
830 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700831 result = memcmp(line1->monitor_stack_.get(), line2->monitor_stack_.get(),
jeffhaobdb76512011-09-07 11:43:16 -0700832 line1->monitor_stack_top_);
833 if (result != 0) {
834 LOG(ERROR) << "monitor_stack_ mismatch";
835 return result;
836 }
837 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700838 return memcmp(line1->reg_types_.get(), line2->reg_types_.get(),
jeffhaobdb76512011-09-07 11:43:16 -0700839 reg_table->insn_reg_count_plus_ * sizeof(RegType));
840 }
841#endif
842
843 /*
844 * Create a new uninitialized instance map.
845 *
jeffhaod1f0fde2011-09-08 17:25:33 -0700846 * The map is allocated and populated with address entries. The addresses
jeffhaobdb76512011-09-07 11:43:16 -0700847 * appear in ascending order to allow binary searching.
848 *
849 * Very few methods have 10 or more new-instance instructions; the
jeffhaod1f0fde2011-09-08 17:25:33 -0700850 * majority have 0 or 1. Occasionally a static initializer will have 200+.
jeffhaobdb76512011-09-07 11:43:16 -0700851 *
852 * TODO: merge this into the static pass or initRegisterTable; want to
853 * avoid walking through the instructions yet again just to set up this table
854 */
855 static UninitInstanceMap* CreateUninitInstanceMap(VerifierData* vdata);
856
857 /* Returns true if this method is a constructor. */
858 static bool IsInitMethod(const Method* method);
859
860 /*
861 * Look up a class reference given as a simple string descriptor.
862 *
863 * If we can't find it, return a generic substitute when possible.
864 */
865 static Class* LookupClassByDescriptor(const Method* method,
866 const char* descriptor, VerifyError* failure);
867
868 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700869 * Look up a class reference in a signature. Could be an arg or the
jeffhaobdb76512011-09-07 11:43:16 -0700870 * return value.
871 *
872 * Advances "*sig" to the last character in the signature (that is, to
873 * the ';').
874 *
875 * NOTE: this is also expected to verify the signature.
876 */
877 static Class* LookupSignatureClass(const Method* method, std::string sig,
878 VerifyError* failure);
879
880 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700881 * Look up an array class reference in a signature. Could be an arg or the
jeffhaobdb76512011-09-07 11:43:16 -0700882 * return value.
883 *
884 * Advances "*sig" to the last character in the signature.
885 *
886 * NOTE: this is also expected to verify the signature.
887 */
888 static Class* LookupSignatureArrayClass(const Method* method,
889 std::string sig, VerifyError* failure);
890
891 /*
892 * Set the register types for the first instruction in the method based on
893 * the method signature.
894 *
895 * This has the side-effect of validating the signature.
896 *
897 * Returns "true" on success.
898 */
899 static bool SetTypesFromSignature(VerifierData* vdata, RegType* reg_types);
900
901 /*
902 * Set the class object associated with the instruction at "addr".
903 *
904 * Returns the map slot index, or -1 if the address isn't listed in the map
905 * (shouldn't happen) or if a class is already associated with the address
906 * (bad bytecode).
907 *
908 * Entries, once set, do not change -- a given address can only allocate
909 * one type of object.
910 */
911 static int SetUninitInstance(UninitInstanceMap* uninit_map, int addr,
912 Class* klass);
913
914 /*
915 * Perform code flow on a method.
916 *
917 * The basic strategy is as outlined in v3 4.11.1.2: set the "changed" bit
918 * on the first instruction, process it (setting additional "changed" bits),
919 * and repeat until there are no more.
920 *
921 * v3 4.11.1.1
922 * - (N/A) operand stack is always the same size
923 * - operand stack [registers] contain the correct types of values
924 * - local variables [registers] contain the correct types of values
925 * - methods are invoked with the appropriate arguments
926 * - fields are assigned using values of appropriate types
927 * - opcodes have the correct type values in operand registers
928 * - there is never an uninitialized class instance in a local variable in
929 * code protected by an exception handler (operand stack is okay, because
930 * the operand stack is discarded when an exception is thrown) [can't
931 * know what's a local var w/o the debug info -- should fall out of
932 * register typing]
933 *
934 * v3 4.11.1.2
935 * - execution cannot fall off the end of the code
936 *
937 * (We also do many of the items described in the "static checks" sections,
938 * because it's easier to do them here.)
939 *
940 * We need an array of RegType values, one per register, for every
jeffhaod1f0fde2011-09-08 17:25:33 -0700941 * instruction. If the method uses monitor-enter, we need extra data
jeffhaobdb76512011-09-07 11:43:16 -0700942 * for every register, and a stack for every "interesting" instruction.
943 * In theory this could become quite large -- up to several megabytes for
944 * a monster function.
945 *
946 * NOTE:
947 * The spec forbids backward branches when there's an uninitialized reference
jeffhaod1f0fde2011-09-08 17:25:33 -0700948 * in a register. The idea is to prevent something like this:
jeffhaobdb76512011-09-07 11:43:16 -0700949 * loop:
950 * move r1, r0
951 * new-instance r0, MyClass
952 * ...
953 * if-eq rN, loop // once
954 * initialize r0
955 *
956 * This leaves us with two different instances, both allocated by the
jeffhaod1f0fde2011-09-08 17:25:33 -0700957 * same instruction, but only one is initialized. The scheme outlined in
jeffhaobdb76512011-09-07 11:43:16 -0700958 * v3 4.11.1.4 wouldn't catch this, so they work around it by preventing
jeffhaod1f0fde2011-09-08 17:25:33 -0700959 * backward branches. We achieve identical results without restricting
jeffhaobdb76512011-09-07 11:43:16 -0700960 * code reordering by specifying that you can't execute the new-instance
961 * instruction if a register contains an uninitialized instance created
962 * by that same instrutcion.
963 */
964 static bool CodeFlowVerifyMethod(VerifierData* vdata,
965 RegisterTable* reg_table);
966
967 /*
968 * Perform verification for a single instruction.
969 *
970 * This requires fully decoding the instruction to determine the effect
971 * it has on registers.
972 *
973 * Finds zero or more following instructions and sets the "changed" flag
jeffhaod1f0fde2011-09-08 17:25:33 -0700974 * if execution at that point needs to be (re-)evaluated. Register changes
975 * are merged into "reg_types_" at the target addresses. Does not set or
jeffhaobdb76512011-09-07 11:43:16 -0700976 * clear any other flags in "insn_flags".
977 */
978 static bool CodeFlowVerifyInstruction(VerifierData* vdata,
979 RegisterTable* reg_table, uint32_t insn_idx, size_t* start_guess);
980
981 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700982 * Replace an instruction with "throw-verification-error". This allows us to
jeffhaobdb76512011-09-07 11:43:16 -0700983 * defer error reporting until the code path is first used.
984 *
985 * This is expected to be called during "just in time" verification, not
jeffhaod1f0fde2011-09-08 17:25:33 -0700986 * from within dexopt. (Verification failures in dexopt will result in
jeffhaobdb76512011-09-07 11:43:16 -0700987 * postponement of verification to first use of the class.)
988 *
jeffhaod1f0fde2011-09-08 17:25:33 -0700989 * The throw-verification-error instruction requires two code units. Some
jeffhaobdb76512011-09-07 11:43:16 -0700990 * of the replaced instructions require three; the third code unit will
jeffhaod1f0fde2011-09-08 17:25:33 -0700991 * receive a "nop". The instruction's length will be left unchanged
jeffhaobdb76512011-09-07 11:43:16 -0700992 * in "insn_flags".
993 *
994 * The VM postpones setting of debugger breakpoints in unverified classes,
995 * so there should be no clashes with the debugger.
996 *
997 * Returns "true" on success.
998 */
999 static bool ReplaceFailingInstruction(const DexFile::CodeItem* code_item,
1000 InsnFlags* insn_flags, int insn_idx, VerifyError failure);
1001
1002 /* Handle a monitor-enter instruction. */
1003 static void HandleMonitorEnter(RegisterLine* work_line, uint32_t reg_idx,
1004 uint32_t insn_idx, VerifyError* failure);
1005
1006 /* Handle a monitor-exit instruction. */
1007 static void HandleMonitorExit(RegisterLine* work_line, uint32_t reg_idx,
1008 uint32_t insn_idx, VerifyError* failure);
1009
1010 /*
1011 * Look up an instance field, specified by "field_idx", that is going to be
jeffhaod1f0fde2011-09-08 17:25:33 -07001012 * accessed in object "obj_type". This resolves the field and then verifies
jeffhaobdb76512011-09-07 11:43:16 -07001013 * that the class containing the field is an instance of the reference in
1014 * "obj_type".
1015 *
1016 * It is possible for "obj_type" to be kRegTypeZero, meaning that we might
jeffhaod1f0fde2011-09-08 17:25:33 -07001017 * have a null reference. This is a runtime problem, so we allow it,
jeffhaobdb76512011-09-07 11:43:16 -07001018 * skipping some of the type checks.
1019 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001020 * In general, "obj_type" must be an initialized reference. However, we
jeffhaobdb76512011-09-07 11:43:16 -07001021 * allow it to be uninitialized if this is an "<init>" method and the field
1022 * is declared within the "obj_type" class.
1023 *
1024 * Returns a Field on success, returns NULL and sets "*failure" on failure.
1025 */
1026 static Field* GetInstField(VerifierData* vdata, RegType obj_type,
1027 int field_idx, VerifyError* failure);
1028
1029 /*
1030 * Look up a static field.
1031 *
1032 * Returns a StaticField on success, returns NULL and sets "*failure"
1033 * on failure.
1034 */
1035 static Field* GetStaticField(VerifierData* vdata, int field_idx,
1036 VerifyError* failure);
1037 /*
1038 * For the "move-exception" instruction at "insn_idx", which must be at an
1039 * exception handler address, determine the first common superclass of
jeffhaod1f0fde2011-09-08 17:25:33 -07001040 * all exceptions that can land here. (For javac output, we're probably
jeffhaobdb76512011-09-07 11:43:16 -07001041 * looking at multiple spans of bytecode covered by one "try" that lands
1042 * at an exception-specific "catch", but in general the handler could be
1043 * shared for multiple exceptions.)
1044 *
1045 * Returns NULL if no matching exception handler can be found, or if the
1046 * exception is not a subclass of Throwable.
1047 */
1048 static Class* GetCaughtExceptionType(VerifierData* vdata, int insn_idx,
1049 VerifyError* failure);
1050
1051 /*
1052 * Get the type of register N.
1053 *
1054 * The register index was validated during the static pass, so we don't
1055 * need to check it here.
1056 */
1057 static inline RegType GetRegisterType(const RegisterLine* register_line,
1058 uint32_t vsrc) {
1059 return register_line->reg_types_[vsrc];
1060 }
1061
1062 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001063 * Return the register type for the method. We can't just use the
jeffhaobdb76512011-09-07 11:43:16 -07001064 * already-computed DalvikJniReturnType, because if it's a reference type
1065 * we need to do the class lookup.
1066 *
1067 * Returned references are assumed to be initialized.
1068 *
1069 * Returns kRegTypeUnknown for "void".
1070 */
1071 static RegType GetMethodReturnType(const DexFile* dex_file,
1072 const Method* method);
1073
1074 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001075 * Get the value from a register, and cast it to a Class. Sets
jeffhaobdb76512011-09-07 11:43:16 -07001076 * "*failure" if something fails.
1077 *
1078 * This fails if the register holds an uninitialized class.
1079 *
1080 * If the register holds kRegTypeZero, this returns a NULL pointer.
1081 */
1082 static Class* GetClassFromRegister(const RegisterLine* register_line,
1083 uint32_t vsrc, VerifyError* failure);
1084
1085 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001086 * Get the "this" pointer from a non-static method invocation. This
jeffhaobdb76512011-09-07 11:43:16 -07001087 * returns the RegType so the caller can decide whether it needs the
jeffhaod1f0fde2011-09-08 17:25:33 -07001088 * reference to be initialized or not. (Can also return kRegTypeZero
jeffhaobdb76512011-09-07 11:43:16 -07001089 * if the reference can only be zero at this point.)
1090 *
1091 * The argument count is in vA, and the first argument is in vC, for both
jeffhaod1f0fde2011-09-08 17:25:33 -07001092 * "simple" and "range" versions. We just need to make sure vA is >= 1
jeffhaobdb76512011-09-07 11:43:16 -07001093 * and then return vC.
1094 */
1095 static RegType GetInvocationThis(const RegisterLine* register_line,
1096 const Instruction::DecodedInstruction* dec_insn, VerifyError* failure);
1097
1098 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001099 * Set the type of register N, verifying that the register is valid. If
jeffhaobdb76512011-09-07 11:43:16 -07001100 * "new_type" is the "Lo" part of a 64-bit value, register N+1 will be
1101 * set to "new_type+1".
1102 *
1103 * The register index was validated during the static pass, so we don't
1104 * need to check it here.
1105 *
1106 * TODO: clear mon stack bits
1107 */
1108 static void SetRegisterType(RegisterLine* register_line, uint32_t vdst,
1109 RegType new_type);
1110
1111 /*
1112 * Verify that the contents of the specified register have the specified
1113 * type (or can be converted to it through an implicit widening conversion).
1114 *
1115 * This will modify the type of the source register if it was originally
1116 * derived from a constant to prevent mixing of int/float and long/double.
1117 *
1118 * If "vsrc" is a reference, both it and the "vsrc" register must be
jeffhaod1f0fde2011-09-08 17:25:33 -07001119 * initialized ("vsrc" may be Zero). This will verify that the value in
jeffhaobdb76512011-09-07 11:43:16 -07001120 * the register is an instance of check_type, or if check_type is an
1121 * interface, verify that the register implements check_type.
1122 */
1123 static void VerifyRegisterType(RegisterLine* register_line, uint32_t vsrc,
1124 RegType check_type, VerifyError* failure);
1125
1126 /* Set the type of the "result" register. */
1127 static void SetResultRegisterType(RegisterLine* register_line,
1128 const int insn_reg_count, RegType new_type);
1129
1130 /*
1131 * Update all registers holding "uninit_type" to instead hold the
jeffhaod1f0fde2011-09-08 17:25:33 -07001132 * corresponding initialized reference type. This is called when an
jeffhaobdb76512011-09-07 11:43:16 -07001133 * appropriate <init> method is invoked -- all copies of the reference
1134 * must be marked as initialized.
1135 */
1136 static void MarkRefsAsInitialized(RegisterLine* register_line,
1137 int insn_reg_count, UninitInstanceMap* uninit_map, RegType uninit_type,
1138 VerifyError* failure);
1139
1140 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001141 * Implement category-1 "move" instructions. Copy a 32-bit value from
jeffhaobdb76512011-09-07 11:43:16 -07001142 * "vsrc" to "vdst".
1143 */
1144 static void CopyRegister1(RegisterLine* register_line, uint32_t vdst,
1145 uint32_t vsrc, TypeCategory cat, VerifyError* failure);
1146
1147 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001148 * Implement category-2 "move" instructions. Copy a 64-bit value from
1149 * "vsrc" to "vdst". This copies both halves of the register.
jeffhaobdb76512011-09-07 11:43:16 -07001150 */
1151 static void CopyRegister2(RegisterLine* register_line, uint32_t vdst,
1152 uint32_t vsrc, VerifyError* failure);
1153
1154 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001155 * Implement "move-result". Copy the category-1 value from the result
jeffhaobdb76512011-09-07 11:43:16 -07001156 * register to another register, and reset the result register.
1157 */
1158 static void CopyResultRegister1(RegisterLine* register_line,
1159 const int insn_reg_count, uint32_t vdst, TypeCategory cat,
1160 VerifyError* failure);
1161
1162 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001163 * Implement "move-result-wide". Copy the category-2 value from the result
jeffhaobdb76512011-09-07 11:43:16 -07001164 * register to another register, and reset the result register.
1165 */
1166 static void CopyResultRegister2(RegisterLine* register_line,
1167 const int insn_reg_count, uint32_t vdst, VerifyError* failure);
1168
1169 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001170 * Compute the "class depth" of a class. This is the distance from the
1171 * class to the top of the tree, chasing superclass links. java.lang.Object
jeffhaobdb76512011-09-07 11:43:16 -07001172 * has a class depth of 0.
1173 */
1174 static int GetClassDepth(Class* klass);
1175
1176 /*
1177 * Given two classes, walk up the superclass tree to find a common
jeffhaod1f0fde2011-09-08 17:25:33 -07001178 * ancestor. (Called from findCommonSuperclass().)
jeffhaobdb76512011-09-07 11:43:16 -07001179 *
1180 * TODO: consider caching the class depth in the class object so we don't
1181 * have to search for it here.
1182 */
1183 static Class* DigForSuperclass(Class* c1, Class* c2);
1184
1185 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001186 * Merge two array classes. We can't use the general "walk up to the
jeffhaobdb76512011-09-07 11:43:16 -07001187 * superclass" merge because the superclass of an array is always Object.
jeffhaod1f0fde2011-09-08 17:25:33 -07001188 * We want String[] + Integer[] = Object[]. This works for higher dimensions
jeffhaobdb76512011-09-07 11:43:16 -07001189 * as well, e.g. String[][] + Integer[][] = Object[][].
1190 *
1191 * If Foo1 and Foo2 are subclasses of Foo, Foo1[] + Foo2[] = Foo[].
1192 *
1193 * If Class implements Type, Class[] + Type[] = Type[].
1194 *
1195 * If the dimensions don't match, we want to convert to an array of Object
1196 * with the least dimension, e.g. String[][] + String[][][][] = Object[][].
1197 *
1198 * Arrays of primitive types effectively have one less dimension when
jeffhaod1f0fde2011-09-08 17:25:33 -07001199 * merging. int[] + float[] = Object, int[] + String[] = Object,
1200 * int[][] + float[][] = Object[], int[][] + String[] = Object[]. (The
jeffhaobdb76512011-09-07 11:43:16 -07001201 * only time this function doesn't return an array class is when one of
1202 * the arguments is a 1-dimensional primitive array.)
1203 *
1204 * This gets a little awkward because we may have to ask the VM to create
jeffhaod1f0fde2011-09-08 17:25:33 -07001205 * a new array type with the appropriate element and dimensions. However, we
jeffhaobdb76512011-09-07 11:43:16 -07001206 * shouldn't be doing this often.
1207 */
1208 static Class* FindCommonArraySuperclass(Class* c1, Class* c2);
1209
1210 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001211 * Find the first common superclass of the two classes. We're not
jeffhaobdb76512011-09-07 11:43:16 -07001212 * interested in common interfaces.
1213 *
1214 * The easiest way to do this for concrete classes is to compute the "class
1215 * depth" of each, move up toward the root of the deepest one until they're
1216 * at the same depth, then walk both up to the root until they match.
1217 *
1218 * If both classes are arrays, we need to merge based on array depth and
1219 * element type.
1220 *
1221 * If one class is an interface, we check to see if the other class/interface
jeffhaod1f0fde2011-09-08 17:25:33 -07001222 * (or one of its predecessors) implements the interface. If so, we return
jeffhaobdb76512011-09-07 11:43:16 -07001223 * the interface; otherwise, we return Object.
1224 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001225 * NOTE: we continue the tradition of "lazy interface handling". To wit,
jeffhaobdb76512011-09-07 11:43:16 -07001226 * suppose we have three classes:
1227 * One implements Fancy, Free
1228 * Two implements Fancy, Free
1229 * Three implements Free
jeffhaod1f0fde2011-09-08 17:25:33 -07001230 * where Fancy and Free are unrelated interfaces. The code requires us
1231 * to merge One into Two. Ideally we'd use a common interface, which
jeffhaobdb76512011-09-07 11:43:16 -07001232 * gives us a choice between Fancy and Free, and no guidance on which to
jeffhaod1f0fde2011-09-08 17:25:33 -07001233 * use. If we use Free, we'll be okay when Three gets merged in, but if
1234 * we choose Fancy, we're hosed. The "ideal" solution is to create a
jeffhaobdb76512011-09-07 11:43:16 -07001235 * set of common interfaces and carry that around, merging further references
jeffhaod1f0fde2011-09-08 17:25:33 -07001236 * into it. This is a pain. The easy solution is to simply boil them
jeffhaobdb76512011-09-07 11:43:16 -07001237 * down to Objects and let the runtime invokeinterface call fail, which
1238 * is what we do.
1239 */
1240 static Class* FindCommonSuperclass(Class* c1, Class* c2);
1241
1242 /*
jeffhao98eacac2011-09-14 16:11:53 -07001243 * Resolves a class based on an index and performs access checks to ensure
1244 * the referrer can access the resolved class.
1245 *
1246 * Exceptions caused by failures are cleared before returning.
1247 *
1248 * Sets "*failure" on failure.
1249 */
1250 static Class* ResolveClassAndCheckAccess(const DexFile* dex_file,
1251 uint32_t class_idx, const Class* referrer, VerifyError* failure);
1252
1253 /*
jeffhaobdb76512011-09-07 11:43:16 -07001254 * Merge two RegType values.
1255 *
1256 * Sets "*changed" to "true" if the result doesn't match "type1".
1257 */
1258 static RegType MergeTypes(RegType type1, RegType type2, bool* changed);
1259
1260 /*
1261 * Merge the bits that indicate which monitor entry addresses on the stack
1262 * are associated with this register.
1263 *
1264 * The merge is a simple bitwise AND.
1265 *
jeffhao98eacac2011-09-14 16:11:53 -07001266 * Sets "*changed" to "true" if the result doesn't match "ents1".
jeffhaobdb76512011-09-07 11:43:16 -07001267 */
1268 static MonitorEntries MergeMonitorEntries(MonitorEntries ents1,
1269 MonitorEntries ents2, bool* changed);
1270
1271 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001272 * We're creating a new instance of class C at address A. Any registers
jeffhaobdb76512011-09-07 11:43:16 -07001273 * holding instances previously created at address A must be initialized
jeffhaod1f0fde2011-09-08 17:25:33 -07001274 * by now. If not, we mark them as "conflict" to prevent them from being
jeffhaobdb76512011-09-07 11:43:16 -07001275 * used (otherwise, MarkRefsAsInitialized would mark the old ones and the
1276 * new ones at the same time).
1277 */
1278 static void MarkUninitRefsAsInvalid(RegisterLine* register_line,
1279 int insn_reg_count, UninitInstanceMap* uninit_map, RegType uninit_type);
1280
1281 /*
1282 * Control can transfer to "next_insn".
1283 *
1284 * Merge the registers from "work_line" into "reg_table" at "next_insn", and
1285 * set the "changed" flag on the target address if any of the registers
1286 * has changed.
1287 *
1288 * Returns "false" if we detect mismatched monitor stacks.
1289 */
1290 static bool UpdateRegisters(InsnFlags* insn_flags, RegisterTable* reg_table,
1291 int next_insn, const RegisterLine* work_line);
1292
1293 /*
1294 * Determine whether we can convert "src_type" to "check_type", where
1295 * "check_type" is one of the category-1 non-reference types.
1296 *
1297 * Constant derived types may become floats, but other values may not.
1298 */
1299 static bool CanConvertTo1nr(RegType src_type, RegType check_type);
1300
1301 /* Determine whether the category-2 types are compatible. */
1302 static bool CanConvertTo2(RegType src_type, RegType check_type);
1303
1304 /* Convert a VM PrimitiveType enum value to the equivalent RegType value. */
1305 static RegType PrimitiveTypeToRegType(Class::PrimitiveType prim_type);
1306
1307 /*
1308 * Convert a const derived RegType to the equivalent non-const RegType value.
1309 * Does nothing if the argument type isn't const derived.
1310 */
1311 static RegType ConstTypeToRegType(RegType const_type);
1312
1313 /*
1314 * Given a 32-bit constant, return the most-restricted RegType enum entry
1315 * that can hold the value. The types used here indicate the value came
1316 * from a const instruction, and may not correctly represent the real type
1317 * of the value. Upon use, a constant derived type is updated with the
1318 * type from the use, which will be unambiguous.
1319 */
1320 static char DetermineCat1Const(int32_t value);
1321
1322 /*
1323 * If "field" is marked "final", make sure this is the either <clinit>
1324 * or <init> as appropriate.
1325 *
1326 * Sets "*failure" on failure.
1327 */
1328 static void CheckFinalFieldAccess(const Method* method, const Field* field,
1329 VerifyError* failure);
1330
1331 /*
1332 * Make sure that the register type is suitable for use as an array index.
1333 *
1334 * Sets "*failure" if not.
1335 */
1336 static void CheckArrayIndexType(const Method* method, RegType reg_type,
1337 VerifyError* failure);
1338
1339 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001340 * Check constraints on constructor return. Specifically, make sure that
jeffhaobdb76512011-09-07 11:43:16 -07001341 * the "this" argument got initialized.
1342 *
1343 * The "this" argument to <init> uses code offset kUninitThisArgAddr, which
jeffhaod1f0fde2011-09-08 17:25:33 -07001344 * puts it at the start of the list in slot 0. If we see a register with
jeffhaobdb76512011-09-07 11:43:16 -07001345 * an uninitialized slot 0 reference, we know it somehow didn't get
1346 * initialized.
1347 *
1348 * Returns "true" if all is well.
1349 */
1350 static bool CheckConstructorReturn(const Method* method,
1351 const RegisterLine* register_line, const int insn_reg_count);
1352
1353 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001354 * Verify that the target instruction is not "move-exception". It's important
jeffhaobdb76512011-09-07 11:43:16 -07001355 * that the only way to execute a move-exception is as the first instruction
1356 * of an exception handler.
1357 *
1358 * Returns "true" if all is well, "false" if the target instruction is
1359 * move-exception.
1360 */
1361 static bool CheckMoveException(const uint16_t* insns, int insn_idx);
1362
1363 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001364 * See if "type" matches "cat". All we're really looking for here is that
jeffhaobdb76512011-09-07 11:43:16 -07001365 * we're not mixing and matching 32-bit and 64-bit quantities, and we're
jeffhaod1f0fde2011-09-08 17:25:33 -07001366 * not mixing references with numerics. (For example, the arguments to
jeffhaobdb76512011-09-07 11:43:16 -07001367 * "a < b" could be integers of different sizes, but they must both be
jeffhaod1f0fde2011-09-08 17:25:33 -07001368 * integers. Dalvik is less specific about int vs. float, so we treat them
jeffhaobdb76512011-09-07 11:43:16 -07001369 * as equivalent here.)
1370 *
1371 * For category 2 values, "type" must be the "low" half of the value.
1372 *
1373 * Sets "*failure" if something looks wrong.
1374 */
1375 static void CheckTypeCategory(RegType type, TypeCategory cat,
1376 VerifyError* failure);
1377
1378 /*
1379 * For a category 2 register pair, verify that "type_h" is the appropriate
1380 * high part for "type_l".
1381 *
1382 * Does not verify that "type_l" is in fact the low part of a 64-bit
1383 * register pair.
1384 */
1385 static void CheckWidePair(RegType type_l, RegType type_h,
1386 VerifyError* failure);
1387
1388 /*
1389 * Verify types for a simple two-register instruction (e.g. "neg-int").
1390 * "dst_type" is stored into vA, and "src_type" is verified against vB.
1391 */
1392 static void CheckUnop(RegisterLine* register_line,
1393 Instruction::DecodedInstruction* dec_insn, RegType dst_type,
1394 RegType src_type, VerifyError* failure);
1395
1396 /*
1397 * Verify types for a simple three-register instruction (e.g. "add-int").
1398 * "dst_type" is stored into vA, and "src_type1"/"src_type2" are verified
1399 * against vB/vC.
1400 */
1401 static void CheckBinop(RegisterLine* register_line,
1402 Instruction::DecodedInstruction* dec_insn, RegType dst_type,
1403 RegType src_type1, RegType src_type2, bool check_boolean_op,
1404 VerifyError* failure);
1405
1406 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001407 * Verify types for a binary "2addr" operation. "src_type1"/"src_type2"
jeffhaobdb76512011-09-07 11:43:16 -07001408 * are verified against vA/vB, then "dst_type" is stored into vA.
1409 */
1410 static void CheckBinop2addr(RegisterLine* register_line,
1411 Instruction::DecodedInstruction* dec_insn, RegType dst_type,
1412 RegType src_type1, RegType src_type2, bool check_boolean_op,
1413 VerifyError* failure);
1414
1415 /*
1416 * Treat right-shifting as a narrowing conversion when possible.
1417 *
1418 * For example, right-shifting an int 24 times results in a value that can
1419 * be treated as a byte.
1420 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001421 * Things get interesting when contemplating sign extension. Right-
jeffhaobdb76512011-09-07 11:43:16 -07001422 * shifting an integer by 16 yields a value that can be represented in a
1423 * "short" but not a "char", but an unsigned right shift by 16 yields a
jeffhaod1f0fde2011-09-08 17:25:33 -07001424 * value that belongs in a char rather than a short. (Consider what would
jeffhaobdb76512011-09-07 11:43:16 -07001425 * happen if the result of the shift were cast to a char or short and then
jeffhaod1f0fde2011-09-08 17:25:33 -07001426 * cast back to an int. If sign extension, or the lack thereof, causes
jeffhaobdb76512011-09-07 11:43:16 -07001427 * a change in the 32-bit representation, then the conversion was lossy.)
1428 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001429 * A signed right shift by 17 on an integer results in a short. An unsigned
jeffhaobdb76512011-09-07 11:43:16 -07001430 * right shfit by 17 on an integer results in a posshort, which can be
1431 * assigned to a short or a char.
1432 *
1433 * An unsigned right shift on a short can actually expand the result into
jeffhaod1f0fde2011-09-08 17:25:33 -07001434 * a 32-bit integer. For example, 0xfffff123 >>> 8 becomes 0x00fffff1,
jeffhaobdb76512011-09-07 11:43:16 -07001435 * which can't be represented in anything smaller than an int.
1436 *
1437 * javac does not generate code that takes advantage of this, but some
jeffhaod1f0fde2011-09-08 17:25:33 -07001438 * of the code optimizers do. It's generally a peephole optimization
jeffhaobdb76512011-09-07 11:43:16 -07001439 * that replaces a particular sequence, e.g. (bipush 24, ishr, i2b) is
jeffhaod1f0fde2011-09-08 17:25:33 -07001440 * replaced by (bipush 24, ishr). Knowing that shifting a short 8 times
jeffhaobdb76512011-09-07 11:43:16 -07001441 * to the right yields a byte is really more than we need to handle the
1442 * code that's out there, but support is not much more complex than just
1443 * handling integer.
1444 *
1445 * Right-shifting never yields a boolean value.
1446 *
1447 * Returns the new register type.
1448 */
1449 static RegType AdjustForRightShift(RegisterLine* register_line, int reg,
1450 unsigned int shift_count, bool is_unsigned_shift, VerifyError* failure);
1451
1452 /*
1453 * We're performing an operation like "and-int/2addr" that can be
jeffhaod1f0fde2011-09-08 17:25:33 -07001454 * performed on booleans as well as integers. We get no indication of
jeffhaobdb76512011-09-07 11:43:16 -07001455 * boolean-ness, but we can infer it from the types of the arguments.
1456 *
1457 * Assumes we've already validated reg1/reg2.
1458 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001459 * TODO: consider generalizing this. The key principle is that the
jeffhaobdb76512011-09-07 11:43:16 -07001460 * result of a bitwise operation can only be as wide as the widest of
jeffhaod1f0fde2011-09-08 17:25:33 -07001461 * the operands. You can safely AND/OR/XOR two chars together and know
jeffhaobdb76512011-09-07 11:43:16 -07001462 * you still have a char, so it's reasonable for the compiler or "dx"
jeffhaod1f0fde2011-09-08 17:25:33 -07001463 * to skip the int-to-char instruction. (We need to do this for boolean
jeffhaobdb76512011-09-07 11:43:16 -07001464 * because there is no int-to-boolean operation.)
1465 *
1466 * Returns true if both args are Boolean, Zero, or One.
1467 */
1468 static bool UpcastBooleanOp(RegisterLine* register_line, uint32_t reg1,
1469 uint32_t reg2);
1470
1471 /*
1472 * Verify types for A two-register instruction with a literal constant
jeffhaod1f0fde2011-09-08 17:25:33 -07001473 * (e.g. "add-int/lit8"). "dst_type" is stored into vA, and "src_type" is
jeffhaobdb76512011-09-07 11:43:16 -07001474 * verified against vB.
1475 *
1476 * If "check_boolean_op" is set, we use the constant value in vC.
1477 */
1478 static void CheckLitop(RegisterLine* register_line,
1479 Instruction::DecodedInstruction* dec_insn, RegType dst_type,
1480 RegType src_type, bool check_boolean_op, VerifyError* failure);
1481
1482 /*
1483 * Verify that the arguments in a filled-new-array instruction are valid.
1484 *
1485 * "res_class" is the class refered to by dec_insn->vB_.
1486 */
1487 static void VerifyFilledNewArrayRegs(const Method* method,
1488 RegisterLine* register_line,
1489 const Instruction::DecodedInstruction* dec_insn, Class* res_class,
1490 bool is_range, VerifyError* failure);
1491
1492 /* See if the method matches the MethodType. */
1493 static bool IsCorrectInvokeKind(MethodType method_type, Method* res_method);
1494
1495 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001496 * Verify the arguments to a method. We're executing in "method", making
jeffhaobdb76512011-09-07 11:43:16 -07001497 * a call to the method reference in vB.
1498 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001499 * If this is a "direct" invoke, we allow calls to <init>. For calls to
1500 * <init>, the first argument may be an uninitialized reference. Otherwise,
jeffhaobdb76512011-09-07 11:43:16 -07001501 * calls to anything starting with '<' will be rejected, as will any
1502 * uninitialized reference arguments.
1503 *
1504 * For non-static method calls, this will verify that the method call is
1505 * appropriate for the "this" argument.
1506 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001507 * The method reference is in vBBBB. The "is_range" parameter determines
jeffhaobdb76512011-09-07 11:43:16 -07001508 * whether we use 0-4 "args" values or a range of registers defined by
1509 * vAA and vCCCC.
1510 *
1511 * Widening conversions on integers and references are allowed, but
1512 * narrowing conversions are not.
1513 *
1514 * Returns the resolved method on success, NULL on failure (with *failure
1515 * set appropriately).
1516 */
1517 static Method* VerifyInvocationArgs(VerifierData* vdata,
1518 RegisterLine* register_line, const int insn_reg_count,
1519 const Instruction::DecodedInstruction* dec_insn, MethodType method_type,
1520 bool is_range, bool is_super, VerifyError* failure);
1521
jeffhaod1f0fde2011-09-08 17:25:33 -07001522 /*
1523 * Generate the register map for a method that has just been verified
1524 * (i.e. we're doing this as part of verification).
1525 *
1526 * For type-precise determination we have all the data we need, so we
1527 * just need to encode it in some clever fashion.
1528 *
1529 * Returns a pointer to a newly-allocated RegisterMap, or NULL on failure.
1530 */
1531 static RegisterMap* GenerateRegisterMapV(VerifierData* vdata);
1532
1533 /*
1534 * Determine if the RegType value is a reference type.
1535 *
1536 * Ordinarily we include kRegTypeZero in the "is it a reference"
1537 * check. There's no value in doing so here, because we know
1538 * the register can't hold anything but zero.
1539 */
1540 static inline bool IsReferenceType(RegType type) {
1541 return (type > kRegTypeMAX || type == kRegTypeUninit);
1542 }
1543
1544 /* Toggle the value of the "idx"th bit in "ptr". */
1545 static inline void ToggleBit(uint8_t* ptr, int idx) {
1546 ptr[idx >> 3] ^= 1 << (idx & 0x07);
1547 }
1548
1549 /*
1550 * Given a line of registers, output a bit vector that indicates whether
1551 * or not the register holds a reference type (which could be null).
1552 *
1553 * We use '1' to indicate it's a reference, '0' for anything else (numeric
1554 * value, uninitialized data, merge conflict). Register 0 will be found
1555 * in the low bit of the first byte.
1556 */
1557 static void OutputTypeVector(const RegType* regs, int insn_reg_count,
1558 uint8_t* data);
1559
1560 /*
1561 * Double-check the map.
1562 *
1563 * We run through all of the data in the map, and compare it to the original.
1564 * Only works on uncompressed data.
1565 */
1566 static bool VerifyMap(VerifierData* vdata, const RegisterMap* map);
1567
1568 /* Compare two register maps. Returns true if they're equal, false if not. */
1569 static bool CompareMaps(const RegisterMap* map1, const RegisterMap* map2);
1570
1571 /* Compute the size, in bytes, of a register map. */
1572 static size_t ComputeRegisterMapSize(const RegisterMap* map);
1573
1574 /*
1575 * Compute the difference between two bit vectors.
1576 *
1577 * If "leb_out_buf" is non-NULL, we output the bit indices in ULEB128 format
1578 * as we go. Otherwise, we just generate the various counts.
1579 *
1580 * The bit vectors are compared byte-by-byte, so any unused bits at the
1581 * end must be zero.
1582 *
1583 * Returns the number of bytes required to hold the ULEB128 output.
1584 *
1585 * If "first_bit_changed_ptr" or "num_bits_changed_ptr" are non-NULL, they
1586 * will receive the index of the first changed bit and the number of changed
1587 * bits, respectively.
1588 */
1589 static int ComputeBitDiff(const uint8_t* bits1, const uint8_t* bits2,
1590 int byte_width, int* first_bit_changed_ptr, int* num_bits_changed_ptr,
1591 uint8_t* leb_out_buf);
1592
1593 /*
1594 * Compress the register map with differential encoding.
1595 *
1596 * On success, returns a newly-allocated RegisterMap. If the map is not
1597 * compatible for some reason, or fails to get smaller, this will return NULL.
1598 */
1599 static RegisterMap* CompressMapDifferential(const RegisterMap* map);
1600
1601 /*
1602 * Expand a compressed map to an uncompressed form.
1603 *
1604 * Returns a newly-allocated RegisterMap on success, or NULL on failure.
1605 *
1606 * TODO: consider using the linear allocator or a custom allocator with
1607 * LRU replacement for these instead of the native heap.
1608 */
1609 static RegisterMap* UncompressMapDifferential(const RegisterMap* map);
1610
jeffhaobdb76512011-09-07 11:43:16 -07001611 DISALLOW_COPY_AND_ASSIGN(DexVerifier);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001612};
1613
1614} // namespace art
1615
1616#endif // ART_SRC_DEX_VERIFY_H_