blob: 96349a3b7e4478b8f2ebb524bf4b422336bbf0da [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:
jeffhaobdb76512011-09-07 11:43:16 -070037 /*
38 * RegType holds information about the type of data held in a register.
jeffhaod1f0fde2011-09-08 17:25:33 -070039 * For most types it's a simple enum. For reference types it holds a
jeffhaobdb76512011-09-07 11:43:16 -070040 * pointer to the ClassObject, and for uninitialized references it holds
41 * an index into the UninitInstanceMap.
42 */
43 typedef uint32_t RegType;
44
45 /*
46 * A bit vector indicating which entries in the monitor stack are
jeffhaod1f0fde2011-09-08 17:25:33 -070047 * associated with this register. The low bit corresponds to the stack's
jeffhaobdb76512011-09-07 11:43:16 -070048 * bottom-most entry.
49 */
50 typedef uint32_t MonitorEntries;
51
52 /*
53 * InsnFlags is a 32-bit integer with the following layout:
54 * 0-15 instruction length (or 0 if this address doesn't hold an opcode)
55 * 16-31 single bit flags:
56 * InTry: in "try" block; exceptions thrown here may be caught locally
57 * BranchTarget: other instructions can branch to this instruction
58 * GcPoint: this instruction is a GC safe point
59 * Visited: verifier has examined this instruction at least once
60 * Changed: set/cleared as bytecode verifier runs
61 */
62 typedef uint32_t InsnFlags;
63
64 enum InsnFlag {
65 kInsnFlagWidthMask = 0x0000ffff,
66 kInsnFlagInTry = (1 << 16),
jeffhaoba5ebb92011-08-25 17:24:37 -070067 kInsnFlagBranchTarget = (1 << 17),
jeffhaobdb76512011-09-07 11:43:16 -070068 kInsnFlagGcPoint = (1 << 18),
69 kInsnFlagVisited = (1 << 30),
70 kInsnFlagChanged = (1 << 31),
jeffhaoba5ebb92011-08-25 17:24:37 -070071 };
72
jeffhaobdb76512011-09-07 11:43:16 -070073 /*
jeffhaod1f0fde2011-09-08 17:25:33 -070074 * "Direct" and "virtual" methods are stored independently. The type of call
jeffhaobdb76512011-09-07 11:43:16 -070075 * used to invoke the method determines which list we search, and whether
76 * we travel up into superclasses.
77 *
78 * (<clinit>, <init>, and methods declared "private" or "static" are stored
jeffhaod1f0fde2011-09-08 17:25:33 -070079 * in the "direct" list. All others are stored in the "virtual" list.)
jeffhaobdb76512011-09-07 11:43:16 -070080 */
81 enum MethodType {
82 METHOD_UNKNOWN = 0,
83 METHOD_DIRECT, // <init>, private
84 METHOD_STATIC, // static
85 METHOD_VIRTUAL, // virtual, super
86 METHOD_INTERFACE // interface
87 };
88
89 /*
90 * We don't need to store the register data for many instructions, because
91 * we either only need it at branch points (for verification) or GC points
92 * and branches (for verification + type-precise register analysis).
93 */
94 enum RegisterTrackingMode {
95 kTrackRegsBranches,
96 kTrackRegsGcPoints,
97 kTrackRegsAll,
98 };
99
100 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700101 * Enumeration for register type values. The "hi" piece of a 64-bit value
jeffhaobdb76512011-09-07 11:43:16 -0700102 * MUST immediately follow the "lo" piece in the enumeration, so we can check
103 * that hi==lo+1.
104 *
105 * Assignment of constants:
106 * [-MAXINT,-32768) : integer
107 * [-32768,-128) : short
108 * [-128,0) : byte
109 * 0 : zero
110 * 1 : one
111 * [2,128) : posbyte
112 * [128,32768) : posshort
113 * [32768,65536) : char
114 * [65536,MAXINT] : integer
115 *
116 * Allowed "implicit" widening conversions:
117 * zero -> boolean, posbyte, byte, posshort, short, char, integer, ref (null)
118 * one -> boolean, posbyte, byte, posshort, short, char, integer
119 * boolean -> posbyte, byte, posshort, short, char, integer
120 * posbyte -> posshort, short, integer, char
121 * byte -> short, integer
122 * posshort -> integer, char
123 * short -> integer
124 * char -> integer
125 *
126 * In addition, all of the above can convert to "float".
127 *
jeffhaod1f0fde2011-09-08 17:25:33 -0700128 * We're more careful with integer values than the spec requires. The
jeffhaobdb76512011-09-07 11:43:16 -0700129 * motivation is to restrict byte/char/short to the correct range of values.
130 * For example, if a method takes a byte argument, we don't want to allow
131 * the code to load the constant "1024" and pass it in.
132 */
133 enum {
134 kRegTypeUnknown = 0, /* initial state; use value=0 so calloc works */
135 kRegTypeUninit = 1, /* MUST be odd to distinguish from pointer */
136 kRegTypeConflict, /* merge clash makes this reg's type unknowable */
137
138 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700139 * Category-1nr types. The order of these is chiseled into a couple
jeffhaobdb76512011-09-07 11:43:16 -0700140 * of tables, so don't add, remove, or reorder if you can avoid it.
141 */
142#define kRegType1nrSTART kRegTypeZero
143 kRegTypeZero, /* 32-bit 0, could be Boolean, Int, Float, or Ref */
144 kRegTypeOne, /* 32-bit 1, could be Boolean, Int, Float */
145 kRegTypeBoolean, /* must be 0 or 1 */
146 kRegTypeConstPosByte, /* const derived byte, known positive */
147 kRegTypeConstByte, /* const derived byte */
148 kRegTypeConstPosShort, /* const derived short, known positive */
149 kRegTypeConstShort, /* const derived short */
150 kRegTypeConstChar, /* const derived char */
151 kRegTypeConstInteger, /* const derived integer */
152 kRegTypePosByte, /* byte, known positive (can become char) */
153 kRegTypeByte,
154 kRegTypePosShort, /* short, known positive (can become char) */
155 kRegTypeShort,
156 kRegTypeChar,
157 kRegTypeInteger,
158 kRegTypeFloat,
159#define kRegType1nrEND kRegTypeFloat
160 kRegTypeConstLo, /* const derived wide, lower half */
161 kRegTypeConstHi, /* const derived wide, upper half */
162 kRegTypeLongLo, /* lower-numbered register; endian-independent */
163 kRegTypeLongHi,
164 kRegTypeDoubleLo,
165 kRegTypeDoubleHi,
166
167 /*
168 * Enumeration max; this is used with "full" (32-bit) RegType values.
169 *
jeffhaod1f0fde2011-09-08 17:25:33 -0700170 * Anything larger than this is a ClassObject or uninit ref. Mask off
jeffhaobdb76512011-09-07 11:43:16 -0700171 * all but the low 8 bits; if you're left with kRegTypeUninit, pull
jeffhaod1f0fde2011-09-08 17:25:33 -0700172 * the uninit index out of the high 24. Because kRegTypeUninit has an
jeffhaobdb76512011-09-07 11:43:16 -0700173 * odd value, there is no risk of a particular ClassObject pointer bit
174 * pattern being confused for it (assuming our class object allocator
175 * uses word alignment).
176 */
177 kRegTypeMAX
178 };
179#define kRegTypeUninitMask 0xff
180#define kRegTypeUninitShift 8
181
182 /*
183 * Register type categories, for type checking.
184 *
185 * The spec says category 1 includes boolean, byte, char, short, int, float,
jeffhaod1f0fde2011-09-08 17:25:33 -0700186 * reference, and returnAddress. Category 2 includes long and double.
jeffhaobdb76512011-09-07 11:43:16 -0700187 *
jeffhaod1f0fde2011-09-08 17:25:33 -0700188 * We treat object references separately, so we have "category1nr". We
jeffhaobdb76512011-09-07 11:43:16 -0700189 * don't support jsr/ret, so there is no "returnAddress" type.
190 */
191 enum TypeCategory {
192 kTypeCategoryUnknown = 0,
193 kTypeCategory1nr = 1, // boolean, byte, char, short, int, float
194 kTypeCategory2 = 2, // long, double
195 kTypeCategoryRef = 3, // object reference
196 };
197
198 /* An enumeration of problems that can turn up during verification. */
199 enum VerifyError {
200 VERIFY_ERROR_NONE = 0, /* no error; must be zero */
201 VERIFY_ERROR_GENERIC, /* VerifyError */
202
203 VERIFY_ERROR_NO_CLASS, /* NoClassDefFoundError */
204 VERIFY_ERROR_NO_FIELD, /* NoSuchFieldError */
205 VERIFY_ERROR_NO_METHOD, /* NoSuchMethodError */
206 VERIFY_ERROR_ACCESS_CLASS, /* IllegalAccessError */
207 VERIFY_ERROR_ACCESS_FIELD, /* IllegalAccessError */
208 VERIFY_ERROR_ACCESS_METHOD, /* IllegalAccessError */
209 VERIFY_ERROR_CLASS_CHANGE, /* IncompatibleClassChangeError */
210 VERIFY_ERROR_INSTANTIATION, /* InstantiationError */
211 };
212
213 /*
214 * Identifies the type of reference in the instruction that generated the
215 * verify error (e.g. VERIFY_ERROR_ACCESS_CLASS could come from a method,
216 * field, or class reference).
217 *
218 * This must fit in two bits.
219 */
220 enum VerifyErrorRefType {
221 VERIFY_ERROR_REF_CLASS = 0,
222 VERIFY_ERROR_REF_FIELD = 1,
223 VERIFY_ERROR_REF_METHOD = 2,
224 };
225#define kVerifyErrorRefTypeShift 6
226
227 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700228 * Format enumeration for RegisterMap data area.
229 */
230 enum RegisterMapFormat {
231 kRegMapFormatUnknown = 0,
232 kRegMapFormatNone, /* indicates no map data follows */
233 kRegMapFormatCompact8, /* compact layout, 8-bit addresses */
234 kRegMapFormatCompact16, /* compact layout, 16-bit addresses */
235 kRegMapFormatDifferential, /* compressed, differential encoding */
236 };
237
238 /*
jeffhaobdb76512011-09-07 11:43:16 -0700239 * During verification, we associate one of these with every "interesting"
jeffhaod1f0fde2011-09-08 17:25:33 -0700240 * instruction. We track the status of all registers, and (if the method
jeffhaobdb76512011-09-07 11:43:16 -0700241 * has any monitor-enter instructions) maintain a stack of entered monitors
242 * (identified by code unit offset).
243 *
244 * If live-precise register maps are enabled, the "liveRegs" vector will
jeffhaod1f0fde2011-09-08 17:25:33 -0700245 * be populated. Unlike the other lists of registers here, we do not
jeffhaobdb76512011-09-07 11:43:16 -0700246 * track the liveness of the method result register (which is not visible
247 * to the GC).
248 */
249 struct RegisterLine {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700250 UniquePtr<RegType[]> reg_types_;
251 UniquePtr<MonitorEntries[]> monitor_entries_;
252 UniquePtr<uint32_t[]> monitor_stack_;
253 uint32_t monitor_stack_top_;
jeffhaobdb76512011-09-07 11:43:16 -0700254
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700255 RegisterLine()
jeffhaod1f0fde2011-09-08 17:25:33 -0700256 : reg_types_(NULL), monitor_entries_(NULL), monitor_stack_(NULL),
257 monitor_stack_top_(0) {
jeffhaobdb76512011-09-07 11:43:16 -0700258 }
259
260 /* Allocate space for the fields. */
261 void Alloc(size_t size, bool track_monitors) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700262 reg_types_.reset(new RegType[size]());
jeffhaobdb76512011-09-07 11:43:16 -0700263 if (track_monitors) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700264 monitor_entries_.reset(new MonitorEntries[size]);
265 monitor_stack_.reset(new uint32_t[kMaxMonitorStackDepth]);
jeffhaobdb76512011-09-07 11:43:16 -0700266 }
267 }
268 };
269
270 /* Big fat collection of register data. */
271 struct RegisterTable {
272 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700273 * Array of RegisterLine structs, one per address in the method. We only
jeffhaobdb76512011-09-07 11:43:16 -0700274 * set the pointers for certain addresses, based on instruction widths
275 * and what we're trying to accomplish.
276 */
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700277 UniquePtr<RegisterLine[]> register_lines_;
jeffhaobdb76512011-09-07 11:43:16 -0700278
279 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700280 * Number of registers we track for each instruction. This is equal
jeffhaobdb76512011-09-07 11:43:16 -0700281 * to the method's declared "registersSize" plus kExtraRegs (2).
282 */
283 size_t insn_reg_count_plus_;
284
285 /* Storage for a register line we're currently working on. */
286 RegisterLine work_line_;
287
288 /* Storage for a register line we're saving for later. */
289 RegisterLine saved_line_;
290
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700291 RegisterTable() : register_lines_(NULL), insn_reg_count_plus_(0) {
jeffhaobdb76512011-09-07 11:43:16 -0700292 }
293 };
294
295 /* Entries in the UninitInstanceMap. */
296 struct UninitInstanceMapEntry {
297 /* Code offset, or -1 for method arg ("this"). */
298 int addr_;
299
300 /* Class created at this address. */
301 Class* klass_;
302 };
303
304 /*
305 * Table that maps uninitialized instances to classes, based on the
jeffhaod1f0fde2011-09-08 17:25:33 -0700306 * address of the new-instance instruction. One per method.
jeffhaobdb76512011-09-07 11:43:16 -0700307 */
308 struct UninitInstanceMap {
309 int num_entries_;
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700310 UniquePtr<UninitInstanceMapEntry[]> map_;
jeffhaobdb76512011-09-07 11:43:16 -0700311
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700312 UninitInstanceMap(int num_entries)
313 : num_entries_(num_entries),
314 map_(new UninitInstanceMapEntry[num_entries]()) {
jeffhaobdb76512011-09-07 11:43:16 -0700315 }
316 };
317 #define kUninitThisArgAddr (-1)
318 #define kUninitThisArgSlot 0
319
320 /* Various bits of data used by the verifier and register map generator. */
321 struct VerifierData {
322 /* The method we're working on. */
323 Method* method_;
324
325 /* The dex file containing the method. */
326 const DexFile* dex_file_;
327
328 /* The code item containing the code for the method. */
329 const DexFile::CodeItem* code_item_;
330
331 /* Instruction widths and flags, one entry per code unit. */
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700332 UniquePtr<InsnFlags[]> insn_flags_;
jeffhaobdb76512011-09-07 11:43:16 -0700333
334 /*
335 * Uninitialized instance map, used for tracking the movement of
336 * objects that have been allocated but not initialized.
337 */
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700338 UniquePtr<UninitInstanceMap> uninit_map_;
jeffhaobdb76512011-09-07 11:43:16 -0700339
340 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700341 * Array of RegisterLine structs, one entry per code unit. We only need
jeffhaobdb76512011-09-07 11:43:16 -0700342 * entries for code units that hold the start of an "interesting"
jeffhaod1f0fde2011-09-08 17:25:33 -0700343 * instruction. For register map generation, we're only interested
jeffhaobdb76512011-09-07 11:43:16 -0700344 * in GC points.
345 */
346 RegisterLine* register_lines_;
347
348 /* The number of occurrences of specific opcodes. */
349 size_t new_instance_count_;
350 size_t monitor_enter_count_;
351
jeffhaobdb76512011-09-07 11:43:16 -0700352 VerifierData(Method* method, const DexFile* dex_file,
353 const DexFile::CodeItem* code_item)
354 : method_(method), dex_file_(dex_file), code_item_(code_item),
355 insn_flags_(NULL), uninit_map_(NULL), register_lines_(NULL),
jeffhaod1f0fde2011-09-08 17:25:33 -0700356 new_instance_count_(0), monitor_enter_count_(0) {
357 }
jeffhaobdb76512011-09-07 11:43:16 -0700358 };
359
jeffhaoe23d93c2011-09-15 14:48:43 -0700360 /* Header for RegisterMap */
361 struct RegisterMapHeader {
362 uint8_t format_; /* enum RegisterMapFormat; MUST be first entry */
363 uint8_t reg_width_; /* bytes per register line, 1+ */
364 uint16_t num_entries_; /* number of entries */
jeffhaoe23d93c2011-09-15 14:48:43 -0700365
jeffhaoa0a764a2011-09-16 10:43:38 -0700366 RegisterMapHeader(uint8_t format, uint8_t reg_width, uint16_t num_entries)
367 : format_(format), reg_width_(reg_width), num_entries_(num_entries) {
jeffhaoe23d93c2011-09-15 14:48:43 -0700368 }
369 };
370
jeffhaobdb76512011-09-07 11:43:16 -0700371 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700372 * This is a single variable-size structure. It may be allocated on the
373 * heap or mapped out of a (post-dexopt) DEX file.
374 *
375 * 32-bit alignment of the structure is NOT guaranteed. This makes it a
376 * little awkward to deal with as a structure; to avoid accidents we use
377 * only byte types. Multi-byte values are little-endian.
378 *
379 * Size of (format==FormatNone): 1 byte
380 * Size of (format==FormatCompact8): 4 + (1 + reg_width) * num_entries
381 * Size of (format==FormatCompact16): 4 + (2 + reg_width) * num_entries
382 */
383 struct RegisterMap {
jeffhaoe23d93c2011-09-15 14:48:43 -0700384 RegisterMapHeader* header_;
385 uint8_t* data_;
386 bool needs_free_;
jeffhaod1f0fde2011-09-08 17:25:33 -0700387
jeffhaoe23d93c2011-09-15 14:48:43 -0700388 RegisterMap(ByteArray* header, ByteArray* data) {
389 header_ = (RegisterMapHeader*) header->GetData();
390 data_ = (uint8_t*) data->GetData();
391 needs_free_ = false;
392 }
jeffhaod1f0fde2011-09-08 17:25:33 -0700393
394 RegisterMap(uint8_t format, uint8_t reg_width, uint16_t num_entries,
jeffhaoa0a764a2011-09-16 10:43:38 -0700395 uint32_t data_size) {
396 header_ = new RegisterMapHeader(format, reg_width, num_entries);
jeffhaoe23d93c2011-09-15 14:48:43 -0700397 data_ = new uint8_t[data_size]();
398 needs_free_ = true;
399 }
400
401 ~RegisterMap() {
402 if (needs_free_) {
403 delete header_;
404 delete [] data_;
405 }
jeffhaod1f0fde2011-09-08 17:25:33 -0700406 }
407 };
408
409 /*
410 * Merge result table for primitive values. The table is symmetric along
jeffhaobdb76512011-09-07 11:43:16 -0700411 * the diagonal.
412 *
jeffhaod1f0fde2011-09-08 17:25:33 -0700413 * Note that 32-bit int/float do not merge into 64-bit long/double. This
414 * is a register merge, not a widening conversion. Only the "implicit"
jeffhaobdb76512011-09-07 11:43:16 -0700415 * widening within a category, e.g. byte to short, is allowed.
416 *
417 * Dalvik does not draw a distinction between int and float, but we enforce
418 * that once a value is used as int, it can't be used as float, and vice
419 * versa. We do not allow free exchange between 32-bit int/float and 64-bit
420 * long/double.
421 *
jeffhaod1f0fde2011-09-08 17:25:33 -0700422 * Note that Uninit+Uninit=Uninit. This holds true because we only
jeffhaobdb76512011-09-07 11:43:16 -0700423 * use this when the RegType value is exactly equal to kRegTypeUninit, which
424 * can only happen for the zeroeth entry in the table.
425 *
jeffhaod1f0fde2011-09-08 17:25:33 -0700426 * "Unknown" never merges with anything known. The only time a register
jeffhaobdb76512011-09-07 11:43:16 -0700427 * transitions from "unknown" to "known" is when we're executing code
428 * for the first time, and we handle that with a simple copy.
429 */
430 static const char merge_table_[kRegTypeMAX][kRegTypeMAX];
431
432 /*
433 * Returns "true" if the flags indicate that this address holds the start
434 * of an instruction.
435 */
436 static inline bool InsnIsOpcode(const InsnFlags insn_flags[], int addr) {
437 return (insn_flags[addr] & kInsnFlagWidthMask) != 0;
438 }
439
440 /* Extract the unsigned 16-bit instruction width from "flags". */
441 static inline int InsnGetWidth(const InsnFlags insn_flags[], int addr) {
442 return insn_flags[addr] & kInsnFlagWidthMask;
443 }
444
445 /* Utilities to check and set kInsnFlagChanged. */
446 static inline bool InsnIsChanged(const InsnFlags insn_flags[], int addr) {
447 return (insn_flags[addr] & kInsnFlagChanged) != 0;
448 }
449 static inline void InsnSetChanged(InsnFlags insn_flags[], int addr,
450 bool changed) {
451 if (changed)
452 insn_flags[addr] |= kInsnFlagChanged;
453 else
454 insn_flags[addr] &= ~kInsnFlagChanged;
455 }
456
457 /* Utilities to check and set kInsnFlagVisited. */
458 static inline bool InsnIsVisited(const InsnFlags insn_flags[], int addr) {
459 return (insn_flags[addr] & kInsnFlagVisited) != 0;
460 }
461 static inline void InsnSetVisited(InsnFlags insn_flags[], int addr,
462 bool visited) {
463 if (visited)
464 insn_flags[addr] |= kInsnFlagVisited;
465 else
466 insn_flags[addr] &= ~kInsnFlagVisited;
467 }
468
469 static inline bool InsnIsVisitedOrChanged(const InsnFlags insn_flags[],
470 int addr) {
471 return (insn_flags[addr] & (kInsnFlagVisited |
472 kInsnFlagChanged)) != 0;
473 }
474
475 /* Utilities to check and set kInsnFlagInTry. */
476 static inline bool InsnIsInTry(const InsnFlags insn_flags[], int addr) {
477 return (insn_flags[addr] & kInsnFlagInTry) != 0;
478 }
479 static inline void InsnSetInTry(InsnFlags insn_flags[], int addr) {
480 insn_flags[addr] |= kInsnFlagInTry;
481 }
482
483 /* Utilities to check and set kInsnFlagBranchTarget. */
484 static inline bool InsnIsBranchTarget(const InsnFlags insn_flags[], int addr)
485 {
486 return (insn_flags[addr] & kInsnFlagBranchTarget) != 0;
487 }
488 static inline void InsnSetBranchTarget(InsnFlags insn_flags[], int addr) {
489 insn_flags[addr] |= kInsnFlagBranchTarget;
490 }
491
492 /* Utilities to check and set kInsnFlagGcPoint. */
493 static inline bool InsnIsGcPoint(const InsnFlags insn_flags[], int addr) {
494 return (insn_flags[addr] & kInsnFlagGcPoint) != 0;
495 }
496 static inline void InsnSetGcPoint(InsnFlags insn_flags[], int addr) {
497 insn_flags[addr] |= kInsnFlagGcPoint;
498 }
499
500 /* Get the class object at the specified index. */
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700501 static inline Class* GetUninitInstance(const UninitInstanceMap* uninit_map, int idx) {
502 DCHECK_GE(idx, 0);
503 DCHECK_LT(idx, uninit_map->num_entries_);
jeffhaobdb76512011-09-07 11:43:16 -0700504 return uninit_map->map_[idx].klass_;
505 }
506
507 /* Determine if "type" is actually an object reference (init/uninit/zero) */
508 static inline bool RegTypeIsReference(RegType type) {
509 return (type > kRegTypeMAX || type == kRegTypeUninit ||
510 type == kRegTypeZero);
511 }
512
513 /* Determine if "type" is an uninitialized object reference */
514 static inline bool RegTypeIsUninitReference(RegType type) {
515 return ((type & kRegTypeUninitMask) == kRegTypeUninit);
516 }
517
518 /*
519 * Convert the initialized reference "type" to a Class pointer
520 * (does not expect uninit ref types or "zero").
521 */
522 static Class* RegTypeInitializedReferenceToClass(RegType type) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700523 DCHECK(RegTypeIsReference(type) && type != kRegTypeZero);
jeffhaobdb76512011-09-07 11:43:16 -0700524 if ((type & 0x01) == 0) {
525 return (Class*) type;
526 } else {
527 LOG(ERROR) << "VFY: attempted to use uninitialized reference";
528 return NULL;
529 }
530 }
531
532 /* Extract the index into the uninitialized instance map table. */
533 static inline int RegTypeToUninitIndex(RegType type) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700534 DCHECK(RegTypeIsUninitReference(type));
jeffhaobdb76512011-09-07 11:43:16 -0700535 return (type & ~kRegTypeUninitMask) >> kRegTypeUninitShift;
536 }
537
538 /* Convert the reference "type" to a Class pointer. */
539 static Class* RegTypeReferenceToClass(RegType type,
540 const UninitInstanceMap* uninit_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700541 DCHECK(RegTypeIsReference(type) && type != kRegTypeZero);
jeffhaobdb76512011-09-07 11:43:16 -0700542 if (RegTypeIsUninitReference(type)) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700543 DCHECK(uninit_map != NULL);
jeffhaobdb76512011-09-07 11:43:16 -0700544 return GetUninitInstance(uninit_map, RegTypeToUninitIndex(type));
545 } else {
546 return (Class*) type;
547 }
548 }
549
550 /* Convert the ClassObject pointer to an (initialized) register type. */
551 static inline RegType RegTypeFromClass(Class* klass) {
552 return (uint32_t) klass;
553 }
554
555 /* Return the RegType for the uninitialized reference in slot "uidx". */
556 static inline RegType RegTypeFromUninitIndex(int uidx) {
557 return (uint32_t) (kRegTypeUninit | (uidx << kRegTypeUninitShift));
558 }
559
jeffhaoa0a764a2011-09-16 10:43:38 -0700560 /*
561 * Generate the register map for a method that has just been verified
562 * (i.e. we're doing this as part of verification).
563 *
564 * For type-precise determination we have all the data we need, so we
565 * just need to encode it in some clever fashion.
566 *
567 * Returns a pointer to a newly-allocated RegisterMap, or NULL on failure.
568 */
569 static RegisterMap* GenerateRegisterMapV(VerifierData* vdata);
570
571 /*
572 * Get the expanded form of the register map associated with the specified
573 * method. May update the RegisterMap, possibly freeing the previous map.
574 *
575 * Returns NULL on failure (e.g. unable to expand map).
576 *
577 * NOTE: this function is not synchronized; external locking is mandatory.
578 * (This is expected to be called at GC time.)
579 */
580 static inline RegisterMap* GetExpandedRegisterMap(Method* method) {
581 if (method->GetRegisterMapHeader() == NULL ||
582 method->GetRegisterMapData() == NULL) {
583 return NULL;
584 }
585 RegisterMap* cur_map = new RegisterMap(method->GetRegisterMapHeader(),
586 method->GetRegisterMapData());
587 uint8_t format = cur_map->header_->format_;
588 if (format == kRegMapFormatCompact8 || format == kRegMapFormatCompact16) {
589 return cur_map;
590 } else {
591 return GetExpandedRegisterMapHelper(method, cur_map);
592 }
593 }
594
595 /*
596 * Get the expanded form of the register map associated with the method.
597 *
598 * If the map is already in one of the uncompressed formats, we return
599 * immediately. Otherwise, we expand the map and replace method's register
600 * map pointer, freeing it if it was allocated on the heap.
601 *
602 * NOTE: this function is not synchronized; external locking is mandatory
603 * (unless we're in the zygote, where single-threaded access is guaranteed).
604 */
605 static RegisterMap* GetExpandedRegisterMapHelper(Method* method,
606 RegisterMap* map);
607
608 /* Return the data for the specified address, or NULL if not found. */
609 static const uint8_t* RegisterMapGetLine(const RegisterMap* map, int addr);
610
611 /*
612 * Determine if the RegType value is a reference type.
613 *
614 * Ordinarily we include kRegTypeZero in the "is it a reference"
615 * check. There's no value in doing so here, because we know
616 * the register can't hold anything but zero.
617 */
618 static inline bool IsReferenceType(RegType type) {
619 return (type > kRegTypeMAX || type == kRegTypeUninit);
620 }
621
622 /* Toggle the value of the "idx"th bit in "ptr". */
623 static inline void ToggleBit(uint8_t* ptr, int idx) {
624 ptr[idx >> 3] ^= 1 << (idx & 0x07);
625 }
626
627 /*
628 * Given a line of registers, output a bit vector that indicates whether
629 * or not the register holds a reference type (which could be null).
630 *
631 * We use '1' to indicate it's a reference, '0' for anything else (numeric
632 * value, uninitialized data, merge conflict). Register 0 will be found
633 * in the low bit of the first byte.
634 */
635 static void OutputTypeVector(const RegType* regs, int insn_reg_count,
636 uint8_t* data);
637
638 /*
639 * Double-check the map.
640 *
641 * We run through all of the data in the map, and compare it to the original.
642 * Only works on uncompressed data.
643 */
644 static bool VerifyMap(VerifierData* vdata, const RegisterMap* map);
645
646 /* Compare two register maps. Returns true if they're equal, false if not. */
647 static bool CompareMaps(const RegisterMap* map1, const RegisterMap* map2);
648
649 /* Compute the size, in bytes, of a register map. */
650 static size_t ComputeRegisterMapSize(const RegisterMap* map);
651
652 /*
653 * Compute the difference between two bit vectors.
654 *
655 * If "leb_out_buf" is non-NULL, we output the bit indices in ULEB128 format
656 * as we go. Otherwise, we just generate the various counts.
657 *
658 * The bit vectors are compared byte-by-byte, so any unused bits at the
659 * end must be zero.
660 *
661 * Returns the number of bytes required to hold the ULEB128 output.
662 *
663 * If "first_bit_changed_ptr" or "num_bits_changed_ptr" are non-NULL, they
664 * will receive the index of the first changed bit and the number of changed
665 * bits, respectively.
666 */
667 static int ComputeBitDiff(const uint8_t* bits1, const uint8_t* bits2,
668 int byte_width, int* first_bit_changed_ptr, int* num_bits_changed_ptr,
669 uint8_t* leb_out_buf);
670
671 /*
672 * Compress the register map with differential encoding.
673 *
674 * On success, returns a newly-allocated RegisterMap. If the map is not
675 * compatible for some reason, or fails to get smaller, this will return NULL.
676 */
677 static RegisterMap* CompressMapDifferential(const RegisterMap* map);
678
679 /*
680 * Expand a compressed map to an uncompressed form.
681 *
682 * Returns a newly-allocated RegisterMap on success, or NULL on failure.
683 *
684 * TODO: consider using the linear allocator or a custom allocator with
685 * LRU replacement for these instead of the native heap.
686 */
687 static RegisterMap* UncompressMapDifferential(const RegisterMap* map);
688
689
jeffhaoe23d93c2011-09-15 14:48:43 -0700690 /* Verify a class. Returns "true" on success. */
691 static bool VerifyClass(Class* klass);
692
693 private:
jeffhaobdb76512011-09-07 11:43:16 -0700694 /*
695 * Perform verification on a single method.
696 *
697 * We do this in three passes:
698 * (1) Walk through all code units, determining instruction locations,
699 * widths, and other characteristics.
700 * (2) Walk through all code units, performing static checks on
701 * operands.
702 * (3) Iterate through the method, checking type safety and looking
703 * for code flow problems.
704 *
jeffhaod1f0fde2011-09-08 17:25:33 -0700705 * Some checks may be bypassed depending on the verification mode. We can't
jeffhaobdb76512011-09-07 11:43:16 -0700706 * turn this stuff off completely if we want to do "exact" GC.
707 *
708 * Confirmed here:
709 * - code array must not be empty
710 * Confirmed by ComputeWidthsAndCountOps():
711 * - opcode of first instruction begins at index 0
712 * - only documented instructions may appear
713 * - each instruction follows the last
714 * - last byte of last instruction is at (code_length-1)
715 */
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700716 static bool VerifyMethod(Method* method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700717
jeffhaobdb76512011-09-07 11:43:16 -0700718 /*
719 * Perform static verification on all instructions in a method.
720 *
721 * Walks through instructions in a method calling VerifyInstruction on each.
722 */
723 static bool VerifyInstructions(VerifierData* vdata);
724
725 /*
726 * Perform static verification on an instruction.
727 *
728 * As a side effect, this sets the "branch target" flags in InsnFlags.
729 *
730 * "(CF)" items are handled during code-flow analysis.
731 *
732 * v3 4.10.1
733 * - target of each jump and branch instruction must be valid
734 * - targets of switch statements must be valid
735 * - operands referencing constant pool entries must be valid
736 * - (CF) operands of getfield, putfield, getstatic, putstatic must be valid
737 * - (CF) operands of method invocation instructions must be valid
738 * - (CF) only invoke-direct can call a method starting with '<'
739 * - (CF) <clinit> must never be called explicitly
740 * - operands of instanceof, checkcast, new (and variants) must be valid
741 * - new-array[-type] limited to 255 dimensions
742 * - can't use "new" on an array class
743 * - (?) limit dimensions in multi-array creation
744 * - local variable load/store register values must be in valid range
745 *
746 * v3 4.11.1.2
747 * - branches must be within the bounds of the code array
748 * - targets of all control-flow instructions are the start of an instruction
749 * - register accesses fall within range of allocated registers
750 * - (N/A) access to constant pool must be of appropriate type
751 * - code does not end in the middle of an instruction
752 * - execution cannot fall off the end of the code
753 * - (earlier) for each exception handler, the "try" area must begin and
754 * end at the start of an instruction (end can be at the end of the code)
755 * - (earlier) for each exception handler, the handler must start at a valid
756 * instruction
757 */
758 static bool VerifyInstruction(VerifierData* vdata,
759 const Instruction* inst, uint32_t code_offset);
760
761 /* Perform detailed code-flow analysis on a single method. */
762 static bool VerifyCodeFlow(VerifierData* vdata);
763
764 /*
765 * Compute the width of the instruction at each address in the instruction
jeffhaod1f0fde2011-09-08 17:25:33 -0700766 * stream, and store it in vdata->insn_flags. Addresses that are in the
jeffhaobdb76512011-09-07 11:43:16 -0700767 * middle of an instruction, or that are part of switch table data, are not
768 * touched (so the caller should probably initialize "insn_flags" to zero).
769 *
770 * The "new_instance_count_" and "monitor_enter_count_" fields in vdata are
771 * also set.
772 *
773 * Performs some static checks, notably:
774 * - opcode of first instruction begins at index 0
775 * - only documented instructions may appear
776 * - each instruction follows the last
777 * - last byte of last instruction is at (code_length-1)
778 *
779 * Logs an error and returns "false" on failure.
780 */
781 static bool ComputeWidthsAndCountOps(VerifierData* vdata);
782
783 /*
784 * Set the "in try" flags for all instructions protected by "try" statements.
785 * Also sets the "branch target" flags for exception handlers.
786 *
787 * Call this after widths have been set in "insn_flags".
788 *
789 * Returns "false" if something in the exception table looks fishy, but
790 * we're expecting the exception table to be somewhat sane.
791 */
792 static bool ScanTryCatchBlocks(VerifierData* vdata);
793
794 /*
795 * Extract the relative offset from a branch instruction.
796 *
797 * Returns "false" on failure (e.g. this isn't a branch instruction).
798 */
799 static bool GetBranchOffset(const DexFile::CodeItem* code_item,
800 const InsnFlags insn_flags[], uint32_t cur_offset, int32_t* pOffset,
801 bool* pConditional, bool* selfOkay);
802
803 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700804 * Verify an array data table. "cur_offset" is the offset of the
jeffhaobdb76512011-09-07 11:43:16 -0700805 * fill-array-data instruction.
806 */
807 static bool CheckArrayData(const DexFile::CodeItem* code_item,
808 uint32_t cur_offset);
809
810 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700811 * Perform static checks on a "new-instance" instruction. Specifically,
jeffhaobdb76512011-09-07 11:43:16 -0700812 * make sure the class reference isn't for an array class.
813 *
814 * We don't need the actual class, just a pointer to the class name.
815 */
816 static bool CheckNewInstance(const DexFile* dex_file, uint32_t idx);
817
818 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700819 * Perform static checks on a "new-array" instruction. Specifically, make
jeffhaobdb76512011-09-07 11:43:16 -0700820 * sure they aren't creating an array of arrays that causes the number of
821 * dimensions to exceed 255.
822 */
823 static bool CheckNewArray(const DexFile* dex_file, uint32_t idx);
824
825 /*
826 * Perform static checks on an instruction that takes a class constant.
827 * Ensure that the class index is in the valid range.
828 */
829 static bool CheckTypeIndex(const DexFile* dex_file, uint32_t idx);
830
831 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700832 * Perform static checks on a field get or set instruction. All we do
jeffhaobdb76512011-09-07 11:43:16 -0700833 * here is ensure that the field index is in the valid range.
834 */
835 static bool CheckFieldIndex(const DexFile* dex_file, uint32_t idx);
836
837 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700838 * Perform static checks on a method invocation instruction. All we do
jeffhaobdb76512011-09-07 11:43:16 -0700839 * here is ensure that the method index is in the valid range.
840 */
841 static bool CheckMethodIndex(const DexFile* dex_file, uint32_t idx);
842
843 /* Ensure that the string index is in the valid range. */
844 static bool CheckStringIndex(const DexFile* dex_file, uint32_t idx);
845
846 /* Ensure that the register index is valid for this code item. */
847 static bool CheckRegisterIndex(const DexFile::CodeItem* code_item,
848 uint32_t idx);
849
850 /* Ensure that the wide register index is valid for this code item. */
851 static bool CheckWideRegisterIndex(const DexFile::CodeItem* code_item,
852 uint32_t idx);
853
854 /*
855 * Check the register indices used in a "vararg" instruction, such as
856 * invoke-virtual or filled-new-array.
857 *
858 * vA holds word count (0-5), args[] have values.
859 *
860 * There are some tests we don't do here, e.g. we don't try to verify
861 * that invoking a method that takes a double is done with consecutive
jeffhaod1f0fde2011-09-08 17:25:33 -0700862 * registers. This requires parsing the target method signature, which
jeffhaobdb76512011-09-07 11:43:16 -0700863 * we will be doing later on during the code flow analysis.
864 */
865 static bool CheckVarArgRegs(const DexFile::CodeItem* code_item, uint32_t vA,
866 uint32_t arg[]);
867
868 /*
869 * Check the register indices used in a "vararg/range" instruction, such as
870 * invoke-virtual/range or filled-new-array/range.
871 *
872 * vA holds word count, vC holds index of first reg.
873 */
874 static bool CheckVarArgRangeRegs(const DexFile::CodeItem* code_item,
875 uint32_t vA, uint32_t vC);
876
877 /*
878 * Verify a switch table. "cur_offset" is the offset of the switch
879 * instruction.
880 *
881 * Updates "insnFlags", setting the "branch target" flag.
882 */
883 static bool CheckSwitchTargets(const DexFile::CodeItem* code_item,
884 InsnFlags insn_flags[], uint32_t cur_offset);
885
886 /*
887 * Verify that the target of a branch instruction is valid.
888 *
889 * We don't expect code to jump directly into an exception handler, but
890 * it's valid to do so as long as the target isn't a "move-exception"
jeffhaod1f0fde2011-09-08 17:25:33 -0700891 * instruction. We verify that in a later stage.
jeffhaobdb76512011-09-07 11:43:16 -0700892 *
893 * The dex format forbids certain instructions from branching to itself.
894 *
895 * Updates "insnFlags", setting the "branch target" flag.
896 */
897 static bool CheckBranchTarget(const DexFile::CodeItem* code_item,
898 InsnFlags insn_flags[], uint32_t cur_offset);
899
900 /*
901 * Initialize the RegisterTable.
902 *
903 * Every instruction address can have a different set of information about
904 * what's in which register, but for verification purposes we only need to
905 * store it at branch target addresses (because we merge into that).
906 *
907 * By zeroing out the regType storage we are effectively initializing the
908 * register information to kRegTypeUnknown.
909 *
910 * We jump through some hoops here to minimize the total number of
911 * allocations we have to perform per method verified.
912 */
913 static bool InitRegisterTable(VerifierData* vdata, RegisterTable* reg_table,
914 RegisterTrackingMode track_regs_for);
915
916 /* Get the register line for the given instruction in the current method. */
917 static inline RegisterLine* GetRegisterLine(const RegisterTable* reg_table,
918 int insn_idx) {
919 return &reg_table->register_lines_[insn_idx];
920 }
921
922 /* Copy a register line. */
923 static inline void CopyRegisterLine(RegisterLine* dst,
924 const RegisterLine* src, size_t num_regs) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700925 memcpy(dst->reg_types_.get(), src->reg_types_.get(), num_regs * sizeof(RegType));
jeffhaobdb76512011-09-07 11:43:16 -0700926
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700927 DCHECK((src->monitor_entries_.get() == NULL && dst->monitor_entries_.get() == NULL) ||
928 (src->monitor_entries_.get() != NULL && dst->monitor_entries_.get() != NULL));
929 if (dst->monitor_entries_.get() != NULL) {
930 DCHECK(dst->monitor_stack_.get() != NULL);
931 memcpy(dst->monitor_entries_.get(), src->monitor_entries_.get(),
jeffhaobdb76512011-09-07 11:43:16 -0700932 num_regs * sizeof(MonitorEntries));
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700933 memcpy(dst->monitor_stack_.get(), src->monitor_stack_.get(),
jeffhaobdb76512011-09-07 11:43:16 -0700934 kMaxMonitorStackDepth * sizeof(uint32_t));
935 dst->monitor_stack_top_ = src->monitor_stack_top_;
936 }
937 }
938
939 /* Copy a register line into the table. */
940 static inline void CopyLineToTable(RegisterTable* reg_table, int insn_idx,
941 const RegisterLine* src) {
942 RegisterLine* dst = GetRegisterLine(reg_table, insn_idx);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700943 DCHECK(dst->reg_types_.get() != NULL);
jeffhaobdb76512011-09-07 11:43:16 -0700944 CopyRegisterLine(dst, src, reg_table->insn_reg_count_plus_);
945 }
946
947 /* Copy a register line out of the table. */
948 static inline void CopyLineFromTable(RegisterLine* dst,
949 const RegisterTable* reg_table, int insn_idx) {
950 RegisterLine* src = GetRegisterLine(reg_table, insn_idx);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700951 DCHECK(src->reg_types_.get() != NULL);
jeffhaobdb76512011-09-07 11:43:16 -0700952 CopyRegisterLine(dst, src, reg_table->insn_reg_count_plus_);
953 }
954
955#ifndef NDEBUG
956 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700957 * Compare two register lines. Returns 0 if they match.
jeffhaobdb76512011-09-07 11:43:16 -0700958 *
959 * Using this for a sort is unwise, since the value can change based on
960 * machine endianness.
961 */
962 static inline int CompareLineToTable(const RegisterTable* reg_table,
963 int insn_idx, const RegisterLine* line2) {
964 const RegisterLine* line1 = GetRegisterLine(reg_table, insn_idx);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700965 if (line1->monitor_entries_.get() != NULL) {
jeffhaobdb76512011-09-07 11:43:16 -0700966 int result;
967
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700968 if (line2->monitor_entries_.get() == NULL)
jeffhaobdb76512011-09-07 11:43:16 -0700969 return 1;
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700970 result = memcmp(line1->monitor_entries_.get(), line2->monitor_entries_.get(),
jeffhaobdb76512011-09-07 11:43:16 -0700971 reg_table->insn_reg_count_plus_ * sizeof(MonitorEntries));
972 if (result != 0) {
973 LOG(ERROR) << "monitor_entries_ mismatch";
974 return result;
975 }
976 result = line1->monitor_stack_top_ - line2->monitor_stack_top_;
977 if (result != 0) {
978 LOG(ERROR) << "monitor_stack_top_ mismatch";
979 return result;
980 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700981 result = memcmp(line1->monitor_stack_.get(), line2->monitor_stack_.get(),
jeffhaobdb76512011-09-07 11:43:16 -0700982 line1->monitor_stack_top_);
983 if (result != 0) {
984 LOG(ERROR) << "monitor_stack_ mismatch";
985 return result;
986 }
987 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700988 return memcmp(line1->reg_types_.get(), line2->reg_types_.get(),
jeffhaobdb76512011-09-07 11:43:16 -0700989 reg_table->insn_reg_count_plus_ * sizeof(RegType));
990 }
991#endif
992
993 /*
994 * Create a new uninitialized instance map.
995 *
jeffhaod1f0fde2011-09-08 17:25:33 -0700996 * The map is allocated and populated with address entries. The addresses
jeffhaobdb76512011-09-07 11:43:16 -0700997 * appear in ascending order to allow binary searching.
998 *
999 * Very few methods have 10 or more new-instance instructions; the
jeffhaod1f0fde2011-09-08 17:25:33 -07001000 * majority have 0 or 1. Occasionally a static initializer will have 200+.
jeffhaobdb76512011-09-07 11:43:16 -07001001 *
1002 * TODO: merge this into the static pass or initRegisterTable; want to
1003 * avoid walking through the instructions yet again just to set up this table
1004 */
1005 static UninitInstanceMap* CreateUninitInstanceMap(VerifierData* vdata);
1006
1007 /* Returns true if this method is a constructor. */
1008 static bool IsInitMethod(const Method* method);
1009
1010 /*
1011 * Look up a class reference given as a simple string descriptor.
1012 *
1013 * If we can't find it, return a generic substitute when possible.
1014 */
1015 static Class* LookupClassByDescriptor(const Method* method,
1016 const char* descriptor, VerifyError* failure);
1017
1018 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001019 * Look up a class reference in a signature. Could be an arg or the
jeffhaobdb76512011-09-07 11:43:16 -07001020 * return value.
1021 *
1022 * Advances "*sig" to the last character in the signature (that is, to
1023 * the ';').
1024 *
1025 * NOTE: this is also expected to verify the signature.
1026 */
1027 static Class* LookupSignatureClass(const Method* method, std::string sig,
1028 VerifyError* failure);
1029
1030 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001031 * Look up an array class reference in a signature. Could be an arg or the
jeffhaobdb76512011-09-07 11:43:16 -07001032 * return value.
1033 *
1034 * Advances "*sig" to the last character in the signature.
1035 *
1036 * NOTE: this is also expected to verify the signature.
1037 */
1038 static Class* LookupSignatureArrayClass(const Method* method,
1039 std::string sig, VerifyError* failure);
1040
1041 /*
1042 * Set the register types for the first instruction in the method based on
1043 * the method signature.
1044 *
1045 * This has the side-effect of validating the signature.
1046 *
1047 * Returns "true" on success.
1048 */
1049 static bool SetTypesFromSignature(VerifierData* vdata, RegType* reg_types);
1050
1051 /*
1052 * Set the class object associated with the instruction at "addr".
1053 *
1054 * Returns the map slot index, or -1 if the address isn't listed in the map
1055 * (shouldn't happen) or if a class is already associated with the address
1056 * (bad bytecode).
1057 *
1058 * Entries, once set, do not change -- a given address can only allocate
1059 * one type of object.
1060 */
1061 static int SetUninitInstance(UninitInstanceMap* uninit_map, int addr,
1062 Class* klass);
1063
1064 /*
1065 * Perform code flow on a method.
1066 *
1067 * The basic strategy is as outlined in v3 4.11.1.2: set the "changed" bit
1068 * on the first instruction, process it (setting additional "changed" bits),
1069 * and repeat until there are no more.
1070 *
1071 * v3 4.11.1.1
1072 * - (N/A) operand stack is always the same size
1073 * - operand stack [registers] contain the correct types of values
1074 * - local variables [registers] contain the correct types of values
1075 * - methods are invoked with the appropriate arguments
1076 * - fields are assigned using values of appropriate types
1077 * - opcodes have the correct type values in operand registers
1078 * - there is never an uninitialized class instance in a local variable in
1079 * code protected by an exception handler (operand stack is okay, because
1080 * the operand stack is discarded when an exception is thrown) [can't
1081 * know what's a local var w/o the debug info -- should fall out of
1082 * register typing]
1083 *
1084 * v3 4.11.1.2
1085 * - execution cannot fall off the end of the code
1086 *
1087 * (We also do many of the items described in the "static checks" sections,
1088 * because it's easier to do them here.)
1089 *
1090 * We need an array of RegType values, one per register, for every
jeffhaod1f0fde2011-09-08 17:25:33 -07001091 * instruction. If the method uses monitor-enter, we need extra data
jeffhaobdb76512011-09-07 11:43:16 -07001092 * for every register, and a stack for every "interesting" instruction.
1093 * In theory this could become quite large -- up to several megabytes for
1094 * a monster function.
1095 *
1096 * NOTE:
1097 * The spec forbids backward branches when there's an uninitialized reference
jeffhaod1f0fde2011-09-08 17:25:33 -07001098 * in a register. The idea is to prevent something like this:
jeffhaobdb76512011-09-07 11:43:16 -07001099 * loop:
1100 * move r1, r0
1101 * new-instance r0, MyClass
1102 * ...
1103 * if-eq rN, loop // once
1104 * initialize r0
1105 *
1106 * This leaves us with two different instances, both allocated by the
jeffhaod1f0fde2011-09-08 17:25:33 -07001107 * same instruction, but only one is initialized. The scheme outlined in
jeffhaobdb76512011-09-07 11:43:16 -07001108 * v3 4.11.1.4 wouldn't catch this, so they work around it by preventing
jeffhaod1f0fde2011-09-08 17:25:33 -07001109 * backward branches. We achieve identical results without restricting
jeffhaobdb76512011-09-07 11:43:16 -07001110 * code reordering by specifying that you can't execute the new-instance
1111 * instruction if a register contains an uninitialized instance created
1112 * by that same instrutcion.
1113 */
1114 static bool CodeFlowVerifyMethod(VerifierData* vdata,
1115 RegisterTable* reg_table);
1116
1117 /*
1118 * Perform verification for a single instruction.
1119 *
1120 * This requires fully decoding the instruction to determine the effect
1121 * it has on registers.
1122 *
1123 * Finds zero or more following instructions and sets the "changed" flag
jeffhaod1f0fde2011-09-08 17:25:33 -07001124 * if execution at that point needs to be (re-)evaluated. Register changes
1125 * are merged into "reg_types_" at the target addresses. Does not set or
jeffhaobdb76512011-09-07 11:43:16 -07001126 * clear any other flags in "insn_flags".
1127 */
1128 static bool CodeFlowVerifyInstruction(VerifierData* vdata,
1129 RegisterTable* reg_table, uint32_t insn_idx, size_t* start_guess);
1130
1131 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001132 * Replace an instruction with "throw-verification-error". This allows us to
jeffhaobdb76512011-09-07 11:43:16 -07001133 * defer error reporting until the code path is first used.
1134 *
1135 * This is expected to be called during "just in time" verification, not
jeffhaod1f0fde2011-09-08 17:25:33 -07001136 * from within dexopt. (Verification failures in dexopt will result in
jeffhaobdb76512011-09-07 11:43:16 -07001137 * postponement of verification to first use of the class.)
1138 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001139 * The throw-verification-error instruction requires two code units. Some
jeffhaobdb76512011-09-07 11:43:16 -07001140 * of the replaced instructions require three; the third code unit will
jeffhaod1f0fde2011-09-08 17:25:33 -07001141 * receive a "nop". The instruction's length will be left unchanged
jeffhaobdb76512011-09-07 11:43:16 -07001142 * in "insn_flags".
1143 *
1144 * The VM postpones setting of debugger breakpoints in unverified classes,
1145 * so there should be no clashes with the debugger.
1146 *
1147 * Returns "true" on success.
1148 */
1149 static bool ReplaceFailingInstruction(const DexFile::CodeItem* code_item,
jeffhaob4df5142011-09-19 20:25:32 -07001150 int insn_idx, VerifyError failure);
1151
1152 /* Update a 16-bit opcode in a dex file. */
1153 static void UpdateCodeUnit(const uint16_t* ptr, uint16_t new_val);
jeffhaobdb76512011-09-07 11:43:16 -07001154
1155 /* Handle a monitor-enter instruction. */
1156 static void HandleMonitorEnter(RegisterLine* work_line, uint32_t reg_idx,
1157 uint32_t insn_idx, VerifyError* failure);
1158
1159 /* Handle a monitor-exit instruction. */
1160 static void HandleMonitorExit(RegisterLine* work_line, uint32_t reg_idx,
1161 uint32_t insn_idx, VerifyError* failure);
1162
1163 /*
1164 * Look up an instance field, specified by "field_idx", that is going to be
jeffhaod1f0fde2011-09-08 17:25:33 -07001165 * accessed in object "obj_type". This resolves the field and then verifies
jeffhaobdb76512011-09-07 11:43:16 -07001166 * that the class containing the field is an instance of the reference in
1167 * "obj_type".
1168 *
1169 * It is possible for "obj_type" to be kRegTypeZero, meaning that we might
jeffhaod1f0fde2011-09-08 17:25:33 -07001170 * have a null reference. This is a runtime problem, so we allow it,
jeffhaobdb76512011-09-07 11:43:16 -07001171 * skipping some of the type checks.
1172 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001173 * In general, "obj_type" must be an initialized reference. However, we
jeffhaobdb76512011-09-07 11:43:16 -07001174 * allow it to be uninitialized if this is an "<init>" method and the field
1175 * is declared within the "obj_type" class.
1176 *
1177 * Returns a Field on success, returns NULL and sets "*failure" on failure.
1178 */
1179 static Field* GetInstField(VerifierData* vdata, RegType obj_type,
1180 int field_idx, VerifyError* failure);
1181
1182 /*
1183 * Look up a static field.
1184 *
1185 * Returns a StaticField on success, returns NULL and sets "*failure"
1186 * on failure.
1187 */
1188 static Field* GetStaticField(VerifierData* vdata, int field_idx,
1189 VerifyError* failure);
1190 /*
1191 * For the "move-exception" instruction at "insn_idx", which must be at an
1192 * exception handler address, determine the first common superclass of
jeffhaod1f0fde2011-09-08 17:25:33 -07001193 * all exceptions that can land here. (For javac output, we're probably
jeffhaobdb76512011-09-07 11:43:16 -07001194 * looking at multiple spans of bytecode covered by one "try" that lands
1195 * at an exception-specific "catch", but in general the handler could be
1196 * shared for multiple exceptions.)
1197 *
1198 * Returns NULL if no matching exception handler can be found, or if the
1199 * exception is not a subclass of Throwable.
1200 */
1201 static Class* GetCaughtExceptionType(VerifierData* vdata, int insn_idx,
1202 VerifyError* failure);
1203
1204 /*
1205 * Get the type of register N.
1206 *
1207 * The register index was validated during the static pass, so we don't
1208 * need to check it here.
1209 */
1210 static inline RegType GetRegisterType(const RegisterLine* register_line,
1211 uint32_t vsrc) {
1212 return register_line->reg_types_[vsrc];
1213 }
1214
1215 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001216 * Return the register type for the method. We can't just use the
jeffhaobdb76512011-09-07 11:43:16 -07001217 * already-computed DalvikJniReturnType, because if it's a reference type
1218 * we need to do the class lookup.
1219 *
1220 * Returned references are assumed to be initialized.
1221 *
1222 * Returns kRegTypeUnknown for "void".
1223 */
1224 static RegType GetMethodReturnType(const DexFile* dex_file,
1225 const Method* method);
1226
1227 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001228 * Get the value from a register, and cast it to a Class. Sets
jeffhaobdb76512011-09-07 11:43:16 -07001229 * "*failure" if something fails.
1230 *
1231 * This fails if the register holds an uninitialized class.
1232 *
1233 * If the register holds kRegTypeZero, this returns a NULL pointer.
1234 */
1235 static Class* GetClassFromRegister(const RegisterLine* register_line,
1236 uint32_t vsrc, VerifyError* failure);
1237
1238 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001239 * Get the "this" pointer from a non-static method invocation. This
jeffhaobdb76512011-09-07 11:43:16 -07001240 * returns the RegType so the caller can decide whether it needs the
jeffhaod1f0fde2011-09-08 17:25:33 -07001241 * reference to be initialized or not. (Can also return kRegTypeZero
jeffhaobdb76512011-09-07 11:43:16 -07001242 * if the reference can only be zero at this point.)
1243 *
1244 * The argument count is in vA, and the first argument is in vC, for both
jeffhaod1f0fde2011-09-08 17:25:33 -07001245 * "simple" and "range" versions. We just need to make sure vA is >= 1
jeffhaobdb76512011-09-07 11:43:16 -07001246 * and then return vC.
1247 */
1248 static RegType GetInvocationThis(const RegisterLine* register_line,
1249 const Instruction::DecodedInstruction* dec_insn, VerifyError* failure);
1250
1251 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001252 * Set the type of register N, verifying that the register is valid. If
jeffhaobdb76512011-09-07 11:43:16 -07001253 * "new_type" is the "Lo" part of a 64-bit value, register N+1 will be
1254 * set to "new_type+1".
1255 *
1256 * The register index was validated during the static pass, so we don't
1257 * need to check it here.
1258 *
1259 * TODO: clear mon stack bits
1260 */
1261 static void SetRegisterType(RegisterLine* register_line, uint32_t vdst,
1262 RegType new_type);
1263
1264 /*
1265 * Verify that the contents of the specified register have the specified
1266 * type (or can be converted to it through an implicit widening conversion).
1267 *
1268 * This will modify the type of the source register if it was originally
1269 * derived from a constant to prevent mixing of int/float and long/double.
1270 *
1271 * If "vsrc" is a reference, both it and the "vsrc" register must be
jeffhaod1f0fde2011-09-08 17:25:33 -07001272 * initialized ("vsrc" may be Zero). This will verify that the value in
jeffhaobdb76512011-09-07 11:43:16 -07001273 * the register is an instance of check_type, or if check_type is an
1274 * interface, verify that the register implements check_type.
1275 */
1276 static void VerifyRegisterType(RegisterLine* register_line, uint32_t vsrc,
1277 RegType check_type, VerifyError* failure);
1278
1279 /* Set the type of the "result" register. */
1280 static void SetResultRegisterType(RegisterLine* register_line,
1281 const int insn_reg_count, RegType new_type);
1282
1283 /*
1284 * Update all registers holding "uninit_type" to instead hold the
jeffhaod1f0fde2011-09-08 17:25:33 -07001285 * corresponding initialized reference type. This is called when an
jeffhaobdb76512011-09-07 11:43:16 -07001286 * appropriate <init> method is invoked -- all copies of the reference
1287 * must be marked as initialized.
1288 */
1289 static void MarkRefsAsInitialized(RegisterLine* register_line,
1290 int insn_reg_count, UninitInstanceMap* uninit_map, RegType uninit_type,
1291 VerifyError* failure);
1292
1293 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001294 * Implement category-1 "move" instructions. Copy a 32-bit value from
jeffhaobdb76512011-09-07 11:43:16 -07001295 * "vsrc" to "vdst".
1296 */
1297 static void CopyRegister1(RegisterLine* register_line, uint32_t vdst,
1298 uint32_t vsrc, TypeCategory cat, VerifyError* failure);
1299
1300 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001301 * Implement category-2 "move" instructions. Copy a 64-bit value from
1302 * "vsrc" to "vdst". This copies both halves of the register.
jeffhaobdb76512011-09-07 11:43:16 -07001303 */
1304 static void CopyRegister2(RegisterLine* register_line, uint32_t vdst,
1305 uint32_t vsrc, VerifyError* failure);
1306
1307 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001308 * Implement "move-result". Copy the category-1 value from the result
jeffhaobdb76512011-09-07 11:43:16 -07001309 * register to another register, and reset the result register.
1310 */
1311 static void CopyResultRegister1(RegisterLine* register_line,
1312 const int insn_reg_count, uint32_t vdst, TypeCategory cat,
1313 VerifyError* failure);
1314
1315 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001316 * Implement "move-result-wide". Copy the category-2 value from the result
jeffhaobdb76512011-09-07 11:43:16 -07001317 * register to another register, and reset the result register.
1318 */
1319 static void CopyResultRegister2(RegisterLine* register_line,
1320 const int insn_reg_count, uint32_t vdst, VerifyError* failure);
1321
1322 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001323 * Compute the "class depth" of a class. This is the distance from the
1324 * class to the top of the tree, chasing superclass links. java.lang.Object
jeffhaobdb76512011-09-07 11:43:16 -07001325 * has a class depth of 0.
1326 */
1327 static int GetClassDepth(Class* klass);
1328
1329 /*
1330 * Given two classes, walk up the superclass tree to find a common
jeffhaod1f0fde2011-09-08 17:25:33 -07001331 * ancestor. (Called from findCommonSuperclass().)
jeffhaobdb76512011-09-07 11:43:16 -07001332 *
1333 * TODO: consider caching the class depth in the class object so we don't
1334 * have to search for it here.
1335 */
1336 static Class* DigForSuperclass(Class* c1, Class* c2);
1337
1338 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001339 * Merge two array classes. We can't use the general "walk up to the
jeffhaobdb76512011-09-07 11:43:16 -07001340 * superclass" merge because the superclass of an array is always Object.
jeffhaod1f0fde2011-09-08 17:25:33 -07001341 * We want String[] + Integer[] = Object[]. This works for higher dimensions
jeffhaobdb76512011-09-07 11:43:16 -07001342 * as well, e.g. String[][] + Integer[][] = Object[][].
1343 *
1344 * If Foo1 and Foo2 are subclasses of Foo, Foo1[] + Foo2[] = Foo[].
1345 *
1346 * If Class implements Type, Class[] + Type[] = Type[].
1347 *
1348 * If the dimensions don't match, we want to convert to an array of Object
1349 * with the least dimension, e.g. String[][] + String[][][][] = Object[][].
1350 *
1351 * Arrays of primitive types effectively have one less dimension when
jeffhaod1f0fde2011-09-08 17:25:33 -07001352 * merging. int[] + float[] = Object, int[] + String[] = Object,
1353 * int[][] + float[][] = Object[], int[][] + String[] = Object[]. (The
jeffhaobdb76512011-09-07 11:43:16 -07001354 * only time this function doesn't return an array class is when one of
1355 * the arguments is a 1-dimensional primitive array.)
1356 *
1357 * This gets a little awkward because we may have to ask the VM to create
jeffhaod1f0fde2011-09-08 17:25:33 -07001358 * a new array type with the appropriate element and dimensions. However, we
jeffhaobdb76512011-09-07 11:43:16 -07001359 * shouldn't be doing this often.
1360 */
1361 static Class* FindCommonArraySuperclass(Class* c1, Class* c2);
1362
1363 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001364 * Find the first common superclass of the two classes. We're not
jeffhaobdb76512011-09-07 11:43:16 -07001365 * interested in common interfaces.
1366 *
1367 * The easiest way to do this for concrete classes is to compute the "class
1368 * depth" of each, move up toward the root of the deepest one until they're
1369 * at the same depth, then walk both up to the root until they match.
1370 *
1371 * If both classes are arrays, we need to merge based on array depth and
1372 * element type.
1373 *
1374 * If one class is an interface, we check to see if the other class/interface
jeffhaod1f0fde2011-09-08 17:25:33 -07001375 * (or one of its predecessors) implements the interface. If so, we return
jeffhaobdb76512011-09-07 11:43:16 -07001376 * the interface; otherwise, we return Object.
1377 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001378 * NOTE: we continue the tradition of "lazy interface handling". To wit,
jeffhaobdb76512011-09-07 11:43:16 -07001379 * suppose we have three classes:
1380 * One implements Fancy, Free
1381 * Two implements Fancy, Free
1382 * Three implements Free
jeffhaod1f0fde2011-09-08 17:25:33 -07001383 * where Fancy and Free are unrelated interfaces. The code requires us
1384 * to merge One into Two. Ideally we'd use a common interface, which
jeffhaobdb76512011-09-07 11:43:16 -07001385 * gives us a choice between Fancy and Free, and no guidance on which to
jeffhaod1f0fde2011-09-08 17:25:33 -07001386 * use. If we use Free, we'll be okay when Three gets merged in, but if
1387 * we choose Fancy, we're hosed. The "ideal" solution is to create a
jeffhaobdb76512011-09-07 11:43:16 -07001388 * set of common interfaces and carry that around, merging further references
jeffhaod1f0fde2011-09-08 17:25:33 -07001389 * into it. This is a pain. The easy solution is to simply boil them
jeffhaobdb76512011-09-07 11:43:16 -07001390 * down to Objects and let the runtime invokeinterface call fail, which
1391 * is what we do.
1392 */
1393 static Class* FindCommonSuperclass(Class* c1, Class* c2);
1394
1395 /*
jeffhao98eacac2011-09-14 16:11:53 -07001396 * Resolves a class based on an index and performs access checks to ensure
1397 * the referrer can access the resolved class.
1398 *
1399 * Exceptions caused by failures are cleared before returning.
1400 *
1401 * Sets "*failure" on failure.
1402 */
1403 static Class* ResolveClassAndCheckAccess(const DexFile* dex_file,
1404 uint32_t class_idx, const Class* referrer, VerifyError* failure);
1405
1406 /*
jeffhaob4df5142011-09-19 20:25:32 -07001407 * Resolves a method based on an index and performs access checks to ensure
1408 * the referrer can access the resolved method.
1409 *
1410 * Does not throw exceptions.
1411 *
1412 * Sets "*failure" on failure.
1413 */
1414 static Method* ResolveMethodAndCheckAccess(const DexFile* dex_file,
1415 uint32_t method_idx, const Class* referrer, VerifyError* failure,
1416 bool is_direct);
1417
1418 /*
1419 * Resolves a field based on an index and performs access checks to ensure
1420 * the referrer can access the resolved field.
1421 *
1422 * Exceptions caused by failures are cleared before returning.
1423 *
1424 * Sets "*failure" on failure.
1425 */
1426 static Field* ResolveFieldAndCheckAccess(const DexFile* dex_file,
1427 uint32_t class_idx, const Class* referrer, VerifyError* failure,
1428 bool is_static);
1429
1430 /*
jeffhaobdb76512011-09-07 11:43:16 -07001431 * Merge two RegType values.
1432 *
1433 * Sets "*changed" to "true" if the result doesn't match "type1".
1434 */
1435 static RegType MergeTypes(RegType type1, RegType type2, bool* changed);
1436
1437 /*
1438 * Merge the bits that indicate which monitor entry addresses on the stack
1439 * are associated with this register.
1440 *
1441 * The merge is a simple bitwise AND.
1442 *
jeffhao98eacac2011-09-14 16:11:53 -07001443 * Sets "*changed" to "true" if the result doesn't match "ents1".
jeffhaobdb76512011-09-07 11:43:16 -07001444 */
1445 static MonitorEntries MergeMonitorEntries(MonitorEntries ents1,
1446 MonitorEntries ents2, bool* changed);
1447
1448 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001449 * We're creating a new instance of class C at address A. Any registers
jeffhaobdb76512011-09-07 11:43:16 -07001450 * holding instances previously created at address A must be initialized
jeffhaod1f0fde2011-09-08 17:25:33 -07001451 * by now. If not, we mark them as "conflict" to prevent them from being
jeffhaobdb76512011-09-07 11:43:16 -07001452 * used (otherwise, MarkRefsAsInitialized would mark the old ones and the
1453 * new ones at the same time).
1454 */
1455 static void MarkUninitRefsAsInvalid(RegisterLine* register_line,
1456 int insn_reg_count, UninitInstanceMap* uninit_map, RegType uninit_type);
1457
1458 /*
1459 * Control can transfer to "next_insn".
1460 *
1461 * Merge the registers from "work_line" into "reg_table" at "next_insn", and
1462 * set the "changed" flag on the target address if any of the registers
1463 * has changed.
1464 *
1465 * Returns "false" if we detect mismatched monitor stacks.
1466 */
1467 static bool UpdateRegisters(InsnFlags* insn_flags, RegisterTable* reg_table,
1468 int next_insn, const RegisterLine* work_line);
1469
1470 /*
1471 * Determine whether we can convert "src_type" to "check_type", where
1472 * "check_type" is one of the category-1 non-reference types.
1473 *
1474 * Constant derived types may become floats, but other values may not.
1475 */
1476 static bool CanConvertTo1nr(RegType src_type, RegType check_type);
1477
1478 /* Determine whether the category-2 types are compatible. */
1479 static bool CanConvertTo2(RegType src_type, RegType check_type);
1480
1481 /* Convert a VM PrimitiveType enum value to the equivalent RegType value. */
1482 static RegType PrimitiveTypeToRegType(Class::PrimitiveType prim_type);
1483
1484 /*
1485 * Convert a const derived RegType to the equivalent non-const RegType value.
1486 * Does nothing if the argument type isn't const derived.
1487 */
1488 static RegType ConstTypeToRegType(RegType const_type);
1489
1490 /*
1491 * Given a 32-bit constant, return the most-restricted RegType enum entry
1492 * that can hold the value. The types used here indicate the value came
1493 * from a const instruction, and may not correctly represent the real type
1494 * of the value. Upon use, a constant derived type is updated with the
1495 * type from the use, which will be unambiguous.
1496 */
1497 static char DetermineCat1Const(int32_t value);
1498
1499 /*
1500 * If "field" is marked "final", make sure this is the either <clinit>
1501 * or <init> as appropriate.
1502 *
1503 * Sets "*failure" on failure.
1504 */
1505 static void CheckFinalFieldAccess(const Method* method, const Field* field,
1506 VerifyError* failure);
1507
1508 /*
1509 * Make sure that the register type is suitable for use as an array index.
1510 *
1511 * Sets "*failure" if not.
1512 */
1513 static void CheckArrayIndexType(const Method* method, RegType reg_type,
1514 VerifyError* failure);
1515
1516 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001517 * Check constraints on constructor return. Specifically, make sure that
jeffhaobdb76512011-09-07 11:43:16 -07001518 * the "this" argument got initialized.
1519 *
1520 * The "this" argument to <init> uses code offset kUninitThisArgAddr, which
jeffhaod1f0fde2011-09-08 17:25:33 -07001521 * puts it at the start of the list in slot 0. If we see a register with
jeffhaobdb76512011-09-07 11:43:16 -07001522 * an uninitialized slot 0 reference, we know it somehow didn't get
1523 * initialized.
1524 *
1525 * Returns "true" if all is well.
1526 */
1527 static bool CheckConstructorReturn(const Method* method,
1528 const RegisterLine* register_line, const int insn_reg_count);
1529
1530 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001531 * Verify that the target instruction is not "move-exception". It's important
jeffhaobdb76512011-09-07 11:43:16 -07001532 * that the only way to execute a move-exception is as the first instruction
1533 * of an exception handler.
1534 *
1535 * Returns "true" if all is well, "false" if the target instruction is
1536 * move-exception.
1537 */
1538 static bool CheckMoveException(const uint16_t* insns, int insn_idx);
1539
1540 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001541 * See if "type" matches "cat". All we're really looking for here is that
jeffhaobdb76512011-09-07 11:43:16 -07001542 * we're not mixing and matching 32-bit and 64-bit quantities, and we're
jeffhaod1f0fde2011-09-08 17:25:33 -07001543 * not mixing references with numerics. (For example, the arguments to
jeffhaobdb76512011-09-07 11:43:16 -07001544 * "a < b" could be integers of different sizes, but they must both be
jeffhaod1f0fde2011-09-08 17:25:33 -07001545 * integers. Dalvik is less specific about int vs. float, so we treat them
jeffhaobdb76512011-09-07 11:43:16 -07001546 * as equivalent here.)
1547 *
1548 * For category 2 values, "type" must be the "low" half of the value.
1549 *
1550 * Sets "*failure" if something looks wrong.
1551 */
1552 static void CheckTypeCategory(RegType type, TypeCategory cat,
1553 VerifyError* failure);
1554
1555 /*
1556 * For a category 2 register pair, verify that "type_h" is the appropriate
1557 * high part for "type_l".
1558 *
1559 * Does not verify that "type_l" is in fact the low part of a 64-bit
1560 * register pair.
1561 */
1562 static void CheckWidePair(RegType type_l, RegType type_h,
1563 VerifyError* failure);
1564
1565 /*
1566 * Verify types for a simple two-register instruction (e.g. "neg-int").
1567 * "dst_type" is stored into vA, and "src_type" is verified against vB.
1568 */
1569 static void CheckUnop(RegisterLine* register_line,
1570 Instruction::DecodedInstruction* dec_insn, RegType dst_type,
1571 RegType src_type, VerifyError* failure);
1572
1573 /*
1574 * Verify types for a simple three-register instruction (e.g. "add-int").
1575 * "dst_type" is stored into vA, and "src_type1"/"src_type2" are verified
1576 * against vB/vC.
1577 */
1578 static void CheckBinop(RegisterLine* register_line,
1579 Instruction::DecodedInstruction* dec_insn, RegType dst_type,
1580 RegType src_type1, RegType src_type2, bool check_boolean_op,
1581 VerifyError* failure);
1582
1583 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001584 * Verify types for a binary "2addr" operation. "src_type1"/"src_type2"
jeffhaobdb76512011-09-07 11:43:16 -07001585 * are verified against vA/vB, then "dst_type" is stored into vA.
1586 */
1587 static void CheckBinop2addr(RegisterLine* register_line,
1588 Instruction::DecodedInstruction* dec_insn, RegType dst_type,
1589 RegType src_type1, RegType src_type2, bool check_boolean_op,
1590 VerifyError* failure);
1591
1592 /*
1593 * Treat right-shifting as a narrowing conversion when possible.
1594 *
1595 * For example, right-shifting an int 24 times results in a value that can
1596 * be treated as a byte.
1597 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001598 * Things get interesting when contemplating sign extension. Right-
jeffhaobdb76512011-09-07 11:43:16 -07001599 * shifting an integer by 16 yields a value that can be represented in a
1600 * "short" but not a "char", but an unsigned right shift by 16 yields a
jeffhaod1f0fde2011-09-08 17:25:33 -07001601 * value that belongs in a char rather than a short. (Consider what would
jeffhaobdb76512011-09-07 11:43:16 -07001602 * happen if the result of the shift were cast to a char or short and then
jeffhaod1f0fde2011-09-08 17:25:33 -07001603 * cast back to an int. If sign extension, or the lack thereof, causes
jeffhaobdb76512011-09-07 11:43:16 -07001604 * a change in the 32-bit representation, then the conversion was lossy.)
1605 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001606 * A signed right shift by 17 on an integer results in a short. An unsigned
jeffhaobdb76512011-09-07 11:43:16 -07001607 * right shfit by 17 on an integer results in a posshort, which can be
1608 * assigned to a short or a char.
1609 *
1610 * An unsigned right shift on a short can actually expand the result into
jeffhaod1f0fde2011-09-08 17:25:33 -07001611 * a 32-bit integer. For example, 0xfffff123 >>> 8 becomes 0x00fffff1,
jeffhaobdb76512011-09-07 11:43:16 -07001612 * which can't be represented in anything smaller than an int.
1613 *
1614 * javac does not generate code that takes advantage of this, but some
jeffhaod1f0fde2011-09-08 17:25:33 -07001615 * of the code optimizers do. It's generally a peephole optimization
jeffhaobdb76512011-09-07 11:43:16 -07001616 * that replaces a particular sequence, e.g. (bipush 24, ishr, i2b) is
jeffhaod1f0fde2011-09-08 17:25:33 -07001617 * replaced by (bipush 24, ishr). Knowing that shifting a short 8 times
jeffhaobdb76512011-09-07 11:43:16 -07001618 * to the right yields a byte is really more than we need to handle the
1619 * code that's out there, but support is not much more complex than just
1620 * handling integer.
1621 *
1622 * Right-shifting never yields a boolean value.
1623 *
1624 * Returns the new register type.
1625 */
1626 static RegType AdjustForRightShift(RegisterLine* register_line, int reg,
jeffhaob4df5142011-09-19 20:25:32 -07001627 unsigned int shift_count, bool is_unsigned_shift);
jeffhaobdb76512011-09-07 11:43:16 -07001628
1629 /*
1630 * We're performing an operation like "and-int/2addr" that can be
jeffhaod1f0fde2011-09-08 17:25:33 -07001631 * performed on booleans as well as integers. We get no indication of
jeffhaobdb76512011-09-07 11:43:16 -07001632 * boolean-ness, but we can infer it from the types of the arguments.
1633 *
1634 * Assumes we've already validated reg1/reg2.
1635 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001636 * TODO: consider generalizing this. The key principle is that the
jeffhaobdb76512011-09-07 11:43:16 -07001637 * result of a bitwise operation can only be as wide as the widest of
jeffhaod1f0fde2011-09-08 17:25:33 -07001638 * the operands. You can safely AND/OR/XOR two chars together and know
jeffhaobdb76512011-09-07 11:43:16 -07001639 * you still have a char, so it's reasonable for the compiler or "dx"
jeffhaod1f0fde2011-09-08 17:25:33 -07001640 * to skip the int-to-char instruction. (We need to do this for boolean
jeffhaobdb76512011-09-07 11:43:16 -07001641 * because there is no int-to-boolean operation.)
1642 *
1643 * Returns true if both args are Boolean, Zero, or One.
1644 */
1645 static bool UpcastBooleanOp(RegisterLine* register_line, uint32_t reg1,
1646 uint32_t reg2);
1647
1648 /*
1649 * Verify types for A two-register instruction with a literal constant
jeffhaod1f0fde2011-09-08 17:25:33 -07001650 * (e.g. "add-int/lit8"). "dst_type" is stored into vA, and "src_type" is
jeffhaobdb76512011-09-07 11:43:16 -07001651 * verified against vB.
1652 *
1653 * If "check_boolean_op" is set, we use the constant value in vC.
1654 */
1655 static void CheckLitop(RegisterLine* register_line,
1656 Instruction::DecodedInstruction* dec_insn, RegType dst_type,
1657 RegType src_type, bool check_boolean_op, VerifyError* failure);
1658
1659 /*
1660 * Verify that the arguments in a filled-new-array instruction are valid.
1661 *
1662 * "res_class" is the class refered to by dec_insn->vB_.
1663 */
1664 static void VerifyFilledNewArrayRegs(const Method* method,
1665 RegisterLine* register_line,
1666 const Instruction::DecodedInstruction* dec_insn, Class* res_class,
1667 bool is_range, VerifyError* failure);
1668
1669 /* See if the method matches the MethodType. */
1670 static bool IsCorrectInvokeKind(MethodType method_type, Method* res_method);
1671
1672 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001673 * Verify the arguments to a method. We're executing in "method", making
jeffhaobdb76512011-09-07 11:43:16 -07001674 * a call to the method reference in vB.
1675 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001676 * If this is a "direct" invoke, we allow calls to <init>. For calls to
1677 * <init>, the first argument may be an uninitialized reference. Otherwise,
jeffhaobdb76512011-09-07 11:43:16 -07001678 * calls to anything starting with '<' will be rejected, as will any
1679 * uninitialized reference arguments.
1680 *
1681 * For non-static method calls, this will verify that the method call is
1682 * appropriate for the "this" argument.
1683 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001684 * The method reference is in vBBBB. The "is_range" parameter determines
jeffhaobdb76512011-09-07 11:43:16 -07001685 * whether we use 0-4 "args" values or a range of registers defined by
1686 * vAA and vCCCC.
1687 *
1688 * Widening conversions on integers and references are allowed, but
1689 * narrowing conversions are not.
1690 *
1691 * Returns the resolved method on success, NULL on failure (with *failure
1692 * set appropriately).
1693 */
1694 static Method* VerifyInvocationArgs(VerifierData* vdata,
1695 RegisterLine* register_line, const int insn_reg_count,
1696 const Instruction::DecodedInstruction* dec_insn, MethodType method_type,
1697 bool is_range, bool is_super, VerifyError* failure);
1698
jeffhaoe0cfb6f2011-09-22 16:42:56 -07001699 /* Dump the register types for the specifed address to the log file. */
1700 static void DumpRegTypes(const VerifierData* vdata,
1701 const RegisterLine* register_line, int addr, const char* addr_name,
1702 const UninitInstanceMap* uninit_map);
1703
jeffhaobdb76512011-09-07 11:43:16 -07001704 DISALLOW_COPY_AND_ASSIGN(DexVerifier);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001705};
1706
1707} // namespace art
1708
1709#endif // ART_SRC_DEX_VERIFY_H_