blob: 9041c95399ecd99b269b8d483098bf554e9fd001 [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 Rogers84fa0742011-10-25 18:13:30 -070014#include <limits>
Ian Rogersd81871c2011-10-03 13:57:23 -070015#include <map>
16#include <stack>
17#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070018
Ian Rogersd81871c2011-10-03 13:57:23 -070019namespace art {
20namespace verifier {
21
22class DexVerifier;
23class PcToReferenceMap;
24class RegTypeCache;
jeffhaobdb76512011-09-07 11:43:16 -070025
26/*
Ian Rogersd81871c2011-10-03 13:57:23 -070027 * Set this to enable dead code scanning. This is not required, but it's very useful when testing
28 * changes to the verifier (to make sure we're not skipping over stuff). The only reason not to do
29 * it is that it slightly increases the time required to perform verification.
jeffhaobdb76512011-09-07 11:43:16 -070030 */
31#ifndef NDEBUG
32# define DEAD_CODE_SCAN true
33#else
34# define DEAD_CODE_SCAN false
35#endif
36
37/*
Ian Rogers84fa0742011-10-25 18:13:30 -070038 * RegType holds information about the "type" of data held in a register.
jeffhaobdb76512011-09-07 11:43:16 -070039 */
Ian Rogersd81871c2011-10-03 13:57:23 -070040class RegType {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070041 public:
Ian Rogersd81871c2011-10-03 13:57:23 -070042 enum Type {
43 kRegTypeUnknown = 0, /* initial state */
jeffhaobdb76512011-09-07 11:43:16 -070044 kRegTypeConflict, /* merge clash makes this reg's type unknowable */
Ian Rogers84fa0742011-10-25 18:13:30 -070045 kRegTypeBoolean, /* Z */
46 kRegType1nrSTART = kRegTypeBoolean,
47 kRegTypeIntegralSTART = kRegTypeBoolean,
Ian Rogersd81871c2011-10-03 13:57:23 -070048 kRegTypeByte, /* B */
Ian Rogersd81871c2011-10-03 13:57:23 -070049 kRegTypeShort, /* S */
50 kRegTypeChar, /* C */
51 kRegTypeInteger, /* I */
52 kRegTypeIntegralEND = kRegTypeInteger,
53 kRegTypeFloat, /* F */
54 kRegType1nrEND = kRegTypeFloat,
Ian Rogers84fa0742011-10-25 18:13:30 -070055 kRegTypeLongLo, /* J - lower-numbered register; endian-independent */
56 kRegTypeLongHi,
57 kRegTypeDoubleLo, /* D */
58 kRegTypeDoubleHi,
Ian Rogersd81871c2011-10-03 13:57:23 -070059 kRegTypeConstLo, /* const derived wide, lower half - could be long or double */
60 kRegTypeConstHi, /* const derived wide, upper half - could be long or double */
Ian Rogers84fa0742011-10-25 18:13:30 -070061 kRegTypeLastFixedLocation = kRegTypeConstHi,
62 kRegTypeConst, /* 32-bit constant derived value - could be float or int */
63 kRegTypeUnresolvedReference, // Reference type that couldn't be resolved
64 kRegTypeUninitializedReference, // Freshly allocated reference type
65 kRegTypeUninitializedThisReference, // Freshly allocated reference passed as "this"
66 kRegTypeUnresolvedAndUninitializedReference, // Freshly allocated unresolved reference type
67 kRegTypeReference, // Reference type
jeffhaobdb76512011-09-07 11:43:16 -070068 };
69
Ian Rogersd81871c2011-10-03 13:57:23 -070070 Type GetType() const {
71 return type_;
jeffhaobdb76512011-09-07 11:43:16 -070072 }
73
Ian Rogersd81871c2011-10-03 13:57:23 -070074 bool IsUnknown() const { return type_ == kRegTypeUnknown; }
75 bool IsConflict() const { return type_ == kRegTypeConflict; }
Ian Rogersd81871c2011-10-03 13:57:23 -070076 bool IsBoolean() const { return type_ == kRegTypeBoolean; }
77 bool IsByte() const { return type_ == kRegTypeByte; }
78 bool IsChar() const { return type_ == kRegTypeChar; }
79 bool IsShort() const { return type_ == kRegTypeShort; }
80 bool IsInteger() const { return type_ == kRegTypeInteger; }
81 bool IsLong() const { return type_ == kRegTypeLongLo; }
82 bool IsFloat() const { return type_ == kRegTypeFloat; }
83 bool IsDouble() const { return type_ == kRegTypeDoubleLo; }
Ian Rogers84fa0742011-10-25 18:13:30 -070084 bool IsUnresolvedReference() const { return type_ == kRegTypeUnresolvedReference; }
85 bool IsUninitializedReference() const { return type_ == kRegTypeUninitializedReference; }
86 bool IsUninitializedThisReference() const { return type_ == kRegTypeUninitializedThisReference; }
87 bool IsUnresolvedAndUninitializedReference() const {
88 return type_ == kRegTypeUnresolvedAndUninitializedReference;
89 }
Ian Rogersd81871c2011-10-03 13:57:23 -070090 bool IsReference() const { return type_ == kRegTypeReference; }
Ian Rogers84fa0742011-10-25 18:13:30 -070091 bool IsUninitializedTypes() const {
92 return IsUninitializedReference() || IsUninitializedThisReference() ||
93 IsUnresolvedAndUninitializedReference();
94 }
Ian Rogers9074b992011-10-26 17:41:55 -070095 bool IsUnresolvedTypes() const {
96 return IsUnresolvedReference() || IsUnresolvedAndUninitializedReference();
97 }
Ian Rogersd81871c2011-10-03 13:57:23 -070098 bool IsLowHalf() const { return type_ == kRegTypeLongLo ||
99 type_ == kRegTypeDoubleLo ||
100 type_ == kRegTypeConstLo; }
101 bool IsHighHalf() const { return type_ == kRegTypeLongHi ||
102 type_ == kRegTypeDoubleHi ||
103 type_ == kRegTypeConstHi; }
104
Ian Rogers84fa0742011-10-25 18:13:30 -0700105 bool IsLongOrDoubleTypes() const { return IsLowHalf(); }
Ian Rogersd81871c2011-10-03 13:57:23 -0700106
Ian Rogers84fa0742011-10-25 18:13:30 -0700107 // Check this is the low half, and that type_h is its matching high-half
Ian Rogersd81871c2011-10-03 13:57:23 -0700108 bool CheckWidePair(const RegType& type_h) const {
109 return IsLowHalf() && (type_h.type_ == type_ + 1);
jeffhaobdb76512011-09-07 11:43:16 -0700110 }
111
Ian Rogers84fa0742011-10-25 18:13:30 -0700112 // The high half that corresponds to this low half
113 const RegType& HighHalf(RegTypeCache* cache) const;
114
115 bool IsConstant() const { return type_ == kRegTypeConst; }
116 bool IsLongConstant() const { return type_ == kRegTypeConstLo; }
117 bool IsLongConstantHigh() const { return type_ == kRegTypeConstHi; }
118
119 // If this is a 32-bit constant, what is the value? This value may just
120 // approximate to the actual constant value by virtue of merging.
121 int32_t ConstantValue() const {
122 DCHECK(IsConstant());
123 return allocation_pc_or_constant_;
124 }
125
126 bool IsZero() const { return IsConstant() && ConstantValue() == 0; }
127 bool IsOne() const { return IsConstant() && ConstantValue() == 1; }
128 bool IsConstantBoolean() const { return IsZero() || IsOne(); }
129 bool IsConstantByte() const {
130 return IsConstant() &&
131 ConstantValue() >= std::numeric_limits<jbyte>::min() &&
132 ConstantValue() <= std::numeric_limits<jbyte>::max();
133 }
134 bool IsConstantShort() const {
135 return IsConstant() &&
136 ConstantValue() >= std::numeric_limits<jshort>::min() &&
137 ConstantValue() <= std::numeric_limits<jshort>::max();
138 }
139 bool IsConstantChar() const {
140 return IsConstant() && ConstantValue() >= 0 &&
141 ConstantValue() <= std::numeric_limits<jchar>::max();
142 }
143
144 bool IsReferenceTypes() const {
145 return IsReference() || IsUnresolvedReference() || IsUninitializedReference() ||
146 IsUninitializedThisReference() || IsZero();
147 }
148 bool IsNonZeroReferenceTypes() const {
149 return IsReference() || IsUnresolvedReference() || IsUninitializedReference() ||
150 IsUninitializedThisReference();
151 }
152 bool IsCategory1Types() const {
153 return (type_ >= kRegType1nrSTART && type_ <= kRegType1nrEND) || IsConstant();
154 }
155 bool IsCategory2Types() const {
156 return IsLowHalf(); // Don't expect explicit testing of high halves
157 }
158
159 bool IsBooleanTypes() const { return IsBoolean() || IsConstantBoolean(); }
160 bool IsByteTypes() const { return IsByte() || IsBoolean() || IsConstantByte(); }
161 bool IsShortTypes() const { return IsShort() || IsByte() || IsBoolean() || IsConstantShort(); }
162 bool IsCharTypes() const { return IsChar() || IsBooleanTypes() || IsConstantChar(); }
163 bool IsIntegralTypes() const {
164 return (type_ >= kRegTypeIntegralSTART && type_ <= kRegTypeIntegralEND) || IsConstant();
165 }
166 bool IsArrayIndexTypes() const { return IsIntegralTypes(); }
167
168 // Float type may be derived from any constant type
169 bool IsFloatTypes() const { return IsFloat() || IsConstant(); }
170
171 bool IsLongTypes() const {
172 return IsLong() || IsLongConstant();
173 }
174 bool IsLongHighTypes() const {
175 return type_ == kRegTypeLongHi || type_ == kRegTypeConstHi;
176 }
177 bool IsDoubleTypes() const {
178 return IsDouble() || IsLongConstant();
179 }
180 bool IsDoubleHighTypes() const {
181 return type_ == kRegTypeDoubleHi || type_ == kRegTypeConstHi;
182 }
183
184 uint32_t GetAllocationPc() const {
185 DCHECK(IsUninitializedReference());
186 return allocation_pc_or_constant_;
187 }
188
189 Class* GetClass() const {
190 DCHECK(!IsUnresolvedReference());
191 DCHECK(klass_or_descriptor_ != NULL);
192 DCHECK(klass_or_descriptor_->IsClass());
193 return down_cast<Class*>(klass_or_descriptor_);
194 }
195
Ian Rogers9074b992011-10-26 17:41:55 -0700196 bool IsJavaLangObject() const {
197 return IsReference() && GetClass()->IsObjectClass();
198 }
Ian Rogers84fa0742011-10-25 18:13:30 -0700199 String* GetDescriptor() const {
200 DCHECK(IsUnresolvedReference());
201 DCHECK(klass_or_descriptor_ != NULL);
202 DCHECK(klass_or_descriptor_->IsString());
203 return down_cast<String*>(klass_or_descriptor_);
204 }
205
Ian Rogersd81871c2011-10-03 13:57:23 -0700206 uint16_t GetId() const {
207 return cache_id_;
jeffhaobdb76512011-09-07 11:43:16 -0700208 }
209
Ian Rogers84fa0742011-10-25 18:13:30 -0700210 std::string Dump() const;
Ian Rogersd81871c2011-10-03 13:57:23 -0700211
Ian Rogersb5e95b92011-10-25 23:28:55 -0700212 bool IsAssignableFrom(const RegType& src) const;
Ian Rogersd81871c2011-10-03 13:57:23 -0700213
214 const RegType& Merge(const RegType& incoming_type, RegTypeCache* reg_types) const;
215
Ian Rogers84fa0742011-10-25 18:13:30 -0700216 bool Equals(const RegType& other) const { return GetId() == other.GetId(); }
jeffhaobdb76512011-09-07 11:43:16 -0700217
218 /*
Ian Rogersd81871c2011-10-03 13:57:23 -0700219 * A basic Join operation on classes. For a pair of types S and T the Join, written S v T = J, is
220 * S <: J, T <: J and for-all U such that S <: U, T <: U then J <: U. That is J is the parent of
221 * 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
222 * is the deepest (lowest upper bound) parent of S and T).
223 *
224 * This operation applies for regular classes and arrays, however, for interface types there needn't
225 * be a partial ordering on the types. We could solve the problem of a lack of a partial order by
226 * introducing sets of types, however, the only operation permissible on an interface is
227 * invoke-interface. In the tradition of Java verifiers [1] we defer the verification of interface
228 * types until an invoke-interface call on the interface typed reference at runtime and allow
229 * the perversion of Object being assignable to an interface type (note, however, that we don't
230 * allow assignment of Object or Interface to any concrete class and are therefore type safe).
231 *
232 * [1] Java bytecode verifcation: algorithms and formalizations, Xavier Leroy
jeffhaobdb76512011-09-07 11:43:16 -0700233 */
Ian Rogersd81871c2011-10-03 13:57:23 -0700234 static Class* ClassJoin(Class* s, Class* t);
jeffhaoe23d93c2011-09-15 14:48:43 -0700235
236 private:
Ian Rogersd81871c2011-10-03 13:57:23 -0700237 friend class RegTypeCache;
238
Ian Rogers84fa0742011-10-25 18:13:30 -0700239 RegType(Type type, Object* klass_or_descriptor, uint32_t allocation_pc_or_constant, uint16_t cache_id) :
240 type_(type), klass_or_descriptor_(klass_or_descriptor), allocation_pc_or_constant_(allocation_pc_or_constant),
241 cache_id_(cache_id) {
242 DCHECK(IsConstant() || IsUninitializedReference() || allocation_pc_or_constant == 0);
243 if (!IsConstant() && !IsLongConstant() && !IsLongConstantHigh() && !IsUnknown() &&
244 !IsConflict()) {
245 DCHECK(klass_or_descriptor != NULL);
246 DCHECK(IsUnresolvedReference() || klass_or_descriptor_->IsClass());
247 DCHECK(!IsUnresolvedReference() || klass_or_descriptor_->IsString());
248 }
Ian Rogersd81871c2011-10-03 13:57:23 -0700249 }
250
251 const Type type_; // The current type of the register
252
Ian Rogers84fa0742011-10-25 18:13:30 -0700253 // If known the type of the register, else a String for the descriptor
254 Object* klass_or_descriptor_;
Ian Rogersd81871c2011-10-03 13:57:23 -0700255
Ian Rogers84fa0742011-10-25 18:13:30 -0700256 // Overloaded field that:
257 // - if IsConstant() holds a 32bit constant value
258 // - is IsReference() holds the allocation_pc or kInitArgAddr for an initialized reference or
259 // kUninitThisArgAddr for an uninitialized this ptr
260 const uint32_t allocation_pc_or_constant_;
Ian Rogersd81871c2011-10-03 13:57:23 -0700261
262 // A RegType cache densely encodes types, this is the location in the cache for this type
263 const uint16_t cache_id_;
264
Ian Rogersd81871c2011-10-03 13:57:23 -0700265 DISALLOW_COPY_AND_ASSIGN(RegType);
266};
267std::ostream& operator<<(std::ostream& os, const RegType& rhs);
268
269class RegTypeCache {
270 public:
Ian Rogers84fa0742011-10-25 18:13:30 -0700271 explicit RegTypeCache() : entries_(RegType::kRegTypeLastFixedLocation + 1) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700272 Unknown(); // ensure Unknown is initialized
273 }
274 ~RegTypeCache() {
275 STLDeleteElements(&entries_);
276 }
277
278 const RegType& GetFromId(uint16_t id) {
279 DCHECK_LT(id, entries_.size());
280 RegType* result = entries_[id];
281 DCHECK(result != NULL);
282 return *result;
283 }
284
285 const RegType& From(RegType::Type type, const ClassLoader* loader, const std::string& descriptor);
286 const RegType& FromClass(Class* klass);
287 const RegType& FromCat1Const(int32_t value);
288 const RegType& FromDescriptor(const ClassLoader* loader, const std::string& descriptor);
289 const RegType& FromType(RegType::Type);
290
291 const RegType& Boolean() { return FromType(RegType::kRegTypeBoolean); }
292 const RegType& Byte() { return FromType(RegType::kRegTypeByte); }
293 const RegType& Char() { return FromType(RegType::kRegTypeChar); }
294 const RegType& Short() { return FromType(RegType::kRegTypeShort); }
295 const RegType& Integer() { return FromType(RegType::kRegTypeInteger); }
296 const RegType& Float() { return FromType(RegType::kRegTypeFloat); }
297 const RegType& Long() { return FromType(RegType::kRegTypeLongLo); }
298 const RegType& Double() { return FromType(RegType::kRegTypeDoubleLo); }
299
300 const RegType& JavaLangClass() { return From(RegType::kRegTypeReference, NULL, "Ljava/lang/Class;"); }
301 const RegType& JavaLangObject() { return From(RegType::kRegTypeReference, NULL, "Ljava/lang/Object;"); }
302 const RegType& JavaLangString() { return From(RegType::kRegTypeReference, NULL, "Ljava/lang/String;"); }
303
304 const RegType& Unknown() { return FromType(RegType::kRegTypeUnknown); }
305 const RegType& Conflict() { return FromType(RegType::kRegTypeConflict); }
Ian Rogersd81871c2011-10-03 13:57:23 -0700306 const RegType& ConstLo() { return FromType(RegType::kRegTypeConstLo); }
Ian Rogers84fa0742011-10-25 18:13:30 -0700307 const RegType& Zero() { return FromCat1Const(0); }
Ian Rogersd81871c2011-10-03 13:57:23 -0700308
309 const RegType& Uninitialized(Class* klass, uint32_t allocation_pc);
310 const RegType& UninitializedThisArgument(Class* klass);
311
Ian Rogers84fa0742011-10-25 18:13:30 -0700312 // Representatives of various constant types. When merging constants we can't infer a type,
313 // (an int may later be used as a float) so we select these representative values meaning future
314 // merges won't know the exact constant value but have some notion of its size.
315 const RegType& ByteConstant() { return FromCat1Const(std::numeric_limits<jbyte>::min()); }
316 const RegType& ShortConstant() { return FromCat1Const(std::numeric_limits<jshort>::min()); }
317 const RegType& IntConstant() { return FromCat1Const(std::numeric_limits<jint>::max()); }
Ian Rogersd81871c2011-10-03 13:57:23 -0700318 private:
319 // The allocated entries
320 std::vector<RegType*> entries_;
321
322 DISALLOW_COPY_AND_ASSIGN(RegTypeCache);
323};
324
325class InsnFlags {
326 public:
327 InsnFlags() : length_(0), flags_(0) {}
328
329 void SetLengthInCodeUnits(size_t length) {
330 CHECK_LT(length, 65536u);
331 length_ = length;
332 }
333 size_t GetLengthInCodeUnits() {
334 return length_;
335 }
336 bool IsOpcode() const {
337 return length_ != 0;
338 }
339
340 void SetInTry() {
341 flags_ |= 1 << kInsnFlagInTry;
342 }
343 void ClearInTry() {
344 flags_ &= ~(1 << kInsnFlagInTry);
345 }
346 bool IsInTry() const {
347 return (flags_ & (1 << kInsnFlagInTry)) != 0;
348 }
349
350 void SetBranchTarget() {
351 flags_ |= 1 << kInsnFlagBranchTarget;
352 }
353 void ClearBranchTarget() {
354 flags_ &= ~(1 << kInsnFlagBranchTarget);
355 }
356 bool IsBranchTarget() const {
357 return (flags_ & (1 << kInsnFlagBranchTarget)) != 0;
358 }
359
360 void SetGcPoint() {
361 flags_ |= 1 << kInsnFlagGcPoint;
362 }
363 void ClearGcPoint() {
364 flags_ &= ~(1 << kInsnFlagGcPoint);
365 }
366 bool IsGcPoint() const {
367 return (flags_ & (1 << kInsnFlagGcPoint)) != 0;
368 }
369
370 void SetVisited() {
371 flags_ |= 1 << kInsnFlagVisited;
372 }
373 void ClearVisited() {
374 flags_ &= ~(1 << kInsnFlagVisited);
375 }
376 bool IsVisited() const {
377 return (flags_ & (1 << kInsnFlagVisited)) != 0;
378 }
379
380 void SetChanged() {
381 flags_ |= 1 << kInsnFlagChanged;
382 }
383 void ClearChanged() {
384 flags_ &= ~(1 << kInsnFlagChanged);
385 }
386 bool IsChanged() const {
387 return (flags_ & (1 << kInsnFlagChanged)) != 0;
388 }
389
390 bool IsVisitedOrChanged() const {
391 return IsVisited() || IsChanged();
392 }
393
Ian Rogers2c8a8572011-10-24 17:11:36 -0700394 std::string Dump() {
Ian Rogersd81871c2011-10-03 13:57:23 -0700395 char encoding[6];
396 if (!IsOpcode()) {
397 strncpy(encoding, "XXXXX", sizeof(encoding));
398 } else {
399 strncpy(encoding, "-----", sizeof(encoding));
400 if (IsInTry()) encoding[kInsnFlagInTry] = 'T';
401 if (IsBranchTarget()) encoding[kInsnFlagBranchTarget] = 'B';
402 if (IsGcPoint()) encoding[kInsnFlagGcPoint] = 'G';
403 if (IsVisited()) encoding[kInsnFlagVisited] = 'V';
404 if (IsChanged()) encoding[kInsnFlagChanged] = 'C';
405 }
Ian Rogers2c8a8572011-10-24 17:11:36 -0700406 return std::string(encoding);
Ian Rogersd81871c2011-10-03 13:57:23 -0700407 }
408 private:
409 enum InsnFlag {
410 kInsnFlagInTry,
411 kInsnFlagBranchTarget,
412 kInsnFlagGcPoint,
413 kInsnFlagVisited,
414 kInsnFlagChanged,
415 };
416
417 // Size of instruction in code units
418 uint16_t length_;
419 uint8_t flags_;
420};
421
422/*
423 * "Direct" and "virtual" methods are stored independently. The type of call used to invoke the
424 * method determines which list we search, and whether we travel up into superclasses.
425 *
426 * (<clinit>, <init>, and methods declared "private" or "static" are stored in the "direct" list.
427 * All others are stored in the "virtual" list.)
428 */
429enum MethodType {
430 METHOD_UNKNOWN = 0,
431 METHOD_DIRECT, // <init>, private
432 METHOD_STATIC, // static
433 METHOD_VIRTUAL, // virtual, super
434 METHOD_INTERFACE // interface
435};
436
437const int kRegTypeUninitMask = 0xff;
438const int kRegTypeUninitShift = 8;
439
440/*
441 * Register type categories, for type checking.
442 *
443 * The spec says category 1 includes boolean, byte, char, short, int, float, reference, and
444 * returnAddress. Category 2 includes long and double.
445 *
446 * We treat object references separately, so we have "category1nr". We don't support jsr/ret, so
447 * there is no "returnAddress" type.
448 */
449enum TypeCategory {
450 kTypeCategoryUnknown = 0,
451 kTypeCategory1nr = 1, // boolean, byte, char, short, int, float
452 kTypeCategory2 = 2, // long, double
453 kTypeCategoryRef = 3, // object reference
454};
455
456/*
457 * An enumeration of problems that can turn up during verification.
458 * VERIFY_ERROR_GENERIC denotes a failure that causes the entire class to be rejected. Other errors
459 * denote verification errors that cause bytecode to be rewritten to fail at runtime.
460 */
461enum VerifyError {
462 VERIFY_ERROR_NONE = 0, /* no error; must be zero */
463 VERIFY_ERROR_GENERIC, /* VerifyError */
464
465 VERIFY_ERROR_NO_CLASS, /* NoClassDefFoundError */
466 VERIFY_ERROR_NO_FIELD, /* NoSuchFieldError */
467 VERIFY_ERROR_NO_METHOD, /* NoSuchMethodError */
468 VERIFY_ERROR_ACCESS_CLASS, /* IllegalAccessError */
469 VERIFY_ERROR_ACCESS_FIELD, /* IllegalAccessError */
470 VERIFY_ERROR_ACCESS_METHOD, /* IllegalAccessError */
471 VERIFY_ERROR_CLASS_CHANGE, /* IncompatibleClassChangeError */
472 VERIFY_ERROR_INSTANTIATION, /* InstantiationError */
473};
474std::ostream& operator<<(std::ostream& os, const VerifyError& rhs);
475
476/*
477 * Identifies the type of reference in the instruction that generated the verify error
478 * (e.g. VERIFY_ERROR_ACCESS_CLASS could come from a method, field, or class reference).
479 *
480 * This must fit in two bits.
481 */
482enum VerifyErrorRefType {
483 VERIFY_ERROR_REF_CLASS = 0,
484 VERIFY_ERROR_REF_FIELD = 1,
485 VERIFY_ERROR_REF_METHOD = 2,
486};
487const int kVerifyErrorRefTypeShift = 6;
488
489/*
490 * Format enumeration for RegisterMap data area.
491 */
492enum RegisterMapFormat {
493 kRegMapFormatUnknown = 0,
494 kRegMapFormatNone, /* indicates no map data follows */
495 kRegMapFormatCompact8, /* compact layout, 8-bit addresses */
496 kRegMapFormatCompact16, /* compact layout, 16-bit addresses */
497};
498
499// During verification, we associate one of these with every "interesting" instruction. We track
500// the status of all registers, and (if the method has any monitor-enter instructions) maintain a
501// stack of entered monitors (identified by code unit offset).
502// If live-precise register maps are enabled, the "liveRegs" vector will be populated. Unlike the
503// other lists of registers here, we do not track the liveness of the method result register
504// (which is not visible to the GC).
505class RegisterLine {
506 public:
507 RegisterLine(size_t num_regs, DexVerifier* verifier) :
508 line_(new uint16_t[num_regs]), verifier_(verifier), num_regs_(num_regs) {
509 memset(line_.get(), 0, num_regs_ * sizeof(uint16_t));
510 result_[0] = RegType::kRegTypeUnknown;
511 result_[1] = RegType::kRegTypeUnknown;
512 }
513
514 // Implement category-1 "move" instructions. Copy a 32-bit value from "vsrc" to "vdst".
515 void CopyRegister1(uint32_t vdst, uint32_t vsrc, TypeCategory cat);
516
517 // Implement category-2 "move" instructions. Copy a 64-bit value from "vsrc" to "vdst". This
518 // copies both halves of the register.
519 void CopyRegister2(uint32_t vdst, uint32_t vsrc);
520
521 // Implement "move-result". Copy the category-1 value from the result register to another
522 // register, and reset the result register.
523 void CopyResultRegister1(uint32_t vdst, bool is_reference);
524
525 // Implement "move-result-wide". Copy the category-2 value from the result register to another
526 // register, and reset the result register.
527 void CopyResultRegister2(uint32_t vdst);
528
529 // Set the invisible result register to unknown
530 void SetResultTypeToUnknown();
531
532 // Set the type of register N, verifying that the register is valid. If "newType" is the "Lo"
533 // part of a 64-bit value, register N+1 will be set to "newType+1".
534 // The register index was validated during the static pass, so we don't need to check it here.
535 void SetRegisterType(uint32_t vdst, const RegType& new_type);
536
537 /* Set the type of the "result" register. */
538 void SetResultRegisterType(const RegType& new_type);
539
540 // Get the type of register vsrc.
541 const RegType& GetRegisterType(uint32_t vsrc) const;
542
543 bool VerifyRegisterType(uint32_t vsrc, const RegType& check_type);
544
545 void CopyFromLine(const RegisterLine* src) {
546 DCHECK_EQ(num_regs_, src->num_regs_);
547 memcpy(line_.get(), src->line_.get(), num_regs_ * sizeof(uint16_t));
548 monitors_ = src->monitors_;
549 reg_to_lock_depths_ = src->reg_to_lock_depths_;
550 }
551
Ian Rogers2c8a8572011-10-24 17:11:36 -0700552 std::string Dump() const {
553 std::string result;
Ian Rogersd81871c2011-10-03 13:57:23 -0700554 for (size_t i = 0; i < num_regs_; i++) {
Ian Rogers84fa0742011-10-25 18:13:30 -0700555 result += StringPrintf("%d:[", i);
Ian Rogers2c8a8572011-10-24 17:11:36 -0700556 result += GetRegisterType(i).Dump();
Ian Rogers84fa0742011-10-25 18:13:30 -0700557 result += "],";
Ian Rogersd81871c2011-10-03 13:57:23 -0700558 }
Ian Rogers2c8a8572011-10-24 17:11:36 -0700559 return result;
Ian Rogersd81871c2011-10-03 13:57:23 -0700560 }
561
562 void FillWithGarbage() {
563 memset(line_.get(), 0xf1, num_regs_ * sizeof(uint16_t));
564 while (!monitors_.empty()) {
565 monitors_.pop();
566 }
567 reg_to_lock_depths_.clear();
568 }
569
570 /*
571 * We're creating a new instance of class C at address A. Any registers holding instances
572 * previously created at address A must be initialized by now. If not, we mark them as "conflict"
573 * to prevent them from being used (otherwise, MarkRefsAsInitialized would mark the old ones and
574 * the new ones at the same time).
575 */
576 void MarkUninitRefsAsInvalid(const RegType& uninit_type);
577
578 /*
579 * Update all registers holding "uninit_type" to instead hold the corresponding initialized
580 * reference type. This is called when an appropriate constructor is invoked -- all copies of
581 * the reference must be marked as initialized.
582 */
583 void MarkRefsAsInitialized(const RegType& uninit_type);
584
585 /*
586 * Check constraints on constructor return. Specifically, make sure that the "this" argument got
587 * initialized.
588 * The "this" argument to <init> uses code offset kUninitThisArgAddr, which puts it at the start
589 * of the list in slot 0. If we see a register with an uninitialized slot 0 reference, we know it
590 * somehow didn't get initialized.
591 */
592 bool CheckConstructorReturn() const;
593
594 // Compare two register lines. Returns 0 if they match.
595 // Using this for a sort is unwise, since the value can change based on machine endianness.
596 int CompareLine(const RegisterLine* line2) const {
597 DCHECK(monitors_ == line2->monitors_);
598 // TODO: DCHECK(reg_to_lock_depths_ == line2->reg_to_lock_depths_);
599 return memcmp(line_.get(), line2->line_.get(), num_regs_ * sizeof(uint16_t));
600 }
601
602 size_t NumRegs() const {
603 return num_regs_;
604 }
605
606 /*
607 * Get the "this" pointer from a non-static method invocation. This returns the RegType so the
608 * caller can decide whether it needs the reference to be initialized or not. (Can also return
609 * kRegTypeZero if the reference can only be zero at this point.)
610 *
611 * The argument count is in vA, and the first argument is in vC, for both "simple" and "range"
612 * versions. We just need to make sure vA is >= 1 and then return vC.
613 */
614 const RegType& GetInvocationThis(const Instruction::DecodedInstruction& dec_insn);
615
616 /*
617 * Get the value from a register, and cast it to a Class. Sets "*failure" if something fails.
618 * This fails if the register holds an uninitialized class.
619 * If the register holds kRegTypeZero, this returns a NULL pointer.
620 */
621 Class* GetClassFromRegister(uint32_t vsrc) const;
622
623 /*
624 * Verify types for a simple two-register instruction (e.g. "neg-int").
625 * "dst_type" is stored into vA, and "src_type" is verified against vB.
626 */
627 void CheckUnaryOp(const Instruction::DecodedInstruction& dec_insn,
628 const RegType& dst_type, const RegType& src_type);
629
630 /*
631 * Verify types for a simple three-register instruction (e.g. "add-int").
632 * "dst_type" is stored into vA, and "src_type1"/"src_type2" are verified
633 * against vB/vC.
634 */
635 void CheckBinaryOp(const Instruction::DecodedInstruction& dec_insn,
636 const RegType& dst_type, const RegType& src_type1, const RegType& src_type2,
637 bool check_boolean_op);
638
639 /*
640 * Verify types for a binary "2addr" operation. "src_type1"/"src_type2"
641 * are verified against vA/vB, then "dst_type" is stored into vA.
642 */
643 void CheckBinaryOp2addr(const Instruction::DecodedInstruction& dec_insn,
644 const RegType& dst_type,
645 const RegType& src_type1, const RegType& src_type2,
646 bool check_boolean_op);
647
648 /*
649 * Verify types for A two-register instruction with a literal constant (e.g. "add-int/lit8").
650 * "dst_type" is stored into vA, and "src_type" is verified against vB.
651 *
652 * If "check_boolean_op" is set, we use the constant value in vC.
653 */
654 void CheckLiteralOp(const Instruction::DecodedInstruction& dec_insn,
655 const RegType& dst_type, const RegType& src_type, bool check_boolean_op);
656
657 // Verify/push monitor onto the monitor stack, locking the value in reg_idx at location insn_idx.
658 void PushMonitor(uint32_t reg_idx, int32_t insn_idx);
659
660 // Verify/pop monitor from monitor stack ensuring that we believe the monitor is locked
661 void PopMonitor(uint32_t reg_idx);
662
663 // Stack of currently held monitors and where they were locked
664 size_t MonitorStackDepth() const {
665 return monitors_.size();
666 }
667
668 // We expect no monitors to be held at certain points, such a method returns. Verify the stack
669 // is empty, failing and returning false if not.
670 bool VerifyMonitorStackEmpty();
671
672 bool MergeRegisters(const RegisterLine* incoming_line);
673
Ian Rogers84fa0742011-10-25 18:13:30 -0700674 size_t GetMaxNonZeroReferenceReg(size_t max_ref_reg) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700675 size_t i = static_cast<int>(max_ref_reg) < 0 ? 0 : max_ref_reg;
676 for(; i < num_regs_; i++) {
Ian Rogers84fa0742011-10-25 18:13:30 -0700677 if (GetRegisterType(i).IsNonZeroReferenceTypes()) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700678 max_ref_reg = i;
679 }
680 }
681 return max_ref_reg;
682 }
683
684 // Write a bit at each register location that holds a reference
685 void WriteReferenceBitMap(int8_t* data, size_t max_bytes);
686 private:
687
688 void CopyRegToLockDepth(size_t dst, size_t src) {
689 if (reg_to_lock_depths_.count(src) > 0) {
690 uint32_t depths = reg_to_lock_depths_[src];
691 reg_to_lock_depths_[dst] = depths;
692 }
693 }
694
695 bool IsSetLockDepth(size_t reg, size_t depth) {
696 if (reg_to_lock_depths_.count(reg) > 0) {
697 uint32_t depths = reg_to_lock_depths_[reg];
698 return (depths & (1 << depth)) != 0;
699 } else {
700 return false;
701 }
702 }
703
704 void SetRegToLockDepth(size_t reg, size_t depth) {
705 CHECK_LT(depth, 32u);
706 DCHECK(!IsSetLockDepth(reg, depth));
707 uint32_t depths;
708 if (reg_to_lock_depths_.count(reg) > 0) {
709 depths = reg_to_lock_depths_[reg];
710 depths = depths | (1 << depth);
711 } else {
712 depths = 1 << depth;
713 }
714 reg_to_lock_depths_[reg] = depths;
715 }
716
717 void ClearRegToLockDepth(size_t reg, size_t depth) {
718 CHECK_LT(depth, 32u);
719 DCHECK(IsSetLockDepth(reg, depth));
720 uint32_t depths = reg_to_lock_depths_[reg];
721 depths = depths ^ (1 << depth);
722 if (depths != 0) {
723 reg_to_lock_depths_[reg] = depths;
724 } else {
725 reg_to_lock_depths_.erase(reg);
726 }
727 }
728
729 void ClearAllRegToLockDepths(size_t reg) {
730 reg_to_lock_depths_.erase(reg);
731 }
732
733 // Storage for the result register's type, valid after an invocation
734 uint16_t result_[2];
735
736 // An array of RegType Ids associated with each dex register
737 UniquePtr<uint16_t[]> line_;
738
739 // Back link to the verifier
740 DexVerifier* verifier_;
741
742 // Length of reg_types_
743 const size_t num_regs_;
744 // A stack of monitor enter locations
745 std::stack<uint32_t> monitors_;
746 // A map from register to a bit vector of indices into the monitors_ stack. As we pop the monitor
747 // stack we verify that monitor-enter/exit are correctly nested. That is, if there was a
748 // monitor-enter on v5 and then on v6, we expect the monitor-exit to be on v6 then on v5
749 std::map<uint32_t, uint32_t> reg_to_lock_depths_;
750};
751std::ostream& operator<<(std::ostream& os, const RegisterLine& rhs);
752
753class PcToRegisterLineTable {
754 public:
755 // We don't need to store the register data for many instructions, because we either only need
756 // it at branch points (for verification) or GC points and branches (for verification +
757 // type-precise register analysis).
758 enum RegisterTrackingMode {
759 kTrackRegsBranches,
760 kTrackRegsGcPoints,
761 kTrackRegsAll,
762 };
763 PcToRegisterLineTable() {}
764 ~PcToRegisterLineTable() {
765 STLDeleteValues(&pc_to_register_line_);
766 }
767
768 // Initialize the RegisterTable. Every instruction address can have a different set of information
769 // about what's in which register, but for verification purposes we only need to store it at
770 // branch target addresses (because we merge into that).
771 void Init(RegisterTrackingMode mode, InsnFlags* flags, uint32_t insns_size,
772 uint16_t registers_size, DexVerifier* verifier);
773
774 RegisterLine* GetLine(size_t idx) {
775 return pc_to_register_line_[idx];
776 }
777
778 private:
779 // Map from a dex pc to the register status associated with it
780 std::map<int32_t, RegisterLine*> pc_to_register_line_;
781
782 // Number of registers we track for each instruction. This is equal to the method's declared
783 // "registersSize" plus kExtraRegs (2).
784 size_t insn_reg_count_plus_;
785};
786
787
788
789// The verifier
790class DexVerifier {
791 public:
792 /* Verify a class. Returns "true" on success. */
793 static bool VerifyClass(const Class* klass);
jeffhaobdb76512011-09-07 11:43:16 -0700794 /*
795 * Perform verification on a single method.
796 *
797 * We do this in three passes:
798 * (1) Walk through all code units, determining instruction locations,
799 * widths, and other characteristics.
800 * (2) Walk through all code units, performing static checks on
801 * operands.
802 * (3) Iterate through the method, checking type safety and looking
803 * for code flow problems.
804 *
jeffhaod1f0fde2011-09-08 17:25:33 -0700805 * Some checks may be bypassed depending on the verification mode. We can't
jeffhaobdb76512011-09-07 11:43:16 -0700806 * turn this stuff off completely if we want to do "exact" GC.
807 *
808 * Confirmed here:
809 * - code array must not be empty
810 * Confirmed by ComputeWidthsAndCountOps():
811 * - opcode of first instruction begins at index 0
812 * - only documented instructions may appear
813 * - each instruction follows the last
814 * - last byte of last instruction is at (code_length-1)
815 */
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700816 static bool VerifyMethod(Method* method);
Shih-wei Liao371814f2011-10-27 16:52:10 -0700817 static void VerifyMethodAndDump(Method* method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700818
Ian Rogersd81871c2011-10-03 13:57:23 -0700819 uint8_t EncodePcToReferenceMapData() const;
820
821 uint32_t DexFileVersion() const {
822 return dex_file_->GetVersion();
823 }
824
825 RegTypeCache* GetRegTypeCache() {
826 return &reg_types_;
827 }
828
829 // Verification failed
830 std::ostream& Fail(VerifyError error) {
831 CHECK_EQ(failure_, VERIFY_ERROR_NONE);
832 failure_ = error;
833 return fail_messages_ << "VFY: " << PrettyMethod(method_)
834 << '[' << (void*)work_insn_idx_ << "] : ";
835 }
836
837 // Log for verification information
838 std::ostream& LogVerifyInfo() {
839 return info_messages_ << "VFY: " << PrettyMethod(method_)
840 << '[' << (void*)work_insn_idx_ << "] : ";
841 }
842
843 // Dump the state of the verifier, namely each instruction, what flags are set on it, register
844 // information
845 void Dump(std::ostream& os);
846
847 private:
848
849 explicit DexVerifier(Method* method);
850
851 bool Verify();
852
853 /*
854 * Compute the width of the instruction at each address in the instruction stream, and store it in
855 * insn_flags_. Addresses that are in the middle of an instruction, or that are part of switch
856 * table data, are not touched (so the caller should probably initialize "insn_flags" to zero).
857 *
858 * The "new_instance_count_" and "monitor_enter_count_" fields in vdata are also set.
859 *
860 * Performs some static checks, notably:
861 * - opcode of first instruction begins at index 0
862 * - only documented instructions may appear
863 * - each instruction follows the last
864 * - last byte of last instruction is at (code_length-1)
865 *
866 * Logs an error and returns "false" on failure.
867 */
868 bool ComputeWidthsAndCountOps();
869
870 /*
871 * Set the "in try" flags for all instructions protected by "try" statements. Also sets the
872 * "branch target" flags for exception handlers.
873 *
874 * Call this after widths have been set in "insn_flags".
875 *
876 * Returns "false" if something in the exception table looks fishy, but we're expecting the
877 * exception table to be somewhat sane.
878 */
879 bool ScanTryCatchBlocks();
880
jeffhaobdb76512011-09-07 11:43:16 -0700881 /*
882 * Perform static verification on all instructions in a method.
883 *
884 * Walks through instructions in a method calling VerifyInstruction on each.
885 */
Ian Rogersd81871c2011-10-03 13:57:23 -0700886 bool VerifyInstructions();
jeffhaobdb76512011-09-07 11:43:16 -0700887
888 /*
889 * Perform static verification on an instruction.
890 *
891 * As a side effect, this sets the "branch target" flags in InsnFlags.
892 *
893 * "(CF)" items are handled during code-flow analysis.
894 *
895 * v3 4.10.1
896 * - target of each jump and branch instruction must be valid
897 * - targets of switch statements must be valid
898 * - operands referencing constant pool entries must be valid
899 * - (CF) operands of getfield, putfield, getstatic, putstatic must be valid
900 * - (CF) operands of method invocation instructions must be valid
901 * - (CF) only invoke-direct can call a method starting with '<'
902 * - (CF) <clinit> must never be called explicitly
903 * - operands of instanceof, checkcast, new (and variants) must be valid
904 * - new-array[-type] limited to 255 dimensions
905 * - can't use "new" on an array class
906 * - (?) limit dimensions in multi-array creation
907 * - local variable load/store register values must be in valid range
908 *
909 * v3 4.11.1.2
910 * - branches must be within the bounds of the code array
911 * - targets of all control-flow instructions are the start of an instruction
912 * - register accesses fall within range of allocated registers
913 * - (N/A) access to constant pool must be of appropriate type
914 * - code does not end in the middle of an instruction
915 * - execution cannot fall off the end of the code
916 * - (earlier) for each exception handler, the "try" area must begin and
917 * end at the start of an instruction (end can be at the end of the code)
918 * - (earlier) for each exception handler, the handler must start at a valid
919 * instruction
920 */
Ian Rogersd81871c2011-10-03 13:57:23 -0700921 bool VerifyInstruction(const Instruction* inst, uint32_t code_offset);
jeffhaobdb76512011-09-07 11:43:16 -0700922
923 /* Ensure that the register index is valid for this code item. */
Ian Rogersd81871c2011-10-03 13:57:23 -0700924 bool CheckRegisterIndex(uint32_t idx);
jeffhaobdb76512011-09-07 11:43:16 -0700925
926 /* Ensure that the wide register index is valid for this code item. */
Ian Rogersd81871c2011-10-03 13:57:23 -0700927 bool CheckWideRegisterIndex(uint32_t idx);
jeffhaobdb76512011-09-07 11:43:16 -0700928
Ian Rogersd81871c2011-10-03 13:57:23 -0700929 // Perform static checks on a field get or set instruction. All we do here is ensure that the
930 // field index is in the valid range.
931 bool CheckFieldIndex(uint32_t idx);
jeffhaobdb76512011-09-07 11:43:16 -0700932
Ian Rogersd81871c2011-10-03 13:57:23 -0700933 // Perform static checks on a method invocation instruction. All we do here is ensure that the
934 // method index is in the valid range.
935 bool CheckMethodIndex(uint32_t idx);
jeffhaobdb76512011-09-07 11:43:16 -0700936
Ian Rogersd81871c2011-10-03 13:57:23 -0700937 // Perform static checks on a "new-instance" instruction. Specifically, make sure the class
938 // reference isn't for an array class.
939 bool CheckNewInstance(uint32_t idx);
jeffhaobdb76512011-09-07 11:43:16 -0700940
Ian Rogersd81871c2011-10-03 13:57:23 -0700941 /* Ensure that the string index is in the valid range. */
942 bool CheckStringIndex(uint32_t idx);
jeffhaobdb76512011-09-07 11:43:16 -0700943
Ian Rogersd81871c2011-10-03 13:57:23 -0700944 // Perform static checks on an instruction that takes a class constant. Ensure that the class
945 // index is in the valid range.
946 bool CheckTypeIndex(uint32_t idx);
jeffhaobdb76512011-09-07 11:43:16 -0700947
Ian Rogersd81871c2011-10-03 13:57:23 -0700948 // Perform static checks on a "new-array" instruction. Specifically, make sure they aren't
949 // creating an array of arrays that causes the number of dimensions to exceed 255.
950 bool CheckNewArray(uint32_t idx);
jeffhaobdb76512011-09-07 11:43:16 -0700951
Ian Rogersd81871c2011-10-03 13:57:23 -0700952 // Verify an array data table. "cur_offset" is the offset of the fill-array-data instruction.
953 bool CheckArrayData(uint32_t cur_offset);
jeffhaobdb76512011-09-07 11:43:16 -0700954
Ian Rogersd81871c2011-10-03 13:57:23 -0700955 // Verify that the target of a branch instruction is valid. We don't expect code to jump directly
956 // into an exception handler, but it's valid to do so as long as the target isn't a
957 // "move-exception" instruction. We verify that in a later stage.
958 // The dex format forbids certain instructions from branching to themselves.
959 // Updates "insnFlags", setting the "branch target" flag.
960 bool CheckBranchTarget(uint32_t cur_offset);
jeffhaobdb76512011-09-07 11:43:16 -0700961
Ian Rogersd81871c2011-10-03 13:57:23 -0700962 // Verify a switch table. "cur_offset" is the offset of the switch instruction.
963 // Updates "insnFlags", setting the "branch target" flag.
964 bool CheckSwitchTargets(uint32_t cur_offset);
jeffhaobdb76512011-09-07 11:43:16 -0700965
Ian Rogersd81871c2011-10-03 13:57:23 -0700966 // Check the register indices used in a "vararg" instruction, such as invoke-virtual or
967 // filled-new-array.
968 // - vA holds word count (0-5), args[] have values.
969 // There are some tests we don't do here, e.g. we don't try to verify that invoking a method that
970 // takes a double is done with consecutive registers. This requires parsing the target method
971 // signature, which we will be doing later on during the code flow analysis.
972 bool CheckVarArgRegs(uint32_t vA, uint32_t arg[]);
jeffhaobdb76512011-09-07 11:43:16 -0700973
Ian Rogersd81871c2011-10-03 13:57:23 -0700974 // Check the register indices used in a "vararg/range" instruction, such as invoke-virtual/range
975 // or filled-new-array/range.
976 // - vA holds word count, vC holds index of first reg.
977 bool CheckVarArgRangeRegs(uint32_t vA, uint32_t vC);
jeffhaobdb76512011-09-07 11:43:16 -0700978
Ian Rogersd81871c2011-10-03 13:57:23 -0700979 // Extract the relative offset from a branch instruction.
980 // Returns "false" on failure (e.g. this isn't a branch instruction).
981 bool GetBranchOffset(uint32_t cur_offset, int32_t* pOffset, bool* pConditional,
982 bool* selfOkay);
jeffhaobdb76512011-09-07 11:43:16 -0700983
Ian Rogersd81871c2011-10-03 13:57:23 -0700984 /* Perform detailed code-flow analysis on a single method. */
985 bool VerifyCodeFlow();
jeffhaobdb76512011-09-07 11:43:16 -0700986
Ian Rogersd81871c2011-10-03 13:57:23 -0700987 // Set the register types for the first instruction in the method based on the method signature.
988 // This has the side-effect of validating the signature.
989 bool SetTypesFromSignature();
jeffhaobdb76512011-09-07 11:43:16 -0700990
991 /*
992 * Perform code flow on a method.
993 *
Ian Rogersd81871c2011-10-03 13:57:23 -0700994 * The basic strategy is as outlined in v3 4.11.1.2: set the "changed" bit on the first
995 * instruction, process it (setting additional "changed" bits), and repeat until there are no
996 * more.
jeffhaobdb76512011-09-07 11:43:16 -0700997 *
998 * v3 4.11.1.1
999 * - (N/A) operand stack is always the same size
1000 * - operand stack [registers] contain the correct types of values
1001 * - local variables [registers] contain the correct types of values
1002 * - methods are invoked with the appropriate arguments
1003 * - fields are assigned using values of appropriate types
1004 * - opcodes have the correct type values in operand registers
Ian Rogersd81871c2011-10-03 13:57:23 -07001005 * - there is never an uninitialized class instance in a local variable in code protected by an
1006 * exception handler (operand stack is okay, because the operand stack is discarded when an
1007 * 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 -07001008 * register typing]
1009 *
1010 * v3 4.11.1.2
1011 * - execution cannot fall off the end of the code
1012 *
Ian Rogersd81871c2011-10-03 13:57:23 -07001013 * (We also do many of the items described in the "static checks" sections, because it's easier to
1014 * do them here.)
jeffhaobdb76512011-09-07 11:43:16 -07001015 *
Ian Rogersd81871c2011-10-03 13:57:23 -07001016 * We need an array of RegType values, one per register, for every instruction. If the method uses
1017 * monitor-enter, we need extra data for every register, and a stack for every "interesting"
1018 * instruction. In theory this could become quite large -- up to several megabytes for a monster
1019 * function.
jeffhaobdb76512011-09-07 11:43:16 -07001020 *
1021 * NOTE:
Ian Rogersd81871c2011-10-03 13:57:23 -07001022 * The spec forbids backward branches when there's an uninitialized reference in a register. The
1023 * idea is to prevent something like this:
jeffhaobdb76512011-09-07 11:43:16 -07001024 * loop:
1025 * move r1, r0
1026 * new-instance r0, MyClass
1027 * ...
1028 * if-eq rN, loop // once
1029 * initialize r0
1030 *
Ian Rogersd81871c2011-10-03 13:57:23 -07001031 * This leaves us with two different instances, both allocated by the same instruction, but only
1032 * one is initialized. The scheme outlined in v3 4.11.1.4 wouldn't catch this, so they work around
1033 * it by preventing backward branches. We achieve identical results without restricting code
1034 * reordering by specifying that you can't execute the new-instance instruction if a register
1035 * contains an uninitialized instance created by that same instruction.
jeffhaobdb76512011-09-07 11:43:16 -07001036 */
Ian Rogersd81871c2011-10-03 13:57:23 -07001037 bool CodeFlowVerifyMethod();
jeffhaobdb76512011-09-07 11:43:16 -07001038
1039 /*
1040 * Perform verification for a single instruction.
1041 *
Ian Rogersd81871c2011-10-03 13:57:23 -07001042 * This requires fully decoding the instruction to determine the effect it has on registers.
jeffhaobdb76512011-09-07 11:43:16 -07001043 *
Ian Rogersd81871c2011-10-03 13:57:23 -07001044 * Finds zero or more following instructions and sets the "changed" flag if execution at that
1045 * point needs to be (re-)evaluated. Register changes are merged into "reg_types_" at the target
1046 * addresses. Does not set or clear any other flags in "insn_flags_".
jeffhaobdb76512011-09-07 11:43:16 -07001047 */
Ian Rogersd81871c2011-10-03 13:57:23 -07001048 bool CodeFlowVerifyInstruction(uint32_t* start_guess);
1049
1050 // Perform verification of an aget instruction. The destination register's type will be set to
1051 // be that of component type of the array unless the array type is unknown, in which case a
1052 // bottom type inferred from the type of instruction is used. is_primitive is false for an
1053 // aget-object.
1054 void VerifyAGet(const Instruction::DecodedInstruction& insn, const RegType& insn_type,
1055 bool is_primitive);
1056
1057 // Perform verification of an aput instruction.
1058 void VerifyAPut(const Instruction::DecodedInstruction& insn, const RegType& insn_type,
1059 bool is_primitive);
1060
1061 // Lookup instance field and fail for resolution violations
1062 Field* GetInstanceField(const RegType& obj_type, int field_idx);
1063
Ian Rogersd81871c2011-10-03 13:57:23 -07001064 // Lookup static field and fail for resolution violations
1065 Field* GetStaticField(int field_idx);
1066
Ian Rogersb94a27b2011-10-26 00:33:41 -07001067 // Perform verification of an iget or sget instruction.
1068 void VerifyISGet(const Instruction::DecodedInstruction& insn, const RegType& insn_type,
1069 bool is_primitive, bool is_static);
Ian Rogersd81871c2011-10-03 13:57:23 -07001070
Ian Rogersb94a27b2011-10-26 00:33:41 -07001071 // Perform verification of an iput or sput instruction.
1072 void VerifyISPut(const Instruction::DecodedInstruction& insn, const RegType& insn_type,
1073 bool is_primitive, bool is_static);
Ian Rogersd81871c2011-10-03 13:57:23 -07001074
1075 // Verify that the arguments in a filled-new-array instruction are valid.
1076 // "res_class" is the class refered to by dec_insn->vB_.
1077 void VerifyFilledNewArrayRegs(const Instruction::DecodedInstruction& dec_insn, Class* res_class,
1078 bool is_range);
jeffhaobdb76512011-09-07 11:43:16 -07001079
1080 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07001081 * Resolves a class based on an index and performs access checks to ensure the referrer can
1082 * access the resolved class.
jeffhao98eacac2011-09-14 16:11:53 -07001083 * Exceptions caused by failures are cleared before returning.
jeffhao98eacac2011-09-14 16:11:53 -07001084 * Sets "*failure" on failure.
1085 */
Ian Rogersd81871c2011-10-03 13:57:23 -07001086 Class* ResolveClassAndCheckAccess(uint32_t class_idx);
1087
1088 /*
1089 * For the "move-exception" instruction at "work_insn_idx_", which must be at an exception handler
1090 * address, determine the first common superclass of all exceptions that can land here.
1091 * Returns NULL if no matching exception handler can be found, or if the exception is not a
1092 * subclass of Throwable.
1093 */
1094 Class* GetCaughtExceptionType();
jeffhao98eacac2011-09-14 16:11:53 -07001095
1096 /*
jeffhaob4df5142011-09-19 20:25:32 -07001097 * Resolves a method based on an index and performs access checks to ensure
1098 * the referrer can access the resolved method.
jeffhaob4df5142011-09-19 20:25:32 -07001099 * Does not throw exceptions.
jeffhaob4df5142011-09-19 20:25:32 -07001100 */
Ian Rogersd81871c2011-10-03 13:57:23 -07001101 Method* ResolveMethodAndCheckAccess(uint32_t method_idx, bool is_direct);
jeffhaobdb76512011-09-07 11:43:16 -07001102
1103 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001104 * Verify the arguments to a method. We're executing in "method", making
jeffhaobdb76512011-09-07 11:43:16 -07001105 * a call to the method reference in vB.
1106 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001107 * If this is a "direct" invoke, we allow calls to <init>. For calls to
1108 * <init>, the first argument may be an uninitialized reference. Otherwise,
jeffhaobdb76512011-09-07 11:43:16 -07001109 * calls to anything starting with '<' will be rejected, as will any
1110 * uninitialized reference arguments.
1111 *
1112 * For non-static method calls, this will verify that the method call is
1113 * appropriate for the "this" argument.
1114 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001115 * The method reference is in vBBBB. The "is_range" parameter determines
jeffhaobdb76512011-09-07 11:43:16 -07001116 * whether we use 0-4 "args" values or a range of registers defined by
1117 * vAA and vCCCC.
1118 *
1119 * Widening conversions on integers and references are allowed, but
1120 * narrowing conversions are not.
1121 *
1122 * Returns the resolved method on success, NULL on failure (with *failure
1123 * set appropriately).
1124 */
Ian Rogersd81871c2011-10-03 13:57:23 -07001125 Method* VerifyInvocationArgs(const Instruction::DecodedInstruction& dec_insn,
1126 MethodType method_type, bool is_range, bool is_super);
jeffhaobdb76512011-09-07 11:43:16 -07001127
Ian Rogersd81871c2011-10-03 13:57:23 -07001128 /*
1129 * Return the register type for the method. We can't just use the already-computed
1130 * DalvikJniReturnType, because if it's a reference type we need to do the class lookup.
1131 * Returned references are assumed to be initialized. Returns kRegTypeUnknown for "void".
1132 */
1133 const RegType& GetMethodReturnType() {
Ian Rogers9074b992011-10-26 17:41:55 -07001134 return reg_types_.FromDescriptor(method_->GetDeclaringClass()->GetClassLoader(),
1135 method_->GetReturnTypeDescriptor());
Ian Rogersd81871c2011-10-03 13:57:23 -07001136 }
jeffhaoe0cfb6f2011-09-22 16:42:56 -07001137
Ian Rogersd81871c2011-10-03 13:57:23 -07001138 /*
1139 * Verify that the target instruction is not "move-exception". It's important that the only way
1140 * to execute a move-exception is as the first instruction of an exception handler.
1141 * Returns "true" if all is well, "false" if the target instruction is move-exception.
1142 */
1143 bool CheckMoveException(const uint16_t* insns, int insn_idx);
1144
1145 /*
1146 * Replace an instruction with "throw-verification-error". This allows us to
1147 * defer error reporting until the code path is first used.
1148 */
1149 void ReplaceFailingInstruction();
1150
1151 /*
1152 * Control can transfer to "next_insn". Merge the registers from merge_line into the table at
1153 * next_insn, and set the changed flag on the target address if any of the registers were changed.
1154 * Returns "false" if an error is encountered.
1155 */
1156 bool UpdateRegisters(uint32_t next_insn, const RegisterLine* merge_line);
1157
1158 /*
1159 * Generate the GC map for a method that has just been verified (i.e. we're doing this as part of
1160 * verification). For type-precise determination we have all the data we need, so we just need to
1161 * encode it in some clever fashion.
1162 * Returns a pointer to a newly-allocated RegisterMap, or NULL on failure.
1163 */
1164 ByteArray* GenerateGcMap();
1165
1166 // Verify that the GC map associated with method_ is well formed
1167 void VerifyGcMap();
1168
1169 // Compute sizes for GC map data
1170 void ComputeGcMapSizes(size_t* gc_points, size_t* ref_bitmap_bits, size_t* log2_max_gc_pc);
1171
1172 Class* JavaLangThrowable();
1173
1174 InsnFlags CurrentInsnFlags() {
1175 return insn_flags_[work_insn_idx_];
1176 }
1177
1178 RegTypeCache reg_types_;
1179
1180 PcToRegisterLineTable reg_table_;
1181
1182 // Storage for the register status we're currently working on.
1183 UniquePtr<RegisterLine> work_line_;
1184
1185 // Lazily initialized reference to java.lang.Class<java.lang.Throwable>
1186 Class* java_lang_throwable_;
1187
1188 // The address of the instruction we're currently working on, note that this is in 2 byte
1189 // quantities
1190 uint32_t work_insn_idx_;
1191
1192 // Storage for the register status we're saving for later.
1193 UniquePtr<RegisterLine> saved_line_;
1194
1195 Method* method_; // The method we're working on.
1196 const DexFile* dex_file_; // The dex file containing the method.
1197 const DexFile::CodeItem* code_item_; // The code item containing the code for the method.
1198 UniquePtr<InsnFlags[]> insn_flags_; // Instruction widths and flags, one entry per code unit.
1199
1200 // The type of any error that occurs
1201 VerifyError failure_;
1202
1203 // Failure message log
1204 std::ostringstream fail_messages_;
1205 // Info message log
1206 std::ostringstream info_messages_;
1207
1208 // The number of occurrences of specific opcodes.
1209 size_t new_instance_count_;
1210 size_t monitor_enter_count_;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001211};
1212
Ian Rogersd81871c2011-10-03 13:57:23 -07001213// Lightweight wrapper for PC to reference bit maps.
1214class PcToReferenceMap {
1215 public:
1216 PcToReferenceMap(Method* m) {
1217 data_ = down_cast<ByteArray*>(m->GetGcMap());
1218 CHECK(data_ != NULL);
1219 // Check the size of the table agrees with the number of entries
1220 size_t data_size = data_->GetLength() - 4;
1221 DCHECK_EQ(EntryWidth() * NumEntries(), data_size);
1222 }
1223
1224 // The number of entries in the table
1225 size_t NumEntries() const {
1226 return GetData()[2] | (GetData()[3] << 8);
1227 }
1228
1229 // Get the PC at the given index
1230 uint16_t GetPC(size_t index) const {
1231 size_t entry_offset = index * EntryWidth();
1232 if (PcWidth() == 1) {
1233 return Table()[entry_offset];
1234 } else {
1235 return Table()[entry_offset] | (Table()[entry_offset + 1] << 8);
1236 }
1237 }
1238
1239 // Return address of bitmap encoding what are live references
1240 const uint8_t* GetBitMap(size_t index) const {
1241 size_t entry_offset = index * EntryWidth();
1242 return &Table()[entry_offset + PcWidth()];
1243 }
1244
1245 // Find the bitmap associated with the given dex pc
1246 const uint8_t* FindBitMap(uint16_t dex_pc, bool error_if_not_present = true) const;
1247
1248 // The number of bytes used to encode registers
1249 size_t RegWidth() const {
1250 return GetData()[1];
1251 }
1252
1253 private:
1254 // Table of num_entries * (dex pc, bitmap)
1255 const uint8_t* Table() const {
1256 return GetData() + 4;
1257 }
1258
1259 // The format of the table of the PCs for the table
1260 RegisterMapFormat Format() const {
1261 return static_cast<RegisterMapFormat>(GetData()[0]);
1262 }
1263
1264 // Number of bytes used to encode a dex pc
1265 size_t PcWidth() const {
1266 RegisterMapFormat format = Format();
1267 switch (format) {
1268 case kRegMapFormatCompact8:
1269 return 1;
1270 case kRegMapFormatCompact16:
1271 return 2;
1272 default:
1273 LOG(FATAL) << "Invalid format " << static_cast<int>(format);
1274 return -1;
1275 }
1276 }
1277
1278 // The width of an entry in the table
1279 size_t EntryWidth() const {
1280 return PcWidth() + RegWidth();
1281 }
1282
1283 const uint8_t* GetData() const {
1284 return reinterpret_cast<uint8_t*>(data_->GetData());
1285 }
1286 ByteArray* data_; // The header and table data
1287};
1288
1289} // namespace verifier
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001290} // namespace art
1291
1292#endif // ART_SRC_DEX_VERIFY_H_