blob: 1f28204796bfcebf139ebcf97afc544d00f3409b [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
Ian Rogersd81871c2011-10-03 13:57:23 -07006#include "casts.h"
Elliott Hughes90a33692011-08-30 13:27:07 -07007#include "dex_file.h"
8#include "dex_instruction.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07009#include "macros.h"
10#include "object.h"
Ian Rogersd81871c2011-10-03 13:57:23 -070011#include "stl_util.h"
Elliott Hughes5fe594f2011-09-08 12:33:17 -070012#include "UniquePtr.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070013
Ian Rogersd81871c2011-10-03 13:57:23 -070014#include <map>
15#include <stack>
16#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070017
Ian Rogersd81871c2011-10-03 13:57:23 -070018namespace art {
19namespace verifier {
20
21class DexVerifier;
22class PcToReferenceMap;
23class RegTypeCache;
jeffhaobdb76512011-09-07 11:43:16 -070024
25/*
Ian Rogersd81871c2011-10-03 13:57:23 -070026 * Set this to enable dead code scanning. This is not required, but it's very useful when testing
27 * changes to the verifier (to make sure we're not skipping over stuff). The only reason not to do
28 * it is that it slightly increases the time required to perform verification.
jeffhaobdb76512011-09-07 11:43:16 -070029 */
30#ifndef NDEBUG
31# define DEAD_CODE_SCAN true
32#else
33# define DEAD_CODE_SCAN false
34#endif
35
36/*
Ian Rogersd81871c2011-10-03 13:57:23 -070037 * RegType holds information about the type of data held in a register. For most types it's a simple
38 * enum. For reference types it holds a pointer to the ClassObject, and for uninitialized references
39 * it holds an index into the UninitInstanceMap.
jeffhaobdb76512011-09-07 11:43:16 -070040 */
Ian Rogersd81871c2011-10-03 13:57:23 -070041class RegType {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070042 public:
jeffhaobdb76512011-09-07 11:43:16 -070043 /*
Ian Rogersd81871c2011-10-03 13:57:23 -070044 * Enumeration for register type values. The "hi" piece of a 64-bit value MUST immediately follow
45 * the "lo" piece in the enumeration, so we can check that hi==lo+1.
jeffhaobdb76512011-09-07 11:43:16 -070046 *
47 * Assignment of constants:
48 * [-MAXINT,-32768) : integer
49 * [-32768,-128) : short
50 * [-128,0) : byte
51 * 0 : zero
52 * 1 : one
53 * [2,128) : posbyte
54 * [128,32768) : posshort
55 * [32768,65536) : char
56 * [65536,MAXINT] : integer
57 *
58 * Allowed "implicit" widening conversions:
59 * zero -> boolean, posbyte, byte, posshort, short, char, integer, ref (null)
60 * one -> boolean, posbyte, byte, posshort, short, char, integer
61 * boolean -> posbyte, byte, posshort, short, char, integer
62 * posbyte -> posshort, short, integer, char
63 * byte -> short, integer
64 * posshort -> integer, char
65 * short -> integer
66 * char -> integer
67 *
68 * In addition, all of the above can convert to "float".
69 *
Ian Rogersd81871c2011-10-03 13:57:23 -070070 * We're more careful with integer values than the spec requires. The motivation is to restrict
71 * byte/char/short to the correct range of values. For example, if a method takes a byte argument,
72 * we don't want to allow the code to load the constant "1024" and pass it in.
jeffhaobdb76512011-09-07 11:43:16 -070073 */
Ian Rogersd81871c2011-10-03 13:57:23 -070074 enum Type {
75 kRegTypeUnknown = 0, /* initial state */
jeffhaobdb76512011-09-07 11:43:16 -070076 kRegTypeConflict, /* merge clash makes this reg's type unknowable */
77
78 /*
Ian Rogersd81871c2011-10-03 13:57:23 -070079 * Category-1nr types. The order of these is chiseled into a couple of tables, so don't add,
80 * remove, or reorder if you can avoid it.
jeffhaobdb76512011-09-07 11:43:16 -070081 */
Ian Rogersd81871c2011-10-03 13:57:23 -070082 kRegTypeZero, /* 0 - 32-bit 0, could be Boolean, Int, Float, or Ref */
83 kRegType1nrSTART = kRegTypeZero,
84 kRegTypeIntegralSTART = kRegTypeZero,
85 kRegTypeOne, /* 1 - 32-bit 1, could be Boolean, Int, Float */
86 kRegTypeBoolean, /* Z - must be 0 or 1 */
87 kRegTypeConstPosByte, /* y - const derived byte, known positive */
88 kRegTypeConstByte, /* Y - const derived byte */
89 kRegTypeConstPosShort, /* h - const derived short, known positive */
90 kRegTypeConstShort, /* H - const derived short */
91 kRegTypeConstChar, /* c - const derived char */
92 kRegTypeConstInteger, /* i - const derived integer */
93 kRegTypePosByte, /* b - byte, known positive (can become char) */
94 kRegTypeByte, /* B */
95 kRegTypePosShort, /* s - short, known positive (can become char) */
96 kRegTypeShort, /* S */
97 kRegTypeChar, /* C */
98 kRegTypeInteger, /* I */
99 kRegTypeIntegralEND = kRegTypeInteger,
100 kRegTypeFloat, /* F */
101 kRegType1nrEND = kRegTypeFloat,
102 kRegTypeConstLo, /* const derived wide, lower half - could be long or double */
103 kRegTypeConstHi, /* const derived wide, upper half - could be long or double */
jeffhaobdb76512011-09-07 11:43:16 -0700104 kRegTypeLongLo, /* lower-numbered register; endian-independent */
105 kRegTypeLongHi,
106 kRegTypeDoubleLo,
107 kRegTypeDoubleHi,
Ian Rogersd81871c2011-10-03 13:57:23 -0700108 kRegTypeReference, // Reference type
109 kRegTypeMAX = kRegTypeReference + 1,
jeffhaobdb76512011-09-07 11:43:16 -0700110 };
111
Ian Rogersd81871c2011-10-03 13:57:23 -0700112 bool IsUninitializedThisReference() const {
113 return allocation_pc_ == kUninitThisArgAddr;
jeffhaobdb76512011-09-07 11:43:16 -0700114 }
115
Ian Rogersd81871c2011-10-03 13:57:23 -0700116 Type GetType() const {
117 return type_;
jeffhaobdb76512011-09-07 11:43:16 -0700118 }
119
Ian Rogersd81871c2011-10-03 13:57:23 -0700120 void Dump(std::ostream& os) const;
121
122 Class* GetClass() const {
123 DCHECK(klass_ != NULL);
124 return klass_;
jeffhaobdb76512011-09-07 11:43:16 -0700125 }
126
Ian Rogersd81871c2011-10-03 13:57:23 -0700127 bool IsInitialized() const { return allocation_pc_ == kInitArgAddr; }
128 bool IsUninitializedReference() const { return allocation_pc_ != kInitArgAddr; }
129
130 bool IsUnknown() const { return type_ == kRegTypeUnknown; }
131 bool IsConflict() const { return type_ == kRegTypeConflict; }
132 bool IsZero() const { return type_ == kRegTypeZero; }
133 bool IsOne() const { return type_ == kRegTypeOne; }
134 bool IsConstLo() const { return type_ == kRegTypeConstLo; }
135 bool IsBoolean() const { return type_ == kRegTypeBoolean; }
136 bool IsByte() const { return type_ == kRegTypeByte; }
137 bool IsChar() const { return type_ == kRegTypeChar; }
138 bool IsShort() const { return type_ == kRegTypeShort; }
139 bool IsInteger() const { return type_ == kRegTypeInteger; }
140 bool IsLong() const { return type_ == kRegTypeLongLo; }
141 bool IsFloat() const { return type_ == kRegTypeFloat; }
142 bool IsDouble() const { return type_ == kRegTypeDoubleLo; }
143 bool IsReference() const { return type_ == kRegTypeReference; }
144
145 bool IsLowHalf() const { return type_ == kRegTypeLongLo ||
146 type_ == kRegTypeDoubleLo ||
147 type_ == kRegTypeConstLo; }
148 bool IsHighHalf() const { return type_ == kRegTypeLongHi ||
149 type_ == kRegTypeDoubleHi ||
150 type_ == kRegTypeConstHi; }
151
152 const RegType& HighHalf(RegTypeCache* cache) const;
153
154 bool CheckWidePair(const RegType& type_h) const {
155 return IsLowHalf() && (type_h.type_ == type_ + 1);
jeffhaobdb76512011-09-07 11:43:16 -0700156 }
157
Ian Rogersd81871c2011-10-03 13:57:23 -0700158 uint16_t GetId() const {
159 return cache_id_;
jeffhaobdb76512011-09-07 11:43:16 -0700160 }
161
Ian Rogersd81871c2011-10-03 13:57:23 -0700162 bool IsLongOrDoubleTypes() const { return IsLowHalf(); }
163
164 bool IsReferenceTypes() const {
165 return type_ == kRegTypeReference || type_ == kRegTypeZero;
jeffhaobdb76512011-09-07 11:43:16 -0700166 }
167
Ian Rogersd81871c2011-10-03 13:57:23 -0700168 bool IsCategory1Types() const {
169 return type_ >= kRegType1nrSTART && type_ <= kRegType1nrEND;
jeffhaobdb76512011-09-07 11:43:16 -0700170 }
171
Ian Rogersd81871c2011-10-03 13:57:23 -0700172 bool IsCategory2Types() const {
173 return IsLowHalf(); // Don't expect explicit testing of high halves
jeffhaobdb76512011-09-07 11:43:16 -0700174 }
175
Ian Rogersd81871c2011-10-03 13:57:23 -0700176 bool IsBooleanTypes() const { return IsBoolean() || IsZero() || IsOne(); }
177
178 bool IsByteTypes() const {
179 return IsByte() || IsBooleanTypes() || type_ == kRegTypeConstPosByte ||
180 type_ == kRegTypeConstByte || type_ == kRegTypePosByte;
jeffhaobdb76512011-09-07 11:43:16 -0700181 }
182
Ian Rogersd81871c2011-10-03 13:57:23 -0700183 bool IsShortTypes() const {
184 return IsShort() || IsByteTypes() || type_ == kRegTypeConstPosShort ||
185 type_ == kRegTypeConstShort || type_ == kRegTypePosShort;
jeffhaobdb76512011-09-07 11:43:16 -0700186 }
187
Ian Rogersd81871c2011-10-03 13:57:23 -0700188 bool IsCharTypes() const {
189 return IsChar() || IsBooleanTypes() || type_ == kRegTypeConstPosByte ||
190 type_ == kRegTypePosByte || type_ == kRegTypeConstPosShort || type_ == kRegTypePosShort ||
191 type_ == kRegTypeConstChar;
192 }
193
194 bool IsIntegralTypes() const {
195 return type_ >= kRegTypeIntegralSTART && type_ <= kRegTypeIntegralEND;
196 }
197
198 bool IsArrayIndexTypes() const {
199 return IsIntegralTypes();
200 }
201
202 // Float type may be derived from any constant type
203 bool IsFloatTypes() const {
204 return IsFloat() || IsZero() || IsOne() ||
205 type_ == kRegTypeConstPosByte || type_ == kRegTypeConstByte ||
206 type_ == kRegTypeConstPosShort || type_ == kRegTypeConstShort ||
207 type_ == kRegTypeConstChar || type_ == kRegTypeConstInteger;
208 }
209
210 bool IsLongTypes() const {
211 return IsLong() || type_ == kRegTypeConstLo;
212 }
213
214 bool IsDoubleTypes() const {
215 return IsDouble() || type_ == kRegTypeConstLo;
216 }
217
218 const RegType& VerifyAgainst(const RegType& check_type, RegTypeCache* reg_types) const;
219
220 const RegType& Merge(const RegType& incoming_type, RegTypeCache* reg_types) const;
221
222 bool Equals(const RegType& other) const {
223 return type_ == other.type_ && klass_ == other.klass_ && allocation_pc_ == other.allocation_pc_;
jeffhaobdb76512011-09-07 11:43:16 -0700224 }
225
226 /*
Ian Rogersd81871c2011-10-03 13:57:23 -0700227 * A basic Join operation on classes. For a pair of types S and T the Join, written S v T = J, is
228 * S <: J, T <: J and for-all U such that S <: U, T <: U then J <: U. That is J is the parent of
229 * S and T such that there isn't a parent of both S and T that isn't also the parent of J (ie J
230 * is the deepest (lowest upper bound) parent of S and T).
231 *
232 * This operation applies for regular classes and arrays, however, for interface types there needn't
233 * be a partial ordering on the types. We could solve the problem of a lack of a partial order by
234 * introducing sets of types, however, the only operation permissible on an interface is
235 * invoke-interface. In the tradition of Java verifiers [1] we defer the verification of interface
236 * types until an invoke-interface call on the interface typed reference at runtime and allow
237 * the perversion of Object being assignable to an interface type (note, however, that we don't
238 * allow assignment of Object or Interface to any concrete class and are therefore type safe).
239 *
240 * [1] Java bytecode verifcation: algorithms and formalizations, Xavier Leroy
jeffhaobdb76512011-09-07 11:43:16 -0700241 */
Ian Rogersd81871c2011-10-03 13:57:23 -0700242 static Class* ClassJoin(Class* s, Class* t);
jeffhaoe23d93c2011-09-15 14:48:43 -0700243
244 private:
Ian Rogersd81871c2011-10-03 13:57:23 -0700245 friend class RegTypeCache;
246
247 // Address given to an allocation_pc for an initialized object.
248 static const uint32_t kInitArgAddr = -2;
249
250 // Address given to an uninitialized allocation_pc if an object is uninitialized through being
251 // a constructor.
252 static const uint32_t kUninitThisArgAddr = -1;
253
254 RegType(Type type, Class* klass, uint32_t allocation_pc, uint16_t cache_id) :
255 type_(type), klass_(klass), allocation_pc_(allocation_pc), cache_id_(cache_id) {
256 DCHECK(type >= kRegTypeReference || allocation_pc_ == kInitArgAddr);
257 }
258
259 const Type type_; // The current type of the register
260
261 // If known the type of the register
262 Class* klass_;
263
264 // Address an uninitialized reference was created
265 const uint32_t allocation_pc_;
266
267 // A RegType cache densely encodes types, this is the location in the cache for this type
268 const uint16_t cache_id_;
269
270 /*
271 * Merge result table for primitive values. The table is symmetric along the diagonal.
272 *
273 * Note that 32-bit int/float do not merge into 64-bit long/double. This is a register merge, not
274 * a widening conversion. Only the "implicit" widening within a category, e.g. byte to short, is
275 * allowed.
276 *
277 * Dalvik does not draw a distinction between int and float, but we enforce that once a value is
278 * used as int, it can't be used as float, and vice-versa. We do not allow free exchange between
279 * 32-bit int/float and 64-bit long/double.
280 *
281 * Note that Uninit + Uninit = Uninit. This holds true because we only use this when the RegType
282 * value is exactly equal to kRegTypeUninit, which can only happen for the zeroth entry in the
283 * table.
284 *
285 * "Unknown" never merges with anything known. The only time a register transitions from "unknown"
286 * to "known" is when we're executing code for the first time, and we handle that with a simple
287 * copy.
288 */
289 static const RegType::Type merge_table_[kRegTypeReference][kRegTypeReference];
290
291 DISALLOW_COPY_AND_ASSIGN(RegType);
292};
293std::ostream& operator<<(std::ostream& os, const RegType& rhs);
294
295class RegTypeCache {
296 public:
297 explicit RegTypeCache() : entries_(RegType::kRegTypeReference) {
298 Unknown(); // ensure Unknown is initialized
299 }
300 ~RegTypeCache() {
301 STLDeleteElements(&entries_);
302 }
303
304 const RegType& GetFromId(uint16_t id) {
305 DCHECK_LT(id, entries_.size());
306 RegType* result = entries_[id];
307 DCHECK(result != NULL);
308 return *result;
309 }
310
311 const RegType& From(RegType::Type type, const ClassLoader* loader, const std::string& descriptor);
312 const RegType& FromClass(Class* klass);
313 const RegType& FromCat1Const(int32_t value);
314 const RegType& FromDescriptor(const ClassLoader* loader, const std::string& descriptor);
315 const RegType& FromType(RegType::Type);
316
317 const RegType& Boolean() { return FromType(RegType::kRegTypeBoolean); }
318 const RegType& Byte() { return FromType(RegType::kRegTypeByte); }
319 const RegType& Char() { return FromType(RegType::kRegTypeChar); }
320 const RegType& Short() { return FromType(RegType::kRegTypeShort); }
321 const RegType& Integer() { return FromType(RegType::kRegTypeInteger); }
322 const RegType& Float() { return FromType(RegType::kRegTypeFloat); }
323 const RegType& Long() { return FromType(RegType::kRegTypeLongLo); }
324 const RegType& Double() { return FromType(RegType::kRegTypeDoubleLo); }
325
326 const RegType& JavaLangClass() { return From(RegType::kRegTypeReference, NULL, "Ljava/lang/Class;"); }
327 const RegType& JavaLangObject() { return From(RegType::kRegTypeReference, NULL, "Ljava/lang/Object;"); }
328 const RegType& JavaLangString() { return From(RegType::kRegTypeReference, NULL, "Ljava/lang/String;"); }
329
330 const RegType& Unknown() { return FromType(RegType::kRegTypeUnknown); }
331 const RegType& Conflict() { return FromType(RegType::kRegTypeConflict); }
332 const RegType& Zero() { return FromType(RegType::kRegTypeZero); }
333 const RegType& ConstLo() { return FromType(RegType::kRegTypeConstLo); }
334
335 const RegType& Uninitialized(Class* klass, uint32_t allocation_pc);
336 const RegType& UninitializedThisArgument(Class* klass);
337
338 private:
339 // The allocated entries
340 std::vector<RegType*> entries_;
341
342 DISALLOW_COPY_AND_ASSIGN(RegTypeCache);
343};
344
345class InsnFlags {
346 public:
347 InsnFlags() : length_(0), flags_(0) {}
348
349 void SetLengthInCodeUnits(size_t length) {
350 CHECK_LT(length, 65536u);
351 length_ = length;
352 }
353 size_t GetLengthInCodeUnits() {
354 return length_;
355 }
356 bool IsOpcode() const {
357 return length_ != 0;
358 }
359
360 void SetInTry() {
361 flags_ |= 1 << kInsnFlagInTry;
362 }
363 void ClearInTry() {
364 flags_ &= ~(1 << kInsnFlagInTry);
365 }
366 bool IsInTry() const {
367 return (flags_ & (1 << kInsnFlagInTry)) != 0;
368 }
369
370 void SetBranchTarget() {
371 flags_ |= 1 << kInsnFlagBranchTarget;
372 }
373 void ClearBranchTarget() {
374 flags_ &= ~(1 << kInsnFlagBranchTarget);
375 }
376 bool IsBranchTarget() const {
377 return (flags_ & (1 << kInsnFlagBranchTarget)) != 0;
378 }
379
380 void SetGcPoint() {
381 flags_ |= 1 << kInsnFlagGcPoint;
382 }
383 void ClearGcPoint() {
384 flags_ &= ~(1 << kInsnFlagGcPoint);
385 }
386 bool IsGcPoint() const {
387 return (flags_ & (1 << kInsnFlagGcPoint)) != 0;
388 }
389
390 void SetVisited() {
391 flags_ |= 1 << kInsnFlagVisited;
392 }
393 void ClearVisited() {
394 flags_ &= ~(1 << kInsnFlagVisited);
395 }
396 bool IsVisited() const {
397 return (flags_ & (1 << kInsnFlagVisited)) != 0;
398 }
399
400 void SetChanged() {
401 flags_ |= 1 << kInsnFlagChanged;
402 }
403 void ClearChanged() {
404 flags_ &= ~(1 << kInsnFlagChanged);
405 }
406 bool IsChanged() const {
407 return (flags_ & (1 << kInsnFlagChanged)) != 0;
408 }
409
410 bool IsVisitedOrChanged() const {
411 return IsVisited() || IsChanged();
412 }
413
414 void Dump(std::ostream& os) {
415 char encoding[6];
416 if (!IsOpcode()) {
417 strncpy(encoding, "XXXXX", sizeof(encoding));
418 } else {
419 strncpy(encoding, "-----", sizeof(encoding));
420 if (IsInTry()) encoding[kInsnFlagInTry] = 'T';
421 if (IsBranchTarget()) encoding[kInsnFlagBranchTarget] = 'B';
422 if (IsGcPoint()) encoding[kInsnFlagGcPoint] = 'G';
423 if (IsVisited()) encoding[kInsnFlagVisited] = 'V';
424 if (IsChanged()) encoding[kInsnFlagChanged] = 'C';
425 }
426 os << encoding;
427 }
428 private:
429 enum InsnFlag {
430 kInsnFlagInTry,
431 kInsnFlagBranchTarget,
432 kInsnFlagGcPoint,
433 kInsnFlagVisited,
434 kInsnFlagChanged,
435 };
436
437 // Size of instruction in code units
438 uint16_t length_;
439 uint8_t flags_;
440};
441
442/*
443 * "Direct" and "virtual" methods are stored independently. The type of call used to invoke the
444 * method determines which list we search, and whether we travel up into superclasses.
445 *
446 * (<clinit>, <init>, and methods declared "private" or "static" are stored in the "direct" list.
447 * All others are stored in the "virtual" list.)
448 */
449enum MethodType {
450 METHOD_UNKNOWN = 0,
451 METHOD_DIRECT, // <init>, private
452 METHOD_STATIC, // static
453 METHOD_VIRTUAL, // virtual, super
454 METHOD_INTERFACE // interface
455};
456
457const int kRegTypeUninitMask = 0xff;
458const int kRegTypeUninitShift = 8;
459
460/*
461 * Register type categories, for type checking.
462 *
463 * The spec says category 1 includes boolean, byte, char, short, int, float, reference, and
464 * returnAddress. Category 2 includes long and double.
465 *
466 * We treat object references separately, so we have "category1nr". We don't support jsr/ret, so
467 * there is no "returnAddress" type.
468 */
469enum TypeCategory {
470 kTypeCategoryUnknown = 0,
471 kTypeCategory1nr = 1, // boolean, byte, char, short, int, float
472 kTypeCategory2 = 2, // long, double
473 kTypeCategoryRef = 3, // object reference
474};
475
476/*
477 * An enumeration of problems that can turn up during verification.
478 * VERIFY_ERROR_GENERIC denotes a failure that causes the entire class to be rejected. Other errors
479 * denote verification errors that cause bytecode to be rewritten to fail at runtime.
480 */
481enum VerifyError {
482 VERIFY_ERROR_NONE = 0, /* no error; must be zero */
483 VERIFY_ERROR_GENERIC, /* VerifyError */
484
485 VERIFY_ERROR_NO_CLASS, /* NoClassDefFoundError */
486 VERIFY_ERROR_NO_FIELD, /* NoSuchFieldError */
487 VERIFY_ERROR_NO_METHOD, /* NoSuchMethodError */
488 VERIFY_ERROR_ACCESS_CLASS, /* IllegalAccessError */
489 VERIFY_ERROR_ACCESS_FIELD, /* IllegalAccessError */
490 VERIFY_ERROR_ACCESS_METHOD, /* IllegalAccessError */
491 VERIFY_ERROR_CLASS_CHANGE, /* IncompatibleClassChangeError */
492 VERIFY_ERROR_INSTANTIATION, /* InstantiationError */
493};
494std::ostream& operator<<(std::ostream& os, const VerifyError& rhs);
495
496/*
497 * Identifies the type of reference in the instruction that generated the verify error
498 * (e.g. VERIFY_ERROR_ACCESS_CLASS could come from a method, field, or class reference).
499 *
500 * This must fit in two bits.
501 */
502enum VerifyErrorRefType {
503 VERIFY_ERROR_REF_CLASS = 0,
504 VERIFY_ERROR_REF_FIELD = 1,
505 VERIFY_ERROR_REF_METHOD = 2,
506};
507const int kVerifyErrorRefTypeShift = 6;
508
509/*
510 * Format enumeration for RegisterMap data area.
511 */
512enum RegisterMapFormat {
513 kRegMapFormatUnknown = 0,
514 kRegMapFormatNone, /* indicates no map data follows */
515 kRegMapFormatCompact8, /* compact layout, 8-bit addresses */
516 kRegMapFormatCompact16, /* compact layout, 16-bit addresses */
517};
518
519// During verification, we associate one of these with every "interesting" instruction. We track
520// the status of all registers, and (if the method has any monitor-enter instructions) maintain a
521// stack of entered monitors (identified by code unit offset).
522// If live-precise register maps are enabled, the "liveRegs" vector will be populated. Unlike the
523// other lists of registers here, we do not track the liveness of the method result register
524// (which is not visible to the GC).
525class RegisterLine {
526 public:
527 RegisterLine(size_t num_regs, DexVerifier* verifier) :
528 line_(new uint16_t[num_regs]), verifier_(verifier), num_regs_(num_regs) {
529 memset(line_.get(), 0, num_regs_ * sizeof(uint16_t));
530 result_[0] = RegType::kRegTypeUnknown;
531 result_[1] = RegType::kRegTypeUnknown;
532 }
533
534 // Implement category-1 "move" instructions. Copy a 32-bit value from "vsrc" to "vdst".
535 void CopyRegister1(uint32_t vdst, uint32_t vsrc, TypeCategory cat);
536
537 // Implement category-2 "move" instructions. Copy a 64-bit value from "vsrc" to "vdst". This
538 // copies both halves of the register.
539 void CopyRegister2(uint32_t vdst, uint32_t vsrc);
540
541 // Implement "move-result". Copy the category-1 value from the result register to another
542 // register, and reset the result register.
543 void CopyResultRegister1(uint32_t vdst, bool is_reference);
544
545 // Implement "move-result-wide". Copy the category-2 value from the result register to another
546 // register, and reset the result register.
547 void CopyResultRegister2(uint32_t vdst);
548
549 // Set the invisible result register to unknown
550 void SetResultTypeToUnknown();
551
552 // Set the type of register N, verifying that the register is valid. If "newType" is the "Lo"
553 // part of a 64-bit value, register N+1 will be set to "newType+1".
554 // The register index was validated during the static pass, so we don't need to check it here.
555 void SetRegisterType(uint32_t vdst, const RegType& new_type);
556
557 /* Set the type of the "result" register. */
558 void SetResultRegisterType(const RegType& new_type);
559
560 // Get the type of register vsrc.
561 const RegType& GetRegisterType(uint32_t vsrc) const;
562
563 bool VerifyRegisterType(uint32_t vsrc, const RegType& check_type);
564
565 void CopyFromLine(const RegisterLine* src) {
566 DCHECK_EQ(num_regs_, src->num_regs_);
567 memcpy(line_.get(), src->line_.get(), num_regs_ * sizeof(uint16_t));
568 monitors_ = src->monitors_;
569 reg_to_lock_depths_ = src->reg_to_lock_depths_;
570 }
571
572 void Dump(std::ostream& os) const {
573 for (size_t i = 0; i < num_regs_; i++) {
574 GetRegisterType(i).Dump(os);
575 }
576 }
577
578 void FillWithGarbage() {
579 memset(line_.get(), 0xf1, num_regs_ * sizeof(uint16_t));
580 while (!monitors_.empty()) {
581 monitors_.pop();
582 }
583 reg_to_lock_depths_.clear();
584 }
585
586 /*
587 * We're creating a new instance of class C at address A. Any registers holding instances
588 * previously created at address A must be initialized by now. If not, we mark them as "conflict"
589 * to prevent them from being used (otherwise, MarkRefsAsInitialized would mark the old ones and
590 * the new ones at the same time).
591 */
592 void MarkUninitRefsAsInvalid(const RegType& uninit_type);
593
594 /*
595 * Update all registers holding "uninit_type" to instead hold the corresponding initialized
596 * reference type. This is called when an appropriate constructor is invoked -- all copies of
597 * the reference must be marked as initialized.
598 */
599 void MarkRefsAsInitialized(const RegType& uninit_type);
600
601 /*
602 * Check constraints on constructor return. Specifically, make sure that the "this" argument got
603 * initialized.
604 * The "this" argument to <init> uses code offset kUninitThisArgAddr, which puts it at the start
605 * of the list in slot 0. If we see a register with an uninitialized slot 0 reference, we know it
606 * somehow didn't get initialized.
607 */
608 bool CheckConstructorReturn() const;
609
610 // Compare two register lines. Returns 0 if they match.
611 // Using this for a sort is unwise, since the value can change based on machine endianness.
612 int CompareLine(const RegisterLine* line2) const {
613 DCHECK(monitors_ == line2->monitors_);
614 // TODO: DCHECK(reg_to_lock_depths_ == line2->reg_to_lock_depths_);
615 return memcmp(line_.get(), line2->line_.get(), num_regs_ * sizeof(uint16_t));
616 }
617
618 size_t NumRegs() const {
619 return num_regs_;
620 }
621
622 /*
623 * Get the "this" pointer from a non-static method invocation. This returns the RegType so the
624 * caller can decide whether it needs the reference to be initialized or not. (Can also return
625 * kRegTypeZero if the reference can only be zero at this point.)
626 *
627 * The argument count is in vA, and the first argument is in vC, for both "simple" and "range"
628 * versions. We just need to make sure vA is >= 1 and then return vC.
629 */
630 const RegType& GetInvocationThis(const Instruction::DecodedInstruction& dec_insn);
631
632 /*
633 * Get the value from a register, and cast it to a Class. Sets "*failure" if something fails.
634 * This fails if the register holds an uninitialized class.
635 * If the register holds kRegTypeZero, this returns a NULL pointer.
636 */
637 Class* GetClassFromRegister(uint32_t vsrc) const;
638
639 /*
640 * Verify types for a simple two-register instruction (e.g. "neg-int").
641 * "dst_type" is stored into vA, and "src_type" is verified against vB.
642 */
643 void CheckUnaryOp(const Instruction::DecodedInstruction& dec_insn,
644 const RegType& dst_type, const RegType& src_type);
645
646 /*
647 * Verify types for a simple three-register instruction (e.g. "add-int").
648 * "dst_type" is stored into vA, and "src_type1"/"src_type2" are verified
649 * against vB/vC.
650 */
651 void CheckBinaryOp(const Instruction::DecodedInstruction& dec_insn,
652 const RegType& dst_type, const RegType& src_type1, const RegType& src_type2,
653 bool check_boolean_op);
654
655 /*
656 * Verify types for a binary "2addr" operation. "src_type1"/"src_type2"
657 * are verified against vA/vB, then "dst_type" is stored into vA.
658 */
659 void CheckBinaryOp2addr(const Instruction::DecodedInstruction& dec_insn,
660 const RegType& dst_type,
661 const RegType& src_type1, const RegType& src_type2,
662 bool check_boolean_op);
663
664 /*
665 * Verify types for A two-register instruction with a literal constant (e.g. "add-int/lit8").
666 * "dst_type" is stored into vA, and "src_type" is verified against vB.
667 *
668 * If "check_boolean_op" is set, we use the constant value in vC.
669 */
670 void CheckLiteralOp(const Instruction::DecodedInstruction& dec_insn,
671 const RegType& dst_type, const RegType& src_type, bool check_boolean_op);
672
673 // Verify/push monitor onto the monitor stack, locking the value in reg_idx at location insn_idx.
674 void PushMonitor(uint32_t reg_idx, int32_t insn_idx);
675
676 // Verify/pop monitor from monitor stack ensuring that we believe the monitor is locked
677 void PopMonitor(uint32_t reg_idx);
678
679 // Stack of currently held monitors and where they were locked
680 size_t MonitorStackDepth() const {
681 return monitors_.size();
682 }
683
684 // We expect no monitors to be held at certain points, such a method returns. Verify the stack
685 // is empty, failing and returning false if not.
686 bool VerifyMonitorStackEmpty();
687
688 bool MergeRegisters(const RegisterLine* incoming_line);
689
690 size_t GetMaxReferenceReg(size_t max_ref_reg) {
691 size_t i = static_cast<int>(max_ref_reg) < 0 ? 0 : max_ref_reg;
692 for(; i < num_regs_; i++) {
693 if (line_[i] >= RegType::kRegTypeReference) {
694 max_ref_reg = i;
695 }
696 }
697 return max_ref_reg;
698 }
699
700 // Write a bit at each register location that holds a reference
701 void WriteReferenceBitMap(int8_t* data, size_t max_bytes);
702 private:
703
704 void CopyRegToLockDepth(size_t dst, size_t src) {
705 if (reg_to_lock_depths_.count(src) > 0) {
706 uint32_t depths = reg_to_lock_depths_[src];
707 reg_to_lock_depths_[dst] = depths;
708 }
709 }
710
711 bool IsSetLockDepth(size_t reg, size_t depth) {
712 if (reg_to_lock_depths_.count(reg) > 0) {
713 uint32_t depths = reg_to_lock_depths_[reg];
714 return (depths & (1 << depth)) != 0;
715 } else {
716 return false;
717 }
718 }
719
720 void SetRegToLockDepth(size_t reg, size_t depth) {
721 CHECK_LT(depth, 32u);
722 DCHECK(!IsSetLockDepth(reg, depth));
723 uint32_t depths;
724 if (reg_to_lock_depths_.count(reg) > 0) {
725 depths = reg_to_lock_depths_[reg];
726 depths = depths | (1 << depth);
727 } else {
728 depths = 1 << depth;
729 }
730 reg_to_lock_depths_[reg] = depths;
731 }
732
733 void ClearRegToLockDepth(size_t reg, size_t depth) {
734 CHECK_LT(depth, 32u);
735 DCHECK(IsSetLockDepth(reg, depth));
736 uint32_t depths = reg_to_lock_depths_[reg];
737 depths = depths ^ (1 << depth);
738 if (depths != 0) {
739 reg_to_lock_depths_[reg] = depths;
740 } else {
741 reg_to_lock_depths_.erase(reg);
742 }
743 }
744
745 void ClearAllRegToLockDepths(size_t reg) {
746 reg_to_lock_depths_.erase(reg);
747 }
748
749 // Storage for the result register's type, valid after an invocation
750 uint16_t result_[2];
751
752 // An array of RegType Ids associated with each dex register
753 UniquePtr<uint16_t[]> line_;
754
755 // Back link to the verifier
756 DexVerifier* verifier_;
757
758 // Length of reg_types_
759 const size_t num_regs_;
760 // A stack of monitor enter locations
761 std::stack<uint32_t> monitors_;
762 // A map from register to a bit vector of indices into the monitors_ stack. As we pop the monitor
763 // stack we verify that monitor-enter/exit are correctly nested. That is, if there was a
764 // monitor-enter on v5 and then on v6, we expect the monitor-exit to be on v6 then on v5
765 std::map<uint32_t, uint32_t> reg_to_lock_depths_;
766};
767std::ostream& operator<<(std::ostream& os, const RegisterLine& rhs);
768
769class PcToRegisterLineTable {
770 public:
771 // We don't need to store the register data for many instructions, because we either only need
772 // it at branch points (for verification) or GC points and branches (for verification +
773 // type-precise register analysis).
774 enum RegisterTrackingMode {
775 kTrackRegsBranches,
776 kTrackRegsGcPoints,
777 kTrackRegsAll,
778 };
779 PcToRegisterLineTable() {}
780 ~PcToRegisterLineTable() {
781 STLDeleteValues(&pc_to_register_line_);
782 }
783
784 // Initialize the RegisterTable. Every instruction address can have a different set of information
785 // about what's in which register, but for verification purposes we only need to store it at
786 // branch target addresses (because we merge into that).
787 void Init(RegisterTrackingMode mode, InsnFlags* flags, uint32_t insns_size,
788 uint16_t registers_size, DexVerifier* verifier);
789
790 RegisterLine* GetLine(size_t idx) {
791 return pc_to_register_line_[idx];
792 }
793
794 private:
795 // Map from a dex pc to the register status associated with it
796 std::map<int32_t, RegisterLine*> pc_to_register_line_;
797
798 // Number of registers we track for each instruction. This is equal to the method's declared
799 // "registersSize" plus kExtraRegs (2).
800 size_t insn_reg_count_plus_;
801};
802
803
804
805// The verifier
806class DexVerifier {
807 public:
808 /* Verify a class. Returns "true" on success. */
809 static bool VerifyClass(const Class* klass);
jeffhaobdb76512011-09-07 11:43:16 -0700810 /*
811 * Perform verification on a single method.
812 *
813 * We do this in three passes:
814 * (1) Walk through all code units, determining instruction locations,
815 * widths, and other characteristics.
816 * (2) Walk through all code units, performing static checks on
817 * operands.
818 * (3) Iterate through the method, checking type safety and looking
819 * for code flow problems.
820 *
jeffhaod1f0fde2011-09-08 17:25:33 -0700821 * Some checks may be bypassed depending on the verification mode. We can't
jeffhaobdb76512011-09-07 11:43:16 -0700822 * turn this stuff off completely if we want to do "exact" GC.
823 *
824 * Confirmed here:
825 * - code array must not be empty
826 * Confirmed by ComputeWidthsAndCountOps():
827 * - opcode of first instruction begins at index 0
828 * - only documented instructions may appear
829 * - each instruction follows the last
830 * - last byte of last instruction is at (code_length-1)
831 */
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700832 static bool VerifyMethod(Method* method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700833
Ian Rogersd81871c2011-10-03 13:57:23 -0700834 uint8_t EncodePcToReferenceMapData() const;
835
836 uint32_t DexFileVersion() const {
837 return dex_file_->GetVersion();
838 }
839
840 RegTypeCache* GetRegTypeCache() {
841 return &reg_types_;
842 }
843
844 // Verification failed
845 std::ostream& Fail(VerifyError error) {
846 CHECK_EQ(failure_, VERIFY_ERROR_NONE);
847 failure_ = error;
848 return fail_messages_ << "VFY: " << PrettyMethod(method_)
849 << '[' << (void*)work_insn_idx_ << "] : ";
850 }
851
852 // Log for verification information
853 std::ostream& LogVerifyInfo() {
854 return info_messages_ << "VFY: " << PrettyMethod(method_)
855 << '[' << (void*)work_insn_idx_ << "] : ";
856 }
857
858 // Dump the state of the verifier, namely each instruction, what flags are set on it, register
859 // information
860 void Dump(std::ostream& os);
861
862 private:
863
864 explicit DexVerifier(Method* method);
865
866 bool Verify();
867
868 /*
869 * Compute the width of the instruction at each address in the instruction stream, and store it in
870 * insn_flags_. Addresses that are in the middle of an instruction, or that are part of switch
871 * table data, are not touched (so the caller should probably initialize "insn_flags" to zero).
872 *
873 * The "new_instance_count_" and "monitor_enter_count_" fields in vdata are also set.
874 *
875 * Performs some static checks, notably:
876 * - opcode of first instruction begins at index 0
877 * - only documented instructions may appear
878 * - each instruction follows the last
879 * - last byte of last instruction is at (code_length-1)
880 *
881 * Logs an error and returns "false" on failure.
882 */
883 bool ComputeWidthsAndCountOps();
884
885 /*
886 * Set the "in try" flags for all instructions protected by "try" statements. Also sets the
887 * "branch target" flags for exception handlers.
888 *
889 * Call this after widths have been set in "insn_flags".
890 *
891 * Returns "false" if something in the exception table looks fishy, but we're expecting the
892 * exception table to be somewhat sane.
893 */
894 bool ScanTryCatchBlocks();
895
jeffhaobdb76512011-09-07 11:43:16 -0700896 /*
897 * Perform static verification on all instructions in a method.
898 *
899 * Walks through instructions in a method calling VerifyInstruction on each.
900 */
Ian Rogersd81871c2011-10-03 13:57:23 -0700901 bool VerifyInstructions();
jeffhaobdb76512011-09-07 11:43:16 -0700902
903 /*
904 * Perform static verification on an instruction.
905 *
906 * As a side effect, this sets the "branch target" flags in InsnFlags.
907 *
908 * "(CF)" items are handled during code-flow analysis.
909 *
910 * v3 4.10.1
911 * - target of each jump and branch instruction must be valid
912 * - targets of switch statements must be valid
913 * - operands referencing constant pool entries must be valid
914 * - (CF) operands of getfield, putfield, getstatic, putstatic must be valid
915 * - (CF) operands of method invocation instructions must be valid
916 * - (CF) only invoke-direct can call a method starting with '<'
917 * - (CF) <clinit> must never be called explicitly
918 * - operands of instanceof, checkcast, new (and variants) must be valid
919 * - new-array[-type] limited to 255 dimensions
920 * - can't use "new" on an array class
921 * - (?) limit dimensions in multi-array creation
922 * - local variable load/store register values must be in valid range
923 *
924 * v3 4.11.1.2
925 * - branches must be within the bounds of the code array
926 * - targets of all control-flow instructions are the start of an instruction
927 * - register accesses fall within range of allocated registers
928 * - (N/A) access to constant pool must be of appropriate type
929 * - code does not end in the middle of an instruction
930 * - execution cannot fall off the end of the code
931 * - (earlier) for each exception handler, the "try" area must begin and
932 * end at the start of an instruction (end can be at the end of the code)
933 * - (earlier) for each exception handler, the handler must start at a valid
934 * instruction
935 */
Ian Rogersd81871c2011-10-03 13:57:23 -0700936 bool VerifyInstruction(const Instruction* inst, uint32_t code_offset);
jeffhaobdb76512011-09-07 11:43:16 -0700937
938 /* Ensure that the register index is valid for this code item. */
Ian Rogersd81871c2011-10-03 13:57:23 -0700939 bool CheckRegisterIndex(uint32_t idx);
jeffhaobdb76512011-09-07 11:43:16 -0700940
941 /* Ensure that the wide register index is valid for this code item. */
Ian Rogersd81871c2011-10-03 13:57:23 -0700942 bool CheckWideRegisterIndex(uint32_t idx);
jeffhaobdb76512011-09-07 11:43:16 -0700943
Ian Rogersd81871c2011-10-03 13:57:23 -0700944 // Perform static checks on a field get or set instruction. All we do here is ensure that the
945 // field index is in the valid range.
946 bool CheckFieldIndex(uint32_t idx);
jeffhaobdb76512011-09-07 11:43:16 -0700947
Ian Rogersd81871c2011-10-03 13:57:23 -0700948 // Perform static checks on a method invocation instruction. All we do here is ensure that the
949 // method index is in the valid range.
950 bool CheckMethodIndex(uint32_t idx);
jeffhaobdb76512011-09-07 11:43:16 -0700951
Ian Rogersd81871c2011-10-03 13:57:23 -0700952 // Perform static checks on a "new-instance" instruction. Specifically, make sure the class
953 // reference isn't for an array class.
954 bool CheckNewInstance(uint32_t idx);
jeffhaobdb76512011-09-07 11:43:16 -0700955
Ian Rogersd81871c2011-10-03 13:57:23 -0700956 /* Ensure that the string index is in the valid range. */
957 bool CheckStringIndex(uint32_t idx);
jeffhaobdb76512011-09-07 11:43:16 -0700958
Ian Rogersd81871c2011-10-03 13:57:23 -0700959 // Perform static checks on an instruction that takes a class constant. Ensure that the class
960 // index is in the valid range.
961 bool CheckTypeIndex(uint32_t idx);
jeffhaobdb76512011-09-07 11:43:16 -0700962
Ian Rogersd81871c2011-10-03 13:57:23 -0700963 // Perform static checks on a "new-array" instruction. Specifically, make sure they aren't
964 // creating an array of arrays that causes the number of dimensions to exceed 255.
965 bool CheckNewArray(uint32_t idx);
jeffhaobdb76512011-09-07 11:43:16 -0700966
Ian Rogersd81871c2011-10-03 13:57:23 -0700967 // Verify an array data table. "cur_offset" is the offset of the fill-array-data instruction.
968 bool CheckArrayData(uint32_t cur_offset);
jeffhaobdb76512011-09-07 11:43:16 -0700969
Ian Rogersd81871c2011-10-03 13:57:23 -0700970 // Verify that the target of a branch instruction is valid. We don't expect code to jump directly
971 // into an exception handler, but it's valid to do so as long as the target isn't a
972 // "move-exception" instruction. We verify that in a later stage.
973 // The dex format forbids certain instructions from branching to themselves.
974 // Updates "insnFlags", setting the "branch target" flag.
975 bool CheckBranchTarget(uint32_t cur_offset);
jeffhaobdb76512011-09-07 11:43:16 -0700976
Ian Rogersd81871c2011-10-03 13:57:23 -0700977 // Verify a switch table. "cur_offset" is the offset of the switch instruction.
978 // Updates "insnFlags", setting the "branch target" flag.
979 bool CheckSwitchTargets(uint32_t cur_offset);
jeffhaobdb76512011-09-07 11:43:16 -0700980
Ian Rogersd81871c2011-10-03 13:57:23 -0700981 // Check the register indices used in a "vararg" instruction, such as invoke-virtual or
982 // filled-new-array.
983 // - vA holds word count (0-5), args[] have values.
984 // There are some tests we don't do here, e.g. we don't try to verify that invoking a method that
985 // takes a double is done with consecutive registers. This requires parsing the target method
986 // signature, which we will be doing later on during the code flow analysis.
987 bool CheckVarArgRegs(uint32_t vA, uint32_t arg[]);
jeffhaobdb76512011-09-07 11:43:16 -0700988
Ian Rogersd81871c2011-10-03 13:57:23 -0700989 // Check the register indices used in a "vararg/range" instruction, such as invoke-virtual/range
990 // or filled-new-array/range.
991 // - vA holds word count, vC holds index of first reg.
992 bool CheckVarArgRangeRegs(uint32_t vA, uint32_t vC);
jeffhaobdb76512011-09-07 11:43:16 -0700993
Ian Rogersd81871c2011-10-03 13:57:23 -0700994 // Extract the relative offset from a branch instruction.
995 // Returns "false" on failure (e.g. this isn't a branch instruction).
996 bool GetBranchOffset(uint32_t cur_offset, int32_t* pOffset, bool* pConditional,
997 bool* selfOkay);
jeffhaobdb76512011-09-07 11:43:16 -0700998
Ian Rogersd81871c2011-10-03 13:57:23 -0700999 /* Perform detailed code-flow analysis on a single method. */
1000 bool VerifyCodeFlow();
jeffhaobdb76512011-09-07 11:43:16 -07001001
Ian Rogersd81871c2011-10-03 13:57:23 -07001002 // Set the register types for the first instruction in the method based on the method signature.
1003 // This has the side-effect of validating the signature.
1004 bool SetTypesFromSignature();
jeffhaobdb76512011-09-07 11:43:16 -07001005
1006 /*
1007 * Perform code flow on a method.
1008 *
Ian Rogersd81871c2011-10-03 13:57:23 -07001009 * The basic strategy is as outlined in v3 4.11.1.2: set the "changed" bit on the first
1010 * instruction, process it (setting additional "changed" bits), and repeat until there are no
1011 * more.
jeffhaobdb76512011-09-07 11:43:16 -07001012 *
1013 * v3 4.11.1.1
1014 * - (N/A) operand stack is always the same size
1015 * - operand stack [registers] contain the correct types of values
1016 * - local variables [registers] contain the correct types of values
1017 * - methods are invoked with the appropriate arguments
1018 * - fields are assigned using values of appropriate types
1019 * - opcodes have the correct type values in operand registers
Ian Rogersd81871c2011-10-03 13:57:23 -07001020 * - there is never an uninitialized class instance in a local variable in code protected by an
1021 * exception handler (operand stack is okay, because the operand stack is discarded when an
1022 * exception is thrown) [can't know what's a local var w/o the debug info -- should fall out of
jeffhaobdb76512011-09-07 11:43:16 -07001023 * register typing]
1024 *
1025 * v3 4.11.1.2
1026 * - execution cannot fall off the end of the code
1027 *
Ian Rogersd81871c2011-10-03 13:57:23 -07001028 * (We also do many of the items described in the "static checks" sections, because it's easier to
1029 * do them here.)
jeffhaobdb76512011-09-07 11:43:16 -07001030 *
Ian Rogersd81871c2011-10-03 13:57:23 -07001031 * We need an array of RegType values, one per register, for every instruction. If the method uses
1032 * monitor-enter, we need extra data for every register, and a stack for every "interesting"
1033 * instruction. In theory this could become quite large -- up to several megabytes for a monster
1034 * function.
jeffhaobdb76512011-09-07 11:43:16 -07001035 *
1036 * NOTE:
Ian Rogersd81871c2011-10-03 13:57:23 -07001037 * The spec forbids backward branches when there's an uninitialized reference in a register. The
1038 * idea is to prevent something like this:
jeffhaobdb76512011-09-07 11:43:16 -07001039 * loop:
1040 * move r1, r0
1041 * new-instance r0, MyClass
1042 * ...
1043 * if-eq rN, loop // once
1044 * initialize r0
1045 *
Ian Rogersd81871c2011-10-03 13:57:23 -07001046 * This leaves us with two different instances, both allocated by the same instruction, but only
1047 * one is initialized. The scheme outlined in v3 4.11.1.4 wouldn't catch this, so they work around
1048 * it by preventing backward branches. We achieve identical results without restricting code
1049 * reordering by specifying that you can't execute the new-instance instruction if a register
1050 * contains an uninitialized instance created by that same instruction.
jeffhaobdb76512011-09-07 11:43:16 -07001051 */
Ian Rogersd81871c2011-10-03 13:57:23 -07001052 bool CodeFlowVerifyMethod();
jeffhaobdb76512011-09-07 11:43:16 -07001053
1054 /*
1055 * Perform verification for a single instruction.
1056 *
Ian Rogersd81871c2011-10-03 13:57:23 -07001057 * This requires fully decoding the instruction to determine the effect it has on registers.
jeffhaobdb76512011-09-07 11:43:16 -07001058 *
Ian Rogersd81871c2011-10-03 13:57:23 -07001059 * Finds zero or more following instructions and sets the "changed" flag if execution at that
1060 * point needs to be (re-)evaluated. Register changes are merged into "reg_types_" at the target
1061 * addresses. Does not set or clear any other flags in "insn_flags_".
jeffhaobdb76512011-09-07 11:43:16 -07001062 */
Ian Rogersd81871c2011-10-03 13:57:23 -07001063 bool CodeFlowVerifyInstruction(uint32_t* start_guess);
1064
1065 // Perform verification of an aget instruction. The destination register's type will be set to
1066 // be that of component type of the array unless the array type is unknown, in which case a
1067 // bottom type inferred from the type of instruction is used. is_primitive is false for an
1068 // aget-object.
1069 void VerifyAGet(const Instruction::DecodedInstruction& insn, const RegType& insn_type,
1070 bool is_primitive);
1071
1072 // Perform verification of an aput instruction.
1073 void VerifyAPut(const Instruction::DecodedInstruction& insn, const RegType& insn_type,
1074 bool is_primitive);
1075
1076 // Lookup instance field and fail for resolution violations
1077 Field* GetInstanceField(const RegType& obj_type, int field_idx);
1078
1079 // Perform verification of an iget instruction.
1080 void VerifyIGet(const Instruction::DecodedInstruction& insn, const RegType& insn_type,
1081 bool is_primitive);
1082
1083 // Perform verification of an iput instruction.
1084 void VerifyIPut(const Instruction::DecodedInstruction& insn, const RegType& insn_type,
1085 bool is_primitive);
1086
1087 // Lookup static field and fail for resolution violations
1088 Field* GetStaticField(int field_idx);
1089
1090 // Perform verification of an sget instruction.
1091 void VerifySGet(const Instruction::DecodedInstruction& insn, const RegType& insn_type,
1092 bool is_primitive);
1093
1094 // Perform verification of an sput instruction.
1095 void VerifySPut(const Instruction::DecodedInstruction& insn, const RegType& insn_type,
1096 bool is_primitive);
1097
1098 // Verify that the arguments in a filled-new-array instruction are valid.
1099 // "res_class" is the class refered to by dec_insn->vB_.
1100 void VerifyFilledNewArrayRegs(const Instruction::DecodedInstruction& dec_insn, Class* res_class,
1101 bool is_range);
jeffhaobdb76512011-09-07 11:43:16 -07001102
1103 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07001104 * Resolves a class based on an index and performs access checks to ensure the referrer can
1105 * access the resolved class.
jeffhao98eacac2011-09-14 16:11:53 -07001106 * Exceptions caused by failures are cleared before returning.
jeffhao98eacac2011-09-14 16:11:53 -07001107 * Sets "*failure" on failure.
1108 */
Ian Rogersd81871c2011-10-03 13:57:23 -07001109 Class* ResolveClassAndCheckAccess(uint32_t class_idx);
1110
1111 /*
1112 * For the "move-exception" instruction at "work_insn_idx_", which must be at an exception handler
1113 * address, determine the first common superclass of all exceptions that can land here.
1114 * Returns NULL if no matching exception handler can be found, or if the exception is not a
1115 * subclass of Throwable.
1116 */
1117 Class* GetCaughtExceptionType();
jeffhao98eacac2011-09-14 16:11:53 -07001118
1119 /*
jeffhaob4df5142011-09-19 20:25:32 -07001120 * Resolves a method based on an index and performs access checks to ensure
1121 * the referrer can access the resolved method.
jeffhaob4df5142011-09-19 20:25:32 -07001122 * Does not throw exceptions.
jeffhaob4df5142011-09-19 20:25:32 -07001123 */
Ian Rogersd81871c2011-10-03 13:57:23 -07001124 Method* ResolveMethodAndCheckAccess(uint32_t method_idx, bool is_direct);
jeffhaobdb76512011-09-07 11:43:16 -07001125
1126 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001127 * Verify the arguments to a method. We're executing in "method", making
jeffhaobdb76512011-09-07 11:43:16 -07001128 * a call to the method reference in vB.
1129 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001130 * If this is a "direct" invoke, we allow calls to <init>. For calls to
1131 * <init>, the first argument may be an uninitialized reference. Otherwise,
jeffhaobdb76512011-09-07 11:43:16 -07001132 * calls to anything starting with '<' will be rejected, as will any
1133 * uninitialized reference arguments.
1134 *
1135 * For non-static method calls, this will verify that the method call is
1136 * appropriate for the "this" argument.
1137 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001138 * The method reference is in vBBBB. The "is_range" parameter determines
jeffhaobdb76512011-09-07 11:43:16 -07001139 * whether we use 0-4 "args" values or a range of registers defined by
1140 * vAA and vCCCC.
1141 *
1142 * Widening conversions on integers and references are allowed, but
1143 * narrowing conversions are not.
1144 *
1145 * Returns the resolved method on success, NULL on failure (with *failure
1146 * set appropriately).
1147 */
Ian Rogersd81871c2011-10-03 13:57:23 -07001148 Method* VerifyInvocationArgs(const Instruction::DecodedInstruction& dec_insn,
1149 MethodType method_type, bool is_range, bool is_super);
jeffhaobdb76512011-09-07 11:43:16 -07001150
Ian Rogersd81871c2011-10-03 13:57:23 -07001151 /*
1152 * Return the register type for the method. We can't just use the already-computed
1153 * DalvikJniReturnType, because if it's a reference type we need to do the class lookup.
1154 * Returned references are assumed to be initialized. Returns kRegTypeUnknown for "void".
1155 */
1156 const RegType& GetMethodReturnType() {
1157 return reg_types_.FromClass(method_->GetReturnType());
1158 }
jeffhaoe0cfb6f2011-09-22 16:42:56 -07001159
Ian Rogersd81871c2011-10-03 13:57:23 -07001160 /*
1161 * Verify that the target instruction is not "move-exception". It's important that the only way
1162 * to execute a move-exception is as the first instruction of an exception handler.
1163 * Returns "true" if all is well, "false" if the target instruction is move-exception.
1164 */
1165 bool CheckMoveException(const uint16_t* insns, int insn_idx);
1166
1167 /*
1168 * Replace an instruction with "throw-verification-error". This allows us to
1169 * defer error reporting until the code path is first used.
1170 */
1171 void ReplaceFailingInstruction();
1172
1173 /*
1174 * Control can transfer to "next_insn". Merge the registers from merge_line into the table at
1175 * next_insn, and set the changed flag on the target address if any of the registers were changed.
1176 * Returns "false" if an error is encountered.
1177 */
1178 bool UpdateRegisters(uint32_t next_insn, const RegisterLine* merge_line);
1179
1180 /*
1181 * Generate the GC map for a method that has just been verified (i.e. we're doing this as part of
1182 * verification). For type-precise determination we have all the data we need, so we just need to
1183 * encode it in some clever fashion.
1184 * Returns a pointer to a newly-allocated RegisterMap, or NULL on failure.
1185 */
1186 ByteArray* GenerateGcMap();
1187
1188 // Verify that the GC map associated with method_ is well formed
1189 void VerifyGcMap();
1190
1191 // Compute sizes for GC map data
1192 void ComputeGcMapSizes(size_t* gc_points, size_t* ref_bitmap_bits, size_t* log2_max_gc_pc);
1193
1194 Class* JavaLangThrowable();
1195
1196 InsnFlags CurrentInsnFlags() {
1197 return insn_flags_[work_insn_idx_];
1198 }
1199
1200 RegTypeCache reg_types_;
1201
1202 PcToRegisterLineTable reg_table_;
1203
1204 // Storage for the register status we're currently working on.
1205 UniquePtr<RegisterLine> work_line_;
1206
1207 // Lazily initialized reference to java.lang.Class<java.lang.Throwable>
1208 Class* java_lang_throwable_;
1209
1210 // The address of the instruction we're currently working on, note that this is in 2 byte
1211 // quantities
1212 uint32_t work_insn_idx_;
1213
1214 // Storage for the register status we're saving for later.
1215 UniquePtr<RegisterLine> saved_line_;
1216
1217 Method* method_; // The method we're working on.
1218 const DexFile* dex_file_; // The dex file containing the method.
1219 const DexFile::CodeItem* code_item_; // The code item containing the code for the method.
1220 UniquePtr<InsnFlags[]> insn_flags_; // Instruction widths and flags, one entry per code unit.
1221
1222 // The type of any error that occurs
1223 VerifyError failure_;
1224
1225 // Failure message log
1226 std::ostringstream fail_messages_;
1227 // Info message log
1228 std::ostringstream info_messages_;
1229
1230 // The number of occurrences of specific opcodes.
1231 size_t new_instance_count_;
1232 size_t monitor_enter_count_;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001233};
1234
Ian Rogersd81871c2011-10-03 13:57:23 -07001235// Lightweight wrapper for PC to reference bit maps.
1236class PcToReferenceMap {
1237 public:
1238 PcToReferenceMap(Method* m) {
1239 data_ = down_cast<ByteArray*>(m->GetGcMap());
1240 CHECK(data_ != NULL);
1241 // Check the size of the table agrees with the number of entries
1242 size_t data_size = data_->GetLength() - 4;
1243 DCHECK_EQ(EntryWidth() * NumEntries(), data_size);
1244 }
1245
1246 // The number of entries in the table
1247 size_t NumEntries() const {
1248 return GetData()[2] | (GetData()[3] << 8);
1249 }
1250
1251 // Get the PC at the given index
1252 uint16_t GetPC(size_t index) const {
1253 size_t entry_offset = index * EntryWidth();
1254 if (PcWidth() == 1) {
1255 return Table()[entry_offset];
1256 } else {
1257 return Table()[entry_offset] | (Table()[entry_offset + 1] << 8);
1258 }
1259 }
1260
1261 // Return address of bitmap encoding what are live references
1262 const uint8_t* GetBitMap(size_t index) const {
1263 size_t entry_offset = index * EntryWidth();
1264 return &Table()[entry_offset + PcWidth()];
1265 }
1266
1267 // Find the bitmap associated with the given dex pc
1268 const uint8_t* FindBitMap(uint16_t dex_pc, bool error_if_not_present = true) const;
1269
1270 // The number of bytes used to encode registers
1271 size_t RegWidth() const {
1272 return GetData()[1];
1273 }
1274
1275 private:
1276 // Table of num_entries * (dex pc, bitmap)
1277 const uint8_t* Table() const {
1278 return GetData() + 4;
1279 }
1280
1281 // The format of the table of the PCs for the table
1282 RegisterMapFormat Format() const {
1283 return static_cast<RegisterMapFormat>(GetData()[0]);
1284 }
1285
1286 // Number of bytes used to encode a dex pc
1287 size_t PcWidth() const {
1288 RegisterMapFormat format = Format();
1289 switch (format) {
1290 case kRegMapFormatCompact8:
1291 return 1;
1292 case kRegMapFormatCompact16:
1293 return 2;
1294 default:
1295 LOG(FATAL) << "Invalid format " << static_cast<int>(format);
1296 return -1;
1297 }
1298 }
1299
1300 // The width of an entry in the table
1301 size_t EntryWidth() const {
1302 return PcWidth() + RegWidth();
1303 }
1304
1305 const uint8_t* GetData() const {
1306 return reinterpret_cast<uint8_t*>(data_->GetData());
1307 }
1308 ByteArray* data_; // The header and table data
1309};
1310
1311} // namespace verifier
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001312} // namespace art
1313
1314#endif // ART_SRC_DEX_VERIFY_H_