blob: 404227dfd6b1cf4b265fa37d901a8e48bfaf69ad [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 */
365 bool format_on_heap_; /* indicates allocation on heap */
366
367 RegisterMapHeader(uint8_t format, uint8_t reg_width, uint16_t num_entries,
368 bool format_on_heap)
369 : format_(format), reg_width_(reg_width), num_entries_(num_entries),
370 format_on_heap_(format_on_heap) {
371 }
372 };
373
jeffhaobdb76512011-09-07 11:43:16 -0700374 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700375 * This is a single variable-size structure. It may be allocated on the
376 * heap or mapped out of a (post-dexopt) DEX file.
377 *
378 * 32-bit alignment of the structure is NOT guaranteed. This makes it a
379 * little awkward to deal with as a structure; to avoid accidents we use
380 * only byte types. Multi-byte values are little-endian.
381 *
382 * Size of (format==FormatNone): 1 byte
383 * Size of (format==FormatCompact8): 4 + (1 + reg_width) * num_entries
384 * Size of (format==FormatCompact16): 4 + (2 + reg_width) * num_entries
385 */
386 struct RegisterMap {
jeffhaoe23d93c2011-09-15 14:48:43 -0700387 RegisterMapHeader* header_;
388 uint8_t* data_;
389 bool needs_free_;
jeffhaod1f0fde2011-09-08 17:25:33 -0700390
jeffhaoe23d93c2011-09-15 14:48:43 -0700391 RegisterMap(ByteArray* header, ByteArray* data) {
392 header_ = (RegisterMapHeader*) header->GetData();
393 data_ = (uint8_t*) data->GetData();
394 needs_free_ = false;
395 }
jeffhaod1f0fde2011-09-08 17:25:33 -0700396
397 RegisterMap(uint8_t format, uint8_t reg_width, uint16_t num_entries,
jeffhaoe23d93c2011-09-15 14:48:43 -0700398 bool format_on_heap, uint32_t data_size) {
399 header_ = new RegisterMapHeader(format, reg_width, num_entries,
400 format_on_heap);
401 data_ = new uint8_t[data_size]();
402 needs_free_ = true;
403 }
404
405 ~RegisterMap() {
406 if (needs_free_) {
407 delete header_;
408 delete [] data_;
409 }
jeffhaod1f0fde2011-09-08 17:25:33 -0700410 }
411 };
412
413 /*
414 * Merge result table for primitive values. The table is symmetric along
jeffhaobdb76512011-09-07 11:43:16 -0700415 * the diagonal.
416 *
jeffhaod1f0fde2011-09-08 17:25:33 -0700417 * Note that 32-bit int/float do not merge into 64-bit long/double. This
418 * is a register merge, not a widening conversion. Only the "implicit"
jeffhaobdb76512011-09-07 11:43:16 -0700419 * widening within a category, e.g. byte to short, is allowed.
420 *
421 * Dalvik does not draw a distinction between int and float, but we enforce
422 * that once a value is used as int, it can't be used as float, and vice
423 * versa. We do not allow free exchange between 32-bit int/float and 64-bit
424 * long/double.
425 *
jeffhaod1f0fde2011-09-08 17:25:33 -0700426 * Note that Uninit+Uninit=Uninit. This holds true because we only
jeffhaobdb76512011-09-07 11:43:16 -0700427 * use this when the RegType value is exactly equal to kRegTypeUninit, which
428 * can only happen for the zeroeth entry in the table.
429 *
jeffhaod1f0fde2011-09-08 17:25:33 -0700430 * "Unknown" never merges with anything known. The only time a register
jeffhaobdb76512011-09-07 11:43:16 -0700431 * transitions from "unknown" to "known" is when we're executing code
432 * for the first time, and we handle that with a simple copy.
433 */
434 static const char merge_table_[kRegTypeMAX][kRegTypeMAX];
435
436 /*
437 * Returns "true" if the flags indicate that this address holds the start
438 * of an instruction.
439 */
440 static inline bool InsnIsOpcode(const InsnFlags insn_flags[], int addr) {
441 return (insn_flags[addr] & kInsnFlagWidthMask) != 0;
442 }
443
444 /* Extract the unsigned 16-bit instruction width from "flags". */
445 static inline int InsnGetWidth(const InsnFlags insn_flags[], int addr) {
446 return insn_flags[addr] & kInsnFlagWidthMask;
447 }
448
449 /* Utilities to check and set kInsnFlagChanged. */
450 static inline bool InsnIsChanged(const InsnFlags insn_flags[], int addr) {
451 return (insn_flags[addr] & kInsnFlagChanged) != 0;
452 }
453 static inline void InsnSetChanged(InsnFlags insn_flags[], int addr,
454 bool changed) {
455 if (changed)
456 insn_flags[addr] |= kInsnFlagChanged;
457 else
458 insn_flags[addr] &= ~kInsnFlagChanged;
459 }
460
461 /* Utilities to check and set kInsnFlagVisited. */
462 static inline bool InsnIsVisited(const InsnFlags insn_flags[], int addr) {
463 return (insn_flags[addr] & kInsnFlagVisited) != 0;
464 }
465 static inline void InsnSetVisited(InsnFlags insn_flags[], int addr,
466 bool visited) {
467 if (visited)
468 insn_flags[addr] |= kInsnFlagVisited;
469 else
470 insn_flags[addr] &= ~kInsnFlagVisited;
471 }
472
473 static inline bool InsnIsVisitedOrChanged(const InsnFlags insn_flags[],
474 int addr) {
475 return (insn_flags[addr] & (kInsnFlagVisited |
476 kInsnFlagChanged)) != 0;
477 }
478
479 /* Utilities to check and set kInsnFlagInTry. */
480 static inline bool InsnIsInTry(const InsnFlags insn_flags[], int addr) {
481 return (insn_flags[addr] & kInsnFlagInTry) != 0;
482 }
483 static inline void InsnSetInTry(InsnFlags insn_flags[], int addr) {
484 insn_flags[addr] |= kInsnFlagInTry;
485 }
486
487 /* Utilities to check and set kInsnFlagBranchTarget. */
488 static inline bool InsnIsBranchTarget(const InsnFlags insn_flags[], int addr)
489 {
490 return (insn_flags[addr] & kInsnFlagBranchTarget) != 0;
491 }
492 static inline void InsnSetBranchTarget(InsnFlags insn_flags[], int addr) {
493 insn_flags[addr] |= kInsnFlagBranchTarget;
494 }
495
496 /* Utilities to check and set kInsnFlagGcPoint. */
497 static inline bool InsnIsGcPoint(const InsnFlags insn_flags[], int addr) {
498 return (insn_flags[addr] & kInsnFlagGcPoint) != 0;
499 }
500 static inline void InsnSetGcPoint(InsnFlags insn_flags[], int addr) {
501 insn_flags[addr] |= kInsnFlagGcPoint;
502 }
503
504 /* Get the class object at the specified index. */
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700505 static inline Class* GetUninitInstance(const UninitInstanceMap* uninit_map, int idx) {
506 DCHECK_GE(idx, 0);
507 DCHECK_LT(idx, uninit_map->num_entries_);
jeffhaobdb76512011-09-07 11:43:16 -0700508 return uninit_map->map_[idx].klass_;
509 }
510
511 /* Determine if "type" is actually an object reference (init/uninit/zero) */
512 static inline bool RegTypeIsReference(RegType type) {
513 return (type > kRegTypeMAX || type == kRegTypeUninit ||
514 type == kRegTypeZero);
515 }
516
517 /* Determine if "type" is an uninitialized object reference */
518 static inline bool RegTypeIsUninitReference(RegType type) {
519 return ((type & kRegTypeUninitMask) == kRegTypeUninit);
520 }
521
522 /*
523 * Convert the initialized reference "type" to a Class pointer
524 * (does not expect uninit ref types or "zero").
525 */
526 static Class* RegTypeInitializedReferenceToClass(RegType type) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700527 DCHECK(RegTypeIsReference(type) && type != kRegTypeZero);
jeffhaobdb76512011-09-07 11:43:16 -0700528 if ((type & 0x01) == 0) {
529 return (Class*) type;
530 } else {
531 LOG(ERROR) << "VFY: attempted to use uninitialized reference";
532 return NULL;
533 }
534 }
535
536 /* Extract the index into the uninitialized instance map table. */
537 static inline int RegTypeToUninitIndex(RegType type) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700538 DCHECK(RegTypeIsUninitReference(type));
jeffhaobdb76512011-09-07 11:43:16 -0700539 return (type & ~kRegTypeUninitMask) >> kRegTypeUninitShift;
540 }
541
542 /* Convert the reference "type" to a Class pointer. */
543 static Class* RegTypeReferenceToClass(RegType type,
544 const UninitInstanceMap* uninit_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700545 DCHECK(RegTypeIsReference(type) && type != kRegTypeZero);
jeffhaobdb76512011-09-07 11:43:16 -0700546 if (RegTypeIsUninitReference(type)) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700547 DCHECK(uninit_map != NULL);
jeffhaobdb76512011-09-07 11:43:16 -0700548 return GetUninitInstance(uninit_map, RegTypeToUninitIndex(type));
549 } else {
550 return (Class*) type;
551 }
552 }
553
554 /* Convert the ClassObject pointer to an (initialized) register type. */
555 static inline RegType RegTypeFromClass(Class* klass) {
556 return (uint32_t) klass;
557 }
558
559 /* Return the RegType for the uninitialized reference in slot "uidx". */
560 static inline RegType RegTypeFromUninitIndex(int uidx) {
561 return (uint32_t) (kRegTypeUninit | (uidx << kRegTypeUninitShift));
562 }
563
jeffhaoe23d93c2011-09-15 14:48:43 -0700564 /* Verify a class. Returns "true" on success. */
565 static bool VerifyClass(Class* klass);
566
567 private:
jeffhaobdb76512011-09-07 11:43:16 -0700568 /*
569 * Perform verification on a single method.
570 *
571 * We do this in three passes:
572 * (1) Walk through all code units, determining instruction locations,
573 * widths, and other characteristics.
574 * (2) Walk through all code units, performing static checks on
575 * operands.
576 * (3) Iterate through the method, checking type safety and looking
577 * for code flow problems.
578 *
jeffhaod1f0fde2011-09-08 17:25:33 -0700579 * Some checks may be bypassed depending on the verification mode. We can't
jeffhaobdb76512011-09-07 11:43:16 -0700580 * turn this stuff off completely if we want to do "exact" GC.
581 *
582 * Confirmed here:
583 * - code array must not be empty
584 * Confirmed by ComputeWidthsAndCountOps():
585 * - opcode of first instruction begins at index 0
586 * - only documented instructions may appear
587 * - each instruction follows the last
588 * - last byte of last instruction is at (code_length-1)
589 */
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700590 static bool VerifyMethod(Method* method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700591
jeffhaobdb76512011-09-07 11:43:16 -0700592 /*
593 * Perform static verification on all instructions in a method.
594 *
595 * Walks through instructions in a method calling VerifyInstruction on each.
596 */
597 static bool VerifyInstructions(VerifierData* vdata);
598
599 /*
600 * Perform static verification on an instruction.
601 *
602 * As a side effect, this sets the "branch target" flags in InsnFlags.
603 *
604 * "(CF)" items are handled during code-flow analysis.
605 *
606 * v3 4.10.1
607 * - target of each jump and branch instruction must be valid
608 * - targets of switch statements must be valid
609 * - operands referencing constant pool entries must be valid
610 * - (CF) operands of getfield, putfield, getstatic, putstatic must be valid
611 * - (CF) operands of method invocation instructions must be valid
612 * - (CF) only invoke-direct can call a method starting with '<'
613 * - (CF) <clinit> must never be called explicitly
614 * - operands of instanceof, checkcast, new (and variants) must be valid
615 * - new-array[-type] limited to 255 dimensions
616 * - can't use "new" on an array class
617 * - (?) limit dimensions in multi-array creation
618 * - local variable load/store register values must be in valid range
619 *
620 * v3 4.11.1.2
621 * - branches must be within the bounds of the code array
622 * - targets of all control-flow instructions are the start of an instruction
623 * - register accesses fall within range of allocated registers
624 * - (N/A) access to constant pool must be of appropriate type
625 * - code does not end in the middle of an instruction
626 * - execution cannot fall off the end of the code
627 * - (earlier) for each exception handler, the "try" area must begin and
628 * end at the start of an instruction (end can be at the end of the code)
629 * - (earlier) for each exception handler, the handler must start at a valid
630 * instruction
631 */
632 static bool VerifyInstruction(VerifierData* vdata,
633 const Instruction* inst, uint32_t code_offset);
634
635 /* Perform detailed code-flow analysis on a single method. */
636 static bool VerifyCodeFlow(VerifierData* vdata);
637
638 /*
639 * Compute the width of the instruction at each address in the instruction
jeffhaod1f0fde2011-09-08 17:25:33 -0700640 * stream, and store it in vdata->insn_flags. Addresses that are in the
jeffhaobdb76512011-09-07 11:43:16 -0700641 * middle of an instruction, or that are part of switch table data, are not
642 * touched (so the caller should probably initialize "insn_flags" to zero).
643 *
644 * The "new_instance_count_" and "monitor_enter_count_" fields in vdata are
645 * also set.
646 *
647 * Performs some static checks, notably:
648 * - opcode of first instruction begins at index 0
649 * - only documented instructions may appear
650 * - each instruction follows the last
651 * - last byte of last instruction is at (code_length-1)
652 *
653 * Logs an error and returns "false" on failure.
654 */
655 static bool ComputeWidthsAndCountOps(VerifierData* vdata);
656
657 /*
658 * Set the "in try" flags for all instructions protected by "try" statements.
659 * Also sets the "branch target" flags for exception handlers.
660 *
661 * Call this after widths have been set in "insn_flags".
662 *
663 * Returns "false" if something in the exception table looks fishy, but
664 * we're expecting the exception table to be somewhat sane.
665 */
666 static bool ScanTryCatchBlocks(VerifierData* vdata);
667
668 /*
669 * Extract the relative offset from a branch instruction.
670 *
671 * Returns "false" on failure (e.g. this isn't a branch instruction).
672 */
673 static bool GetBranchOffset(const DexFile::CodeItem* code_item,
674 const InsnFlags insn_flags[], uint32_t cur_offset, int32_t* pOffset,
675 bool* pConditional, bool* selfOkay);
676
677 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700678 * Verify an array data table. "cur_offset" is the offset of the
jeffhaobdb76512011-09-07 11:43:16 -0700679 * fill-array-data instruction.
680 */
681 static bool CheckArrayData(const DexFile::CodeItem* code_item,
682 uint32_t cur_offset);
683
684 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700685 * Perform static checks on a "new-instance" instruction. Specifically,
jeffhaobdb76512011-09-07 11:43:16 -0700686 * make sure the class reference isn't for an array class.
687 *
688 * We don't need the actual class, just a pointer to the class name.
689 */
690 static bool CheckNewInstance(const DexFile* dex_file, uint32_t idx);
691
692 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700693 * Perform static checks on a "new-array" instruction. Specifically, make
jeffhaobdb76512011-09-07 11:43:16 -0700694 * sure they aren't creating an array of arrays that causes the number of
695 * dimensions to exceed 255.
696 */
697 static bool CheckNewArray(const DexFile* dex_file, uint32_t idx);
698
699 /*
700 * Perform static checks on an instruction that takes a class constant.
701 * Ensure that the class index is in the valid range.
702 */
703 static bool CheckTypeIndex(const DexFile* dex_file, uint32_t idx);
704
705 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700706 * Perform static checks on a field get or set instruction. All we do
jeffhaobdb76512011-09-07 11:43:16 -0700707 * here is ensure that the field index is in the valid range.
708 */
709 static bool CheckFieldIndex(const DexFile* dex_file, uint32_t idx);
710
711 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700712 * Perform static checks on a method invocation instruction. All we do
jeffhaobdb76512011-09-07 11:43:16 -0700713 * here is ensure that the method index is in the valid range.
714 */
715 static bool CheckMethodIndex(const DexFile* dex_file, uint32_t idx);
716
717 /* Ensure that the string index is in the valid range. */
718 static bool CheckStringIndex(const DexFile* dex_file, uint32_t idx);
719
720 /* Ensure that the register index is valid for this code item. */
721 static bool CheckRegisterIndex(const DexFile::CodeItem* code_item,
722 uint32_t idx);
723
724 /* Ensure that the wide register index is valid for this code item. */
725 static bool CheckWideRegisterIndex(const DexFile::CodeItem* code_item,
726 uint32_t idx);
727
728 /*
729 * Check the register indices used in a "vararg" instruction, such as
730 * invoke-virtual or filled-new-array.
731 *
732 * vA holds word count (0-5), args[] have values.
733 *
734 * There are some tests we don't do here, e.g. we don't try to verify
735 * that invoking a method that takes a double is done with consecutive
jeffhaod1f0fde2011-09-08 17:25:33 -0700736 * registers. This requires parsing the target method signature, which
jeffhaobdb76512011-09-07 11:43:16 -0700737 * we will be doing later on during the code flow analysis.
738 */
739 static bool CheckVarArgRegs(const DexFile::CodeItem* code_item, uint32_t vA,
740 uint32_t arg[]);
741
742 /*
743 * Check the register indices used in a "vararg/range" instruction, such as
744 * invoke-virtual/range or filled-new-array/range.
745 *
746 * vA holds word count, vC holds index of first reg.
747 */
748 static bool CheckVarArgRangeRegs(const DexFile::CodeItem* code_item,
749 uint32_t vA, uint32_t vC);
750
751 /*
752 * Verify a switch table. "cur_offset" is the offset of the switch
753 * instruction.
754 *
755 * Updates "insnFlags", setting the "branch target" flag.
756 */
757 static bool CheckSwitchTargets(const DexFile::CodeItem* code_item,
758 InsnFlags insn_flags[], uint32_t cur_offset);
759
760 /*
761 * Verify that the target of a branch instruction is valid.
762 *
763 * We don't expect code to jump directly into an exception handler, but
764 * it's valid to do so as long as the target isn't a "move-exception"
jeffhaod1f0fde2011-09-08 17:25:33 -0700765 * instruction. We verify that in a later stage.
jeffhaobdb76512011-09-07 11:43:16 -0700766 *
767 * The dex format forbids certain instructions from branching to itself.
768 *
769 * Updates "insnFlags", setting the "branch target" flag.
770 */
771 static bool CheckBranchTarget(const DexFile::CodeItem* code_item,
772 InsnFlags insn_flags[], uint32_t cur_offset);
773
774 /*
775 * Initialize the RegisterTable.
776 *
777 * Every instruction address can have a different set of information about
778 * what's in which register, but for verification purposes we only need to
779 * store it at branch target addresses (because we merge into that).
780 *
781 * By zeroing out the regType storage we are effectively initializing the
782 * register information to kRegTypeUnknown.
783 *
784 * We jump through some hoops here to minimize the total number of
785 * allocations we have to perform per method verified.
786 */
787 static bool InitRegisterTable(VerifierData* vdata, RegisterTable* reg_table,
788 RegisterTrackingMode track_regs_for);
789
790 /* Get the register line for the given instruction in the current method. */
791 static inline RegisterLine* GetRegisterLine(const RegisterTable* reg_table,
792 int insn_idx) {
793 return &reg_table->register_lines_[insn_idx];
794 }
795
796 /* Copy a register line. */
797 static inline void CopyRegisterLine(RegisterLine* dst,
798 const RegisterLine* src, size_t num_regs) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700799 memcpy(dst->reg_types_.get(), src->reg_types_.get(), num_regs * sizeof(RegType));
jeffhaobdb76512011-09-07 11:43:16 -0700800
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700801 DCHECK((src->monitor_entries_.get() == NULL && dst->monitor_entries_.get() == NULL) ||
802 (src->monitor_entries_.get() != NULL && dst->monitor_entries_.get() != NULL));
803 if (dst->monitor_entries_.get() != NULL) {
804 DCHECK(dst->monitor_stack_.get() != NULL);
805 memcpy(dst->monitor_entries_.get(), src->monitor_entries_.get(),
jeffhaobdb76512011-09-07 11:43:16 -0700806 num_regs * sizeof(MonitorEntries));
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700807 memcpy(dst->monitor_stack_.get(), src->monitor_stack_.get(),
jeffhaobdb76512011-09-07 11:43:16 -0700808 kMaxMonitorStackDepth * sizeof(uint32_t));
809 dst->monitor_stack_top_ = src->monitor_stack_top_;
810 }
811 }
812
813 /* Copy a register line into the table. */
814 static inline void CopyLineToTable(RegisterTable* reg_table, int insn_idx,
815 const RegisterLine* src) {
816 RegisterLine* dst = GetRegisterLine(reg_table, insn_idx);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700817 DCHECK(dst->reg_types_.get() != NULL);
jeffhaobdb76512011-09-07 11:43:16 -0700818 CopyRegisterLine(dst, src, reg_table->insn_reg_count_plus_);
819 }
820
821 /* Copy a register line out of the table. */
822 static inline void CopyLineFromTable(RegisterLine* dst,
823 const RegisterTable* reg_table, int insn_idx) {
824 RegisterLine* src = GetRegisterLine(reg_table, insn_idx);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700825 DCHECK(src->reg_types_.get() != NULL);
jeffhaobdb76512011-09-07 11:43:16 -0700826 CopyRegisterLine(dst, src, reg_table->insn_reg_count_plus_);
827 }
828
829#ifndef NDEBUG
830 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700831 * Compare two register lines. Returns 0 if they match.
jeffhaobdb76512011-09-07 11:43:16 -0700832 *
833 * Using this for a sort is unwise, since the value can change based on
834 * machine endianness.
835 */
836 static inline int CompareLineToTable(const RegisterTable* reg_table,
837 int insn_idx, const RegisterLine* line2) {
838 const RegisterLine* line1 = GetRegisterLine(reg_table, insn_idx);
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700839 if (line1->monitor_entries_.get() != NULL) {
jeffhaobdb76512011-09-07 11:43:16 -0700840 int result;
841
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700842 if (line2->monitor_entries_.get() == NULL)
jeffhaobdb76512011-09-07 11:43:16 -0700843 return 1;
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700844 result = memcmp(line1->monitor_entries_.get(), line2->monitor_entries_.get(),
jeffhaobdb76512011-09-07 11:43:16 -0700845 reg_table->insn_reg_count_plus_ * sizeof(MonitorEntries));
846 if (result != 0) {
847 LOG(ERROR) << "monitor_entries_ mismatch";
848 return result;
849 }
850 result = line1->monitor_stack_top_ - line2->monitor_stack_top_;
851 if (result != 0) {
852 LOG(ERROR) << "monitor_stack_top_ mismatch";
853 return result;
854 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700855 result = memcmp(line1->monitor_stack_.get(), line2->monitor_stack_.get(),
jeffhaobdb76512011-09-07 11:43:16 -0700856 line1->monitor_stack_top_);
857 if (result != 0) {
858 LOG(ERROR) << "monitor_stack_ mismatch";
859 return result;
860 }
861 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700862 return memcmp(line1->reg_types_.get(), line2->reg_types_.get(),
jeffhaobdb76512011-09-07 11:43:16 -0700863 reg_table->insn_reg_count_plus_ * sizeof(RegType));
864 }
865#endif
866
867 /*
868 * Create a new uninitialized instance map.
869 *
jeffhaod1f0fde2011-09-08 17:25:33 -0700870 * The map is allocated and populated with address entries. The addresses
jeffhaobdb76512011-09-07 11:43:16 -0700871 * appear in ascending order to allow binary searching.
872 *
873 * Very few methods have 10 or more new-instance instructions; the
jeffhaod1f0fde2011-09-08 17:25:33 -0700874 * majority have 0 or 1. Occasionally a static initializer will have 200+.
jeffhaobdb76512011-09-07 11:43:16 -0700875 *
876 * TODO: merge this into the static pass or initRegisterTable; want to
877 * avoid walking through the instructions yet again just to set up this table
878 */
879 static UninitInstanceMap* CreateUninitInstanceMap(VerifierData* vdata);
880
881 /* Returns true if this method is a constructor. */
882 static bool IsInitMethod(const Method* method);
883
884 /*
885 * Look up a class reference given as a simple string descriptor.
886 *
887 * If we can't find it, return a generic substitute when possible.
888 */
889 static Class* LookupClassByDescriptor(const Method* method,
890 const char* descriptor, VerifyError* failure);
891
892 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700893 * Look up a class reference in a signature. Could be an arg or the
jeffhaobdb76512011-09-07 11:43:16 -0700894 * return value.
895 *
896 * Advances "*sig" to the last character in the signature (that is, to
897 * the ';').
898 *
899 * NOTE: this is also expected to verify the signature.
900 */
901 static Class* LookupSignatureClass(const Method* method, std::string sig,
902 VerifyError* failure);
903
904 /*
jeffhaod1f0fde2011-09-08 17:25:33 -0700905 * Look up an array class reference in a signature. Could be an arg or the
jeffhaobdb76512011-09-07 11:43:16 -0700906 * return value.
907 *
908 * Advances "*sig" to the last character in the signature.
909 *
910 * NOTE: this is also expected to verify the signature.
911 */
912 static Class* LookupSignatureArrayClass(const Method* method,
913 std::string sig, VerifyError* failure);
914
915 /*
916 * Set the register types for the first instruction in the method based on
917 * the method signature.
918 *
919 * This has the side-effect of validating the signature.
920 *
921 * Returns "true" on success.
922 */
923 static bool SetTypesFromSignature(VerifierData* vdata, RegType* reg_types);
924
925 /*
926 * Set the class object associated with the instruction at "addr".
927 *
928 * Returns the map slot index, or -1 if the address isn't listed in the map
929 * (shouldn't happen) or if a class is already associated with the address
930 * (bad bytecode).
931 *
932 * Entries, once set, do not change -- a given address can only allocate
933 * one type of object.
934 */
935 static int SetUninitInstance(UninitInstanceMap* uninit_map, int addr,
936 Class* klass);
937
938 /*
939 * Perform code flow on a method.
940 *
941 * The basic strategy is as outlined in v3 4.11.1.2: set the "changed" bit
942 * on the first instruction, process it (setting additional "changed" bits),
943 * and repeat until there are no more.
944 *
945 * v3 4.11.1.1
946 * - (N/A) operand stack is always the same size
947 * - operand stack [registers] contain the correct types of values
948 * - local variables [registers] contain the correct types of values
949 * - methods are invoked with the appropriate arguments
950 * - fields are assigned using values of appropriate types
951 * - opcodes have the correct type values in operand registers
952 * - there is never an uninitialized class instance in a local variable in
953 * code protected by an exception handler (operand stack is okay, because
954 * the operand stack is discarded when an exception is thrown) [can't
955 * know what's a local var w/o the debug info -- should fall out of
956 * register typing]
957 *
958 * v3 4.11.1.2
959 * - execution cannot fall off the end of the code
960 *
961 * (We also do many of the items described in the "static checks" sections,
962 * because it's easier to do them here.)
963 *
964 * We need an array of RegType values, one per register, for every
jeffhaod1f0fde2011-09-08 17:25:33 -0700965 * instruction. If the method uses monitor-enter, we need extra data
jeffhaobdb76512011-09-07 11:43:16 -0700966 * for every register, and a stack for every "interesting" instruction.
967 * In theory this could become quite large -- up to several megabytes for
968 * a monster function.
969 *
970 * NOTE:
971 * The spec forbids backward branches when there's an uninitialized reference
jeffhaod1f0fde2011-09-08 17:25:33 -0700972 * in a register. The idea is to prevent something like this:
jeffhaobdb76512011-09-07 11:43:16 -0700973 * loop:
974 * move r1, r0
975 * new-instance r0, MyClass
976 * ...
977 * if-eq rN, loop // once
978 * initialize r0
979 *
980 * This leaves us with two different instances, both allocated by the
jeffhaod1f0fde2011-09-08 17:25:33 -0700981 * same instruction, but only one is initialized. The scheme outlined in
jeffhaobdb76512011-09-07 11:43:16 -0700982 * v3 4.11.1.4 wouldn't catch this, so they work around it by preventing
jeffhaod1f0fde2011-09-08 17:25:33 -0700983 * backward branches. We achieve identical results without restricting
jeffhaobdb76512011-09-07 11:43:16 -0700984 * code reordering by specifying that you can't execute the new-instance
985 * instruction if a register contains an uninitialized instance created
986 * by that same instrutcion.
987 */
988 static bool CodeFlowVerifyMethod(VerifierData* vdata,
989 RegisterTable* reg_table);
990
991 /*
992 * Perform verification for a single instruction.
993 *
994 * This requires fully decoding the instruction to determine the effect
995 * it has on registers.
996 *
997 * Finds zero or more following instructions and sets the "changed" flag
jeffhaod1f0fde2011-09-08 17:25:33 -0700998 * if execution at that point needs to be (re-)evaluated. Register changes
999 * are merged into "reg_types_" at the target addresses. Does not set or
jeffhaobdb76512011-09-07 11:43:16 -07001000 * clear any other flags in "insn_flags".
1001 */
1002 static bool CodeFlowVerifyInstruction(VerifierData* vdata,
1003 RegisterTable* reg_table, uint32_t insn_idx, size_t* start_guess);
1004
1005 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001006 * Replace an instruction with "throw-verification-error". This allows us to
jeffhaobdb76512011-09-07 11:43:16 -07001007 * defer error reporting until the code path is first used.
1008 *
1009 * This is expected to be called during "just in time" verification, not
jeffhaod1f0fde2011-09-08 17:25:33 -07001010 * from within dexopt. (Verification failures in dexopt will result in
jeffhaobdb76512011-09-07 11:43:16 -07001011 * postponement of verification to first use of the class.)
1012 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001013 * The throw-verification-error instruction requires two code units. Some
jeffhaobdb76512011-09-07 11:43:16 -07001014 * of the replaced instructions require three; the third code unit will
jeffhaod1f0fde2011-09-08 17:25:33 -07001015 * receive a "nop". The instruction's length will be left unchanged
jeffhaobdb76512011-09-07 11:43:16 -07001016 * in "insn_flags".
1017 *
1018 * The VM postpones setting of debugger breakpoints in unverified classes,
1019 * so there should be no clashes with the debugger.
1020 *
1021 * Returns "true" on success.
1022 */
1023 static bool ReplaceFailingInstruction(const DexFile::CodeItem* code_item,
1024 InsnFlags* insn_flags, int insn_idx, VerifyError failure);
1025
1026 /* Handle a monitor-enter instruction. */
1027 static void HandleMonitorEnter(RegisterLine* work_line, uint32_t reg_idx,
1028 uint32_t insn_idx, VerifyError* failure);
1029
1030 /* Handle a monitor-exit instruction. */
1031 static void HandleMonitorExit(RegisterLine* work_line, uint32_t reg_idx,
1032 uint32_t insn_idx, VerifyError* failure);
1033
1034 /*
1035 * Look up an instance field, specified by "field_idx", that is going to be
jeffhaod1f0fde2011-09-08 17:25:33 -07001036 * accessed in object "obj_type". This resolves the field and then verifies
jeffhaobdb76512011-09-07 11:43:16 -07001037 * that the class containing the field is an instance of the reference in
1038 * "obj_type".
1039 *
1040 * It is possible for "obj_type" to be kRegTypeZero, meaning that we might
jeffhaod1f0fde2011-09-08 17:25:33 -07001041 * have a null reference. This is a runtime problem, so we allow it,
jeffhaobdb76512011-09-07 11:43:16 -07001042 * skipping some of the type checks.
1043 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001044 * In general, "obj_type" must be an initialized reference. However, we
jeffhaobdb76512011-09-07 11:43:16 -07001045 * allow it to be uninitialized if this is an "<init>" method and the field
1046 * is declared within the "obj_type" class.
1047 *
1048 * Returns a Field on success, returns NULL and sets "*failure" on failure.
1049 */
1050 static Field* GetInstField(VerifierData* vdata, RegType obj_type,
1051 int field_idx, VerifyError* failure);
1052
1053 /*
1054 * Look up a static field.
1055 *
1056 * Returns a StaticField on success, returns NULL and sets "*failure"
1057 * on failure.
1058 */
1059 static Field* GetStaticField(VerifierData* vdata, int field_idx,
1060 VerifyError* failure);
1061 /*
1062 * For the "move-exception" instruction at "insn_idx", which must be at an
1063 * exception handler address, determine the first common superclass of
jeffhaod1f0fde2011-09-08 17:25:33 -07001064 * all exceptions that can land here. (For javac output, we're probably
jeffhaobdb76512011-09-07 11:43:16 -07001065 * looking at multiple spans of bytecode covered by one "try" that lands
1066 * at an exception-specific "catch", but in general the handler could be
1067 * shared for multiple exceptions.)
1068 *
1069 * Returns NULL if no matching exception handler can be found, or if the
1070 * exception is not a subclass of Throwable.
1071 */
1072 static Class* GetCaughtExceptionType(VerifierData* vdata, int insn_idx,
1073 VerifyError* failure);
1074
1075 /*
1076 * Get the type of register N.
1077 *
1078 * The register index was validated during the static pass, so we don't
1079 * need to check it here.
1080 */
1081 static inline RegType GetRegisterType(const RegisterLine* register_line,
1082 uint32_t vsrc) {
1083 return register_line->reg_types_[vsrc];
1084 }
1085
1086 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001087 * Return the register type for the method. We can't just use the
jeffhaobdb76512011-09-07 11:43:16 -07001088 * already-computed DalvikJniReturnType, because if it's a reference type
1089 * we need to do the class lookup.
1090 *
1091 * Returned references are assumed to be initialized.
1092 *
1093 * Returns kRegTypeUnknown for "void".
1094 */
1095 static RegType GetMethodReturnType(const DexFile* dex_file,
1096 const Method* method);
1097
1098 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001099 * Get the value from a register, and cast it to a Class. Sets
jeffhaobdb76512011-09-07 11:43:16 -07001100 * "*failure" if something fails.
1101 *
1102 * This fails if the register holds an uninitialized class.
1103 *
1104 * If the register holds kRegTypeZero, this returns a NULL pointer.
1105 */
1106 static Class* GetClassFromRegister(const RegisterLine* register_line,
1107 uint32_t vsrc, VerifyError* failure);
1108
1109 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001110 * Get the "this" pointer from a non-static method invocation. This
jeffhaobdb76512011-09-07 11:43:16 -07001111 * returns the RegType so the caller can decide whether it needs the
jeffhaod1f0fde2011-09-08 17:25:33 -07001112 * reference to be initialized or not. (Can also return kRegTypeZero
jeffhaobdb76512011-09-07 11:43:16 -07001113 * if the reference can only be zero at this point.)
1114 *
1115 * The argument count is in vA, and the first argument is in vC, for both
jeffhaod1f0fde2011-09-08 17:25:33 -07001116 * "simple" and "range" versions. We just need to make sure vA is >= 1
jeffhaobdb76512011-09-07 11:43:16 -07001117 * and then return vC.
1118 */
1119 static RegType GetInvocationThis(const RegisterLine* register_line,
1120 const Instruction::DecodedInstruction* dec_insn, VerifyError* failure);
1121
1122 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001123 * Set the type of register N, verifying that the register is valid. If
jeffhaobdb76512011-09-07 11:43:16 -07001124 * "new_type" is the "Lo" part of a 64-bit value, register N+1 will be
1125 * set to "new_type+1".
1126 *
1127 * The register index was validated during the static pass, so we don't
1128 * need to check it here.
1129 *
1130 * TODO: clear mon stack bits
1131 */
1132 static void SetRegisterType(RegisterLine* register_line, uint32_t vdst,
1133 RegType new_type);
1134
1135 /*
1136 * Verify that the contents of the specified register have the specified
1137 * type (or can be converted to it through an implicit widening conversion).
1138 *
1139 * This will modify the type of the source register if it was originally
1140 * derived from a constant to prevent mixing of int/float and long/double.
1141 *
1142 * If "vsrc" is a reference, both it and the "vsrc" register must be
jeffhaod1f0fde2011-09-08 17:25:33 -07001143 * initialized ("vsrc" may be Zero). This will verify that the value in
jeffhaobdb76512011-09-07 11:43:16 -07001144 * the register is an instance of check_type, or if check_type is an
1145 * interface, verify that the register implements check_type.
1146 */
1147 static void VerifyRegisterType(RegisterLine* register_line, uint32_t vsrc,
1148 RegType check_type, VerifyError* failure);
1149
1150 /* Set the type of the "result" register. */
1151 static void SetResultRegisterType(RegisterLine* register_line,
1152 const int insn_reg_count, RegType new_type);
1153
1154 /*
1155 * Update all registers holding "uninit_type" to instead hold the
jeffhaod1f0fde2011-09-08 17:25:33 -07001156 * corresponding initialized reference type. This is called when an
jeffhaobdb76512011-09-07 11:43:16 -07001157 * appropriate <init> method is invoked -- all copies of the reference
1158 * must be marked as initialized.
1159 */
1160 static void MarkRefsAsInitialized(RegisterLine* register_line,
1161 int insn_reg_count, UninitInstanceMap* uninit_map, RegType uninit_type,
1162 VerifyError* failure);
1163
1164 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001165 * Implement category-1 "move" instructions. Copy a 32-bit value from
jeffhaobdb76512011-09-07 11:43:16 -07001166 * "vsrc" to "vdst".
1167 */
1168 static void CopyRegister1(RegisterLine* register_line, uint32_t vdst,
1169 uint32_t vsrc, TypeCategory cat, VerifyError* failure);
1170
1171 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001172 * Implement category-2 "move" instructions. Copy a 64-bit value from
1173 * "vsrc" to "vdst". This copies both halves of the register.
jeffhaobdb76512011-09-07 11:43:16 -07001174 */
1175 static void CopyRegister2(RegisterLine* register_line, uint32_t vdst,
1176 uint32_t vsrc, VerifyError* failure);
1177
1178 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001179 * Implement "move-result". Copy the category-1 value from the result
jeffhaobdb76512011-09-07 11:43:16 -07001180 * register to another register, and reset the result register.
1181 */
1182 static void CopyResultRegister1(RegisterLine* register_line,
1183 const int insn_reg_count, uint32_t vdst, TypeCategory cat,
1184 VerifyError* failure);
1185
1186 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001187 * Implement "move-result-wide". Copy the category-2 value from the result
jeffhaobdb76512011-09-07 11:43:16 -07001188 * register to another register, and reset the result register.
1189 */
1190 static void CopyResultRegister2(RegisterLine* register_line,
1191 const int insn_reg_count, uint32_t vdst, VerifyError* failure);
1192
1193 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001194 * Compute the "class depth" of a class. This is the distance from the
1195 * class to the top of the tree, chasing superclass links. java.lang.Object
jeffhaobdb76512011-09-07 11:43:16 -07001196 * has a class depth of 0.
1197 */
1198 static int GetClassDepth(Class* klass);
1199
1200 /*
1201 * Given two classes, walk up the superclass tree to find a common
jeffhaod1f0fde2011-09-08 17:25:33 -07001202 * ancestor. (Called from findCommonSuperclass().)
jeffhaobdb76512011-09-07 11:43:16 -07001203 *
1204 * TODO: consider caching the class depth in the class object so we don't
1205 * have to search for it here.
1206 */
1207 static Class* DigForSuperclass(Class* c1, Class* c2);
1208
1209 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001210 * Merge two array classes. We can't use the general "walk up to the
jeffhaobdb76512011-09-07 11:43:16 -07001211 * superclass" merge because the superclass of an array is always Object.
jeffhaod1f0fde2011-09-08 17:25:33 -07001212 * We want String[] + Integer[] = Object[]. This works for higher dimensions
jeffhaobdb76512011-09-07 11:43:16 -07001213 * as well, e.g. String[][] + Integer[][] = Object[][].
1214 *
1215 * If Foo1 and Foo2 are subclasses of Foo, Foo1[] + Foo2[] = Foo[].
1216 *
1217 * If Class implements Type, Class[] + Type[] = Type[].
1218 *
1219 * If the dimensions don't match, we want to convert to an array of Object
1220 * with the least dimension, e.g. String[][] + String[][][][] = Object[][].
1221 *
1222 * Arrays of primitive types effectively have one less dimension when
jeffhaod1f0fde2011-09-08 17:25:33 -07001223 * merging. int[] + float[] = Object, int[] + String[] = Object,
1224 * int[][] + float[][] = Object[], int[][] + String[] = Object[]. (The
jeffhaobdb76512011-09-07 11:43:16 -07001225 * only time this function doesn't return an array class is when one of
1226 * the arguments is a 1-dimensional primitive array.)
1227 *
1228 * This gets a little awkward because we may have to ask the VM to create
jeffhaod1f0fde2011-09-08 17:25:33 -07001229 * a new array type with the appropriate element and dimensions. However, we
jeffhaobdb76512011-09-07 11:43:16 -07001230 * shouldn't be doing this often.
1231 */
1232 static Class* FindCommonArraySuperclass(Class* c1, Class* c2);
1233
1234 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001235 * Find the first common superclass of the two classes. We're not
jeffhaobdb76512011-09-07 11:43:16 -07001236 * interested in common interfaces.
1237 *
1238 * The easiest way to do this for concrete classes is to compute the "class
1239 * depth" of each, move up toward the root of the deepest one until they're
1240 * at the same depth, then walk both up to the root until they match.
1241 *
1242 * If both classes are arrays, we need to merge based on array depth and
1243 * element type.
1244 *
1245 * If one class is an interface, we check to see if the other class/interface
jeffhaod1f0fde2011-09-08 17:25:33 -07001246 * (or one of its predecessors) implements the interface. If so, we return
jeffhaobdb76512011-09-07 11:43:16 -07001247 * the interface; otherwise, we return Object.
1248 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001249 * NOTE: we continue the tradition of "lazy interface handling". To wit,
jeffhaobdb76512011-09-07 11:43:16 -07001250 * suppose we have three classes:
1251 * One implements Fancy, Free
1252 * Two implements Fancy, Free
1253 * Three implements Free
jeffhaod1f0fde2011-09-08 17:25:33 -07001254 * where Fancy and Free are unrelated interfaces. The code requires us
1255 * to merge One into Two. Ideally we'd use a common interface, which
jeffhaobdb76512011-09-07 11:43:16 -07001256 * gives us a choice between Fancy and Free, and no guidance on which to
jeffhaod1f0fde2011-09-08 17:25:33 -07001257 * use. If we use Free, we'll be okay when Three gets merged in, but if
1258 * we choose Fancy, we're hosed. The "ideal" solution is to create a
jeffhaobdb76512011-09-07 11:43:16 -07001259 * set of common interfaces and carry that around, merging further references
jeffhaod1f0fde2011-09-08 17:25:33 -07001260 * into it. This is a pain. The easy solution is to simply boil them
jeffhaobdb76512011-09-07 11:43:16 -07001261 * down to Objects and let the runtime invokeinterface call fail, which
1262 * is what we do.
1263 */
1264 static Class* FindCommonSuperclass(Class* c1, Class* c2);
1265
1266 /*
jeffhao98eacac2011-09-14 16:11:53 -07001267 * Resolves a class based on an index and performs access checks to ensure
1268 * the referrer can access the resolved class.
1269 *
1270 * Exceptions caused by failures are cleared before returning.
1271 *
1272 * Sets "*failure" on failure.
1273 */
1274 static Class* ResolveClassAndCheckAccess(const DexFile* dex_file,
1275 uint32_t class_idx, const Class* referrer, VerifyError* failure);
1276
1277 /*
jeffhaobdb76512011-09-07 11:43:16 -07001278 * Merge two RegType values.
1279 *
1280 * Sets "*changed" to "true" if the result doesn't match "type1".
1281 */
1282 static RegType MergeTypes(RegType type1, RegType type2, bool* changed);
1283
1284 /*
1285 * Merge the bits that indicate which monitor entry addresses on the stack
1286 * are associated with this register.
1287 *
1288 * The merge is a simple bitwise AND.
1289 *
jeffhao98eacac2011-09-14 16:11:53 -07001290 * Sets "*changed" to "true" if the result doesn't match "ents1".
jeffhaobdb76512011-09-07 11:43:16 -07001291 */
1292 static MonitorEntries MergeMonitorEntries(MonitorEntries ents1,
1293 MonitorEntries ents2, bool* changed);
1294
1295 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001296 * We're creating a new instance of class C at address A. Any registers
jeffhaobdb76512011-09-07 11:43:16 -07001297 * holding instances previously created at address A must be initialized
jeffhaod1f0fde2011-09-08 17:25:33 -07001298 * by now. If not, we mark them as "conflict" to prevent them from being
jeffhaobdb76512011-09-07 11:43:16 -07001299 * used (otherwise, MarkRefsAsInitialized would mark the old ones and the
1300 * new ones at the same time).
1301 */
1302 static void MarkUninitRefsAsInvalid(RegisterLine* register_line,
1303 int insn_reg_count, UninitInstanceMap* uninit_map, RegType uninit_type);
1304
1305 /*
1306 * Control can transfer to "next_insn".
1307 *
1308 * Merge the registers from "work_line" into "reg_table" at "next_insn", and
1309 * set the "changed" flag on the target address if any of the registers
1310 * has changed.
1311 *
1312 * Returns "false" if we detect mismatched monitor stacks.
1313 */
1314 static bool UpdateRegisters(InsnFlags* insn_flags, RegisterTable* reg_table,
1315 int next_insn, const RegisterLine* work_line);
1316
1317 /*
1318 * Determine whether we can convert "src_type" to "check_type", where
1319 * "check_type" is one of the category-1 non-reference types.
1320 *
1321 * Constant derived types may become floats, but other values may not.
1322 */
1323 static bool CanConvertTo1nr(RegType src_type, RegType check_type);
1324
1325 /* Determine whether the category-2 types are compatible. */
1326 static bool CanConvertTo2(RegType src_type, RegType check_type);
1327
1328 /* Convert a VM PrimitiveType enum value to the equivalent RegType value. */
1329 static RegType PrimitiveTypeToRegType(Class::PrimitiveType prim_type);
1330
1331 /*
1332 * Convert a const derived RegType to the equivalent non-const RegType value.
1333 * Does nothing if the argument type isn't const derived.
1334 */
1335 static RegType ConstTypeToRegType(RegType const_type);
1336
1337 /*
1338 * Given a 32-bit constant, return the most-restricted RegType enum entry
1339 * that can hold the value. The types used here indicate the value came
1340 * from a const instruction, and may not correctly represent the real type
1341 * of the value. Upon use, a constant derived type is updated with the
1342 * type from the use, which will be unambiguous.
1343 */
1344 static char DetermineCat1Const(int32_t value);
1345
1346 /*
1347 * If "field" is marked "final", make sure this is the either <clinit>
1348 * or <init> as appropriate.
1349 *
1350 * Sets "*failure" on failure.
1351 */
1352 static void CheckFinalFieldAccess(const Method* method, const Field* field,
1353 VerifyError* failure);
1354
1355 /*
1356 * Make sure that the register type is suitable for use as an array index.
1357 *
1358 * Sets "*failure" if not.
1359 */
1360 static void CheckArrayIndexType(const Method* method, RegType reg_type,
1361 VerifyError* failure);
1362
1363 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001364 * Check constraints on constructor return. Specifically, make sure that
jeffhaobdb76512011-09-07 11:43:16 -07001365 * the "this" argument got initialized.
1366 *
1367 * The "this" argument to <init> uses code offset kUninitThisArgAddr, which
jeffhaod1f0fde2011-09-08 17:25:33 -07001368 * puts it at the start of the list in slot 0. If we see a register with
jeffhaobdb76512011-09-07 11:43:16 -07001369 * an uninitialized slot 0 reference, we know it somehow didn't get
1370 * initialized.
1371 *
1372 * Returns "true" if all is well.
1373 */
1374 static bool CheckConstructorReturn(const Method* method,
1375 const RegisterLine* register_line, const int insn_reg_count);
1376
1377 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001378 * Verify that the target instruction is not "move-exception". It's important
jeffhaobdb76512011-09-07 11:43:16 -07001379 * that the only way to execute a move-exception is as the first instruction
1380 * of an exception handler.
1381 *
1382 * Returns "true" if all is well, "false" if the target instruction is
1383 * move-exception.
1384 */
1385 static bool CheckMoveException(const uint16_t* insns, int insn_idx);
1386
1387 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001388 * See if "type" matches "cat". All we're really looking for here is that
jeffhaobdb76512011-09-07 11:43:16 -07001389 * we're not mixing and matching 32-bit and 64-bit quantities, and we're
jeffhaod1f0fde2011-09-08 17:25:33 -07001390 * not mixing references with numerics. (For example, the arguments to
jeffhaobdb76512011-09-07 11:43:16 -07001391 * "a < b" could be integers of different sizes, but they must both be
jeffhaod1f0fde2011-09-08 17:25:33 -07001392 * integers. Dalvik is less specific about int vs. float, so we treat them
jeffhaobdb76512011-09-07 11:43:16 -07001393 * as equivalent here.)
1394 *
1395 * For category 2 values, "type" must be the "low" half of the value.
1396 *
1397 * Sets "*failure" if something looks wrong.
1398 */
1399 static void CheckTypeCategory(RegType type, TypeCategory cat,
1400 VerifyError* failure);
1401
1402 /*
1403 * For a category 2 register pair, verify that "type_h" is the appropriate
1404 * high part for "type_l".
1405 *
1406 * Does not verify that "type_l" is in fact the low part of a 64-bit
1407 * register pair.
1408 */
1409 static void CheckWidePair(RegType type_l, RegType type_h,
1410 VerifyError* failure);
1411
1412 /*
1413 * Verify types for a simple two-register instruction (e.g. "neg-int").
1414 * "dst_type" is stored into vA, and "src_type" is verified against vB.
1415 */
1416 static void CheckUnop(RegisterLine* register_line,
1417 Instruction::DecodedInstruction* dec_insn, RegType dst_type,
1418 RegType src_type, VerifyError* failure);
1419
1420 /*
1421 * Verify types for a simple three-register instruction (e.g. "add-int").
1422 * "dst_type" is stored into vA, and "src_type1"/"src_type2" are verified
1423 * against vB/vC.
1424 */
1425 static void CheckBinop(RegisterLine* register_line,
1426 Instruction::DecodedInstruction* dec_insn, RegType dst_type,
1427 RegType src_type1, RegType src_type2, bool check_boolean_op,
1428 VerifyError* failure);
1429
1430 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001431 * Verify types for a binary "2addr" operation. "src_type1"/"src_type2"
jeffhaobdb76512011-09-07 11:43:16 -07001432 * are verified against vA/vB, then "dst_type" is stored into vA.
1433 */
1434 static void CheckBinop2addr(RegisterLine* register_line,
1435 Instruction::DecodedInstruction* dec_insn, RegType dst_type,
1436 RegType src_type1, RegType src_type2, bool check_boolean_op,
1437 VerifyError* failure);
1438
1439 /*
1440 * Treat right-shifting as a narrowing conversion when possible.
1441 *
1442 * For example, right-shifting an int 24 times results in a value that can
1443 * be treated as a byte.
1444 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001445 * Things get interesting when contemplating sign extension. Right-
jeffhaobdb76512011-09-07 11:43:16 -07001446 * shifting an integer by 16 yields a value that can be represented in a
1447 * "short" but not a "char", but an unsigned right shift by 16 yields a
jeffhaod1f0fde2011-09-08 17:25:33 -07001448 * value that belongs in a char rather than a short. (Consider what would
jeffhaobdb76512011-09-07 11:43:16 -07001449 * happen if the result of the shift were cast to a char or short and then
jeffhaod1f0fde2011-09-08 17:25:33 -07001450 * cast back to an int. If sign extension, or the lack thereof, causes
jeffhaobdb76512011-09-07 11:43:16 -07001451 * a change in the 32-bit representation, then the conversion was lossy.)
1452 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001453 * A signed right shift by 17 on an integer results in a short. An unsigned
jeffhaobdb76512011-09-07 11:43:16 -07001454 * right shfit by 17 on an integer results in a posshort, which can be
1455 * assigned to a short or a char.
1456 *
1457 * An unsigned right shift on a short can actually expand the result into
jeffhaod1f0fde2011-09-08 17:25:33 -07001458 * a 32-bit integer. For example, 0xfffff123 >>> 8 becomes 0x00fffff1,
jeffhaobdb76512011-09-07 11:43:16 -07001459 * which can't be represented in anything smaller than an int.
1460 *
1461 * javac does not generate code that takes advantage of this, but some
jeffhaod1f0fde2011-09-08 17:25:33 -07001462 * of the code optimizers do. It's generally a peephole optimization
jeffhaobdb76512011-09-07 11:43:16 -07001463 * that replaces a particular sequence, e.g. (bipush 24, ishr, i2b) is
jeffhaod1f0fde2011-09-08 17:25:33 -07001464 * replaced by (bipush 24, ishr). Knowing that shifting a short 8 times
jeffhaobdb76512011-09-07 11:43:16 -07001465 * to the right yields a byte is really more than we need to handle the
1466 * code that's out there, but support is not much more complex than just
1467 * handling integer.
1468 *
1469 * Right-shifting never yields a boolean value.
1470 *
1471 * Returns the new register type.
1472 */
1473 static RegType AdjustForRightShift(RegisterLine* register_line, int reg,
1474 unsigned int shift_count, bool is_unsigned_shift, VerifyError* failure);
1475
1476 /*
1477 * We're performing an operation like "and-int/2addr" that can be
jeffhaod1f0fde2011-09-08 17:25:33 -07001478 * performed on booleans as well as integers. We get no indication of
jeffhaobdb76512011-09-07 11:43:16 -07001479 * boolean-ness, but we can infer it from the types of the arguments.
1480 *
1481 * Assumes we've already validated reg1/reg2.
1482 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001483 * TODO: consider generalizing this. The key principle is that the
jeffhaobdb76512011-09-07 11:43:16 -07001484 * result of a bitwise operation can only be as wide as the widest of
jeffhaod1f0fde2011-09-08 17:25:33 -07001485 * the operands. You can safely AND/OR/XOR two chars together and know
jeffhaobdb76512011-09-07 11:43:16 -07001486 * you still have a char, so it's reasonable for the compiler or "dx"
jeffhaod1f0fde2011-09-08 17:25:33 -07001487 * to skip the int-to-char instruction. (We need to do this for boolean
jeffhaobdb76512011-09-07 11:43:16 -07001488 * because there is no int-to-boolean operation.)
1489 *
1490 * Returns true if both args are Boolean, Zero, or One.
1491 */
1492 static bool UpcastBooleanOp(RegisterLine* register_line, uint32_t reg1,
1493 uint32_t reg2);
1494
1495 /*
1496 * Verify types for A two-register instruction with a literal constant
jeffhaod1f0fde2011-09-08 17:25:33 -07001497 * (e.g. "add-int/lit8"). "dst_type" is stored into vA, and "src_type" is
jeffhaobdb76512011-09-07 11:43:16 -07001498 * verified against vB.
1499 *
1500 * If "check_boolean_op" is set, we use the constant value in vC.
1501 */
1502 static void CheckLitop(RegisterLine* register_line,
1503 Instruction::DecodedInstruction* dec_insn, RegType dst_type,
1504 RegType src_type, bool check_boolean_op, VerifyError* failure);
1505
1506 /*
1507 * Verify that the arguments in a filled-new-array instruction are valid.
1508 *
1509 * "res_class" is the class refered to by dec_insn->vB_.
1510 */
1511 static void VerifyFilledNewArrayRegs(const Method* method,
1512 RegisterLine* register_line,
1513 const Instruction::DecodedInstruction* dec_insn, Class* res_class,
1514 bool is_range, VerifyError* failure);
1515
1516 /* See if the method matches the MethodType. */
1517 static bool IsCorrectInvokeKind(MethodType method_type, Method* res_method);
1518
1519 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001520 * Verify the arguments to a method. We're executing in "method", making
jeffhaobdb76512011-09-07 11:43:16 -07001521 * a call to the method reference in vB.
1522 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001523 * If this is a "direct" invoke, we allow calls to <init>. For calls to
1524 * <init>, the first argument may be an uninitialized reference. Otherwise,
jeffhaobdb76512011-09-07 11:43:16 -07001525 * calls to anything starting with '<' will be rejected, as will any
1526 * uninitialized reference arguments.
1527 *
1528 * For non-static method calls, this will verify that the method call is
1529 * appropriate for the "this" argument.
1530 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001531 * The method reference is in vBBBB. The "is_range" parameter determines
jeffhaobdb76512011-09-07 11:43:16 -07001532 * whether we use 0-4 "args" values or a range of registers defined by
1533 * vAA and vCCCC.
1534 *
1535 * Widening conversions on integers and references are allowed, but
1536 * narrowing conversions are not.
1537 *
1538 * Returns the resolved method on success, NULL on failure (with *failure
1539 * set appropriately).
1540 */
1541 static Method* VerifyInvocationArgs(VerifierData* vdata,
1542 RegisterLine* register_line, const int insn_reg_count,
1543 const Instruction::DecodedInstruction* dec_insn, MethodType method_type,
1544 bool is_range, bool is_super, VerifyError* failure);
1545
jeffhaod1f0fde2011-09-08 17:25:33 -07001546 /*
1547 * Generate the register map for a method that has just been verified
1548 * (i.e. we're doing this as part of verification).
1549 *
1550 * For type-precise determination we have all the data we need, so we
1551 * just need to encode it in some clever fashion.
1552 *
1553 * Returns a pointer to a newly-allocated RegisterMap, or NULL on failure.
1554 */
1555 static RegisterMap* GenerateRegisterMapV(VerifierData* vdata);
1556
1557 /*
1558 * Determine if the RegType value is a reference type.
1559 *
1560 * Ordinarily we include kRegTypeZero in the "is it a reference"
1561 * check. There's no value in doing so here, because we know
1562 * the register can't hold anything but zero.
1563 */
1564 static inline bool IsReferenceType(RegType type) {
1565 return (type > kRegTypeMAX || type == kRegTypeUninit);
1566 }
1567
1568 /* Toggle the value of the "idx"th bit in "ptr". */
1569 static inline void ToggleBit(uint8_t* ptr, int idx) {
1570 ptr[idx >> 3] ^= 1 << (idx & 0x07);
1571 }
1572
1573 /*
1574 * Given a line of registers, output a bit vector that indicates whether
1575 * or not the register holds a reference type (which could be null).
1576 *
1577 * We use '1' to indicate it's a reference, '0' for anything else (numeric
1578 * value, uninitialized data, merge conflict). Register 0 will be found
1579 * in the low bit of the first byte.
1580 */
1581 static void OutputTypeVector(const RegType* regs, int insn_reg_count,
1582 uint8_t* data);
1583
1584 /*
1585 * Double-check the map.
1586 *
1587 * We run through all of the data in the map, and compare it to the original.
1588 * Only works on uncompressed data.
1589 */
1590 static bool VerifyMap(VerifierData* vdata, const RegisterMap* map);
1591
1592 /* Compare two register maps. Returns true if they're equal, false if not. */
1593 static bool CompareMaps(const RegisterMap* map1, const RegisterMap* map2);
1594
1595 /* Compute the size, in bytes, of a register map. */
1596 static size_t ComputeRegisterMapSize(const RegisterMap* map);
1597
1598 /*
1599 * Compute the difference between two bit vectors.
1600 *
1601 * If "leb_out_buf" is non-NULL, we output the bit indices in ULEB128 format
1602 * as we go. Otherwise, we just generate the various counts.
1603 *
1604 * The bit vectors are compared byte-by-byte, so any unused bits at the
1605 * end must be zero.
1606 *
1607 * Returns the number of bytes required to hold the ULEB128 output.
1608 *
1609 * If "first_bit_changed_ptr" or "num_bits_changed_ptr" are non-NULL, they
1610 * will receive the index of the first changed bit and the number of changed
1611 * bits, respectively.
1612 */
1613 static int ComputeBitDiff(const uint8_t* bits1, const uint8_t* bits2,
1614 int byte_width, int* first_bit_changed_ptr, int* num_bits_changed_ptr,
1615 uint8_t* leb_out_buf);
1616
1617 /*
1618 * Compress the register map with differential encoding.
1619 *
1620 * On success, returns a newly-allocated RegisterMap. If the map is not
1621 * compatible for some reason, or fails to get smaller, this will return NULL.
1622 */
1623 static RegisterMap* CompressMapDifferential(const RegisterMap* map);
1624
1625 /*
1626 * Expand a compressed map to an uncompressed form.
1627 *
1628 * Returns a newly-allocated RegisterMap on success, or NULL on failure.
1629 *
1630 * TODO: consider using the linear allocator or a custom allocator with
1631 * LRU replacement for these instead of the native heap.
1632 */
1633 static RegisterMap* UncompressMapDifferential(const RegisterMap* map);
1634
jeffhaobdb76512011-09-07 11:43:16 -07001635 DISALLOW_COPY_AND_ASSIGN(DexVerifier);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001636};
1637
1638} // namespace art
1639
1640#endif // ART_SRC_DEX_VERIFY_H_