blob: 7c3b4dbc52e4b64141cf6ddac50bf46bff8dbc76 [file] [log] [blame]
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001// Copyright 2011 Google Inc. All Rights Reserved.
2
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003#include "dex_verifier.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004
Elliott Hughes1f359b02011-07-17 14:27:17 -07005#include <iostream>
6
Brian Carlstrom1f870082011-08-23 16:02:11 -07007#include "class_linker.h"
jeffhaob4df5142011-09-19 20:25:32 -07008#include "dex_cache.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -07009#include "dex_file.h"
10#include "dex_instruction.h"
11#include "dex_instruction_visitor.h"
jeffhaobdb76512011-09-07 11:43:16 -070012#include "dex_verifier.h"
Ian Rogers84fa0742011-10-25 18:13:30 -070013#include "intern_table.h"
Ian Rogers0571d352011-11-03 19:51:38 -070014#include "leb128.h"
Elliott Hughes1f359b02011-07-17 14:27:17 -070015#include "logging.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080016#include "object_utils.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070017#include "runtime.h"
Elliott Hughes1f359b02011-07-17 14:27:17 -070018#include "stringpiece.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070019
20namespace art {
Ian Rogersd81871c2011-10-03 13:57:23 -070021namespace verifier {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070022
Ian Rogers2c8a8572011-10-24 17:11:36 -070023static const bool gDebugVerify = false;
24
Ian Rogersd81871c2011-10-03 13:57:23 -070025std::ostream& operator<<(std::ostream& os, const VerifyError& rhs) {
26 return os << (int)rhs;
27}
jeffhaobdb76512011-09-07 11:43:16 -070028
Ian Rogers84fa0742011-10-25 18:13:30 -070029static const char* type_strings[] = {
30 "Unknown",
31 "Conflict",
32 "Boolean",
33 "Byte",
34 "Short",
35 "Char",
36 "Integer",
37 "Float",
38 "Long (Low Half)",
39 "Long (High Half)",
40 "Double (Low Half)",
41 "Double (High Half)",
42 "64-bit Constant (Low Half)",
43 "64-bit Constant (High Half)",
44 "32-bit Constant",
45 "Unresolved Reference",
46 "Uninitialized Reference",
47 "Uninitialized This Reference",
Ian Rogers28ad40d2011-10-27 15:19:26 -070048 "Unresolved And Uninitialized Reference",
Ian Rogers84fa0742011-10-25 18:13:30 -070049 "Reference",
50};
Ian Rogersd81871c2011-10-03 13:57:23 -070051
Ian Rogers2c8a8572011-10-24 17:11:36 -070052std::string RegType::Dump() const {
Ian Rogers84fa0742011-10-25 18:13:30 -070053 DCHECK(type_ >= kRegTypeUnknown && type_ <= kRegTypeReference);
54 std::string result;
55 if (IsConstant()) {
56 uint32_t val = ConstantValue();
57 if (val == 0) {
58 result = "Zero";
Ian Rogersd81871c2011-10-03 13:57:23 -070059 } else {
Ian Rogers84fa0742011-10-25 18:13:30 -070060 if(IsConstantShort()) {
61 result = StringPrintf("32-bit Constant: %d", val);
62 } else {
63 result = StringPrintf("32-bit Constant: 0x%x", val);
64 }
65 }
66 } else {
67 result = type_strings[type_];
68 if (IsReferenceTypes()) {
69 result += ": ";
Ian Rogers28ad40d2011-10-27 15:19:26 -070070 if (IsUnresolvedTypes()) {
Ian Rogers84fa0742011-10-25 18:13:30 -070071 result += PrettyDescriptor(GetDescriptor());
72 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080073 result += PrettyDescriptor(GetClass());
Ian Rogers84fa0742011-10-25 18:13:30 -070074 }
Ian Rogersd81871c2011-10-03 13:57:23 -070075 }
76 }
Ian Rogers84fa0742011-10-25 18:13:30 -070077 return result;
Ian Rogersd81871c2011-10-03 13:57:23 -070078}
79
80const RegType& RegType::HighHalf(RegTypeCache* cache) const {
81 CHECK(IsLowHalf());
82 if (type_ == kRegTypeLongLo) {
83 return cache->FromType(kRegTypeLongHi);
84 } else if (type_ == kRegTypeDoubleLo) {
85 return cache->FromType(kRegTypeDoubleHi);
86 } else {
87 return cache->FromType(kRegTypeConstHi);
88 }
89}
90
91/*
92 * A basic Join operation on classes. For a pair of types S and T the Join, written S v T = J, is
93 * S <: J, T <: J and for-all U such that S <: U, T <: U then J <: U. That is J is the parent of
94 * 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
95 * is the deepest (lowest upper bound) parent of S and T).
96 *
97 * This operation applies for regular classes and arrays, however, for interface types there needn't
98 * be a partial ordering on the types. We could solve the problem of a lack of a partial order by
99 * introducing sets of types, however, the only operation permissible on an interface is
100 * invoke-interface. In the tradition of Java verifiers we defer the verification of interface
101 * types until an invoke-interface call on the interface typed reference at runtime and allow
Ian Rogers5ed29bf2011-10-26 12:22:21 -0700102 * the perversion of any Object being assignable to an interface type (note, however, that we don't
103 * allow assignment of Object or Interface to any concrete subclass of Object and are therefore type
104 * safe; further the Join on a Object cannot result in a sub-class by definition).
Ian Rogersd81871c2011-10-03 13:57:23 -0700105 */
106Class* RegType::ClassJoin(Class* s, Class* t) {
107 DCHECK(!s->IsPrimitive()) << PrettyClass(s);
108 DCHECK(!t->IsPrimitive()) << PrettyClass(t);
109 if (s == t) {
110 return s;
111 } else if (s->IsAssignableFrom(t)) {
112 return s;
113 } else if (t->IsAssignableFrom(s)) {
114 return t;
115 } else if (s->IsArrayClass() && t->IsArrayClass()) {
116 Class* s_ct = s->GetComponentType();
117 Class* t_ct = t->GetComponentType();
118 if (s_ct->IsPrimitive() || t_ct->IsPrimitive()) {
119 // Given the types aren't the same, if either array is of primitive types then the only
120 // common parent is java.lang.Object
121 Class* result = s->GetSuperClass(); // short-cut to java.lang.Object
122 DCHECK(result->IsObjectClass());
123 return result;
124 }
125 Class* common_elem = ClassJoin(s_ct, t_ct);
126 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
127 const ClassLoader* class_loader = s->GetClassLoader();
Elliott Hughes95572412011-12-13 18:14:20 -0800128 std::string descriptor("[");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800129 descriptor += ClassHelper(common_elem).GetDescriptor();
Ian Rogersd81871c2011-10-03 13:57:23 -0700130 Class* array_class = class_linker->FindClass(descriptor.c_str(), class_loader);
131 DCHECK(array_class != NULL);
132 return array_class;
133 } else {
134 size_t s_depth = s->Depth();
135 size_t t_depth = t->Depth();
136 // Get s and t to the same depth in the hierarchy
137 if (s_depth > t_depth) {
138 while (s_depth > t_depth) {
139 s = s->GetSuperClass();
140 s_depth--;
141 }
142 } else {
143 while (t_depth > s_depth) {
144 t = t->GetSuperClass();
145 t_depth--;
146 }
147 }
148 // Go up the hierarchy until we get to the common parent
149 while (s != t) {
150 s = s->GetSuperClass();
151 t = t->GetSuperClass();
152 }
153 return s;
154 }
155}
156
Ian Rogersb5e95b92011-10-25 23:28:55 -0700157bool RegType::IsAssignableFrom(const RegType& src) const {
158 if (Equals(src)) {
159 return true;
Ian Rogersd81871c2011-10-03 13:57:23 -0700160 } else {
Ian Rogersb5e95b92011-10-25 23:28:55 -0700161 switch (GetType()) {
Ian Rogers9074b992011-10-26 17:41:55 -0700162 case RegType::kRegTypeBoolean: return src.IsBooleanTypes();
163 case RegType::kRegTypeByte: return src.IsByteTypes();
164 case RegType::kRegTypeShort: return src.IsShortTypes();
165 case RegType::kRegTypeChar: return src.IsCharTypes();
166 case RegType::kRegTypeInteger: return src.IsIntegralTypes();
167 case RegType::kRegTypeFloat: return src.IsFloatTypes();
168 case RegType::kRegTypeLongLo: return src.IsLongTypes();
169 case RegType::kRegTypeDoubleLo: return src.IsDoubleTypes();
Ian Rogers84fa0742011-10-25 18:13:30 -0700170 default:
Ian Rogersb5e95b92011-10-25 23:28:55 -0700171 if (!IsReferenceTypes()) {
172 LOG(FATAL) << "Unexpected register type in IsAssignableFrom: '" << src << "'";
Ian Rogers84fa0742011-10-25 18:13:30 -0700173 }
Ian Rogersb5e95b92011-10-25 23:28:55 -0700174 if (src.IsZero()) {
Ian Rogers9074b992011-10-26 17:41:55 -0700175 return true; // all reference types can be assigned null
176 } else if (!src.IsReferenceTypes()) {
177 return false; // expect src to be a reference type
178 } else if (IsJavaLangObject()) {
179 return true; // all reference types can be assigned to Object
180 } else if (!IsUnresolvedTypes() && GetClass()->IsInterface()) {
Ian Rogers5ed29bf2011-10-26 12:22:21 -0700181 return true; // We allow assignment to any interface, see comment in ClassJoin
Ian Rogers9074b992011-10-26 17:41:55 -0700182 } else if (!IsUnresolvedTypes() && !src.IsUnresolvedTypes() &&
Ian Rogers5ed29bf2011-10-26 12:22:21 -0700183 GetClass()->IsAssignableFrom(src.GetClass())) {
184 // We're assignable from the Class point-of-view
Ian Rogersb5e95b92011-10-25 23:28:55 -0700185 return true;
Ian Rogersd81871c2011-10-03 13:57:23 -0700186 } else {
Ian Rogersb5e95b92011-10-25 23:28:55 -0700187 return false;
Ian Rogersd81871c2011-10-03 13:57:23 -0700188 }
Ian Rogersd81871c2011-10-03 13:57:23 -0700189 }
190 }
191}
192
Ian Rogers84fa0742011-10-25 18:13:30 -0700193static const RegType& SelectNonConstant(const RegType& a, const RegType& b) {
194 return a.IsConstant() ? b : a;
195}
jeffhaobdb76512011-09-07 11:43:16 -0700196
Ian Rogersd81871c2011-10-03 13:57:23 -0700197const RegType& RegType::Merge(const RegType& incoming_type, RegTypeCache* reg_types) const {
198 DCHECK(!Equals(incoming_type)); // Trivial equality handled by caller
Ian Rogers84fa0742011-10-25 18:13:30 -0700199 if (IsUnknown() && incoming_type.IsUnknown()) {
200 return *this; // Unknown MERGE Unknown => Unknown
201 } else if (IsConflict()) {
202 return *this; // Conflict MERGE * => Conflict
203 } else if (incoming_type.IsConflict()) {
204 return incoming_type; // * MERGE Conflict => Conflict
205 } else if (IsUnknown() || incoming_type.IsUnknown()) {
206 return reg_types->Conflict(); // Unknown MERGE * => Conflict
207 } else if(IsConstant() && incoming_type.IsConstant()) {
208 int32_t val1 = ConstantValue();
209 int32_t val2 = incoming_type.ConstantValue();
210 if (val1 >= 0 && val2 >= 0) {
211 // +ve1 MERGE +ve2 => MAX(+ve1, +ve2)
212 if (val1 >= val2) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700213 return *this;
Ian Rogers84fa0742011-10-25 18:13:30 -0700214 } else {
215 return incoming_type;
216 }
217 } else if (val1 < 0 && val2 < 0) {
218 // -ve1 MERGE -ve2 => MIN(-ve1, -ve2)
219 if (val1 <= val2) {
220 return *this;
221 } else {
222 return incoming_type;
223 }
224 } else {
225 // Values are +ve and -ve, choose smallest signed type in which they both fit
226 if (IsConstantByte()) {
227 if (incoming_type.IsConstantByte()) {
228 return reg_types->ByteConstant();
229 } else if (incoming_type.IsConstantShort()) {
230 return reg_types->ShortConstant();
231 } else {
232 return reg_types->IntConstant();
233 }
234 } else if (IsConstantShort()) {
Ian Rogers1592bc72011-10-27 20:08:53 -0700235 if (incoming_type.IsConstantShort()) {
Ian Rogers84fa0742011-10-25 18:13:30 -0700236 return reg_types->ShortConstant();
237 } else {
238 return reg_types->IntConstant();
239 }
240 } else {
241 return reg_types->IntConstant();
242 }
243 }
244 } else if (IsIntegralTypes() && incoming_type.IsIntegralTypes()) {
245 if (IsBooleanTypes() && incoming_type.IsBooleanTypes()) {
246 return reg_types->Boolean(); // boolean MERGE boolean => boolean
247 }
248 if (IsByteTypes() && incoming_type.IsByteTypes()) {
249 return reg_types->Byte(); // byte MERGE byte => byte
250 }
251 if (IsShortTypes() && incoming_type.IsShortTypes()) {
252 return reg_types->Short(); // short MERGE short => short
253 }
254 if (IsCharTypes() && incoming_type.IsCharTypes()) {
255 return reg_types->Char(); // char MERGE char => char
256 }
257 return reg_types->Integer(); // int MERGE * => int
258 } else if ((IsFloatTypes() && incoming_type.IsFloatTypes()) ||
259 (IsLongTypes() && incoming_type.IsLongTypes()) ||
260 (IsLongHighTypes() && incoming_type.IsLongHighTypes()) ||
261 (IsDoubleTypes() && incoming_type.IsDoubleTypes()) ||
262 (IsDoubleHighTypes() && incoming_type.IsDoubleHighTypes())) {
263 // check constant case was handled prior to entry
264 DCHECK(!IsConstant() || !incoming_type.IsConstant());
265 // float/long/double MERGE float/long/double_constant => float/long/double
266 return SelectNonConstant(*this, incoming_type);
267 } else if (IsReferenceTypes() && incoming_type.IsReferenceTypes()) {
Ian Rogers9074b992011-10-26 17:41:55 -0700268 if (IsZero() || incoming_type.IsZero()) {
Ian Rogers84fa0742011-10-25 18:13:30 -0700269 return SelectNonConstant(*this, incoming_type); // 0 MERGE ref => ref
Ian Rogers9074b992011-10-26 17:41:55 -0700270 } else if (IsJavaLangObject() || incoming_type.IsJavaLangObject()) {
271 return reg_types->JavaLangObject(); // Object MERGE ref => Object
272 } else if (IsUninitializedTypes() || incoming_type.IsUninitializedTypes() ||
273 IsUnresolvedTypes() || incoming_type.IsUnresolvedTypes()) {
274 // Can only merge an unresolved or uninitialized type with itself, 0 or Object, we've already
275 // checked these so => Conflict
Ian Rogers84fa0742011-10-25 18:13:30 -0700276 return reg_types->Conflict();
277 } else { // Two reference types, compute Join
278 Class* c1 = GetClass();
279 Class* c2 = incoming_type.GetClass();
280 DCHECK(c1 != NULL && !c1->IsPrimitive());
281 DCHECK(c2 != NULL && !c2->IsPrimitive());
282 Class* join_class = ClassJoin(c1, c2);
283 if (c1 == join_class) {
284 return *this;
285 } else if (c2 == join_class) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700286 return incoming_type;
287 } else {
Ian Rogers84fa0742011-10-25 18:13:30 -0700288 return reg_types->FromClass(join_class);
Ian Rogersd81871c2011-10-03 13:57:23 -0700289 }
Ian Rogersd81871c2011-10-03 13:57:23 -0700290 }
Ian Rogers84fa0742011-10-25 18:13:30 -0700291 } else {
292 return reg_types->Conflict(); // Unexpected types => Conflict
Ian Rogersd81871c2011-10-03 13:57:23 -0700293 }
294}
295
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700296static RegType::Type RegTypeFromPrimitiveType(Primitive::Type prim_type) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700297 switch (prim_type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700298 case Primitive::kPrimBoolean: return RegType::kRegTypeBoolean;
299 case Primitive::kPrimByte: return RegType::kRegTypeByte;
300 case Primitive::kPrimShort: return RegType::kRegTypeShort;
301 case Primitive::kPrimChar: return RegType::kRegTypeChar;
302 case Primitive::kPrimInt: return RegType::kRegTypeInteger;
303 case Primitive::kPrimLong: return RegType::kRegTypeLongLo;
304 case Primitive::kPrimFloat: return RegType::kRegTypeFloat;
305 case Primitive::kPrimDouble: return RegType::kRegTypeDoubleLo;
306 case Primitive::kPrimVoid:
307 default: return RegType::kRegTypeUnknown;
Ian Rogersd81871c2011-10-03 13:57:23 -0700308 }
309}
310
311static RegType::Type RegTypeFromDescriptor(const std::string& descriptor) {
312 if (descriptor.length() == 1) {
313 switch (descriptor[0]) {
314 case 'Z': return RegType::kRegTypeBoolean;
315 case 'B': return RegType::kRegTypeByte;
316 case 'S': return RegType::kRegTypeShort;
317 case 'C': return RegType::kRegTypeChar;
318 case 'I': return RegType::kRegTypeInteger;
319 case 'J': return RegType::kRegTypeLongLo;
320 case 'F': return RegType::kRegTypeFloat;
321 case 'D': return RegType::kRegTypeDoubleLo;
322 case 'V':
323 default: return RegType::kRegTypeUnknown;
324 }
325 } else if(descriptor[0] == 'L' || descriptor[0] == '[') {
326 return RegType::kRegTypeReference;
327 } else {
328 return RegType::kRegTypeUnknown;
329 }
330}
331
332std::ostream& operator<<(std::ostream& os, const RegType& rhs) {
Ian Rogers2c8a8572011-10-24 17:11:36 -0700333 os << rhs.Dump();
Ian Rogersd81871c2011-10-03 13:57:23 -0700334 return os;
335}
336
337const RegType& RegTypeCache::FromDescriptor(const ClassLoader* loader,
338 const std::string& descriptor) {
339 return From(RegTypeFromDescriptor(descriptor), loader, descriptor);
340}
341
342const RegType& RegTypeCache::From(RegType::Type type, const ClassLoader* loader,
343 const std::string& descriptor) {
Ian Rogers84fa0742011-10-25 18:13:30 -0700344 if (type <= RegType::kRegTypeLastFixedLocation) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700345 // entries should be sized greater than primitive types
346 DCHECK_GT(entries_.size(), static_cast<size_t>(type));
347 RegType* entry = entries_[type];
348 if (entry == NULL) {
Ian Rogers84fa0742011-10-25 18:13:30 -0700349 Class* klass = NULL;
Ian Rogersd81871c2011-10-03 13:57:23 -0700350 if (descriptor.size() != 0) {
351 klass = Runtime::Current()->GetClassLinker()->FindSystemClass(descriptor);
352 }
Ian Rogers84fa0742011-10-25 18:13:30 -0700353 entry = new RegType(type, klass, 0, type);
Ian Rogersd81871c2011-10-03 13:57:23 -0700354 entries_[type] = entry;
355 }
356 return *entry;
357 } else {
358 DCHECK (type == RegType::kRegTypeReference);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800359 ClassHelper kh;
Ian Rogers84fa0742011-10-25 18:13:30 -0700360 for (size_t i = RegType::kRegTypeLastFixedLocation + 1; i < entries_.size(); i++) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700361 RegType* cur_entry = entries_[i];
Ian Rogers84fa0742011-10-25 18:13:30 -0700362 // check resolved and unresolved references, ignore uninitialized references
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800363 if (cur_entry->IsReference()) {
364 kh.ChangeClass(cur_entry->GetClass());
365 if (descriptor == kh.GetDescriptor()) {
366 return *cur_entry;
367 }
Ian Rogers84fa0742011-10-25 18:13:30 -0700368 } else if (cur_entry->IsUnresolvedReference() &&
369 cur_entry->GetDescriptor()->Equals(descriptor)) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700370 return *cur_entry;
371 }
372 }
373 Class* klass = Runtime::Current()->GetClassLinker()->FindClass(descriptor, loader);
Ian Rogers2c8a8572011-10-24 17:11:36 -0700374 if (klass != NULL) {
Ian Rogers84fa0742011-10-25 18:13:30 -0700375 // Able to resolve so create resolved register type
376 RegType* entry = new RegType(type, klass, 0, entries_.size());
Ian Rogers2c8a8572011-10-24 17:11:36 -0700377 entries_.push_back(entry);
378 return *entry;
379 } else {
Ian Rogers28ad40d2011-10-27 15:19:26 -0700380 // TODO: we assume unresolved, but we may be able to do better by validating whether the
381 // descriptor string is valid
Ian Rogers84fa0742011-10-25 18:13:30 -0700382 // Unable to resolve so create unresolved register type
Ian Rogers2c8a8572011-10-24 17:11:36 -0700383 DCHECK(Thread::Current()->IsExceptionPending());
Ian Rogers84fa0742011-10-25 18:13:30 -0700384 Thread::Current()->ClearException();
Ian Rogers28ad40d2011-10-27 15:19:26 -0700385 if (IsValidDescriptor(descriptor.c_str())) {
386 String* string_descriptor =
387 Runtime::Current()->GetInternTable()->InternStrong(descriptor.c_str());
388 RegType* entry = new RegType(RegType::kRegTypeUnresolvedReference, string_descriptor, 0,
389 entries_.size());
390 entries_.push_back(entry);
391 return *entry;
392 } else {
393 // The descriptor is broken return the unknown type as there's nothing sensible that
394 // could be done at runtime
395 return Unknown();
396 }
Ian Rogers2c8a8572011-10-24 17:11:36 -0700397 }
Ian Rogersd81871c2011-10-03 13:57:23 -0700398 }
399}
400
401const RegType& RegTypeCache::FromClass(Class* klass) {
402 if (klass->IsPrimitive()) {
403 RegType::Type type = RegTypeFromPrimitiveType(klass->GetPrimitiveType());
404 // entries should be sized greater than primitive types
405 DCHECK_GT(entries_.size(), static_cast<size_t>(type));
406 RegType* entry = entries_[type];
407 if (entry == NULL) {
Ian Rogers84fa0742011-10-25 18:13:30 -0700408 entry = new RegType(type, klass, 0, type);
Ian Rogersd81871c2011-10-03 13:57:23 -0700409 entries_[type] = entry;
410 }
411 return *entry;
412 } else {
Ian Rogers84fa0742011-10-25 18:13:30 -0700413 for (size_t i = RegType::kRegTypeLastFixedLocation + 1; i < entries_.size(); i++) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700414 RegType* cur_entry = entries_[i];
Ian Rogers84fa0742011-10-25 18:13:30 -0700415 if (cur_entry->IsReference() && cur_entry->GetClass() == klass) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700416 return *cur_entry;
417 }
418 }
Ian Rogers84fa0742011-10-25 18:13:30 -0700419 RegType* entry = new RegType(RegType::kRegTypeReference, klass, 0, entries_.size());
Ian Rogersd81871c2011-10-03 13:57:23 -0700420 entries_.push_back(entry);
421 return *entry;
422 }
423}
424
Ian Rogers28ad40d2011-10-27 15:19:26 -0700425const RegType& RegTypeCache::Uninitialized(const RegType& type, uint32_t allocation_pc) {
426 RegType* entry;
427 if (type.IsUnresolvedTypes()) {
428 String* descriptor = type.GetDescriptor();
429 for (size_t i = RegType::kRegTypeLastFixedLocation + 1; i < entries_.size(); i++) {
430 RegType* cur_entry = entries_[i];
431 if (cur_entry->IsUnresolvedAndUninitializedReference() &&
432 cur_entry->GetAllocationPc() == allocation_pc &&
433 cur_entry->GetDescriptor() == descriptor) {
434 return *cur_entry;
435 }
Ian Rogersd81871c2011-10-03 13:57:23 -0700436 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700437 entry = new RegType(RegType::kRegTypeUnresolvedAndUninitializedReference,
438 descriptor, allocation_pc, entries_.size());
439 } else {
440 Class* klass = type.GetClass();
441 for (size_t i = RegType::kRegTypeLastFixedLocation + 1; i < entries_.size(); i++) {
442 RegType* cur_entry = entries_[i];
443 if (cur_entry->IsUninitializedReference() &&
444 cur_entry->GetAllocationPc() == allocation_pc &&
445 cur_entry->GetClass() == klass) {
446 return *cur_entry;
447 }
448 }
449 entry = new RegType(RegType::kRegTypeUninitializedReference,
450 klass, allocation_pc, entries_.size());
Ian Rogersd81871c2011-10-03 13:57:23 -0700451 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700452 entries_.push_back(entry);
453 return *entry;
454}
455
456const RegType& RegTypeCache::FromUninitialized(const RegType& uninit_type) {
457 RegType* entry;
458 if (uninit_type.IsUnresolvedTypes()) {
459 String* descriptor = uninit_type.GetDescriptor();
460 for (size_t i = RegType::kRegTypeLastFixedLocation + 1; i < entries_.size(); i++) {
461 RegType* cur_entry = entries_[i];
462 if (cur_entry->IsUnresolvedReference() && cur_entry->GetDescriptor() == descriptor) {
463 return *cur_entry;
464 }
465 }
466 entry = new RegType(RegType::kRegTypeUnresolvedReference, descriptor, 0, entries_.size());
467 } else {
468 Class* klass = uninit_type.GetClass();
469 for (size_t i = RegType::kRegTypeLastFixedLocation + 1; i < entries_.size(); i++) {
470 RegType* cur_entry = entries_[i];
471 if (cur_entry->IsReference() && cur_entry->GetClass() == klass) {
472 return *cur_entry;
473 }
474 }
475 entry = new RegType(RegType::kRegTypeReference, klass, 0, entries_.size());
476 }
Ian Rogersd81871c2011-10-03 13:57:23 -0700477 entries_.push_back(entry);
478 return *entry;
479}
480
481const RegType& RegTypeCache::UninitializedThisArgument(Class* klass) {
Ian Rogers84fa0742011-10-25 18:13:30 -0700482 for (size_t i = RegType::kRegTypeLastFixedLocation + 1; i < entries_.size(); i++) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700483 RegType* cur_entry = entries_[i];
484 if (cur_entry->IsUninitializedThisReference() && cur_entry->GetClass() == klass) {
485 return *cur_entry;
486 }
487 }
Ian Rogers84fa0742011-10-25 18:13:30 -0700488 RegType* entry = new RegType(RegType::kRegTypeUninitializedThisReference, klass, 0,
Ian Rogersd81871c2011-10-03 13:57:23 -0700489 entries_.size());
490 entries_.push_back(entry);
491 return *entry;
492}
493
494const RegType& RegTypeCache::FromType(RegType::Type type) {
495 CHECK(type < RegType::kRegTypeReference);
496 switch (type) {
497 case RegType::kRegTypeBoolean: return From(type, NULL, "Z");
498 case RegType::kRegTypeByte: return From(type, NULL, "B");
499 case RegType::kRegTypeShort: return From(type, NULL, "S");
500 case RegType::kRegTypeChar: return From(type, NULL, "C");
501 case RegType::kRegTypeInteger: return From(type, NULL, "I");
502 case RegType::kRegTypeFloat: return From(type, NULL, "F");
503 case RegType::kRegTypeLongLo:
504 case RegType::kRegTypeLongHi: return From(type, NULL, "J");
505 case RegType::kRegTypeDoubleLo:
506 case RegType::kRegTypeDoubleHi: return From(type, NULL, "D");
507 default: return From(type, NULL, "");
508 }
509}
510
511const RegType& RegTypeCache::FromCat1Const(int32_t value) {
Ian Rogers84fa0742011-10-25 18:13:30 -0700512 for (size_t i = RegType::kRegTypeLastFixedLocation + 1; i < entries_.size(); i++) {
513 RegType* cur_entry = entries_[i];
514 if (cur_entry->IsConstant() && cur_entry->ConstantValue() == value) {
515 return *cur_entry;
516 }
Ian Rogersd81871c2011-10-03 13:57:23 -0700517 }
Ian Rogers84fa0742011-10-25 18:13:30 -0700518 RegType* entry = new RegType(RegType::kRegTypeConst, NULL, value, entries_.size());
519 entries_.push_back(entry);
520 return *entry;
Ian Rogersd81871c2011-10-03 13:57:23 -0700521}
522
Ian Rogers28ad40d2011-10-27 15:19:26 -0700523const RegType& RegTypeCache::GetComponentType(const RegType& array, const ClassLoader* loader) {
524 CHECK(array.IsArrayClass());
525 if (array.IsUnresolvedTypes()) {
Elliott Hughes95572412011-12-13 18:14:20 -0800526 std::string descriptor(array.GetDescriptor()->ToModifiedUtf8());
527 std::string component(descriptor.substr(1, descriptor.size() - 1));
Ian Rogers28ad40d2011-10-27 15:19:26 -0700528 return FromDescriptor(loader, component);
529 } else {
530 return FromClass(array.GetClass()->GetComponentType());
531 }
532}
533
534
Ian Rogersd81871c2011-10-03 13:57:23 -0700535bool RegisterLine::CheckConstructorReturn() const {
536 for (size_t i = 0; i < num_regs_; i++) {
537 if (GetRegisterType(i).IsUninitializedThisReference()) {
538 verifier_->Fail(VERIFY_ERROR_GENERIC)
539 << "Constructor returning without calling superclass constructor";
540 return false;
541 }
542 }
543 return true;
544}
545
546void RegisterLine::SetRegisterType(uint32_t vdst, const RegType& new_type) {
547 DCHECK(vdst < num_regs_);
548 if (new_type.IsLowHalf()) {
549 line_[vdst] = new_type.GetId();
550 line_[vdst + 1] = new_type.HighHalf(verifier_->GetRegTypeCache()).GetId();
551 } else if (new_type.IsHighHalf()) {
552 /* should never set these explicitly */
553 verifier_->Fail(VERIFY_ERROR_GENERIC) << "Explicit set of high register type";
554 } else if (new_type.IsConflict()) { // should only be set during a merge
555 verifier_->Fail(VERIFY_ERROR_GENERIC) << "Set register to unknown type " << new_type;
556 } else {
557 line_[vdst] = new_type.GetId();
558 }
559 // Clear the monitor entry bits for this register.
560 ClearAllRegToLockDepths(vdst);
561}
562
563void RegisterLine::SetResultTypeToUnknown() {
564 uint16_t unknown_id = verifier_->GetRegTypeCache()->Unknown().GetId();
565 result_[0] = unknown_id;
566 result_[1] = unknown_id;
567}
568
569void RegisterLine::SetResultRegisterType(const RegType& new_type) {
570 result_[0] = new_type.GetId();
571 if(new_type.IsLowHalf()) {
572 DCHECK_EQ(new_type.HighHalf(verifier_->GetRegTypeCache()).GetId(), new_type.GetId() + 1);
573 result_[1] = new_type.GetId() + 1;
574 } else {
575 result_[1] = verifier_->GetRegTypeCache()->Unknown().GetId();
576 }
577}
578
579const RegType& RegisterLine::GetRegisterType(uint32_t vsrc) const {
580 // The register index was validated during the static pass, so we don't need to check it here.
581 DCHECK_LT(vsrc, num_regs_);
582 return verifier_->GetRegTypeCache()->GetFromId(line_[vsrc]);
583}
584
585const RegType& RegisterLine::GetInvocationThis(const Instruction::DecodedInstruction& dec_insn) {
586 if (dec_insn.vA_ < 1) {
587 verifier_->Fail(VERIFY_ERROR_GENERIC) << "invoke lacks 'this'";
588 return verifier_->GetRegTypeCache()->Unknown();
589 }
590 /* get the element type of the array held in vsrc */
591 const RegType& this_type = GetRegisterType(dec_insn.vC_);
592 if (!this_type.IsReferenceTypes()) {
593 verifier_->Fail(VERIFY_ERROR_GENERIC) << "tried to get class from non-reference register v"
594 << dec_insn.vC_ << " (type=" << this_type << ")";
595 return verifier_->GetRegTypeCache()->Unknown();
596 }
597 return this_type;
598}
599
600Class* RegisterLine::GetClassFromRegister(uint32_t vsrc) const {
601 /* get the element type of the array held in vsrc */
602 const RegType& type = GetRegisterType(vsrc);
603 /* if "always zero", we allow it to fail at runtime */
604 if (type.IsZero()) {
605 return NULL;
606 } else if (!type.IsReferenceTypes()) {
607 verifier_->Fail(VERIFY_ERROR_GENERIC) << "tried to get class from non-ref register v" << vsrc
608 << " (type=" << type << ")";
609 return NULL;
610 } else if (type.IsUninitializedReference()) {
611 verifier_->Fail(VERIFY_ERROR_GENERIC) << "register " << vsrc << " holds uninitialized reference";
612 return NULL;
613 } else {
614 return type.GetClass();
615 }
616}
617
618bool RegisterLine::VerifyRegisterType(uint32_t vsrc, const RegType& check_type) {
619 // Verify the src register type against the check type refining the type of the register
620 const RegType& src_type = GetRegisterType(vsrc);
Ian Rogersb5e95b92011-10-25 23:28:55 -0700621 if (!check_type.IsAssignableFrom(src_type)) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700622 verifier_->Fail(VERIFY_ERROR_GENERIC) << "register v" << vsrc << " has type " << src_type
623 << " but expected " << check_type;
624 return false;
625 }
626 // The register at vsrc has a defined type, we know the lower-upper-bound, but this is less
627 // precise than the subtype in vsrc so leave it for reference types. For primitive types
628 // if they are a defined type then they are as precise as we can get, however, for constant
629 // types we may wish to refine them. Unfortunately constant propagation has rendered this useless.
630 return true;
631}
632
633void RegisterLine::MarkRefsAsInitialized(const RegType& uninit_type) {
Ian Rogers28ad40d2011-10-27 15:19:26 -0700634 DCHECK(uninit_type.IsUninitializedTypes());
635 const RegType& init_type = verifier_->GetRegTypeCache()->FromUninitialized(uninit_type);
636 size_t changed = 0;
637 for (size_t i = 0; i < num_regs_; i++) {
638 if (GetRegisterType(i).Equals(uninit_type)) {
639 line_[i] = init_type.GetId();
640 changed++;
Ian Rogersd81871c2011-10-03 13:57:23 -0700641 }
Ian Rogersd81871c2011-10-03 13:57:23 -0700642 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700643 DCHECK_GT(changed, 0u);
Ian Rogersd81871c2011-10-03 13:57:23 -0700644}
645
646void RegisterLine::MarkUninitRefsAsInvalid(const RegType& uninit_type) {
647 for (size_t i = 0; i < num_regs_; i++) {
648 if (GetRegisterType(i).Equals(uninit_type)) {
649 line_[i] = verifier_->GetRegTypeCache()->Conflict().GetId();
650 ClearAllRegToLockDepths(i);
651 }
652 }
653}
654
655void RegisterLine::CopyRegister1(uint32_t vdst, uint32_t vsrc, TypeCategory cat) {
656 DCHECK(cat == kTypeCategory1nr || cat == kTypeCategoryRef);
657 const RegType& type = GetRegisterType(vsrc);
658 SetRegisterType(vdst, type);
659 if ((cat == kTypeCategory1nr && !type.IsCategory1Types()) ||
660 (cat == kTypeCategoryRef && !type.IsReferenceTypes())) {
661 verifier_->Fail(VERIFY_ERROR_GENERIC) << "copy1 v" << vdst << "<-v" << vsrc << " type=" << type
662 << " cat=" << static_cast<int>(cat);
663 } else if (cat == kTypeCategoryRef) {
664 CopyRegToLockDepth(vdst, vsrc);
665 }
666}
667
668void RegisterLine::CopyRegister2(uint32_t vdst, uint32_t vsrc) {
669 const RegType& type_l = GetRegisterType(vsrc);
670 const RegType& type_h = GetRegisterType(vsrc + 1);
671
672 if (!type_l.CheckWidePair(type_h)) {
673 verifier_->Fail(VERIFY_ERROR_GENERIC) << "copy2 v" << vdst << "<-v" << vsrc
674 << " type=" << type_l << "/" << type_h;
675 } else {
676 SetRegisterType(vdst, type_l); // implicitly sets the second half
677 }
678}
679
680void RegisterLine::CopyResultRegister1(uint32_t vdst, bool is_reference) {
681 const RegType& type = verifier_->GetRegTypeCache()->GetFromId(result_[0]);
682 if ((!is_reference && !type.IsCategory1Types()) ||
683 (is_reference && !type.IsReferenceTypes())) {
684 verifier_->Fail(VERIFY_ERROR_GENERIC)
685 << "copyRes1 v" << vdst << "<- result0" << " type=" << type;
686 } else {
687 DCHECK(verifier_->GetRegTypeCache()->GetFromId(result_[1]).IsUnknown());
688 SetRegisterType(vdst, type);
689 result_[0] = verifier_->GetRegTypeCache()->Unknown().GetId();
690 }
691}
692
693/*
694 * Implement "move-result-wide". Copy the category-2 value from the result
695 * register to another register, and reset the result register.
696 */
697void RegisterLine::CopyResultRegister2(uint32_t vdst) {
698 const RegType& type_l = verifier_->GetRegTypeCache()->GetFromId(result_[0]);
699 const RegType& type_h = verifier_->GetRegTypeCache()->GetFromId(result_[1]);
700 if (!type_l.IsCategory2Types()) {
701 verifier_->Fail(VERIFY_ERROR_GENERIC)
702 << "copyRes2 v" << vdst << "<- result0" << " type=" << type_l;
703 } else {
704 DCHECK(type_l.CheckWidePair(type_h)); // Set should never allow this case
705 SetRegisterType(vdst, type_l); // also sets the high
706 result_[0] = verifier_->GetRegTypeCache()->Unknown().GetId();
707 result_[1] = verifier_->GetRegTypeCache()->Unknown().GetId();
708 }
709}
710
711void RegisterLine::CheckUnaryOp(const Instruction::DecodedInstruction& dec_insn,
712 const RegType& dst_type, const RegType& src_type) {
713 if (VerifyRegisterType(dec_insn.vB_, src_type)) {
714 SetRegisterType(dec_insn.vA_, dst_type);
715 }
716}
717
718void RegisterLine::CheckBinaryOp(const Instruction::DecodedInstruction& dec_insn,
719 const RegType& dst_type,
720 const RegType& src_type1, const RegType& src_type2,
721 bool check_boolean_op) {
722 if (VerifyRegisterType(dec_insn.vB_, src_type1) &&
723 VerifyRegisterType(dec_insn.vC_, src_type2)) {
724 if (check_boolean_op) {
725 DCHECK(dst_type.IsInteger());
726 if (GetRegisterType(dec_insn.vB_).IsBooleanTypes() &&
727 GetRegisterType(dec_insn.vC_).IsBooleanTypes()) {
728 SetRegisterType(dec_insn.vA_, verifier_->GetRegTypeCache()->Boolean());
729 return;
730 }
731 }
732 SetRegisterType(dec_insn.vA_, dst_type);
733 }
734}
735
736void RegisterLine::CheckBinaryOp2addr(const Instruction::DecodedInstruction& dec_insn,
737 const RegType& dst_type, const RegType& src_type1,
738 const RegType& src_type2, bool check_boolean_op) {
739 if (VerifyRegisterType(dec_insn.vA_, src_type1) &&
740 VerifyRegisterType(dec_insn.vB_, src_type2)) {
741 if (check_boolean_op) {
742 DCHECK(dst_type.IsInteger());
743 if (GetRegisterType(dec_insn.vA_).IsBooleanTypes() &&
744 GetRegisterType(dec_insn.vB_).IsBooleanTypes()) {
745 SetRegisterType(dec_insn.vA_, verifier_->GetRegTypeCache()->Boolean());
746 return;
747 }
748 }
749 SetRegisterType(dec_insn.vA_, dst_type);
750 }
751}
752
753void RegisterLine::CheckLiteralOp(const Instruction::DecodedInstruction& dec_insn,
754 const RegType& dst_type, const RegType& src_type,
755 bool check_boolean_op) {
756 if (VerifyRegisterType(dec_insn.vB_, src_type)) {
757 if (check_boolean_op) {
758 DCHECK(dst_type.IsInteger());
759 /* check vB with the call, then check the constant manually */
760 if (GetRegisterType(dec_insn.vB_).IsBooleanTypes() &&
761 (dec_insn.vC_ == 0 || dec_insn.vC_ == 1)) {
762 SetRegisterType(dec_insn.vA_, verifier_->GetRegTypeCache()->Boolean());
763 return;
764 }
765 }
766 SetRegisterType(dec_insn.vA_, dst_type);
767 }
768}
769
770void RegisterLine::PushMonitor(uint32_t reg_idx, int32_t insn_idx) {
771 const RegType& reg_type = GetRegisterType(reg_idx);
772 if (!reg_type.IsReferenceTypes()) {
773 verifier_->Fail(VERIFY_ERROR_GENERIC) << "monitor-enter on non-object (" << reg_type << ")";
Elliott Hughesfbef9462011-12-14 14:24:40 -0800774 } else if (monitors_.size() >= 32) {
775 verifier_->Fail(VERIFY_ERROR_GENERIC) << "monitor-enter stack overflow: " << monitors_.size();
Ian Rogersd81871c2011-10-03 13:57:23 -0700776 } else {
777 SetRegToLockDepth(reg_idx, monitors_.size());
Ian Rogers55d249f2011-11-02 16:48:09 -0700778 monitors_.push_back(insn_idx);
Ian Rogersd81871c2011-10-03 13:57:23 -0700779 }
780}
781
782void RegisterLine::PopMonitor(uint32_t reg_idx) {
783 const RegType& reg_type = GetRegisterType(reg_idx);
784 if (!reg_type.IsReferenceTypes()) {
785 verifier_->Fail(VERIFY_ERROR_GENERIC) << "monitor-exit on non-object (" << reg_type << ")";
786 } else if (monitors_.empty()) {
787 verifier_->Fail(VERIFY_ERROR_GENERIC) << "monitor-exit stack underflow";
788 } else {
Ian Rogers55d249f2011-11-02 16:48:09 -0700789 monitors_.pop_back();
Ian Rogersd81871c2011-10-03 13:57:23 -0700790 if(!IsSetLockDepth(reg_idx, monitors_.size())) {
791 // Bug 3215458: Locks and unlocks are on objects, if that object is a literal then before
792 // format "036" the constant collector may create unlocks on the same object but referenced
793 // via different registers.
794 ((verifier_->DexFileVersion() >= 36) ? verifier_->Fail(VERIFY_ERROR_GENERIC)
795 : verifier_->LogVerifyInfo())
796 << "monitor-exit not unlocking the top of the monitor stack";
797 } else {
798 // Record the register was unlocked
799 ClearRegToLockDepth(reg_idx, monitors_.size());
800 }
801 }
802}
803
804bool RegisterLine::VerifyMonitorStackEmpty() {
805 if (MonitorStackDepth() != 0) {
806 verifier_->Fail(VERIFY_ERROR_GENERIC) << "expected empty monitor stack";
807 return false;
808 } else {
809 return true;
810 }
811}
812
813bool RegisterLine::MergeRegisters(const RegisterLine* incoming_line) {
814 bool changed = false;
815 for (size_t idx = 0; idx < num_regs_; idx++) {
816 if (line_[idx] != incoming_line->line_[idx]) {
817 const RegType& incoming_reg_type = incoming_line->GetRegisterType(idx);
818 const RegType& cur_type = GetRegisterType(idx);
819 const RegType& new_type = cur_type.Merge(incoming_reg_type, verifier_->GetRegTypeCache());
820 changed = changed || !cur_type.Equals(new_type);
821 line_[idx] = new_type.GetId();
822 }
823 }
Ian Rogers55d249f2011-11-02 16:48:09 -0700824 if(monitors_.size() != incoming_line->monitors_.size()) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700825 verifier_->Fail(VERIFY_ERROR_GENERIC) << "mismatched stack depths (depth="
826 << MonitorStackDepth() << ", incoming depth=" << incoming_line->MonitorStackDepth() << ")";
827 } else if (reg_to_lock_depths_ != incoming_line->reg_to_lock_depths_) {
828 for (uint32_t idx = 0; idx < num_regs_; idx++) {
829 size_t depths = reg_to_lock_depths_.count(idx);
830 size_t incoming_depths = incoming_line->reg_to_lock_depths_.count(idx);
831 if (depths != incoming_depths) {
832 if (depths == 0 || incoming_depths == 0) {
833 reg_to_lock_depths_.erase(idx);
834 } else {
835 verifier_->Fail(VERIFY_ERROR_GENERIC) << "mismatched stack depths for register v" << idx
836 << ": " << depths << " != " << incoming_depths;
837 break;
838 }
839 }
840 }
841 }
842 return changed;
843}
844
845void RegisterLine::WriteReferenceBitMap(int8_t* data, size_t max_bytes) {
846 for (size_t i = 0; i < num_regs_; i += 8) {
847 uint8_t val = 0;
848 for (size_t j = 0; j < 8 && (i + j) < num_regs_; j++) {
849 // Note: we write 1 for a Reference but not for Null
Ian Rogers84fa0742011-10-25 18:13:30 -0700850 if (GetRegisterType(i + j).IsNonZeroReferenceTypes()) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700851 val |= 1 << j;
852 }
853 }
854 if (val != 0) {
855 DCHECK_LT(i / 8, max_bytes);
856 data[i / 8] = val;
857 }
858 }
859}
860
861std::ostream& operator<<(std::ostream& os, const RegisterLine& rhs) {
Ian Rogers2c8a8572011-10-24 17:11:36 -0700862 os << rhs.Dump();
Ian Rogersd81871c2011-10-03 13:57:23 -0700863 return os;
864}
865
866
867void PcToRegisterLineTable::Init(RegisterTrackingMode mode, InsnFlags* flags,
868 uint32_t insns_size, uint16_t registers_size,
869 DexVerifier* verifier) {
870 DCHECK_GT(insns_size, 0U);
871
872 for (uint32_t i = 0; i < insns_size; i++) {
873 bool interesting = false;
874 switch (mode) {
875 case kTrackRegsAll:
876 interesting = flags[i].IsOpcode();
877 break;
878 case kTrackRegsGcPoints:
879 interesting = flags[i].IsGcPoint() || flags[i].IsBranchTarget();
880 break;
881 case kTrackRegsBranches:
882 interesting = flags[i].IsBranchTarget();
883 break;
884 default:
885 break;
886 }
887 if (interesting) {
888 pc_to_register_line_[i] = new RegisterLine(registers_size, verifier);
889 }
890 }
891}
892
893bool DexVerifier::VerifyClass(const Class* klass) {
jeffhaobdb76512011-09-07 11:43:16 -0700894 if (klass->IsVerified()) {
895 return true;
896 }
Ian Rogersd81871c2011-10-03 13:57:23 -0700897 Class* super = klass->GetSuperClass();
Elliott Hughes91250e02011-12-13 22:30:35 -0800898 if (super == NULL && StringPiece(ClassHelper(klass).GetDescriptor()) != "Ljava/lang/Object;") {
Ian Rogersd81871c2011-10-03 13:57:23 -0700899 LOG(ERROR) << "Verifier rejected class " << PrettyClass(klass) << " that has no super class";
900 return false;
901 }
902 if (super != NULL) {
903 if (!super->IsVerified() && !super->IsErroneous()) {
904 Runtime::Current()->GetClassLinker()->VerifyClass(super);
905 }
906 if (!super->IsVerified()) {
907 LOG(ERROR) << "Verifier rejected class " << PrettyClass(klass)
908 << " that attempts to sub-class corrupt class " << PrettyClass(super);
909 return false;
910 } else if (super->IsFinal()) {
911 LOG(ERROR) << "Verifier rejected class " << PrettyClass(klass)
912 << " that attempts to sub-class final class " << PrettyClass(super);
913 return false;
914 }
915 }
jeffhaobdb76512011-09-07 11:43:16 -0700916 for (size_t i = 0; i < klass->NumDirectMethods(); ++i) {
917 Method* method = klass->GetDirectMethod(i);
918 if (!VerifyMethod(method)) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700919 LOG(ERROR) << "Verifier rejected class " << PrettyClass(klass) << " due to bad method "
920 << PrettyMethod(method, true);
jeffhaobdb76512011-09-07 11:43:16 -0700921 return false;
922 }
923 }
924 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
925 Method* method = klass->GetVirtualMethod(i);
926 if (!VerifyMethod(method)) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700927 LOG(ERROR) << "Verifier rejected class " << PrettyClass(klass) << " due to bad method "
928 << PrettyMethod(method, true);
jeffhaobdb76512011-09-07 11:43:16 -0700929 return false;
930 }
931 }
932 return true;
jeffhaoba5ebb92011-08-25 17:24:37 -0700933}
934
jeffhaobdb76512011-09-07 11:43:16 -0700935bool DexVerifier::VerifyMethod(Method* method) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700936 DexVerifier verifier(method);
937 bool success = verifier.Verify();
938 // We expect either success and no verification error, or failure and a generic failure to
939 // reject the class.
940 if (success) {
941 if (verifier.failure_ != VERIFY_ERROR_NONE) {
942 LOG(FATAL) << "Unhandled failure in verification of " << PrettyMethod(method) << std::endl
943 << verifier.fail_messages_;
944 }
945 } else {
946 LOG(INFO) << "Verification error in " << PrettyMethod(method) << " "
Ian Rogers5ed29bf2011-10-26 12:22:21 -0700947 << verifier.fail_messages_.str();
Ian Rogers2c8a8572011-10-24 17:11:36 -0700948 if (gDebugVerify) {
Ian Rogers5ed29bf2011-10-26 12:22:21 -0700949 std::cout << std::endl << verifier.info_messages_.str();
Ian Rogers2c8a8572011-10-24 17:11:36 -0700950 verifier.Dump(std::cout);
951 }
Ian Rogersd81871c2011-10-03 13:57:23 -0700952 DCHECK_EQ(verifier.failure_, VERIFY_ERROR_GENERIC);
953 }
954 return success;
955}
956
Shih-wei Liao371814f2011-10-27 16:52:10 -0700957void DexVerifier::VerifyMethodAndDump(Method* method) {
958 DexVerifier verifier(method);
959 verifier.Verify();
960
Elliott Hughese0918552011-10-28 17:18:29 -0700961 LOG(INFO) << "Dump of method " << PrettyMethod(method) << " "
962 << verifier.fail_messages_.str() << std::endl
963 << verifier.info_messages_.str() << Dumpable<DexVerifier>(verifier);
Shih-wei Liao371814f2011-10-27 16:52:10 -0700964}
965
Ian Rogers28ad40d2011-10-27 15:19:26 -0700966DexVerifier::DexVerifier(Method* method) : work_insn_idx_(-1), method_(method),
967 failure_(VERIFY_ERROR_NONE),
968
Ian Rogersd81871c2011-10-03 13:57:23 -0700969 new_instance_count_(0), monitor_enter_count_(0) {
jeffhaobdb76512011-09-07 11:43:16 -0700970 const DexCache* dex_cache = method->GetDeclaringClass()->GetDexCache();
971 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogersd81871c2011-10-03 13:57:23 -0700972 dex_file_ = &class_linker->FindDexFile(dex_cache);
973 code_item_ = dex_file_->GetCodeItem(method->GetCodeItemOffset());
jeffhaoba5ebb92011-08-25 17:24:37 -0700974}
975
Ian Rogersd81871c2011-10-03 13:57:23 -0700976bool DexVerifier::Verify() {
977 // If there aren't any instructions, make sure that's expected, then exit successfully.
978 if (code_item_ == NULL) {
979 if (!method_->IsNative() && !method_->IsAbstract()) {
980 Fail(VERIFY_ERROR_GENERIC) << "zero-length code in concrete non-native method";
jeffhaobdb76512011-09-07 11:43:16 -0700981 return false;
Ian Rogersd81871c2011-10-03 13:57:23 -0700982 } else {
983 return true;
jeffhaobdb76512011-09-07 11:43:16 -0700984 }
jeffhaobdb76512011-09-07 11:43:16 -0700985 }
Ian Rogersd81871c2011-10-03 13:57:23 -0700986 // Sanity-check the register counts. ins + locals = registers, so make sure that ins <= registers.
987 if (code_item_->ins_size_ > code_item_->registers_size_) {
988 Fail(VERIFY_ERROR_GENERIC) << "bad register counts (ins=" << code_item_->ins_size_
989 << " regs=" << code_item_->registers_size_;
990 return false;
jeffhaobdb76512011-09-07 11:43:16 -0700991 }
Ian Rogersd81871c2011-10-03 13:57:23 -0700992 // Allocate and initialize an array to hold instruction data.
993 insn_flags_.reset(new InsnFlags[code_item_->insns_size_in_code_units_]());
994 // Run through the instructions and see if the width checks out.
995 bool result = ComputeWidthsAndCountOps();
996 // Flag instructions guarded by a "try" block and check exception handlers.
997 result = result && ScanTryCatchBlocks();
998 // Perform static instruction verification.
999 result = result && VerifyInstructions();
1000 // Perform code flow analysis.
1001 result = result && VerifyCodeFlow();
jeffhaobdb76512011-09-07 11:43:16 -07001002 return result;
jeffhaoba5ebb92011-08-25 17:24:37 -07001003}
1004
Ian Rogersd81871c2011-10-03 13:57:23 -07001005bool DexVerifier::ComputeWidthsAndCountOps() {
1006 const uint16_t* insns = code_item_->insns_;
1007 size_t insns_size = code_item_->insns_size_in_code_units_;
1008 const Instruction* inst = Instruction::At(insns);
jeffhaobdb76512011-09-07 11:43:16 -07001009 size_t new_instance_count = 0;
1010 size_t monitor_enter_count = 0;
Ian Rogersd81871c2011-10-03 13:57:23 -07001011 size_t dex_pc = 0;
jeffhaobdb76512011-09-07 11:43:16 -07001012
Ian Rogersd81871c2011-10-03 13:57:23 -07001013 while (dex_pc < insns_size) {
jeffhaobdb76512011-09-07 11:43:16 -07001014 Instruction::Code opcode = inst->Opcode();
1015 if (opcode == Instruction::NEW_INSTANCE) {
1016 new_instance_count++;
1017 } else if (opcode == Instruction::MONITOR_ENTER) {
1018 monitor_enter_count++;
1019 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001020 size_t inst_size = inst->SizeInCodeUnits();
1021 insn_flags_[dex_pc].SetLengthInCodeUnits(inst_size);
1022 dex_pc += inst_size;
jeffhaobdb76512011-09-07 11:43:16 -07001023 inst = inst->Next();
1024 }
1025
Ian Rogersd81871c2011-10-03 13:57:23 -07001026 if (dex_pc != insns_size) {
1027 Fail(VERIFY_ERROR_GENERIC) << "code did not end where expected ("
1028 << dex_pc << " vs. " << insns_size << ")";
jeffhaobdb76512011-09-07 11:43:16 -07001029 return false;
1030 }
1031
Ian Rogersd81871c2011-10-03 13:57:23 -07001032 new_instance_count_ = new_instance_count;
1033 monitor_enter_count_ = monitor_enter_count;
jeffhaobdb76512011-09-07 11:43:16 -07001034 return true;
1035}
1036
Ian Rogersd81871c2011-10-03 13:57:23 -07001037bool DexVerifier::ScanTryCatchBlocks() {
1038 uint32_t tries_size = code_item_->tries_size_;
jeffhaobdb76512011-09-07 11:43:16 -07001039 if (tries_size == 0) {
1040 return true;
1041 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001042 uint32_t insns_size = code_item_->insns_size_in_code_units_;
Ian Rogers0571d352011-11-03 19:51:38 -07001043 const DexFile::TryItem* tries = DexFile::GetTryItems(*code_item_, 0);
jeffhaobdb76512011-09-07 11:43:16 -07001044
1045 for (uint32_t idx = 0; idx < tries_size; idx++) {
1046 const DexFile::TryItem* try_item = &tries[idx];
1047 uint32_t start = try_item->start_addr_;
1048 uint32_t end = start + try_item->insn_count_;
jeffhaobdb76512011-09-07 11:43:16 -07001049 if ((start >= end) || (start >= insns_size) || (end > insns_size)) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001050 Fail(VERIFY_ERROR_GENERIC) << "bad exception entry: startAddr=" << start
1051 << " endAddr=" << end << " (size=" << insns_size << ")";
jeffhaobdb76512011-09-07 11:43:16 -07001052 return false;
1053 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001054 if (!insn_flags_[start].IsOpcode()) {
1055 Fail(VERIFY_ERROR_GENERIC) << "'try' block starts inside an instruction (" << start << ")";
jeffhaobdb76512011-09-07 11:43:16 -07001056 return false;
1057 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001058 for (uint32_t dex_pc = start; dex_pc < end;
1059 dex_pc += insn_flags_[dex_pc].GetLengthInCodeUnits()) {
1060 insn_flags_[dex_pc].SetInTry();
jeffhaobdb76512011-09-07 11:43:16 -07001061 }
1062 }
jeffhaobdb76512011-09-07 11:43:16 -07001063 /* Iterate over each of the handlers to verify target addresses. */
Ian Rogers0571d352011-11-03 19:51:38 -07001064 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item_, 0);
jeffhaobdb76512011-09-07 11:43:16 -07001065 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Ian Rogers28ad40d2011-10-27 15:19:26 -07001066 ClassLinker* linker = Runtime::Current()->GetClassLinker();
jeffhaobdb76512011-09-07 11:43:16 -07001067 for (uint32_t idx = 0; idx < handlers_size; idx++) {
Ian Rogers0571d352011-11-03 19:51:38 -07001068 CatchHandlerIterator iterator(handlers_ptr);
1069 for (; iterator.HasNext(); iterator.Next()) {
1070 uint32_t dex_pc= iterator.GetHandlerAddress();
Ian Rogersd81871c2011-10-03 13:57:23 -07001071 if (!insn_flags_[dex_pc].IsOpcode()) {
1072 Fail(VERIFY_ERROR_GENERIC) << "exception handler starts at bad address (" << dex_pc << ")";
jeffhaobdb76512011-09-07 11:43:16 -07001073 return false;
1074 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001075 insn_flags_[dex_pc].SetBranchTarget();
Ian Rogers28ad40d2011-10-27 15:19:26 -07001076 // Ensure exception types are resolved so that they don't need resolution to be delivered,
1077 // unresolved exception types will be ignored by exception delivery
Ian Rogers0571d352011-11-03 19:51:38 -07001078 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
1079 Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method_);
Ian Rogers28ad40d2011-10-27 15:19:26 -07001080 if (exception_type == NULL) {
1081 DCHECK(Thread::Current()->IsExceptionPending());
1082 Thread::Current()->ClearException();
1083 }
1084 }
jeffhaobdb76512011-09-07 11:43:16 -07001085 }
Ian Rogers0571d352011-11-03 19:51:38 -07001086 handlers_ptr = iterator.EndDataPointer();
jeffhaobdb76512011-09-07 11:43:16 -07001087 }
jeffhaobdb76512011-09-07 11:43:16 -07001088 return true;
1089}
1090
Ian Rogersd81871c2011-10-03 13:57:23 -07001091bool DexVerifier::VerifyInstructions() {
1092 const Instruction* inst = Instruction::At(code_item_->insns_);
jeffhaoba5ebb92011-08-25 17:24:37 -07001093
Ian Rogersd81871c2011-10-03 13:57:23 -07001094 /* Flag the start of the method as a branch target. */
1095 insn_flags_[0].SetBranchTarget();
1096
1097 uint32_t insns_size = code_item_->insns_size_in_code_units_;
1098 for(uint32_t dex_pc = 0; dex_pc < insns_size;) {
1099 if (!VerifyInstruction(inst, dex_pc)) {
Ian Rogers2c8a8572011-10-24 17:11:36 -07001100 DCHECK_NE(failure_, VERIFY_ERROR_NONE);
1101 fail_messages_ << "Rejecting opcode " << inst->DumpString(dex_file_) << " at " << dex_pc;
Ian Rogersd81871c2011-10-03 13:57:23 -07001102 return false;
1103 }
1104 /* Flag instructions that are garbage collection points */
1105 if (inst->IsBranch() || inst->IsSwitch() || inst->IsThrow() || inst->IsReturn()) {
1106 insn_flags_[dex_pc].SetGcPoint();
1107 }
1108 dex_pc += inst->SizeInCodeUnits();
1109 inst = inst->Next();
1110 }
1111 return true;
1112}
1113
1114bool DexVerifier::VerifyInstruction(const Instruction* inst, uint32_t code_offset) {
1115 Instruction::DecodedInstruction dec_insn(inst);
1116 bool result = true;
1117 switch (inst->GetVerifyTypeArgumentA()) {
1118 case Instruction::kVerifyRegA:
1119 result = result && CheckRegisterIndex(dec_insn.vA_);
1120 break;
1121 case Instruction::kVerifyRegAWide:
1122 result = result && CheckWideRegisterIndex(dec_insn.vA_);
1123 break;
1124 }
1125 switch (inst->GetVerifyTypeArgumentB()) {
1126 case Instruction::kVerifyRegB:
1127 result = result && CheckRegisterIndex(dec_insn.vB_);
1128 break;
1129 case Instruction::kVerifyRegBField:
1130 result = result && CheckFieldIndex(dec_insn.vB_);
1131 break;
1132 case Instruction::kVerifyRegBMethod:
1133 result = result && CheckMethodIndex(dec_insn.vB_);
1134 break;
1135 case Instruction::kVerifyRegBNewInstance:
1136 result = result && CheckNewInstance(dec_insn.vB_);
1137 break;
1138 case Instruction::kVerifyRegBString:
1139 result = result && CheckStringIndex(dec_insn.vB_);
1140 break;
1141 case Instruction::kVerifyRegBType:
1142 result = result && CheckTypeIndex(dec_insn.vB_);
1143 break;
1144 case Instruction::kVerifyRegBWide:
1145 result = result && CheckWideRegisterIndex(dec_insn.vB_);
1146 break;
1147 }
1148 switch (inst->GetVerifyTypeArgumentC()) {
1149 case Instruction::kVerifyRegC:
1150 result = result && CheckRegisterIndex(dec_insn.vC_);
1151 break;
1152 case Instruction::kVerifyRegCField:
1153 result = result && CheckFieldIndex(dec_insn.vC_);
1154 break;
1155 case Instruction::kVerifyRegCNewArray:
1156 result = result && CheckNewArray(dec_insn.vC_);
1157 break;
1158 case Instruction::kVerifyRegCType:
1159 result = result && CheckTypeIndex(dec_insn.vC_);
1160 break;
1161 case Instruction::kVerifyRegCWide:
1162 result = result && CheckWideRegisterIndex(dec_insn.vC_);
1163 break;
1164 }
1165 switch (inst->GetVerifyExtraFlags()) {
1166 case Instruction::kVerifyArrayData:
1167 result = result && CheckArrayData(code_offset);
1168 break;
1169 case Instruction::kVerifyBranchTarget:
1170 result = result && CheckBranchTarget(code_offset);
1171 break;
1172 case Instruction::kVerifySwitchTargets:
1173 result = result && CheckSwitchTargets(code_offset);
1174 break;
1175 case Instruction::kVerifyVarArg:
1176 result = result && CheckVarArgRegs(dec_insn.vA_, dec_insn.arg_);
1177 break;
1178 case Instruction::kVerifyVarArgRange:
1179 result = result && CheckVarArgRangeRegs(dec_insn.vA_, dec_insn.vC_);
1180 break;
1181 case Instruction::kVerifyError:
1182 Fail(VERIFY_ERROR_GENERIC) << "unexpected opcode " << inst->Name();
1183 result = false;
1184 break;
1185 }
1186 return result;
1187}
1188
1189bool DexVerifier::CheckRegisterIndex(uint32_t idx) {
1190 if (idx >= code_item_->registers_size_) {
1191 Fail(VERIFY_ERROR_GENERIC) << "register index out of range (" << idx << " >= "
1192 << code_item_->registers_size_ << ")";
1193 return false;
1194 }
1195 return true;
1196}
1197
1198bool DexVerifier::CheckWideRegisterIndex(uint32_t idx) {
1199 if (idx + 1 >= code_item_->registers_size_) {
1200 Fail(VERIFY_ERROR_GENERIC) << "wide register index out of range (" << idx
1201 << "+1 >= " << code_item_->registers_size_ << ")";
1202 return false;
1203 }
1204 return true;
1205}
1206
1207bool DexVerifier::CheckFieldIndex(uint32_t idx) {
1208 if (idx >= dex_file_->GetHeader().field_ids_size_) {
1209 Fail(VERIFY_ERROR_GENERIC) << "bad field index " << idx << " (max "
1210 << dex_file_->GetHeader().field_ids_size_ << ")";
1211 return false;
1212 }
1213 return true;
1214}
1215
1216bool DexVerifier::CheckMethodIndex(uint32_t idx) {
1217 if (idx >= dex_file_->GetHeader().method_ids_size_) {
1218 Fail(VERIFY_ERROR_GENERIC) << "bad method index " << idx << " (max "
1219 << dex_file_->GetHeader().method_ids_size_ << ")";
1220 return false;
1221 }
1222 return true;
1223}
1224
1225bool DexVerifier::CheckNewInstance(uint32_t idx) {
1226 if (idx >= dex_file_->GetHeader().type_ids_size_) {
1227 Fail(VERIFY_ERROR_GENERIC) << "bad type index " << idx << " (max "
1228 << dex_file_->GetHeader().type_ids_size_ << ")";
1229 return false;
1230 }
1231 // We don't need the actual class, just a pointer to the class name.
Ian Rogers0571d352011-11-03 19:51:38 -07001232 const char* descriptor = dex_file_->StringByTypeIdx(idx);
Ian Rogersd81871c2011-10-03 13:57:23 -07001233 if (descriptor[0] != 'L') {
1234 Fail(VERIFY_ERROR_GENERIC) << "can't call new-instance on type '" << descriptor << "'";
1235 return false;
1236 }
1237 return true;
1238}
1239
1240bool DexVerifier::CheckStringIndex(uint32_t idx) {
1241 if (idx >= dex_file_->GetHeader().string_ids_size_) {
1242 Fail(VERIFY_ERROR_GENERIC) << "bad string index " << idx << " (max "
1243 << dex_file_->GetHeader().string_ids_size_ << ")";
1244 return false;
1245 }
1246 return true;
1247}
1248
1249bool DexVerifier::CheckTypeIndex(uint32_t idx) {
1250 if (idx >= dex_file_->GetHeader().type_ids_size_) {
1251 Fail(VERIFY_ERROR_GENERIC) << "bad type index " << idx << " (max "
1252 << dex_file_->GetHeader().type_ids_size_ << ")";
1253 return false;
1254 }
1255 return true;
1256}
1257
1258bool DexVerifier::CheckNewArray(uint32_t idx) {
1259 if (idx >= dex_file_->GetHeader().type_ids_size_) {
1260 Fail(VERIFY_ERROR_GENERIC) << "bad type index " << idx << " (max "
1261 << dex_file_->GetHeader().type_ids_size_ << ")";
1262 return false;
1263 }
1264 int bracket_count = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001265 const char* descriptor = dex_file_->StringByTypeIdx(idx);
Ian Rogersd81871c2011-10-03 13:57:23 -07001266 const char* cp = descriptor;
1267 while (*cp++ == '[') {
1268 bracket_count++;
1269 }
1270 if (bracket_count == 0) {
1271 /* The given class must be an array type. */
1272 Fail(VERIFY_ERROR_GENERIC) << "can't new-array class '" << descriptor << "' (not an array)";
1273 return false;
1274 } else if (bracket_count > 255) {
1275 /* It is illegal to create an array of more than 255 dimensions. */
1276 Fail(VERIFY_ERROR_GENERIC) << "can't new-array class '" << descriptor << "' (exceeds limit)";
1277 return false;
1278 }
1279 return true;
1280}
1281
1282bool DexVerifier::CheckArrayData(uint32_t cur_offset) {
1283 const uint32_t insn_count = code_item_->insns_size_in_code_units_;
1284 const uint16_t* insns = code_item_->insns_ + cur_offset;
1285 const uint16_t* array_data;
1286 int32_t array_data_offset;
1287
1288 DCHECK_LT(cur_offset, insn_count);
1289 /* make sure the start of the array data table is in range */
1290 array_data_offset = insns[1] | (((int32_t) insns[2]) << 16);
1291 if ((int32_t) cur_offset + array_data_offset < 0 ||
1292 cur_offset + array_data_offset + 2 >= insn_count) {
1293 Fail(VERIFY_ERROR_GENERIC) << "invalid array data start: at " << cur_offset
1294 << ", data offset " << array_data_offset << ", count " << insn_count;
1295 return false;
1296 }
1297 /* offset to array data table is a relative branch-style offset */
1298 array_data = insns + array_data_offset;
1299 /* make sure the table is 32-bit aligned */
1300 if ((((uint32_t) array_data) & 0x03) != 0) {
1301 Fail(VERIFY_ERROR_GENERIC) << "unaligned array data table: at " << cur_offset
1302 << ", data offset " << array_data_offset;
1303 return false;
1304 }
1305 uint32_t value_width = array_data[1];
1306 uint32_t value_count = *(uint32_t*) (&array_data[2]);
1307 uint32_t table_size = 4 + (value_width * value_count + 1) / 2;
1308 /* make sure the end of the switch is in range */
1309 if (cur_offset + array_data_offset + table_size > insn_count) {
1310 Fail(VERIFY_ERROR_GENERIC) << "invalid array data end: at " << cur_offset
1311 << ", data offset " << array_data_offset << ", end "
1312 << cur_offset + array_data_offset + table_size
1313 << ", count " << insn_count;
1314 return false;
1315 }
1316 return true;
1317}
1318
1319bool DexVerifier::CheckBranchTarget(uint32_t cur_offset) {
1320 int32_t offset;
1321 bool isConditional, selfOkay;
1322 if (!GetBranchOffset(cur_offset, &offset, &isConditional, &selfOkay)) {
1323 return false;
1324 }
1325 if (!selfOkay && offset == 0) {
1326 Fail(VERIFY_ERROR_GENERIC) << "branch offset of zero not allowed at" << (void*) cur_offset;
1327 return false;
1328 }
1329 // Check for 32-bit overflow. This isn't strictly necessary if we can depend on the VM to have
1330 // identical "wrap-around" behavior, but it's unwise to depend on that.
1331 if (((int64_t) cur_offset + (int64_t) offset) != (int64_t) (cur_offset + offset)) {
1332 Fail(VERIFY_ERROR_GENERIC) << "branch target overflow " << (void*) cur_offset << " +" << offset;
1333 return false;
1334 }
1335 const uint32_t insn_count = code_item_->insns_size_in_code_units_;
1336 int32_t abs_offset = cur_offset + offset;
1337 if (abs_offset < 0 || (uint32_t) abs_offset >= insn_count || !insn_flags_[abs_offset].IsOpcode()) {
1338 Fail(VERIFY_ERROR_GENERIC) << "invalid branch target " << offset << " (-> "
1339 << (void*) abs_offset << ") at " << (void*) cur_offset;
1340 return false;
1341 }
1342 insn_flags_[abs_offset].SetBranchTarget();
1343 return true;
1344}
1345
1346bool DexVerifier::GetBranchOffset(uint32_t cur_offset, int32_t* pOffset, bool* pConditional,
1347 bool* selfOkay) {
1348 const uint16_t* insns = code_item_->insns_ + cur_offset;
1349 *pConditional = false;
1350 *selfOkay = false;
jeffhaoba5ebb92011-08-25 17:24:37 -07001351 switch (*insns & 0xff) {
1352 case Instruction::GOTO:
1353 *pOffset = ((int16_t) *insns) >> 8;
jeffhaoba5ebb92011-08-25 17:24:37 -07001354 break;
1355 case Instruction::GOTO_32:
1356 *pOffset = insns[1] | (((uint32_t) insns[2]) << 16);
jeffhaoba5ebb92011-08-25 17:24:37 -07001357 *selfOkay = true;
1358 break;
1359 case Instruction::GOTO_16:
1360 *pOffset = (int16_t) insns[1];
jeffhaoba5ebb92011-08-25 17:24:37 -07001361 break;
1362 case Instruction::IF_EQ:
1363 case Instruction::IF_NE:
1364 case Instruction::IF_LT:
1365 case Instruction::IF_GE:
1366 case Instruction::IF_GT:
1367 case Instruction::IF_LE:
1368 case Instruction::IF_EQZ:
1369 case Instruction::IF_NEZ:
1370 case Instruction::IF_LTZ:
1371 case Instruction::IF_GEZ:
1372 case Instruction::IF_GTZ:
1373 case Instruction::IF_LEZ:
1374 *pOffset = (int16_t) insns[1];
1375 *pConditional = true;
jeffhaoba5ebb92011-08-25 17:24:37 -07001376 break;
1377 default:
1378 return false;
1379 break;
1380 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001381 return true;
1382}
1383
Ian Rogersd81871c2011-10-03 13:57:23 -07001384bool DexVerifier::CheckSwitchTargets(uint32_t cur_offset) {
1385 const uint32_t insn_count = code_item_->insns_size_in_code_units_;
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001386 DCHECK_LT(cur_offset, insn_count);
Ian Rogersd81871c2011-10-03 13:57:23 -07001387 const uint16_t* insns = code_item_->insns_ + cur_offset;
jeffhaoba5ebb92011-08-25 17:24:37 -07001388 /* make sure the start of the switch is in range */
Ian Rogersd81871c2011-10-03 13:57:23 -07001389 int32_t switch_offset = insns[1] | ((int32_t) insns[2]) << 16;
1390 if ((int32_t) cur_offset + switch_offset < 0 || cur_offset + switch_offset + 2 >= insn_count) {
1391 Fail(VERIFY_ERROR_GENERIC) << "invalid switch start: at " << cur_offset
1392 << ", switch offset " << switch_offset << ", count " << insn_count;
jeffhaoba5ebb92011-08-25 17:24:37 -07001393 return false;
1394 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001395 /* offset to switch table is a relative branch-style offset */
Ian Rogersd81871c2011-10-03 13:57:23 -07001396 const uint16_t* switch_insns = insns + switch_offset;
jeffhaoba5ebb92011-08-25 17:24:37 -07001397 /* make sure the table is 32-bit aligned */
1398 if ((((uint32_t) switch_insns) & 0x03) != 0) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001399 Fail(VERIFY_ERROR_GENERIC) << "unaligned switch table: at " << cur_offset
1400 << ", switch offset " << switch_offset;
jeffhaoba5ebb92011-08-25 17:24:37 -07001401 return false;
1402 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001403 uint32_t switch_count = switch_insns[1];
1404 int32_t keys_offset, targets_offset;
1405 uint16_t expected_signature;
jeffhaoba5ebb92011-08-25 17:24:37 -07001406 if ((*insns & 0xff) == Instruction::PACKED_SWITCH) {
1407 /* 0=sig, 1=count, 2/3=firstKey */
1408 targets_offset = 4;
1409 keys_offset = -1;
1410 expected_signature = Instruction::kPackedSwitchSignature;
1411 } else {
1412 /* 0=sig, 1=count, 2..count*2 = keys */
1413 keys_offset = 2;
1414 targets_offset = 2 + 2 * switch_count;
1415 expected_signature = Instruction::kSparseSwitchSignature;
1416 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001417 uint32_t table_size = targets_offset + switch_count * 2;
jeffhaoba5ebb92011-08-25 17:24:37 -07001418 if (switch_insns[0] != expected_signature) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001419 Fail(VERIFY_ERROR_GENERIC) << "wrong signature for switch table (" << (void*) switch_insns[0]
1420 << ", wanted " << (void*) expected_signature << ")";
jeffhaoba5ebb92011-08-25 17:24:37 -07001421 return false;
1422 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001423 /* make sure the end of the switch is in range */
1424 if (cur_offset + switch_offset + table_size > (uint32_t) insn_count) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001425 Fail(VERIFY_ERROR_GENERIC) << "invalid switch end: at " << cur_offset << ", switch offset "
1426 << switch_offset << ", end "
1427 << (cur_offset + switch_offset + table_size)
1428 << ", count " << insn_count;
jeffhaoba5ebb92011-08-25 17:24:37 -07001429 return false;
1430 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001431 /* for a sparse switch, verify the keys are in ascending order */
1432 if (keys_offset > 0 && switch_count > 1) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001433 int32_t last_key = switch_insns[keys_offset] | (switch_insns[keys_offset + 1] << 16);
1434 for (uint32_t targ = 1; targ < switch_count; targ++) {
jeffhaoba5ebb92011-08-25 17:24:37 -07001435 int32_t key = (int32_t) switch_insns[keys_offset + targ * 2] |
1436 (int32_t) (switch_insns[keys_offset + targ * 2 + 1] << 16);
1437 if (key <= last_key) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001438 Fail(VERIFY_ERROR_GENERIC) << "invalid packed switch: last key=" << last_key
1439 << ", this=" << key;
jeffhaoba5ebb92011-08-25 17:24:37 -07001440 return false;
1441 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001442 last_key = key;
1443 }
1444 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001445 /* verify each switch target */
Ian Rogersd81871c2011-10-03 13:57:23 -07001446 for (uint32_t targ = 0; targ < switch_count; targ++) {
1447 int32_t offset = (int32_t) switch_insns[targets_offset + targ * 2] |
1448 (int32_t) (switch_insns[targets_offset + targ * 2 + 1] << 16);
1449 int32_t abs_offset = cur_offset + offset;
1450 if (abs_offset < 0 || abs_offset >= (int32_t) insn_count || !insn_flags_[abs_offset].IsOpcode()) {
1451 Fail(VERIFY_ERROR_GENERIC) << "invalid switch target " << offset << " (-> "
1452 << (void*) abs_offset << ") at "
1453 << (void*) cur_offset << "[" << targ << "]";
jeffhaoba5ebb92011-08-25 17:24:37 -07001454 return false;
1455 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001456 insn_flags_[abs_offset].SetBranchTarget();
1457 }
1458 return true;
1459}
1460
1461bool DexVerifier::CheckVarArgRegs(uint32_t vA, uint32_t arg[]) {
1462 if (vA > 5) {
1463 Fail(VERIFY_ERROR_GENERIC) << "invalid arg count (" << vA << ") in non-range invoke)";
1464 return false;
1465 }
1466 uint16_t registers_size = code_item_->registers_size_;
1467 for (uint32_t idx = 0; idx < vA; idx++) {
1468 if (arg[idx] > registers_size) {
1469 Fail(VERIFY_ERROR_GENERIC) << "invalid reg index (" << arg[idx]
1470 << ") in non-range invoke (> " << registers_size << ")";
1471 return false;
1472 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001473 }
1474
1475 return true;
1476}
1477
Ian Rogersd81871c2011-10-03 13:57:23 -07001478bool DexVerifier::CheckVarArgRangeRegs(uint32_t vA, uint32_t vC) {
1479 uint16_t registers_size = code_item_->registers_size_;
1480 // vA/vC are unsigned 8-bit/16-bit quantities for /range instructions, so there's no risk of
1481 // integer overflow when adding them here.
1482 if (vA + vC > registers_size) {
1483 Fail(VERIFY_ERROR_GENERIC) << "invalid reg index " << vA << "+" << vC << " in range invoke (> "
1484 << registers_size << ")";
jeffhaoba5ebb92011-08-25 17:24:37 -07001485 return false;
1486 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001487 return true;
1488}
1489
Ian Rogersd81871c2011-10-03 13:57:23 -07001490bool DexVerifier::VerifyCodeFlow() {
1491 uint16_t registers_size = code_item_->registers_size_;
1492 uint32_t insns_size = code_item_->insns_size_in_code_units_;
jeffhaobdb76512011-09-07 11:43:16 -07001493
Ian Rogersd81871c2011-10-03 13:57:23 -07001494 if (registers_size * insns_size > 4*1024*1024) {
1495 Fail(VERIFY_ERROR_GENERIC) << "warning: method is huge (regs=" << registers_size
1496 << " insns_size=" << insns_size << ")";
1497 }
1498 /* Create and initialize table holding register status */
1499 reg_table_.Init(PcToRegisterLineTable::kTrackRegsGcPoints, insn_flags_.get(), insns_size,
1500 registers_size, this);
jeffhaobdb76512011-09-07 11:43:16 -07001501
Ian Rogersd81871c2011-10-03 13:57:23 -07001502 work_line_.reset(new RegisterLine(registers_size, this));
1503 saved_line_.reset(new RegisterLine(registers_size, this));
jeffhaobdb76512011-09-07 11:43:16 -07001504
Ian Rogersd81871c2011-10-03 13:57:23 -07001505 /* Initialize register types of method arguments. */
1506 if (!SetTypesFromSignature()) {
Ian Rogers2c8a8572011-10-24 17:11:36 -07001507 DCHECK_NE(failure_, VERIFY_ERROR_NONE);
1508 fail_messages_ << "Bad signature in " << PrettyMethod(method_);
Ian Rogersd81871c2011-10-03 13:57:23 -07001509 return false;
1510 }
1511 /* Perform code flow verification. */
1512 if (!CodeFlowVerifyMethod()) {
1513 return false;
jeffhaobdb76512011-09-07 11:43:16 -07001514 }
1515
Ian Rogersd81871c2011-10-03 13:57:23 -07001516 /* Generate a register map and add it to the method. */
1517 ByteArray* map = GenerateGcMap();
1518 if (map == NULL) {
1519 return false; // Not a real failure, but a failure to encode
1520 }
1521 method_->SetGcMap(map);
1522#ifndef NDEBUG
1523 VerifyGcMap();
1524#endif
jeffhaobdb76512011-09-07 11:43:16 -07001525 return true;
1526}
1527
Ian Rogersd81871c2011-10-03 13:57:23 -07001528void DexVerifier::Dump(std::ostream& os) {
1529 if (method_->IsNative()) {
1530 os << "Native method" << std::endl;
1531 return;
jeffhaobdb76512011-09-07 11:43:16 -07001532 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001533 DCHECK(code_item_ != NULL);
1534 const Instruction* inst = Instruction::At(code_item_->insns_);
1535 for (size_t dex_pc = 0; dex_pc < code_item_->insns_size_in_code_units_;
1536 dex_pc += insn_flags_[dex_pc].GetLengthInCodeUnits()) {
Ian Rogers2c8a8572011-10-24 17:11:36 -07001537 os << StringPrintf("0x%04x", dex_pc) << ": " << insn_flags_[dex_pc].Dump()
1538 << " " << inst->DumpHex(5) << " " << inst->DumpString(dex_file_) << std::endl;
Ian Rogersd81871c2011-10-03 13:57:23 -07001539 RegisterLine* reg_line = reg_table_.GetLine(dex_pc);
1540 if (reg_line != NULL) {
Ian Rogers2c8a8572011-10-24 17:11:36 -07001541 os << reg_line->Dump() << std::endl;
jeffhaobdb76512011-09-07 11:43:16 -07001542 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001543 inst = inst->Next();
1544 }
jeffhaobdb76512011-09-07 11:43:16 -07001545}
1546
Ian Rogersd81871c2011-10-03 13:57:23 -07001547static bool IsPrimitiveDescriptor(char descriptor) {
1548 switch (descriptor) {
jeffhaobdb76512011-09-07 11:43:16 -07001549 case 'I':
1550 case 'C':
1551 case 'S':
1552 case 'B':
1553 case 'Z':
jeffhaobdb76512011-09-07 11:43:16 -07001554 case 'F':
1555 case 'D':
1556 case 'J':
Ian Rogersd81871c2011-10-03 13:57:23 -07001557 return true;
jeffhaobdb76512011-09-07 11:43:16 -07001558 default:
1559 return false;
1560 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001561}
1562
Ian Rogersd81871c2011-10-03 13:57:23 -07001563bool DexVerifier::SetTypesFromSignature() {
1564 RegisterLine* reg_line = reg_table_.GetLine(0);
1565 int arg_start = code_item_->registers_size_ - code_item_->ins_size_;
1566 size_t expected_args = code_item_->ins_size_; /* long/double count as two */
jeffhaobdb76512011-09-07 11:43:16 -07001567
Ian Rogersd81871c2011-10-03 13:57:23 -07001568 DCHECK_GE(arg_start, 0); /* should have been verified earlier */
1569 //Include the "this" pointer.
1570 size_t cur_arg = 0;
1571 if (!method_->IsStatic()) {
1572 // If this is a constructor for a class other than java.lang.Object, mark the first ("this")
1573 // argument as uninitialized. This restricts field access until the superclass constructor is
1574 // called.
1575 Class* declaring_class = method_->GetDeclaringClass();
1576 if (method_->IsConstructor() && !declaring_class->IsObjectClass()) {
1577 reg_line->SetRegisterType(arg_start + cur_arg,
1578 reg_types_.UninitializedThisArgument(declaring_class));
1579 } else {
1580 reg_line->SetRegisterType(arg_start + cur_arg, reg_types_.FromClass(declaring_class));
jeffhaobdb76512011-09-07 11:43:16 -07001581 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001582 cur_arg++;
jeffhaobdb76512011-09-07 11:43:16 -07001583 }
1584
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001585 const DexFile::ProtoId& proto_id =
1586 dex_file_->GetMethodPrototype(dex_file_->GetMethodId(method_->GetDexMethodIndex()));
Ian Rogers0571d352011-11-03 19:51:38 -07001587 DexFileParameterIterator iterator(*dex_file_, proto_id);
Ian Rogersd81871c2011-10-03 13:57:23 -07001588
1589 for (; iterator.HasNext(); iterator.Next()) {
1590 const char* descriptor = iterator.GetDescriptor();
1591 if (descriptor == NULL) {
1592 LOG(FATAL) << "Null descriptor";
1593 }
1594 if (cur_arg >= expected_args) {
1595 Fail(VERIFY_ERROR_GENERIC) << "expected " << expected_args
1596 << " args, found more (" << descriptor << ")";
1597 return false;
1598 }
1599 switch (descriptor[0]) {
1600 case 'L':
1601 case '[':
1602 // We assume that reference arguments are initialized. The only way it could be otherwise
1603 // (assuming the caller was verified) is if the current method is <init>, but in that case
1604 // it's effectively considered initialized the instant we reach here (in the sense that we
1605 // can return without doing anything or call virtual methods).
1606 {
1607 const RegType& reg_type =
1608 reg_types_.FromDescriptor(method_->GetDeclaringClass()->GetClassLoader(), descriptor);
Ian Rogers84fa0742011-10-25 18:13:30 -07001609 reg_line->SetRegisterType(arg_start + cur_arg, reg_type);
Ian Rogersd81871c2011-10-03 13:57:23 -07001610 }
1611 break;
1612 case 'Z':
1613 reg_line->SetRegisterType(arg_start + cur_arg, reg_types_.Boolean());
1614 break;
1615 case 'C':
1616 reg_line->SetRegisterType(arg_start + cur_arg, reg_types_.Char());
1617 break;
1618 case 'B':
1619 reg_line->SetRegisterType(arg_start + cur_arg, reg_types_.Byte());
1620 break;
1621 case 'I':
1622 reg_line->SetRegisterType(arg_start + cur_arg, reg_types_.Integer());
1623 break;
1624 case 'S':
1625 reg_line->SetRegisterType(arg_start + cur_arg, reg_types_.Short());
1626 break;
1627 case 'F':
1628 reg_line->SetRegisterType(arg_start + cur_arg, reg_types_.Float());
1629 break;
1630 case 'J':
1631 case 'D': {
1632 const RegType& low_half = descriptor[0] == 'J' ? reg_types_.Long() : reg_types_.Double();
1633 reg_line->SetRegisterType(arg_start + cur_arg, low_half); // implicitly sets high-register
1634 cur_arg++;
1635 break;
1636 }
1637 default:
1638 Fail(VERIFY_ERROR_GENERIC) << "unexpected signature type char '" << descriptor << "'";
1639 return false;
1640 }
1641 cur_arg++;
1642 }
1643 if (cur_arg != expected_args) {
1644 Fail(VERIFY_ERROR_GENERIC) << "expected " << expected_args << " arguments, found " << cur_arg;
1645 return false;
1646 }
1647 const char* descriptor = dex_file_->GetReturnTypeDescriptor(proto_id);
1648 // Validate return type. We don't do the type lookup; just want to make sure that it has the right
1649 // format. Only major difference from the method argument format is that 'V' is supported.
1650 bool result;
1651 if (IsPrimitiveDescriptor(descriptor[0]) || descriptor[0] == 'V') {
1652 result = descriptor[1] == '\0';
1653 } else if (descriptor[0] == '[') { // single/multi-dimensional array of object/primitive
1654 size_t i = 0;
1655 do {
1656 i++;
1657 } while (descriptor[i] == '['); // process leading [
1658 if (descriptor[i] == 'L') { // object array
1659 do {
1660 i++; // find closing ;
1661 } while (descriptor[i] != ';' && descriptor[i] != '\0');
1662 result = descriptor[i] == ';';
1663 } else { // primitive array
1664 result = IsPrimitiveDescriptor(descriptor[i]) && descriptor[i + 1] == '\0';
1665 }
1666 } else if (descriptor[0] == 'L') {
1667 // could be more thorough here, but shouldn't be required
1668 size_t i = 0;
1669 do {
1670 i++;
1671 } while (descriptor[i] != ';' && descriptor[i] != '\0');
1672 result = descriptor[i] == ';';
1673 } else {
1674 result = false;
1675 }
1676 if (!result) {
1677 Fail(VERIFY_ERROR_GENERIC) << "unexpected char in return type descriptor '"
1678 << descriptor << "'";
1679 }
1680 return result;
jeffhaobdb76512011-09-07 11:43:16 -07001681}
1682
Ian Rogersd81871c2011-10-03 13:57:23 -07001683bool DexVerifier::CodeFlowVerifyMethod() {
1684 const uint16_t* insns = code_item_->insns_;
1685 const uint32_t insns_size = code_item_->insns_size_in_code_units_;
jeffhaoba5ebb92011-08-25 17:24:37 -07001686
jeffhaobdb76512011-09-07 11:43:16 -07001687 /* Begin by marking the first instruction as "changed". */
Ian Rogersd81871c2011-10-03 13:57:23 -07001688 insn_flags_[0].SetChanged();
1689 uint32_t start_guess = 0;
jeffhaoba5ebb92011-08-25 17:24:37 -07001690
jeffhaobdb76512011-09-07 11:43:16 -07001691 /* Continue until no instructions are marked "changed". */
1692 while (true) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001693 // Find the first marked one. Use "start_guess" as a way to find one quickly.
1694 uint32_t insn_idx = start_guess;
1695 for (; insn_idx < insns_size; insn_idx++) {
1696 if (insn_flags_[insn_idx].IsChanged())
jeffhaobdb76512011-09-07 11:43:16 -07001697 break;
1698 }
jeffhaobdb76512011-09-07 11:43:16 -07001699 if (insn_idx == insns_size) {
1700 if (start_guess != 0) {
1701 /* try again, starting from the top */
1702 start_guess = 0;
1703 continue;
1704 } else {
1705 /* all flags are clear */
1706 break;
1707 }
1708 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001709 // We carry the working set of registers from instruction to instruction. If this address can
1710 // be the target of a branch (or throw) instruction, or if we're skipping around chasing
1711 // "changed" flags, we need to load the set of registers from the table.
1712 // Because we always prefer to continue on to the next instruction, we should never have a
1713 // situation where we have a stray "changed" flag set on an instruction that isn't a branch
1714 // target.
1715 work_insn_idx_ = insn_idx;
1716 if (insn_flags_[insn_idx].IsBranchTarget()) {
1717 work_line_->CopyFromLine(reg_table_.GetLine(insn_idx));
jeffhaobdb76512011-09-07 11:43:16 -07001718 } else {
1719#ifndef NDEBUG
1720 /*
1721 * Sanity check: retrieve the stored register line (assuming
1722 * a full table) and make sure it actually matches.
1723 */
Ian Rogersd81871c2011-10-03 13:57:23 -07001724 RegisterLine* register_line = reg_table_.GetLine(insn_idx);
1725 if (register_line != NULL) {
1726 if (work_line_->CompareLine(register_line) != 0) {
1727 Dump(std::cout);
1728 std::cout << info_messages_.str();
1729 LOG(FATAL) << "work_line diverged in " << PrettyMethod(method_)
1730 << "@" << (void*)work_insn_idx_ << std::endl
1731 << " work_line=" << *work_line_ << std::endl
1732 << " expected=" << *register_line;
1733 }
jeffhaobdb76512011-09-07 11:43:16 -07001734 }
1735#endif
1736 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001737 if (!CodeFlowVerifyInstruction(&start_guess)) {
1738 fail_messages_ << std::endl << PrettyMethod(method_) << " failed to verify";
jeffhaoba5ebb92011-08-25 17:24:37 -07001739 return false;
1740 }
jeffhaobdb76512011-09-07 11:43:16 -07001741 /* Clear "changed" and mark as visited. */
Ian Rogersd81871c2011-10-03 13:57:23 -07001742 insn_flags_[insn_idx].SetVisited();
1743 insn_flags_[insn_idx].ClearChanged();
jeffhaobdb76512011-09-07 11:43:16 -07001744 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001745
Ian Rogersd81871c2011-10-03 13:57:23 -07001746 if (DEAD_CODE_SCAN && ((method_->GetAccessFlags() & kAccWritable) == 0)) {
jeffhaobdb76512011-09-07 11:43:16 -07001747 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001748 * Scan for dead code. There's nothing "evil" about dead code
jeffhaobdb76512011-09-07 11:43:16 -07001749 * (besides the wasted space), but it indicates a flaw somewhere
1750 * down the line, possibly in the verifier.
1751 *
1752 * If we've substituted "always throw" instructions into the stream,
1753 * we are almost certainly going to have some dead code.
1754 */
1755 int dead_start = -1;
Ian Rogersd81871c2011-10-03 13:57:23 -07001756 uint32_t insn_idx = 0;
1757 for (; insn_idx < insns_size; insn_idx += insn_flags_[insn_idx].GetLengthInCodeUnits()) {
jeffhaobdb76512011-09-07 11:43:16 -07001758 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001759 * Switch-statement data doesn't get "visited" by scanner. It
jeffhaobdb76512011-09-07 11:43:16 -07001760 * may or may not be preceded by a padding NOP (for alignment).
1761 */
1762 if (insns[insn_idx] == Instruction::kPackedSwitchSignature ||
1763 insns[insn_idx] == Instruction::kSparseSwitchSignature ||
1764 insns[insn_idx] == Instruction::kArrayDataSignature ||
1765 (insns[insn_idx] == Instruction::NOP &&
1766 (insns[insn_idx + 1] == Instruction::kPackedSwitchSignature ||
1767 insns[insn_idx + 1] == Instruction::kSparseSwitchSignature ||
1768 insns[insn_idx + 1] == Instruction::kArrayDataSignature))) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001769 insn_flags_[insn_idx].SetVisited();
jeffhaobdb76512011-09-07 11:43:16 -07001770 }
1771
Ian Rogersd81871c2011-10-03 13:57:23 -07001772 if (!insn_flags_[insn_idx].IsVisited()) {
jeffhaobdb76512011-09-07 11:43:16 -07001773 if (dead_start < 0)
1774 dead_start = insn_idx;
1775 } else if (dead_start >= 0) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001776 LogVerifyInfo() << "dead code " << (void*) dead_start << "-" << (void*) (insn_idx - 1);
jeffhaobdb76512011-09-07 11:43:16 -07001777 dead_start = -1;
1778 }
1779 }
1780 if (dead_start >= 0) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001781 LogVerifyInfo() << "dead code " << (void*) dead_start << "-" << (void*) (insn_idx - 1);
jeffhaoba5ebb92011-08-25 17:24:37 -07001782 }
1783 }
jeffhaobdb76512011-09-07 11:43:16 -07001784 return true;
1785}
1786
Ian Rogersd81871c2011-10-03 13:57:23 -07001787bool DexVerifier::CodeFlowVerifyInstruction(uint32_t* start_guess) {
jeffhaobdb76512011-09-07 11:43:16 -07001788#ifdef VERIFIER_STATS
Ian Rogersd81871c2011-10-03 13:57:23 -07001789 if (CurrentInsnFlags().IsVisited()) {
jeffhaobdb76512011-09-07 11:43:16 -07001790 gDvm.verifierStats.instrsReexamined++;
1791 } else {
1792 gDvm.verifierStats.instrsExamined++;
1793 }
1794#endif
1795
1796 /*
1797 * Once we finish decoding the instruction, we need to figure out where
jeffhaod1f0fde2011-09-08 17:25:33 -07001798 * we can go from here. There are three possible ways to transfer
jeffhaobdb76512011-09-07 11:43:16 -07001799 * control to another statement:
1800 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001801 * (1) Continue to the next instruction. Applies to all but
jeffhaobdb76512011-09-07 11:43:16 -07001802 * unconditional branches, method returns, and exception throws.
jeffhaod1f0fde2011-09-08 17:25:33 -07001803 * (2) Branch to one or more possible locations. Applies to branches
jeffhaobdb76512011-09-07 11:43:16 -07001804 * and switch statements.
jeffhaod1f0fde2011-09-08 17:25:33 -07001805 * (3) Exception handlers. Applies to any instruction that can
jeffhaobdb76512011-09-07 11:43:16 -07001806 * throw an exception that is handled by an encompassing "try"
1807 * block.
1808 *
1809 * We can also return, in which case there is no successor instruction
1810 * from this point.
1811 *
1812 * The behavior can be determined from the OpcodeFlags.
1813 */
Ian Rogersd81871c2011-10-03 13:57:23 -07001814 const uint16_t* insns = code_item_->insns_ + work_insn_idx_;
1815 const Instruction* inst = Instruction::At(insns);
jeffhaobdb76512011-09-07 11:43:16 -07001816 Instruction::DecodedInstruction dec_insn(inst);
1817 int opcode_flag = inst->Flag();
1818
jeffhaobdb76512011-09-07 11:43:16 -07001819 int32_t branch_target = 0;
jeffhaobdb76512011-09-07 11:43:16 -07001820 bool just_set_result = false;
Ian Rogers2c8a8572011-10-24 17:11:36 -07001821 if (gDebugVerify) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001822 // Generate processing back trace to debug verifier
Ian Rogers5ed29bf2011-10-26 12:22:21 -07001823 LogVerifyInfo() << "Processing " << inst->DumpString(dex_file_) << std::endl
1824 << *work_line_.get() << std::endl;
Ian Rogersd81871c2011-10-03 13:57:23 -07001825 }
jeffhaobdb76512011-09-07 11:43:16 -07001826
1827 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001828 * Make a copy of the previous register state. If the instruction
jeffhaobdb76512011-09-07 11:43:16 -07001829 * can throw an exception, we will copy/merge this into the "catch"
1830 * address rather than work_line, because we don't want the result
1831 * from the "successful" code path (e.g. a check-cast that "improves"
1832 * a type) to be visible to the exception handler.
1833 */
Ian Rogersd81871c2011-10-03 13:57:23 -07001834 if ((opcode_flag & Instruction::kThrow) != 0 && CurrentInsnFlags().IsInTry()) {
1835 saved_line_->CopyFromLine(work_line_.get());
jeffhaobdb76512011-09-07 11:43:16 -07001836 } else {
1837#ifndef NDEBUG
Ian Rogersd81871c2011-10-03 13:57:23 -07001838 saved_line_->FillWithGarbage();
jeffhaobdb76512011-09-07 11:43:16 -07001839#endif
1840 }
1841
1842 switch (dec_insn.opcode_) {
1843 case Instruction::NOP:
1844 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001845 * A "pure" NOP has no effect on anything. Data tables start with
jeffhaobdb76512011-09-07 11:43:16 -07001846 * a signature that looks like a NOP; if we see one of these in
1847 * the course of executing code then we have a problem.
1848 */
1849 if (dec_insn.vA_ != 0) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001850 Fail(VERIFY_ERROR_GENERIC) << "encountered data table in instruction stream";
jeffhaobdb76512011-09-07 11:43:16 -07001851 }
1852 break;
1853
1854 case Instruction::MOVE:
1855 case Instruction::MOVE_FROM16:
1856 case Instruction::MOVE_16:
Ian Rogersd81871c2011-10-03 13:57:23 -07001857 work_line_->CopyRegister1(dec_insn.vA_, dec_insn.vB_, kTypeCategory1nr);
jeffhaobdb76512011-09-07 11:43:16 -07001858 break;
1859 case Instruction::MOVE_WIDE:
1860 case Instruction::MOVE_WIDE_FROM16:
1861 case Instruction::MOVE_WIDE_16:
Ian Rogersd81871c2011-10-03 13:57:23 -07001862 work_line_->CopyRegister2(dec_insn.vA_, dec_insn.vB_);
jeffhaobdb76512011-09-07 11:43:16 -07001863 break;
1864 case Instruction::MOVE_OBJECT:
1865 case Instruction::MOVE_OBJECT_FROM16:
1866 case Instruction::MOVE_OBJECT_16:
Ian Rogersd81871c2011-10-03 13:57:23 -07001867 work_line_->CopyRegister1(dec_insn.vA_, dec_insn.vB_, kTypeCategoryRef);
jeffhaobdb76512011-09-07 11:43:16 -07001868 break;
1869
1870 /*
1871 * The move-result instructions copy data out of a "pseudo-register"
jeffhaod1f0fde2011-09-08 17:25:33 -07001872 * with the results from the last method invocation. In practice we
jeffhaobdb76512011-09-07 11:43:16 -07001873 * might want to hold the result in an actual CPU register, so the
1874 * Dalvik spec requires that these only appear immediately after an
1875 * invoke or filled-new-array.
1876 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001877 * These calls invalidate the "result" register. (This is now
jeffhaobdb76512011-09-07 11:43:16 -07001878 * redundant with the reset done below, but it can make the debug info
1879 * easier to read in some cases.)
1880 */
1881 case Instruction::MOVE_RESULT:
Ian Rogersd81871c2011-10-03 13:57:23 -07001882 work_line_->CopyResultRegister1(dec_insn.vA_, false);
jeffhaobdb76512011-09-07 11:43:16 -07001883 break;
1884 case Instruction::MOVE_RESULT_WIDE:
Ian Rogersd81871c2011-10-03 13:57:23 -07001885 work_line_->CopyResultRegister2(dec_insn.vA_);
jeffhaobdb76512011-09-07 11:43:16 -07001886 break;
1887 case Instruction::MOVE_RESULT_OBJECT:
Ian Rogersd81871c2011-10-03 13:57:23 -07001888 work_line_->CopyResultRegister1(dec_insn.vA_, true);
jeffhaobdb76512011-09-07 11:43:16 -07001889 break;
1890
Ian Rogersd81871c2011-10-03 13:57:23 -07001891 case Instruction::MOVE_EXCEPTION: {
jeffhaobdb76512011-09-07 11:43:16 -07001892 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07001893 * This statement can only appear as the first instruction in an exception handler (though not
1894 * all exception handlers need to have one of these). We verify that as part of extracting the
jeffhaobdb76512011-09-07 11:43:16 -07001895 * exception type from the catch block list.
jeffhaobdb76512011-09-07 11:43:16 -07001896 */
Ian Rogers28ad40d2011-10-27 15:19:26 -07001897 const RegType& res_type = GetCaughtExceptionType();
1898 work_line_->SetRegisterType(dec_insn.vA_, res_type);
jeffhaobdb76512011-09-07 11:43:16 -07001899 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07001900 }
jeffhaobdb76512011-09-07 11:43:16 -07001901 case Instruction::RETURN_VOID:
Ian Rogersd81871c2011-10-03 13:57:23 -07001902 if (!method_->IsConstructor() || work_line_->CheckConstructorReturn()) {
1903 if (!GetMethodReturnType().IsUnknown()) {
1904 Fail(VERIFY_ERROR_GENERIC) << "return-void not expected";
1905 }
jeffhaobdb76512011-09-07 11:43:16 -07001906 }
1907 break;
1908 case Instruction::RETURN:
Ian Rogersd81871c2011-10-03 13:57:23 -07001909 if (!method_->IsConstructor() || work_line_->CheckConstructorReturn()) {
jeffhaobdb76512011-09-07 11:43:16 -07001910 /* check the method signature */
Ian Rogersd81871c2011-10-03 13:57:23 -07001911 const RegType& return_type = GetMethodReturnType();
1912 if (!return_type.IsCategory1Types()) {
1913 Fail(VERIFY_ERROR_GENERIC) << "unexpected non-category 1 return type " << return_type;
1914 } else {
1915 // Compilers may generate synthetic functions that write byte values into boolean fields.
1916 // Also, it may use integer values for boolean, byte, short, and character return types.
1917 const RegType& src_type = work_line_->GetRegisterType(dec_insn.vA_);
1918 bool use_src = ((return_type.IsBoolean() && src_type.IsByte()) ||
1919 ((return_type.IsBoolean() || return_type.IsByte() ||
1920 return_type.IsShort() || return_type.IsChar()) &&
1921 src_type.IsInteger()));
1922 /* check the register contents */
1923 work_line_->VerifyRegisterType(dec_insn.vA_, use_src ? src_type : return_type);
1924 if (failure_ != VERIFY_ERROR_NONE) {
Ian Rogers84fa0742011-10-25 18:13:30 -07001925 fail_messages_ << " return-1nr on invalid register v" << dec_insn.vA_;
Ian Rogersd81871c2011-10-03 13:57:23 -07001926 }
jeffhaobdb76512011-09-07 11:43:16 -07001927 }
1928 }
1929 break;
1930 case Instruction::RETURN_WIDE:
Ian Rogersd81871c2011-10-03 13:57:23 -07001931 if (!method_->IsConstructor() || work_line_->CheckConstructorReturn()) {
jeffhaobdb76512011-09-07 11:43:16 -07001932 /* check the method signature */
Ian Rogersd81871c2011-10-03 13:57:23 -07001933 const RegType& return_type = GetMethodReturnType();
1934 if (!return_type.IsCategory2Types()) {
1935 Fail(VERIFY_ERROR_GENERIC) << "return-wide not expected";
1936 } else {
1937 /* check the register contents */
1938 work_line_->VerifyRegisterType(dec_insn.vA_, return_type);
1939 if (failure_ != VERIFY_ERROR_NONE) {
Ian Rogers84fa0742011-10-25 18:13:30 -07001940 fail_messages_ << " return-wide on invalid register pair v" << dec_insn.vA_;
Ian Rogersd81871c2011-10-03 13:57:23 -07001941 }
jeffhaobdb76512011-09-07 11:43:16 -07001942 }
1943 }
1944 break;
1945 case Instruction::RETURN_OBJECT:
Ian Rogersd81871c2011-10-03 13:57:23 -07001946 if (!method_->IsConstructor() || work_line_->CheckConstructorReturn()) {
1947 const RegType& return_type = GetMethodReturnType();
1948 if (!return_type.IsReferenceTypes()) {
1949 Fail(VERIFY_ERROR_GENERIC) << "return-object not expected";
1950 } else {
1951 /* return_type is the *expected* return type, not register value */
1952 DCHECK(!return_type.IsZero());
1953 DCHECK(!return_type.IsUninitializedReference());
Ian Rogers9074b992011-10-26 17:41:55 -07001954 const RegType& reg_type = work_line_->GetRegisterType(dec_insn.vA_);
1955 // Disallow returning uninitialized values and verify that the reference in vAA is an
1956 // instance of the "return_type"
1957 if (reg_type.IsUninitializedTypes()) {
1958 Fail(VERIFY_ERROR_GENERIC) << "returning uninitialized object '" << reg_type << "'";
1959 } else if (!return_type.IsAssignableFrom(reg_type)) {
1960 Fail(VERIFY_ERROR_GENERIC) << "returning '" << reg_type
1961 << "', but expected from declaration '" << return_type << "'";
jeffhaobdb76512011-09-07 11:43:16 -07001962 }
1963 }
1964 }
1965 break;
1966
1967 case Instruction::CONST_4:
1968 case Instruction::CONST_16:
1969 case Instruction::CONST:
1970 /* could be boolean, int, float, or a null reference */
Ian Rogersd81871c2011-10-03 13:57:23 -07001971 work_line_->SetRegisterType(dec_insn.vA_, reg_types_.FromCat1Const((int32_t) dec_insn.vB_));
jeffhaobdb76512011-09-07 11:43:16 -07001972 break;
1973 case Instruction::CONST_HIGH16:
1974 /* could be boolean, int, float, or a null reference */
Ian Rogersd81871c2011-10-03 13:57:23 -07001975 work_line_->SetRegisterType(dec_insn.vA_,
1976 reg_types_.FromCat1Const((int32_t) dec_insn.vB_ << 16));
jeffhaobdb76512011-09-07 11:43:16 -07001977 break;
1978 case Instruction::CONST_WIDE_16:
1979 case Instruction::CONST_WIDE_32:
1980 case Instruction::CONST_WIDE:
1981 case Instruction::CONST_WIDE_HIGH16:
1982 /* could be long or double; resolved upon use */
Ian Rogersd81871c2011-10-03 13:57:23 -07001983 work_line_->SetRegisterType(dec_insn.vA_, reg_types_.ConstLo());
jeffhaobdb76512011-09-07 11:43:16 -07001984 break;
1985 case Instruction::CONST_STRING:
1986 case Instruction::CONST_STRING_JUMBO:
Ian Rogersd81871c2011-10-03 13:57:23 -07001987 work_line_->SetRegisterType(dec_insn.vA_, reg_types_.JavaLangString());
jeffhaobdb76512011-09-07 11:43:16 -07001988 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07001989 case Instruction::CONST_CLASS: {
Ian Rogers28ad40d2011-10-27 15:19:26 -07001990 // Get type from instruction if unresolved then we need an access check
1991 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved
1992 const RegType& res_type = ResolveClassAndCheckAccess(dec_insn.vB_);
1993 // Register holds class, ie its type is class, but on error we keep it Unknown
1994 work_line_->SetRegisterType(dec_insn.vA_,
1995 res_type.IsUnknown() ? res_type : reg_types_.JavaLangClass());
jeffhaobdb76512011-09-07 11:43:16 -07001996 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07001997 }
jeffhaobdb76512011-09-07 11:43:16 -07001998 case Instruction::MONITOR_ENTER:
Ian Rogersd81871c2011-10-03 13:57:23 -07001999 work_line_->PushMonitor(dec_insn.vA_, work_insn_idx_);
jeffhaobdb76512011-09-07 11:43:16 -07002000 break;
2001 case Instruction::MONITOR_EXIT:
2002 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07002003 * monitor-exit instructions are odd. They can throw exceptions,
jeffhaobdb76512011-09-07 11:43:16 -07002004 * but when they do they act as if they succeeded and the PC is
jeffhaod1f0fde2011-09-08 17:25:33 -07002005 * pointing to the following instruction. (This behavior goes back
jeffhaobdb76512011-09-07 11:43:16 -07002006 * to the need to handle asynchronous exceptions, a now-deprecated
2007 * feature that Dalvik doesn't support.)
2008 *
jeffhaod1f0fde2011-09-08 17:25:33 -07002009 * In practice we don't need to worry about this. The only
jeffhaobdb76512011-09-07 11:43:16 -07002010 * exceptions that can be thrown from monitor-exit are for a
jeffhaod1f0fde2011-09-08 17:25:33 -07002011 * null reference and -exit without a matching -enter. If the
jeffhaobdb76512011-09-07 11:43:16 -07002012 * structured locking checks are working, the former would have
2013 * failed on the -enter instruction, and the latter is impossible.
2014 *
2015 * This is fortunate, because issue 3221411 prevents us from
2016 * chasing the "can throw" path when monitor verification is
jeffhaod1f0fde2011-09-08 17:25:33 -07002017 * enabled. If we can fully verify the locking we can ignore
jeffhaobdb76512011-09-07 11:43:16 -07002018 * some catch blocks (which will show up as "dead" code when
2019 * we skip them here); if we can't, then the code path could be
2020 * "live" so we still need to check it.
2021 */
Ian Rogersd81871c2011-10-03 13:57:23 -07002022 opcode_flag &= ~Instruction::kThrow;
2023 work_line_->PopMonitor(dec_insn.vA_);
jeffhaobdb76512011-09-07 11:43:16 -07002024 break;
2025
Ian Rogers28ad40d2011-10-27 15:19:26 -07002026 case Instruction::CHECK_CAST:
Ian Rogersd81871c2011-10-03 13:57:23 -07002027 case Instruction::INSTANCE_OF: {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002028 /*
2029 * If this instruction succeeds, we will "downcast" register vA to the type in vB. (This
2030 * could be a "upcast" -- not expected, so we don't try to address it.)
2031 *
2032 * If it fails, an exception is thrown, which we deal with later by ignoring the update to
2033 * dec_insn.vA_ when branching to a handler.
2034 */
2035 bool is_checkcast = dec_insn.opcode_ == Instruction::CHECK_CAST;
2036 const RegType& res_type =
2037 ResolveClassAndCheckAccess(is_checkcast ? dec_insn.vB_ : dec_insn.vC_);
Ian Rogers9f1ab122011-12-12 08:52:43 -08002038 if (res_type.IsUnknown()) {
2039 CHECK_NE(failure_, VERIFY_ERROR_NONE);
2040 break; // couldn't resolve class
2041 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07002042 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved
2043 const RegType& orig_type =
2044 work_line_->GetRegisterType(is_checkcast ? dec_insn.vA_ : dec_insn.vB_);
2045 if (!res_type.IsNonZeroReferenceTypes()) {
2046 Fail(VERIFY_ERROR_GENERIC) << "check-cast on unexpected class " << res_type;
2047 } else if (!orig_type.IsReferenceTypes()) {
2048 Fail(VERIFY_ERROR_GENERIC) << "check-cast on non-reference in v" << dec_insn.vA_;
jeffhao2a8a90e2011-09-26 14:25:31 -07002049 } else {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002050 if (is_checkcast) {
2051 work_line_->SetRegisterType(dec_insn.vA_, res_type);
Ian Rogersd81871c2011-10-03 13:57:23 -07002052 } else {
Ian Rogersd81871c2011-10-03 13:57:23 -07002053 work_line_->SetRegisterType(dec_insn.vA_, reg_types_.Boolean());
jeffhaobdb76512011-09-07 11:43:16 -07002054 }
jeffhaobdb76512011-09-07 11:43:16 -07002055 }
jeffhao2a8a90e2011-09-26 14:25:31 -07002056 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002057 }
2058 case Instruction::ARRAY_LENGTH: {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002059 const RegType& res_type = work_line_->GetRegisterType(dec_insn.vB_);
2060 if (res_type.IsReferenceTypes()) {
Ian Rogers90f2b302011-10-29 15:05:54 -07002061 if (!res_type.IsArrayClass() && !res_type.IsZero()) { // ie not an array or null
Ian Rogers28ad40d2011-10-27 15:19:26 -07002062 Fail(VERIFY_ERROR_GENERIC) << "array-length on non-array " << res_type;
Ian Rogersd81871c2011-10-03 13:57:23 -07002063 } else {
2064 work_line_->SetRegisterType(dec_insn.vA_, reg_types_.Integer());
2065 }
2066 }
2067 break;
2068 }
2069 case Instruction::NEW_INSTANCE: {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002070 const RegType& res_type = ResolveClassAndCheckAccess(dec_insn.vB_);
2071 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved
2072 // can't create an instance of an interface or abstract class */
2073 if (!res_type.IsInstantiableTypes()) {
2074 Fail(VERIFY_ERROR_INSTANTIATION)
2075 << "new-instance on primitive, interface or abstract class" << res_type;
Ian Rogersd81871c2011-10-03 13:57:23 -07002076 } else {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002077 const RegType& uninit_type = reg_types_.Uninitialized(res_type, work_insn_idx_);
2078 // Any registers holding previous allocations from this address that have not yet been
2079 // initialized must be marked invalid.
2080 work_line_->MarkUninitRefsAsInvalid(uninit_type);
2081 // add the new uninitialized reference to the register state
2082 work_line_->SetRegisterType(dec_insn.vA_, uninit_type);
Ian Rogersd81871c2011-10-03 13:57:23 -07002083 }
2084 break;
2085 }
2086 case Instruction::NEW_ARRAY: {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002087 const RegType& res_type = ResolveClassAndCheckAccess(dec_insn.vC_);
2088 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved
2089 if (!res_type.IsArrayClass()) {
2090 Fail(VERIFY_ERROR_GENERIC) << "new-array on non-array class " << res_type;
jeffhaobdb76512011-09-07 11:43:16 -07002091 } else {
2092 /* make sure "size" register is valid type */
Ian Rogersd81871c2011-10-03 13:57:23 -07002093 work_line_->VerifyRegisterType(dec_insn.vB_, reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07002094 /* set register type to array class */
Ian Rogers28ad40d2011-10-27 15:19:26 -07002095 work_line_->SetRegisterType(dec_insn.vA_, res_type);
jeffhaobdb76512011-09-07 11:43:16 -07002096 }
2097 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002098 }
jeffhaobdb76512011-09-07 11:43:16 -07002099 case Instruction::FILLED_NEW_ARRAY:
Ian Rogersd81871c2011-10-03 13:57:23 -07002100 case Instruction::FILLED_NEW_ARRAY_RANGE: {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002101 const RegType& res_type = ResolveClassAndCheckAccess(dec_insn.vB_);
2102 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved
2103 if (!res_type.IsArrayClass()) {
Ian Rogersd81871c2011-10-03 13:57:23 -07002104 Fail(VERIFY_ERROR_GENERIC) << "filled-new-array on non-array class";
jeffhaobdb76512011-09-07 11:43:16 -07002105 } else {
jeffhaoe0cfb6f2011-09-22 16:42:56 -07002106 bool is_range = (dec_insn.opcode_ == Instruction::FILLED_NEW_ARRAY_RANGE);
jeffhaobdb76512011-09-07 11:43:16 -07002107 /* check the arguments to the instruction */
Ian Rogers28ad40d2011-10-27 15:19:26 -07002108 VerifyFilledNewArrayRegs(dec_insn, res_type, is_range);
jeffhaobdb76512011-09-07 11:43:16 -07002109 /* filled-array result goes into "result" register */
Ian Rogers28ad40d2011-10-27 15:19:26 -07002110 work_line_->SetResultRegisterType(res_type);
jeffhaobdb76512011-09-07 11:43:16 -07002111 just_set_result = true;
2112 }
2113 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002114 }
jeffhaobdb76512011-09-07 11:43:16 -07002115 case Instruction::CMPL_FLOAT:
2116 case Instruction::CMPG_FLOAT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002117 work_line_->VerifyRegisterType(dec_insn.vB_, reg_types_.Float());
2118 work_line_->VerifyRegisterType(dec_insn.vC_, reg_types_.Float());
2119 work_line_->SetRegisterType(dec_insn.vA_, reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07002120 break;
2121 case Instruction::CMPL_DOUBLE:
2122 case Instruction::CMPG_DOUBLE:
Ian Rogersd81871c2011-10-03 13:57:23 -07002123 work_line_->VerifyRegisterType(dec_insn.vB_, reg_types_.Double());
2124 work_line_->VerifyRegisterType(dec_insn.vC_, reg_types_.Double());
2125 work_line_->SetRegisterType(dec_insn.vA_, reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07002126 break;
2127 case Instruction::CMP_LONG:
Ian Rogersd81871c2011-10-03 13:57:23 -07002128 work_line_->VerifyRegisterType(dec_insn.vB_, reg_types_.Long());
2129 work_line_->VerifyRegisterType(dec_insn.vC_, reg_types_.Long());
2130 work_line_->SetRegisterType(dec_insn.vA_, reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07002131 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002132 case Instruction::THROW: {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002133 const RegType& res_type = work_line_->GetRegisterType(dec_insn.vA_);
2134 if (!reg_types_.JavaLangThrowable().IsAssignableFrom(res_type)) {
2135 Fail(VERIFY_ERROR_GENERIC) << "thrown class " << res_type << " not instanceof Throwable";
jeffhaobdb76512011-09-07 11:43:16 -07002136 }
2137 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002138 }
jeffhaobdb76512011-09-07 11:43:16 -07002139 case Instruction::GOTO:
2140 case Instruction::GOTO_16:
2141 case Instruction::GOTO_32:
2142 /* no effect on or use of registers */
2143 break;
2144
2145 case Instruction::PACKED_SWITCH:
2146 case Instruction::SPARSE_SWITCH:
2147 /* verify that vAA is an integer, or can be converted to one */
Ian Rogersd81871c2011-10-03 13:57:23 -07002148 work_line_->VerifyRegisterType(dec_insn.vA_, reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07002149 break;
2150
Ian Rogersd81871c2011-10-03 13:57:23 -07002151 case Instruction::FILL_ARRAY_DATA: {
2152 /* Similar to the verification done for APUT */
2153 Class* res_class = work_line_->GetClassFromRegister(dec_insn.vA_);
2154 if (failure_ == VERIFY_ERROR_NONE) {
jeffhaobdb76512011-09-07 11:43:16 -07002155 /* res_class can be null if the reg type is Zero */
Ian Rogersd81871c2011-10-03 13:57:23 -07002156 if (res_class != NULL) {
2157 Class* component_type = res_class->GetComponentType();
2158 if (!res_class->IsArrayClass() || !component_type->IsPrimitive() ||
2159 component_type->IsPrimitiveVoid()) {
2160 Fail(VERIFY_ERROR_GENERIC) << "invalid fill-array-data on "
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002161 << PrettyDescriptor(res_class);
Ian Rogersd81871c2011-10-03 13:57:23 -07002162 } else {
2163 const RegType& value_type = reg_types_.FromClass(component_type);
2164 DCHECK(!value_type.IsUnknown());
2165 // Now verify if the element width in the table matches the element width declared in
2166 // the array
2167 const uint16_t* array_data = insns + (insns[1] | (((int32_t) insns[2]) << 16));
2168 if (array_data[0] != Instruction::kArrayDataSignature) {
2169 Fail(VERIFY_ERROR_GENERIC) << "invalid magic for array-data";
2170 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002171 size_t elem_width = Primitive::ComponentSize(component_type->GetPrimitiveType());
Ian Rogersd81871c2011-10-03 13:57:23 -07002172 // Since we don't compress the data in Dex, expect to see equal width of data stored
2173 // in the table and expected from the array class.
2174 if (array_data[1] != elem_width) {
2175 Fail(VERIFY_ERROR_GENERIC) << "array-data size mismatch (" << array_data[1]
2176 << " vs " << elem_width << ")";
2177 }
2178 }
2179 }
jeffhaobdb76512011-09-07 11:43:16 -07002180 }
2181 }
2182 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002183 }
jeffhaobdb76512011-09-07 11:43:16 -07002184 case Instruction::IF_EQ:
Ian Rogersd81871c2011-10-03 13:57:23 -07002185 case Instruction::IF_NE: {
2186 const RegType& reg_type1 = work_line_->GetRegisterType(dec_insn.vA_);
2187 const RegType& reg_type2 = work_line_->GetRegisterType(dec_insn.vB_);
2188 bool mismatch = false;
2189 if (reg_type1.IsZero()) { // zero then integral or reference expected
2190 mismatch = !reg_type2.IsReferenceTypes() && !reg_type2.IsIntegralTypes();
2191 } else if (reg_type1.IsReferenceTypes()) { // both references?
2192 mismatch = !reg_type2.IsReferenceTypes();
2193 } else { // both integral?
2194 mismatch = !reg_type1.IsIntegralTypes() || !reg_type2.IsIntegralTypes();
2195 }
2196 if (mismatch) {
2197 Fail(VERIFY_ERROR_GENERIC) << "args to if-eq/if-ne (" << reg_type1 << "," << reg_type2
2198 << ") must both be references or integral";
jeffhaobdb76512011-09-07 11:43:16 -07002199 }
2200 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002201 }
jeffhaobdb76512011-09-07 11:43:16 -07002202 case Instruction::IF_LT:
2203 case Instruction::IF_GE:
2204 case Instruction::IF_GT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002205 case Instruction::IF_LE: {
2206 const RegType& reg_type1 = work_line_->GetRegisterType(dec_insn.vA_);
2207 const RegType& reg_type2 = work_line_->GetRegisterType(dec_insn.vB_);
2208 if (!reg_type1.IsIntegralTypes() || !reg_type2.IsIntegralTypes()) {
2209 Fail(VERIFY_ERROR_GENERIC) << "args to 'if' (" << reg_type1 << ","
2210 << reg_type2 << ") must be integral";
jeffhaobdb76512011-09-07 11:43:16 -07002211 }
2212 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002213 }
jeffhaobdb76512011-09-07 11:43:16 -07002214 case Instruction::IF_EQZ:
Ian Rogersd81871c2011-10-03 13:57:23 -07002215 case Instruction::IF_NEZ: {
2216 const RegType& reg_type = work_line_->GetRegisterType(dec_insn.vA_);
2217 if (!reg_type.IsReferenceTypes() && !reg_type.IsIntegralTypes()) {
2218 Fail(VERIFY_ERROR_GENERIC) << "type " << reg_type << " unexpected as arg to if-eqz/if-nez";
2219 }
jeffhaobdb76512011-09-07 11:43:16 -07002220 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002221 }
jeffhaobdb76512011-09-07 11:43:16 -07002222 case Instruction::IF_LTZ:
2223 case Instruction::IF_GEZ:
2224 case Instruction::IF_GTZ:
Ian Rogersd81871c2011-10-03 13:57:23 -07002225 case Instruction::IF_LEZ: {
2226 const RegType& reg_type = work_line_->GetRegisterType(dec_insn.vA_);
2227 if (!reg_type.IsIntegralTypes()) {
2228 Fail(VERIFY_ERROR_GENERIC) << "type " << reg_type
2229 << " unexpected as arg to if-ltz/if-gez/if-gtz/if-lez";
2230 }
jeffhaobdb76512011-09-07 11:43:16 -07002231 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002232 }
jeffhaobdb76512011-09-07 11:43:16 -07002233 case Instruction::AGET_BOOLEAN:
Ian Rogersd81871c2011-10-03 13:57:23 -07002234 VerifyAGet(dec_insn, reg_types_.Boolean(), true);
2235 break;
jeffhaobdb76512011-09-07 11:43:16 -07002236 case Instruction::AGET_BYTE:
Ian Rogersd81871c2011-10-03 13:57:23 -07002237 VerifyAGet(dec_insn, reg_types_.Byte(), true);
2238 break;
jeffhaobdb76512011-09-07 11:43:16 -07002239 case Instruction::AGET_CHAR:
Ian Rogersd81871c2011-10-03 13:57:23 -07002240 VerifyAGet(dec_insn, reg_types_.Char(), true);
2241 break;
jeffhaobdb76512011-09-07 11:43:16 -07002242 case Instruction::AGET_SHORT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002243 VerifyAGet(dec_insn, reg_types_.Short(), true);
jeffhaobdb76512011-09-07 11:43:16 -07002244 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002245 case Instruction::AGET:
2246 VerifyAGet(dec_insn, reg_types_.Integer(), true);
2247 break;
jeffhaobdb76512011-09-07 11:43:16 -07002248 case Instruction::AGET_WIDE:
Ian Rogersd81871c2011-10-03 13:57:23 -07002249 VerifyAGet(dec_insn, reg_types_.Long(), true);
2250 break;
2251 case Instruction::AGET_OBJECT:
2252 VerifyAGet(dec_insn, reg_types_.JavaLangObject(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002253 break;
2254
Ian Rogersd81871c2011-10-03 13:57:23 -07002255 case Instruction::APUT_BOOLEAN:
2256 VerifyAPut(dec_insn, reg_types_.Boolean(), true);
2257 break;
2258 case Instruction::APUT_BYTE:
2259 VerifyAPut(dec_insn, reg_types_.Byte(), true);
2260 break;
2261 case Instruction::APUT_CHAR:
2262 VerifyAPut(dec_insn, reg_types_.Char(), true);
2263 break;
2264 case Instruction::APUT_SHORT:
2265 VerifyAPut(dec_insn, reg_types_.Short(), true);
jeffhaobdb76512011-09-07 11:43:16 -07002266 break;
2267 case Instruction::APUT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002268 VerifyAPut(dec_insn, reg_types_.Integer(), true);
jeffhaobdb76512011-09-07 11:43:16 -07002269 break;
2270 case Instruction::APUT_WIDE:
Ian Rogersd81871c2011-10-03 13:57:23 -07002271 VerifyAPut(dec_insn, reg_types_.Long(), true);
jeffhaobdb76512011-09-07 11:43:16 -07002272 break;
2273 case Instruction::APUT_OBJECT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002274 VerifyAPut(dec_insn, reg_types_.JavaLangObject(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002275 break;
2276
jeffhaobdb76512011-09-07 11:43:16 -07002277 case Instruction::IGET_BOOLEAN:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002278 VerifyISGet(dec_insn, reg_types_.Boolean(), true, false);
Ian Rogersd81871c2011-10-03 13:57:23 -07002279 break;
jeffhaobdb76512011-09-07 11:43:16 -07002280 case Instruction::IGET_BYTE:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002281 VerifyISGet(dec_insn, reg_types_.Byte(), true, false);
Ian Rogersd81871c2011-10-03 13:57:23 -07002282 break;
jeffhaobdb76512011-09-07 11:43:16 -07002283 case Instruction::IGET_CHAR:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002284 VerifyISGet(dec_insn, reg_types_.Char(), true, false);
Ian Rogersd81871c2011-10-03 13:57:23 -07002285 break;
jeffhaobdb76512011-09-07 11:43:16 -07002286 case Instruction::IGET_SHORT:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002287 VerifyISGet(dec_insn, reg_types_.Short(), true, false);
Ian Rogersd81871c2011-10-03 13:57:23 -07002288 break;
2289 case Instruction::IGET:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002290 VerifyISGet(dec_insn, reg_types_.Integer(), true, false);
jeffhaobdb76512011-09-07 11:43:16 -07002291 break;
2292 case Instruction::IGET_WIDE:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002293 VerifyISGet(dec_insn, reg_types_.Long(), true, false);
jeffhaobdb76512011-09-07 11:43:16 -07002294 break;
2295 case Instruction::IGET_OBJECT:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002296 VerifyISGet(dec_insn, reg_types_.JavaLangObject(), false, false);
Ian Rogersd81871c2011-10-03 13:57:23 -07002297 break;
jeffhaobdb76512011-09-07 11:43:16 -07002298
Ian Rogersd81871c2011-10-03 13:57:23 -07002299 case Instruction::IPUT_BOOLEAN:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002300 VerifyISPut(dec_insn, reg_types_.Boolean(), true, false);
Ian Rogersd81871c2011-10-03 13:57:23 -07002301 break;
2302 case Instruction::IPUT_BYTE:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002303 VerifyISPut(dec_insn, reg_types_.Byte(), true, false);
Ian Rogersd81871c2011-10-03 13:57:23 -07002304 break;
2305 case Instruction::IPUT_CHAR:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002306 VerifyISPut(dec_insn, reg_types_.Char(), true, false);
Ian Rogersd81871c2011-10-03 13:57:23 -07002307 break;
2308 case Instruction::IPUT_SHORT:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002309 VerifyISPut(dec_insn, reg_types_.Short(), true, false);
jeffhaobdb76512011-09-07 11:43:16 -07002310 break;
2311 case Instruction::IPUT:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002312 VerifyISPut(dec_insn, reg_types_.Integer(), true, false);
jeffhaobdb76512011-09-07 11:43:16 -07002313 break;
2314 case Instruction::IPUT_WIDE:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002315 VerifyISPut(dec_insn, reg_types_.Long(), true, false);
Ian Rogersd81871c2011-10-03 13:57:23 -07002316 break;
jeffhaobdb76512011-09-07 11:43:16 -07002317 case Instruction::IPUT_OBJECT:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002318 VerifyISPut(dec_insn, reg_types_.JavaLangObject(), false, false);
jeffhaobdb76512011-09-07 11:43:16 -07002319 break;
2320
jeffhaobdb76512011-09-07 11:43:16 -07002321 case Instruction::SGET_BOOLEAN:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002322 VerifyISGet(dec_insn, reg_types_.Boolean(), true, true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002323 break;
jeffhaobdb76512011-09-07 11:43:16 -07002324 case Instruction::SGET_BYTE:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002325 VerifyISGet(dec_insn, reg_types_.Byte(), true, true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002326 break;
jeffhaobdb76512011-09-07 11:43:16 -07002327 case Instruction::SGET_CHAR:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002328 VerifyISGet(dec_insn, reg_types_.Char(), true, true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002329 break;
jeffhaobdb76512011-09-07 11:43:16 -07002330 case Instruction::SGET_SHORT:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002331 VerifyISGet(dec_insn, reg_types_.Short(), true, true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002332 break;
2333 case Instruction::SGET:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002334 VerifyISGet(dec_insn, reg_types_.Integer(), true, true);
jeffhaobdb76512011-09-07 11:43:16 -07002335 break;
2336 case Instruction::SGET_WIDE:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002337 VerifyISGet(dec_insn, reg_types_.Long(), true, true);
jeffhaobdb76512011-09-07 11:43:16 -07002338 break;
2339 case Instruction::SGET_OBJECT:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002340 VerifyISGet(dec_insn, reg_types_.JavaLangObject(), false, true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002341 break;
2342
2343 case Instruction::SPUT_BOOLEAN:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002344 VerifyISPut(dec_insn, reg_types_.Boolean(), true, true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002345 break;
2346 case Instruction::SPUT_BYTE:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002347 VerifyISPut(dec_insn, reg_types_.Byte(), true, true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002348 break;
2349 case Instruction::SPUT_CHAR:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002350 VerifyISPut(dec_insn, reg_types_.Char(), true, true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002351 break;
2352 case Instruction::SPUT_SHORT:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002353 VerifyISPut(dec_insn, reg_types_.Short(), true, true);
jeffhaobdb76512011-09-07 11:43:16 -07002354 break;
2355 case Instruction::SPUT:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002356 VerifyISPut(dec_insn, reg_types_.Integer(), true, true);
jeffhaobdb76512011-09-07 11:43:16 -07002357 break;
2358 case Instruction::SPUT_WIDE:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002359 VerifyISPut(dec_insn, reg_types_.Long(), true, true);
jeffhaobdb76512011-09-07 11:43:16 -07002360 break;
2361 case Instruction::SPUT_OBJECT:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002362 VerifyISPut(dec_insn, reg_types_.JavaLangObject(), false, true);
jeffhaobdb76512011-09-07 11:43:16 -07002363 break;
2364
2365 case Instruction::INVOKE_VIRTUAL:
2366 case Instruction::INVOKE_VIRTUAL_RANGE:
2367 case Instruction::INVOKE_SUPER:
Ian Rogersd81871c2011-10-03 13:57:23 -07002368 case Instruction::INVOKE_SUPER_RANGE: {
2369 bool is_range = (dec_insn.opcode_ == Instruction::INVOKE_VIRTUAL_RANGE ||
2370 dec_insn.opcode_ == Instruction::INVOKE_SUPER_RANGE);
2371 bool is_super = (dec_insn.opcode_ == Instruction::INVOKE_SUPER ||
2372 dec_insn.opcode_ == Instruction::INVOKE_SUPER_RANGE);
2373 Method* called_method = VerifyInvocationArgs(dec_insn, METHOD_VIRTUAL, is_range, is_super);
2374 if (failure_ == VERIFY_ERROR_NONE) {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002375 const char* descriptor;
2376 if (called_method == NULL) {
2377 uint32_t method_idx = dec_insn.vB_;
2378 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx);
2379 uint32_t return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_;
Ian Rogers0571d352011-11-03 19:51:38 -07002380 descriptor = dex_file_->StringByTypeIdx(return_type_idx);
Ian Rogers28ad40d2011-10-27 15:19:26 -07002381 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002382 descriptor = MethodHelper(called_method).GetReturnTypeDescriptor();
Ian Rogers28ad40d2011-10-27 15:19:26 -07002383 }
Ian Rogers9074b992011-10-26 17:41:55 -07002384 const RegType& return_type =
Ian Rogers28ad40d2011-10-27 15:19:26 -07002385 reg_types_.FromDescriptor(method_->GetDeclaringClass()->GetClassLoader(), descriptor);
Ian Rogersd81871c2011-10-03 13:57:23 -07002386 work_line_->SetResultRegisterType(return_type);
jeffhaobdb76512011-09-07 11:43:16 -07002387 just_set_result = true;
2388 }
2389 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002390 }
jeffhaobdb76512011-09-07 11:43:16 -07002391 case Instruction::INVOKE_DIRECT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002392 case Instruction::INVOKE_DIRECT_RANGE: {
2393 bool is_range = (dec_insn.opcode_ == Instruction::INVOKE_DIRECT_RANGE);
2394 Method* called_method = VerifyInvocationArgs(dec_insn, METHOD_DIRECT, is_range, false);
2395 if (failure_ == VERIFY_ERROR_NONE) {
jeffhaobdb76512011-09-07 11:43:16 -07002396 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07002397 * Some additional checks when calling a constructor. We know from the invocation arg check
2398 * that the "this" argument is an instance of called_method->klass. Now we further restrict
2399 * that to require that called_method->klass is the same as this->klass or this->super,
2400 * allowing the latter only if the "this" argument is the same as the "this" argument to
2401 * this method (which implies that we're in a constructor ourselves).
jeffhaobdb76512011-09-07 11:43:16 -07002402 */
Ian Rogers28ad40d2011-10-27 15:19:26 -07002403 bool is_constructor;
2404 if (called_method != NULL) {
2405 is_constructor = called_method->IsConstructor();
2406 } else {
2407 uint32_t method_idx = dec_insn.vB_;
2408 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx);
2409 const char* name = dex_file_->GetMethodName(method_id);
2410 is_constructor = strcmp(name, "<init>") == 0;
2411 }
2412 if (is_constructor) {
Ian Rogersd81871c2011-10-03 13:57:23 -07002413 const RegType& this_type = work_line_->GetInvocationThis(dec_insn);
2414 if (failure_ != VERIFY_ERROR_NONE)
jeffhaobdb76512011-09-07 11:43:16 -07002415 break;
2416
2417 /* no null refs allowed (?) */
Ian Rogersd81871c2011-10-03 13:57:23 -07002418 if (this_type.IsZero()) {
2419 Fail(VERIFY_ERROR_GENERIC) << "unable to initialize null ref";
jeffhaobdb76512011-09-07 11:43:16 -07002420 break;
2421 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07002422 if (called_method != NULL) {
2423 Class* this_class = this_type.GetClass();
2424 DCHECK(this_class != NULL);
2425 /* must be in same class or in superclass */
2426 if (called_method->GetDeclaringClass() == this_class->GetSuperClass()) {
2427 if (this_class != method_->GetDeclaringClass()) {
2428 Fail(VERIFY_ERROR_GENERIC)
2429 << "invoke-direct <init> on super only allowed for 'this' in <init>";
2430 break;
2431 }
2432 } else if (called_method->GetDeclaringClass() != this_class) {
2433 Fail(VERIFY_ERROR_GENERIC) << "invoke-direct <init> must be on current class or super";
jeffhaobdb76512011-09-07 11:43:16 -07002434 break;
2435 }
jeffhaobdb76512011-09-07 11:43:16 -07002436 }
2437
2438 /* arg must be an uninitialized reference */
Ian Rogers84fa0742011-10-25 18:13:30 -07002439 if (!this_type.IsUninitializedTypes()) {
Ian Rogersd81871c2011-10-03 13:57:23 -07002440 Fail(VERIFY_ERROR_GENERIC) << "Expected initialization on uninitialized reference "
2441 << this_type;
jeffhaobdb76512011-09-07 11:43:16 -07002442 break;
2443 }
2444
2445 /*
Ian Rogers84fa0742011-10-25 18:13:30 -07002446 * Replace the uninitialized reference with an initialized one. We need to do this for all
2447 * registers that have the same object instance in them, not just the "this" register.
jeffhaobdb76512011-09-07 11:43:16 -07002448 */
Ian Rogersd81871c2011-10-03 13:57:23 -07002449 work_line_->MarkRefsAsInitialized(this_type);
2450 if (failure_ != VERIFY_ERROR_NONE)
jeffhaobdb76512011-09-07 11:43:16 -07002451 break;
jeffhao2a8a90e2011-09-26 14:25:31 -07002452 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07002453 const char* descriptor;
2454 if (called_method == NULL) {
2455 uint32_t method_idx = dec_insn.vB_;
2456 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx);
2457 uint32_t return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_;
Ian Rogers0571d352011-11-03 19:51:38 -07002458 descriptor = dex_file_->StringByTypeIdx(return_type_idx);
Ian Rogers28ad40d2011-10-27 15:19:26 -07002459 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002460 descriptor = MethodHelper(called_method).GetReturnTypeDescriptor();
Ian Rogers28ad40d2011-10-27 15:19:26 -07002461 }
Ian Rogers9074b992011-10-26 17:41:55 -07002462 const RegType& return_type =
Ian Rogers28ad40d2011-10-27 15:19:26 -07002463 reg_types_.FromDescriptor(method_->GetDeclaringClass()->GetClassLoader(), descriptor);
Ian Rogersd81871c2011-10-03 13:57:23 -07002464 work_line_->SetResultRegisterType(return_type);
jeffhaobdb76512011-09-07 11:43:16 -07002465 just_set_result = true;
2466 }
2467 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002468 }
jeffhaobdb76512011-09-07 11:43:16 -07002469 case Instruction::INVOKE_STATIC:
Ian Rogersd81871c2011-10-03 13:57:23 -07002470 case Instruction::INVOKE_STATIC_RANGE: {
2471 bool is_range = (dec_insn.opcode_ == Instruction::INVOKE_STATIC_RANGE);
2472 Method* called_method = VerifyInvocationArgs(dec_insn, METHOD_STATIC, is_range, false);
2473 if (failure_ == VERIFY_ERROR_NONE) {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002474 const char* descriptor;
2475 if (called_method == NULL) {
2476 uint32_t method_idx = dec_insn.vB_;
2477 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx);
2478 uint32_t return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_;
Ian Rogers0571d352011-11-03 19:51:38 -07002479 descriptor = dex_file_->StringByTypeIdx(return_type_idx);
Ian Rogers28ad40d2011-10-27 15:19:26 -07002480 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002481 descriptor = MethodHelper(called_method).GetReturnTypeDescriptor();
Ian Rogers28ad40d2011-10-27 15:19:26 -07002482 }
Ian Rogers9074b992011-10-26 17:41:55 -07002483 const RegType& return_type =
Ian Rogers28ad40d2011-10-27 15:19:26 -07002484 reg_types_.FromDescriptor(method_->GetDeclaringClass()->GetClassLoader(), descriptor);
Ian Rogersd81871c2011-10-03 13:57:23 -07002485 work_line_->SetResultRegisterType(return_type);
2486 just_set_result = true;
2487 }
jeffhaobdb76512011-09-07 11:43:16 -07002488 }
2489 break;
2490 case Instruction::INVOKE_INTERFACE:
Ian Rogersd81871c2011-10-03 13:57:23 -07002491 case Instruction::INVOKE_INTERFACE_RANGE: {
2492 bool is_range = (dec_insn.opcode_ == Instruction::INVOKE_INTERFACE_RANGE);
2493 Method* abs_method = VerifyInvocationArgs(dec_insn, METHOD_INTERFACE, is_range, false);
2494 if (failure_ == VERIFY_ERROR_NONE) {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002495 if (abs_method != NULL) {
2496 Class* called_interface = abs_method->GetDeclaringClass();
Ian Rogersf3c1f782011-11-02 14:12:15 -07002497 if (!called_interface->IsInterface() && !called_interface->IsObjectClass()) {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002498 Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected interface class in invoke-interface '"
2499 << PrettyMethod(abs_method) << "'";
2500 break;
2501 }
2502 }
2503 /* Get the type of the "this" arg, which should either be a sub-interface of called
2504 * interface or Object (see comments in RegType::JoinClass).
2505 */
2506 const RegType& this_type = work_line_->GetInvocationThis(dec_insn);
2507 if (failure_ == VERIFY_ERROR_NONE) {
2508 if (this_type.IsZero()) {
2509 /* null pointer always passes (and always fails at runtime) */
2510 } else {
2511 if (this_type.IsUninitializedTypes()) {
2512 Fail(VERIFY_ERROR_GENERIC) << "interface call on uninitialized object "
2513 << this_type;
2514 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002515 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07002516 // In the past we have tried to assert that "called_interface" is assignable
2517 // from "this_type.GetClass()", however, as we do an imprecise Join
2518 // (RegType::JoinClass) we don't have full information on what interfaces are
2519 // implemented by "this_type". For example, two classes may implement the same
2520 // interfaces and have a common parent that doesn't implement the interface. The
2521 // join will set "this_type" to the parent class and a test that this implements
2522 // the interface will incorrectly fail.
jeffhaobdb76512011-09-07 11:43:16 -07002523 }
2524 }
jeffhaobdb76512011-09-07 11:43:16 -07002525 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07002526 * We don't have an object instance, so we can't find the concrete method. However, all of
2527 * the type information is in the abstract method, so we're good.
jeffhaobdb76512011-09-07 11:43:16 -07002528 */
Ian Rogers28ad40d2011-10-27 15:19:26 -07002529 const char* descriptor;
2530 if (abs_method == NULL) {
2531 uint32_t method_idx = dec_insn.vB_;
2532 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx);
2533 uint32_t return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_;
Ian Rogers0571d352011-11-03 19:51:38 -07002534 descriptor = dex_file_->StringByTypeIdx(return_type_idx);
Ian Rogers28ad40d2011-10-27 15:19:26 -07002535 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002536 descriptor = MethodHelper(abs_method).GetReturnTypeDescriptor();
Ian Rogers28ad40d2011-10-27 15:19:26 -07002537 }
Ian Rogers9074b992011-10-26 17:41:55 -07002538 const RegType& return_type =
Ian Rogers28ad40d2011-10-27 15:19:26 -07002539 reg_types_.FromDescriptor(method_->GetDeclaringClass()->GetClassLoader(), descriptor);
2540 work_line_->SetResultRegisterType(return_type);
Ian Rogersd81871c2011-10-03 13:57:23 -07002541 work_line_->SetResultRegisterType(return_type);
jeffhaobdb76512011-09-07 11:43:16 -07002542 just_set_result = true;
2543 }
2544 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002545 }
jeffhaobdb76512011-09-07 11:43:16 -07002546 case Instruction::NEG_INT:
2547 case Instruction::NOT_INT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002548 work_line_->CheckUnaryOp(dec_insn, reg_types_.Integer(), reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07002549 break;
2550 case Instruction::NEG_LONG:
2551 case Instruction::NOT_LONG:
Ian Rogersd81871c2011-10-03 13:57:23 -07002552 work_line_->CheckUnaryOp(dec_insn, reg_types_.Long(), reg_types_.Long());
jeffhaobdb76512011-09-07 11:43:16 -07002553 break;
2554 case Instruction::NEG_FLOAT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002555 work_line_->CheckUnaryOp(dec_insn, reg_types_.Float(), reg_types_.Float());
jeffhaobdb76512011-09-07 11:43:16 -07002556 break;
2557 case Instruction::NEG_DOUBLE:
Ian Rogersd81871c2011-10-03 13:57:23 -07002558 work_line_->CheckUnaryOp(dec_insn, reg_types_.Double(), reg_types_.Double());
jeffhaobdb76512011-09-07 11:43:16 -07002559 break;
2560 case Instruction::INT_TO_LONG:
Ian Rogersd81871c2011-10-03 13:57:23 -07002561 work_line_->CheckUnaryOp(dec_insn, reg_types_.Long(), reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07002562 break;
2563 case Instruction::INT_TO_FLOAT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002564 work_line_->CheckUnaryOp(dec_insn, reg_types_.Float(), reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07002565 break;
2566 case Instruction::INT_TO_DOUBLE:
Ian Rogersd81871c2011-10-03 13:57:23 -07002567 work_line_->CheckUnaryOp(dec_insn, reg_types_.Double(), reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07002568 break;
2569 case Instruction::LONG_TO_INT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002570 work_line_->CheckUnaryOp(dec_insn, reg_types_.Integer(), reg_types_.Long());
jeffhaobdb76512011-09-07 11:43:16 -07002571 break;
2572 case Instruction::LONG_TO_FLOAT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002573 work_line_->CheckUnaryOp(dec_insn, reg_types_.Float(), reg_types_.Long());
jeffhaobdb76512011-09-07 11:43:16 -07002574 break;
2575 case Instruction::LONG_TO_DOUBLE:
Ian Rogersd81871c2011-10-03 13:57:23 -07002576 work_line_->CheckUnaryOp(dec_insn, reg_types_.Double(), reg_types_.Long());
jeffhaobdb76512011-09-07 11:43:16 -07002577 break;
2578 case Instruction::FLOAT_TO_INT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002579 work_line_->CheckUnaryOp(dec_insn, reg_types_.Integer(), reg_types_.Float());
jeffhaobdb76512011-09-07 11:43:16 -07002580 break;
2581 case Instruction::FLOAT_TO_LONG:
Ian Rogersd81871c2011-10-03 13:57:23 -07002582 work_line_->CheckUnaryOp(dec_insn, reg_types_.Long(), reg_types_.Float());
jeffhaobdb76512011-09-07 11:43:16 -07002583 break;
2584 case Instruction::FLOAT_TO_DOUBLE:
Ian Rogersd81871c2011-10-03 13:57:23 -07002585 work_line_->CheckUnaryOp(dec_insn, reg_types_.Double(), reg_types_.Float());
jeffhaobdb76512011-09-07 11:43:16 -07002586 break;
2587 case Instruction::DOUBLE_TO_INT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002588 work_line_->CheckUnaryOp(dec_insn, reg_types_.Integer(), reg_types_.Double());
jeffhaobdb76512011-09-07 11:43:16 -07002589 break;
2590 case Instruction::DOUBLE_TO_LONG:
Ian Rogersd81871c2011-10-03 13:57:23 -07002591 work_line_->CheckUnaryOp(dec_insn, reg_types_.Long(), reg_types_.Double());
jeffhaobdb76512011-09-07 11:43:16 -07002592 break;
2593 case Instruction::DOUBLE_TO_FLOAT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002594 work_line_->CheckUnaryOp(dec_insn, reg_types_.Float(), reg_types_.Double());
jeffhaobdb76512011-09-07 11:43:16 -07002595 break;
2596 case Instruction::INT_TO_BYTE:
Ian Rogersd81871c2011-10-03 13:57:23 -07002597 work_line_->CheckUnaryOp(dec_insn, reg_types_.Byte(), reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07002598 break;
2599 case Instruction::INT_TO_CHAR:
Ian Rogersd81871c2011-10-03 13:57:23 -07002600 work_line_->CheckUnaryOp(dec_insn, reg_types_.Char(), reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07002601 break;
2602 case Instruction::INT_TO_SHORT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002603 work_line_->CheckUnaryOp(dec_insn, reg_types_.Short(), reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07002604 break;
2605
2606 case Instruction::ADD_INT:
2607 case Instruction::SUB_INT:
2608 case Instruction::MUL_INT:
2609 case Instruction::REM_INT:
2610 case Instruction::DIV_INT:
2611 case Instruction::SHL_INT:
2612 case Instruction::SHR_INT:
2613 case Instruction::USHR_INT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002614 work_line_->CheckBinaryOp(dec_insn, reg_types_.Integer(), reg_types_.Integer(), reg_types_.Integer(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002615 break;
2616 case Instruction::AND_INT:
2617 case Instruction::OR_INT:
2618 case Instruction::XOR_INT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002619 work_line_->CheckBinaryOp(dec_insn, reg_types_.Integer(), reg_types_.Integer(), reg_types_.Integer(), true);
jeffhaobdb76512011-09-07 11:43:16 -07002620 break;
2621 case Instruction::ADD_LONG:
2622 case Instruction::SUB_LONG:
2623 case Instruction::MUL_LONG:
2624 case Instruction::DIV_LONG:
2625 case Instruction::REM_LONG:
2626 case Instruction::AND_LONG:
2627 case Instruction::OR_LONG:
2628 case Instruction::XOR_LONG:
Ian Rogersd81871c2011-10-03 13:57:23 -07002629 work_line_->CheckBinaryOp(dec_insn, reg_types_.Long(), reg_types_.Long(), reg_types_.Long(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002630 break;
2631 case Instruction::SHL_LONG:
2632 case Instruction::SHR_LONG:
2633 case Instruction::USHR_LONG:
Ian Rogersd81871c2011-10-03 13:57:23 -07002634 /* shift distance is Int, making these different from other binary operations */
2635 work_line_->CheckBinaryOp(dec_insn, reg_types_.Long(), reg_types_.Long(), reg_types_.Integer(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002636 break;
2637 case Instruction::ADD_FLOAT:
2638 case Instruction::SUB_FLOAT:
2639 case Instruction::MUL_FLOAT:
2640 case Instruction::DIV_FLOAT:
2641 case Instruction::REM_FLOAT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002642 work_line_->CheckBinaryOp(dec_insn, reg_types_.Float(), reg_types_.Float(), reg_types_.Float(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002643 break;
2644 case Instruction::ADD_DOUBLE:
2645 case Instruction::SUB_DOUBLE:
2646 case Instruction::MUL_DOUBLE:
2647 case Instruction::DIV_DOUBLE:
2648 case Instruction::REM_DOUBLE:
Ian Rogersd81871c2011-10-03 13:57:23 -07002649 work_line_->CheckBinaryOp(dec_insn, reg_types_.Double(), reg_types_.Double(), reg_types_.Double(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002650 break;
2651 case Instruction::ADD_INT_2ADDR:
2652 case Instruction::SUB_INT_2ADDR:
2653 case Instruction::MUL_INT_2ADDR:
2654 case Instruction::REM_INT_2ADDR:
2655 case Instruction::SHL_INT_2ADDR:
2656 case Instruction::SHR_INT_2ADDR:
2657 case Instruction::USHR_INT_2ADDR:
Ian Rogersd81871c2011-10-03 13:57:23 -07002658 work_line_->CheckBinaryOp2addr(dec_insn, reg_types_.Integer(), reg_types_.Integer(), reg_types_.Integer(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002659 break;
2660 case Instruction::AND_INT_2ADDR:
2661 case Instruction::OR_INT_2ADDR:
2662 case Instruction::XOR_INT_2ADDR:
Ian Rogersd81871c2011-10-03 13:57:23 -07002663 work_line_->CheckBinaryOp2addr(dec_insn, reg_types_.Integer(), reg_types_.Integer(), reg_types_.Integer(), true);
jeffhaobdb76512011-09-07 11:43:16 -07002664 break;
2665 case Instruction::DIV_INT_2ADDR:
Ian Rogersd81871c2011-10-03 13:57:23 -07002666 work_line_->CheckBinaryOp2addr(dec_insn, reg_types_.Integer(), reg_types_.Integer(), reg_types_.Integer(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002667 break;
2668 case Instruction::ADD_LONG_2ADDR:
2669 case Instruction::SUB_LONG_2ADDR:
2670 case Instruction::MUL_LONG_2ADDR:
2671 case Instruction::DIV_LONG_2ADDR:
2672 case Instruction::REM_LONG_2ADDR:
2673 case Instruction::AND_LONG_2ADDR:
2674 case Instruction::OR_LONG_2ADDR:
2675 case Instruction::XOR_LONG_2ADDR:
Ian Rogersd81871c2011-10-03 13:57:23 -07002676 work_line_->CheckBinaryOp2addr(dec_insn, reg_types_.Long(), reg_types_.Long(), reg_types_.Long(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002677 break;
2678 case Instruction::SHL_LONG_2ADDR:
2679 case Instruction::SHR_LONG_2ADDR:
2680 case Instruction::USHR_LONG_2ADDR:
Ian Rogersd81871c2011-10-03 13:57:23 -07002681 work_line_->CheckBinaryOp2addr(dec_insn, reg_types_.Long(), reg_types_.Long(), reg_types_.Integer(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002682 break;
2683 case Instruction::ADD_FLOAT_2ADDR:
2684 case Instruction::SUB_FLOAT_2ADDR:
2685 case Instruction::MUL_FLOAT_2ADDR:
2686 case Instruction::DIV_FLOAT_2ADDR:
2687 case Instruction::REM_FLOAT_2ADDR:
Ian Rogersd81871c2011-10-03 13:57:23 -07002688 work_line_->CheckBinaryOp2addr(dec_insn, reg_types_.Float(), reg_types_.Float(), reg_types_.Float(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002689 break;
2690 case Instruction::ADD_DOUBLE_2ADDR:
2691 case Instruction::SUB_DOUBLE_2ADDR:
2692 case Instruction::MUL_DOUBLE_2ADDR:
2693 case Instruction::DIV_DOUBLE_2ADDR:
2694 case Instruction::REM_DOUBLE_2ADDR:
Ian Rogersd81871c2011-10-03 13:57:23 -07002695 work_line_->CheckBinaryOp2addr(dec_insn, reg_types_.Double(), reg_types_.Double(), reg_types_.Double(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002696 break;
2697 case Instruction::ADD_INT_LIT16:
2698 case Instruction::RSUB_INT:
2699 case Instruction::MUL_INT_LIT16:
2700 case Instruction::DIV_INT_LIT16:
2701 case Instruction::REM_INT_LIT16:
Ian Rogersd81871c2011-10-03 13:57:23 -07002702 work_line_->CheckLiteralOp(dec_insn, reg_types_.Integer(), reg_types_.Integer(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002703 break;
2704 case Instruction::AND_INT_LIT16:
2705 case Instruction::OR_INT_LIT16:
2706 case Instruction::XOR_INT_LIT16:
Ian Rogersd81871c2011-10-03 13:57:23 -07002707 work_line_->CheckLiteralOp(dec_insn, reg_types_.Integer(), reg_types_.Integer(), true);
jeffhaobdb76512011-09-07 11:43:16 -07002708 break;
2709 case Instruction::ADD_INT_LIT8:
2710 case Instruction::RSUB_INT_LIT8:
2711 case Instruction::MUL_INT_LIT8:
2712 case Instruction::DIV_INT_LIT8:
2713 case Instruction::REM_INT_LIT8:
2714 case Instruction::SHL_INT_LIT8:
jeffhaobdb76512011-09-07 11:43:16 -07002715 case Instruction::SHR_INT_LIT8:
jeffhaobdb76512011-09-07 11:43:16 -07002716 case Instruction::USHR_INT_LIT8:
Ian Rogersd81871c2011-10-03 13:57:23 -07002717 work_line_->CheckLiteralOp(dec_insn, reg_types_.Integer(), reg_types_.Integer(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002718 break;
2719 case Instruction::AND_INT_LIT8:
2720 case Instruction::OR_INT_LIT8:
2721 case Instruction::XOR_INT_LIT8:
Ian Rogersd81871c2011-10-03 13:57:23 -07002722 work_line_->CheckLiteralOp(dec_insn, reg_types_.Integer(), reg_types_.Integer(), true);
jeffhaobdb76512011-09-07 11:43:16 -07002723 break;
2724
2725 /*
2726 * This falls into the general category of "optimized" instructions,
jeffhaod1f0fde2011-09-08 17:25:33 -07002727 * which don't generally appear during verification. Because it's
jeffhaobdb76512011-09-07 11:43:16 -07002728 * inserted in the course of verification, we can expect to see it here.
2729 */
jeffhaob4df5142011-09-19 20:25:32 -07002730 case Instruction::THROW_VERIFICATION_ERROR:
jeffhaobdb76512011-09-07 11:43:16 -07002731 break;
2732
Ian Rogersd81871c2011-10-03 13:57:23 -07002733 /* These should never appear during verification. */
jeffhaobdb76512011-09-07 11:43:16 -07002734 case Instruction::UNUSED_EE:
2735 case Instruction::UNUSED_EF:
2736 case Instruction::UNUSED_F2:
2737 case Instruction::UNUSED_F3:
2738 case Instruction::UNUSED_F4:
2739 case Instruction::UNUSED_F5:
2740 case Instruction::UNUSED_F6:
2741 case Instruction::UNUSED_F7:
2742 case Instruction::UNUSED_F8:
2743 case Instruction::UNUSED_F9:
2744 case Instruction::UNUSED_FA:
2745 case Instruction::UNUSED_FB:
jeffhaobdb76512011-09-07 11:43:16 -07002746 case Instruction::UNUSED_F0:
2747 case Instruction::UNUSED_F1:
2748 case Instruction::UNUSED_E3:
2749 case Instruction::UNUSED_E8:
2750 case Instruction::UNUSED_E7:
2751 case Instruction::UNUSED_E4:
2752 case Instruction::UNUSED_E9:
2753 case Instruction::UNUSED_FC:
2754 case Instruction::UNUSED_E5:
2755 case Instruction::UNUSED_EA:
2756 case Instruction::UNUSED_FD:
2757 case Instruction::UNUSED_E6:
2758 case Instruction::UNUSED_EB:
2759 case Instruction::UNUSED_FE:
jeffhaobdb76512011-09-07 11:43:16 -07002760 case Instruction::UNUSED_3E:
2761 case Instruction::UNUSED_3F:
2762 case Instruction::UNUSED_40:
2763 case Instruction::UNUSED_41:
2764 case Instruction::UNUSED_42:
2765 case Instruction::UNUSED_43:
2766 case Instruction::UNUSED_73:
2767 case Instruction::UNUSED_79:
2768 case Instruction::UNUSED_7A:
2769 case Instruction::UNUSED_EC:
2770 case Instruction::UNUSED_FF:
Ian Rogers2c8a8572011-10-24 17:11:36 -07002771 Fail(VERIFY_ERROR_GENERIC) << "Unexpected opcode " << inst->DumpString(dex_file_);
jeffhaobdb76512011-09-07 11:43:16 -07002772 break;
2773
2774 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07002775 * DO NOT add a "default" clause here. Without it the compiler will
jeffhaobdb76512011-09-07 11:43:16 -07002776 * complain if an instruction is missing (which is desirable).
2777 */
Ian Rogersd81871c2011-10-03 13:57:23 -07002778 } // end - switch (dec_insn.opcode_)
jeffhaobdb76512011-09-07 11:43:16 -07002779
Ian Rogersd81871c2011-10-03 13:57:23 -07002780 if (failure_ != VERIFY_ERROR_NONE) {
2781 if (failure_ == VERIFY_ERROR_GENERIC) {
jeffhaobdb76512011-09-07 11:43:16 -07002782 /* immediate failure, reject class */
Ian Rogers2c8a8572011-10-24 17:11:36 -07002783 fail_messages_ << std::endl << "Rejecting opcode " << inst->DumpString(dex_file_);
jeffhaobdb76512011-09-07 11:43:16 -07002784 return false;
2785 } else {
2786 /* replace opcode and continue on */
Ian Rogers2c8a8572011-10-24 17:11:36 -07002787 fail_messages_ << std::endl << "Replacing opcode " << inst->DumpString(dex_file_);
Ian Rogersd81871c2011-10-03 13:57:23 -07002788 ReplaceFailingInstruction();
jeffhaobdb76512011-09-07 11:43:16 -07002789 /* IMPORTANT: method->insns may have been changed */
Ian Rogersd81871c2011-10-03 13:57:23 -07002790 insns = code_item_->insns_ + work_insn_idx_;
jeffhaobdb76512011-09-07 11:43:16 -07002791 /* continue on as if we just handled a throw-verification-error */
Ian Rogersd81871c2011-10-03 13:57:23 -07002792 failure_ = VERIFY_ERROR_NONE;
jeffhaobdb76512011-09-07 11:43:16 -07002793 opcode_flag = Instruction::kThrow;
2794 }
2795 }
jeffhaobdb76512011-09-07 11:43:16 -07002796 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07002797 * If we didn't just set the result register, clear it out. This ensures that you can only use
2798 * "move-result" immediately after the result is set. (We could check this statically, but it's
2799 * not expensive and it makes our debugging output cleaner.)
jeffhaobdb76512011-09-07 11:43:16 -07002800 */
2801 if (!just_set_result) {
Ian Rogersd81871c2011-10-03 13:57:23 -07002802 work_line_->SetResultTypeToUnknown();
jeffhaobdb76512011-09-07 11:43:16 -07002803 }
2804
jeffhaoa0a764a2011-09-16 10:43:38 -07002805 /* Handle "continue". Tag the next consecutive instruction. */
jeffhaobdb76512011-09-07 11:43:16 -07002806 if ((opcode_flag & Instruction::kContinue) != 0) {
Ian Rogersd81871c2011-10-03 13:57:23 -07002807 uint32_t next_insn_idx = work_insn_idx_ + CurrentInsnFlags().GetLengthInCodeUnits();
2808 if (next_insn_idx >= code_item_->insns_size_in_code_units_) {
2809 Fail(VERIFY_ERROR_GENERIC) << "Execution can walk off end of code area";
jeffhaobdb76512011-09-07 11:43:16 -07002810 return false;
2811 }
Ian Rogersd81871c2011-10-03 13:57:23 -07002812 // The only way to get to a move-exception instruction is to get thrown there. Make sure the
2813 // next instruction isn't one.
2814 if (!CheckMoveException(code_item_->insns_, next_insn_idx)) {
jeffhaobdb76512011-09-07 11:43:16 -07002815 return false;
Ian Rogersd81871c2011-10-03 13:57:23 -07002816 }
2817 RegisterLine* next_line = reg_table_.GetLine(next_insn_idx);
2818 if (next_line != NULL) {
2819 // Merge registers into what we have for the next instruction, and set the "changed" flag if
2820 // needed.
2821 if (!UpdateRegisters(next_insn_idx, work_line_.get())) {
jeffhaobdb76512011-09-07 11:43:16 -07002822 return false;
Ian Rogersd81871c2011-10-03 13:57:23 -07002823 }
jeffhaobdb76512011-09-07 11:43:16 -07002824 } else {
2825 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07002826 * We're not recording register data for the next instruction, so we don't know what the prior
2827 * state was. We have to assume that something has changed and re-evaluate it.
jeffhaobdb76512011-09-07 11:43:16 -07002828 */
Ian Rogersd81871c2011-10-03 13:57:23 -07002829 insn_flags_[next_insn_idx].SetChanged();
jeffhaobdb76512011-09-07 11:43:16 -07002830 }
2831 }
2832
2833 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07002834 * Handle "branch". Tag the branch target.
jeffhaobdb76512011-09-07 11:43:16 -07002835 *
2836 * NOTE: instructions like Instruction::EQZ provide information about the
jeffhaod1f0fde2011-09-08 17:25:33 -07002837 * state of the register when the branch is taken or not taken. For example,
jeffhaobdb76512011-09-07 11:43:16 -07002838 * somebody could get a reference field, check it for zero, and if the
2839 * branch is taken immediately store that register in a boolean field
jeffhaod1f0fde2011-09-08 17:25:33 -07002840 * since the value is known to be zero. We do not currently account for
jeffhaobdb76512011-09-07 11:43:16 -07002841 * that, and will reject the code.
2842 *
2843 * TODO: avoid re-fetching the branch target
2844 */
2845 if ((opcode_flag & Instruction::kBranch) != 0) {
2846 bool isConditional, selfOkay;
Ian Rogersd81871c2011-10-03 13:57:23 -07002847 if (!GetBranchOffset(work_insn_idx_, &branch_target, &isConditional, &selfOkay)) {
jeffhaobdb76512011-09-07 11:43:16 -07002848 /* should never happen after static verification */
Ian Rogersd81871c2011-10-03 13:57:23 -07002849 Fail(VERIFY_ERROR_GENERIC) << "bad branch";
jeffhaobdb76512011-09-07 11:43:16 -07002850 return false;
2851 }
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002852 DCHECK_EQ(isConditional, (opcode_flag & Instruction::kContinue) != 0);
Ian Rogersd81871c2011-10-03 13:57:23 -07002853 if (!CheckMoveException(code_item_->insns_, work_insn_idx_ + branch_target)) {
jeffhaobdb76512011-09-07 11:43:16 -07002854 return false;
Ian Rogersd81871c2011-10-03 13:57:23 -07002855 }
jeffhaobdb76512011-09-07 11:43:16 -07002856 /* update branch target, set "changed" if appropriate */
Ian Rogersd81871c2011-10-03 13:57:23 -07002857 if (!UpdateRegisters(work_insn_idx_ + branch_target, work_line_.get())) {
jeffhaobdb76512011-09-07 11:43:16 -07002858 return false;
Ian Rogersd81871c2011-10-03 13:57:23 -07002859 }
jeffhaobdb76512011-09-07 11:43:16 -07002860 }
2861
2862 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07002863 * Handle "switch". Tag all possible branch targets.
jeffhaobdb76512011-09-07 11:43:16 -07002864 *
2865 * We've already verified that the table is structurally sound, so we
2866 * just need to walk through and tag the targets.
2867 */
2868 if ((opcode_flag & Instruction::kSwitch) != 0) {
2869 int offset_to_switch = insns[1] | (((int32_t) insns[2]) << 16);
2870 const uint16_t* switch_insns = insns + offset_to_switch;
2871 int switch_count = switch_insns[1];
2872 int offset_to_targets, targ;
2873
2874 if ((*insns & 0xff) == Instruction::PACKED_SWITCH) {
2875 /* 0 = sig, 1 = count, 2/3 = first key */
2876 offset_to_targets = 4;
2877 } else {
2878 /* 0 = sig, 1 = count, 2..count * 2 = keys */
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002879 DCHECK((*insns & 0xff) == Instruction::SPARSE_SWITCH);
jeffhaobdb76512011-09-07 11:43:16 -07002880 offset_to_targets = 2 + 2 * switch_count;
2881 }
2882
2883 /* verify each switch target */
2884 for (targ = 0; targ < switch_count; targ++) {
2885 int offset;
2886 uint32_t abs_offset;
2887
2888 /* offsets are 32-bit, and only partly endian-swapped */
2889 offset = switch_insns[offset_to_targets + targ * 2] |
2890 (((int32_t) switch_insns[offset_to_targets + targ * 2 + 1]) << 16);
Ian Rogersd81871c2011-10-03 13:57:23 -07002891 abs_offset = work_insn_idx_ + offset;
2892 DCHECK_LT(abs_offset, code_item_->insns_size_in_code_units_);
2893 if (!CheckMoveException(code_item_->insns_, abs_offset)) {
jeffhaobdb76512011-09-07 11:43:16 -07002894 return false;
Ian Rogersd81871c2011-10-03 13:57:23 -07002895 }
2896 if (!UpdateRegisters(abs_offset, work_line_.get()))
jeffhaobdb76512011-09-07 11:43:16 -07002897 return false;
2898 }
2899 }
2900
2901 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07002902 * Handle instructions that can throw and that are sitting in a "try" block. (If they're not in a
2903 * "try" block when they throw, control transfers out of the method.)
jeffhaobdb76512011-09-07 11:43:16 -07002904 */
Ian Rogersd81871c2011-10-03 13:57:23 -07002905 if ((opcode_flag & Instruction::kThrow) != 0 && insn_flags_[work_insn_idx_].IsInTry()) {
2906 bool within_catch_all = false;
Ian Rogers0571d352011-11-03 19:51:38 -07002907 CatchHandlerIterator iterator(*code_item_, work_insn_idx_);
jeffhaobdb76512011-09-07 11:43:16 -07002908
Ian Rogers0571d352011-11-03 19:51:38 -07002909 for (; iterator.HasNext(); iterator.Next()) {
2910 if (iterator.GetHandlerTypeIndex() == DexFile::kDexNoIndex16) {
Ian Rogersd81871c2011-10-03 13:57:23 -07002911 within_catch_all = true;
2912 }
jeffhaobdb76512011-09-07 11:43:16 -07002913 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07002914 * Merge registers into the "catch" block. We want to use the "savedRegs" rather than
2915 * "work_regs", because at runtime the exception will be thrown before the instruction
2916 * modifies any registers.
jeffhaobdb76512011-09-07 11:43:16 -07002917 */
Ian Rogers0571d352011-11-03 19:51:38 -07002918 if (!UpdateRegisters(iterator.GetHandlerAddress(), saved_line_.get())) {
jeffhaobdb76512011-09-07 11:43:16 -07002919 return false;
Ian Rogersd81871c2011-10-03 13:57:23 -07002920 }
jeffhaobdb76512011-09-07 11:43:16 -07002921 }
2922
2923 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07002924 * If the monitor stack depth is nonzero, there must be a "catch all" handler for this
2925 * instruction. This does apply to monitor-exit because of async exception handling.
jeffhaobdb76512011-09-07 11:43:16 -07002926 */
Ian Rogersd81871c2011-10-03 13:57:23 -07002927 if (work_line_->MonitorStackDepth() > 0 && !within_catch_all) {
jeffhaobdb76512011-09-07 11:43:16 -07002928 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07002929 * The state in work_line reflects the post-execution state. If the current instruction is a
2930 * monitor-enter and the monitor stack was empty, we don't need a catch-all (if it throws,
jeffhaobdb76512011-09-07 11:43:16 -07002931 * it will do so before grabbing the lock).
2932 */
Ian Rogersd81871c2011-10-03 13:57:23 -07002933 if (dec_insn.opcode_ != Instruction::MONITOR_ENTER || work_line_->MonitorStackDepth() != 1) {
2934 Fail(VERIFY_ERROR_GENERIC)
2935 << "expected to be within a catch-all for an instruction where a monitor is held";
jeffhaobdb76512011-09-07 11:43:16 -07002936 return false;
2937 }
2938 }
2939 }
2940
jeffhaod1f0fde2011-09-08 17:25:33 -07002941 /* If we're returning from the method, make sure monitor stack is empty. */
Ian Rogersd81871c2011-10-03 13:57:23 -07002942 if ((opcode_flag & Instruction::kReturn) != 0) {
2943 if(!work_line_->VerifyMonitorStackEmpty()) {
2944 return false;
2945 }
jeffhaobdb76512011-09-07 11:43:16 -07002946 }
2947
2948 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07002949 * Update start_guess. Advance to the next instruction of that's
2950 * possible, otherwise use the branch target if one was found. If
jeffhaobdb76512011-09-07 11:43:16 -07002951 * neither of those exists we're in a return or throw; leave start_guess
2952 * alone and let the caller sort it out.
2953 */
2954 if ((opcode_flag & Instruction::kContinue) != 0) {
Ian Rogersd81871c2011-10-03 13:57:23 -07002955 *start_guess = work_insn_idx_ + insn_flags_[work_insn_idx_].GetLengthInCodeUnits();
jeffhaobdb76512011-09-07 11:43:16 -07002956 } else if ((opcode_flag & Instruction::kBranch) != 0) {
2957 /* we're still okay if branch_target is zero */
Ian Rogersd81871c2011-10-03 13:57:23 -07002958 *start_guess = work_insn_idx_ + branch_target;
jeffhaobdb76512011-09-07 11:43:16 -07002959 }
2960
Ian Rogersd81871c2011-10-03 13:57:23 -07002961 DCHECK_LT(*start_guess, code_item_->insns_size_in_code_units_);
2962 DCHECK(insn_flags_[*start_guess].IsOpcode());
jeffhaobdb76512011-09-07 11:43:16 -07002963
2964 return true;
2965}
2966
Ian Rogers28ad40d2011-10-27 15:19:26 -07002967const RegType& DexVerifier::ResolveClassAndCheckAccess(uint32_t class_idx) {
Ian Rogers0571d352011-11-03 19:51:38 -07002968 const char* descriptor = dex_file_->StringByTypeIdx(class_idx);
Ian Rogers28ad40d2011-10-27 15:19:26 -07002969 Class* referrer = method_->GetDeclaringClass();
2970 Class* klass = method_->GetDexCacheResolvedTypes()->Get(class_idx);
2971 const RegType& result =
2972 klass != NULL ? reg_types_.FromClass(klass)
2973 : reg_types_.FromDescriptor(referrer->GetClassLoader(), descriptor);
2974 if (klass == NULL && !result.IsUnresolvedTypes()) {
2975 method_->GetDexCacheResolvedTypes()->Set(class_idx, result.GetClass());
Ian Rogersd81871c2011-10-03 13:57:23 -07002976 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07002977 // Check if access is allowed. Unresolved types use AllocObjectFromCodeWithAccessCheck to
2978 // check at runtime if access is allowed and so pass here.
2979 if (!result.IsUnresolvedTypes() && !referrer->CanAccess(result.GetClass())) {
2980 Fail(VERIFY_ERROR_ACCESS_CLASS) << "illegal class access: '"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002981 << PrettyDescriptor(referrer) << "' -> '"
Ian Rogers28ad40d2011-10-27 15:19:26 -07002982 << result << "'";
2983 return reg_types_.Unknown();
2984 } else {
2985 return result;
2986 }
Ian Rogersd81871c2011-10-03 13:57:23 -07002987}
2988
Ian Rogers28ad40d2011-10-27 15:19:26 -07002989const RegType& DexVerifier::GetCaughtExceptionType() {
2990 const RegType* common_super = NULL;
Ian Rogersd81871c2011-10-03 13:57:23 -07002991 if (code_item_->tries_size_ != 0) {
Ian Rogers0571d352011-11-03 19:51:38 -07002992 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item_, 0);
Ian Rogersd81871c2011-10-03 13:57:23 -07002993 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
2994 for (uint32_t i = 0; i < handlers_size; i++) {
Ian Rogers0571d352011-11-03 19:51:38 -07002995 CatchHandlerIterator iterator(handlers_ptr);
2996 for (; iterator.HasNext(); iterator.Next()) {
2997 if (iterator.GetHandlerAddress() == (uint32_t) work_insn_idx_) {
2998 if (iterator.GetHandlerTypeIndex() == DexFile::kDexNoIndex16) {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002999 common_super = &reg_types_.JavaLangThrowable();
Ian Rogersd81871c2011-10-03 13:57:23 -07003000 } else {
Ian Rogers0571d352011-11-03 19:51:38 -07003001 const RegType& exception = ResolveClassAndCheckAccess(iterator.GetHandlerTypeIndex());
Ian Rogersd81871c2011-10-03 13:57:23 -07003002 /* TODO: on error do we want to keep going? If we don't fail this we run the risk of
3003 * having a non-Throwable introduced at runtime. However, that won't pass an instanceof
3004 * test, so is essentially harmless.
3005 */
Ian Rogers28ad40d2011-10-27 15:19:26 -07003006 if(!reg_types_.JavaLangThrowable().IsAssignableFrom(exception)) {
3007 Fail(VERIFY_ERROR_GENERIC) << "unexpected non-exception class " << exception;
3008 return reg_types_.Unknown();
Ian Rogersd81871c2011-10-03 13:57:23 -07003009 } else if (common_super == NULL) {
Ian Rogers28ad40d2011-10-27 15:19:26 -07003010 common_super = &exception;
3011 } else if (common_super->Equals(exception)) {
3012 // nothing to do
Ian Rogersd81871c2011-10-03 13:57:23 -07003013 } else {
Ian Rogers28ad40d2011-10-27 15:19:26 -07003014 common_super = &common_super->Merge(exception, &reg_types_);
3015 CHECK(reg_types_.JavaLangThrowable().IsAssignableFrom(*common_super));
Ian Rogersd81871c2011-10-03 13:57:23 -07003016 }
3017 }
3018 }
3019 }
Ian Rogers0571d352011-11-03 19:51:38 -07003020 handlers_ptr = iterator.EndDataPointer();
Ian Rogersd81871c2011-10-03 13:57:23 -07003021 }
3022 }
3023 if (common_super == NULL) {
3024 /* no catch blocks, or no catches with classes we can find */
3025 Fail(VERIFY_ERROR_GENERIC) << "unable to find exception handler";
3026 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07003027 return *common_super;
Ian Rogersd81871c2011-10-03 13:57:23 -07003028}
3029
3030Method* DexVerifier::ResolveMethodAndCheckAccess(uint32_t method_idx, bool is_direct) {
3031 Class* referrer = method_->GetDeclaringClass();
3032 DexCache* dex_cache = referrer->GetDexCache();
3033 Method* res_method = dex_cache->GetResolvedMethod(method_idx);
3034 if (res_method == NULL) {
3035 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx);
Ian Rogers28ad40d2011-10-27 15:19:26 -07003036 const RegType& klass_type = ResolveClassAndCheckAccess(method_id.class_idx_);
Ian Rogers9f1ab122011-12-12 08:52:43 -08003037 if(klass_type.IsUnresolvedTypes() || klass_type.IsUnknown()) {
Ian Rogers28ad40d2011-10-27 15:19:26 -07003038 return NULL; // Can't resolve Class so no more to do here
Ian Rogersd81871c2011-10-03 13:57:23 -07003039 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07003040 Class* klass = klass_type.GetClass();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003041 const char* name = dex_file_->GetMethodName(method_id);
Ian Rogers0571d352011-11-03 19:51:38 -07003042 std::string signature(dex_file_->CreateMethodSignature(method_id.proto_idx_, NULL));
Ian Rogersd81871c2011-10-03 13:57:23 -07003043 if (is_direct) {
3044 res_method = klass->FindDirectMethod(name, signature);
3045 } else if (klass->IsInterface()) {
3046 res_method = klass->FindInterfaceMethod(name, signature);
3047 } else {
3048 res_method = klass->FindVirtualMethod(name, signature);
3049 }
3050 if (res_method != NULL) {
3051 dex_cache->SetResolvedMethod(method_idx, res_method);
3052 } else {
3053 Fail(VERIFY_ERROR_NO_METHOD) << "couldn't find method "
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003054 << PrettyDescriptor(klass) << "." << name
Ian Rogersd81871c2011-10-03 13:57:23 -07003055 << " " << signature;
3056 return NULL;
3057 }
3058 }
3059 /* Check if access is allowed. */
3060 if (!referrer->CanAccessMember(res_method->GetDeclaringClass(), res_method->GetAccessFlags())) {
3061 Fail(VERIFY_ERROR_ACCESS_METHOD) << "illegal method access (call " << PrettyMethod(res_method)
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003062 << " from " << PrettyDescriptor(referrer) << ")";
Ian Rogersd81871c2011-10-03 13:57:23 -07003063 return NULL;
3064 }
3065 return res_method;
3066}
3067
3068Method* DexVerifier::VerifyInvocationArgs(const Instruction::DecodedInstruction& dec_insn,
3069 MethodType method_type, bool is_range, bool is_super) {
3070 // Resolve the method. This could be an abstract or concrete method depending on what sort of call
3071 // we're making.
3072 Method* res_method = ResolveMethodAndCheckAccess(dec_insn.vB_,
3073 (method_type == METHOD_DIRECT || method_type == METHOD_STATIC));
Ian Rogers28ad40d2011-10-27 15:19:26 -07003074 if (res_method == NULL) { // error or class is unresolved
Ian Rogersd81871c2011-10-03 13:57:23 -07003075 return NULL;
3076 }
3077 // Make sure calls to constructors are "direct". There are additional restrictions but we don't
3078 // enforce them here.
3079 if (res_method->IsConstructor() && method_type != METHOD_DIRECT) {
3080 Fail(VERIFY_ERROR_GENERIC) << "rejecting non-direct call to constructor "
3081 << PrettyMethod(res_method);
3082 return NULL;
3083 }
3084 // See if the method type implied by the invoke instruction matches the access flags for the
3085 // target method.
3086 if ((method_type == METHOD_DIRECT && !res_method->IsDirect()) ||
3087 (method_type == METHOD_STATIC && !res_method->IsStatic()) ||
3088 ((method_type == METHOD_VIRTUAL || method_type == METHOD_INTERFACE) && res_method->IsDirect())
3089 ) {
Ian Rogers573db4a2011-12-13 15:30:50 -08003090 Fail(VERIFY_ERROR_CLASS_CHANGE) << "invoke type does not match method type of "
3091 << PrettyMethod(res_method);
Ian Rogersd81871c2011-10-03 13:57:23 -07003092 return NULL;
3093 }
3094 // If we're using invoke-super(method), make sure that the executing method's class' superclass
3095 // has a vtable entry for the target method.
3096 if (is_super) {
3097 DCHECK(method_type == METHOD_VIRTUAL);
3098 Class* super = method_->GetDeclaringClass()->GetSuperClass();
3099 if (super == NULL || res_method->GetMethodIndex() > super->GetVTable()->GetLength()) {
3100 if (super == NULL) { // Only Object has no super class
3101 Fail(VERIFY_ERROR_NO_METHOD) << "invalid invoke-super from " << PrettyMethod(method_)
3102 << " to super " << PrettyMethod(res_method);
3103 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003104 MethodHelper mh(res_method);
Ian Rogersd81871c2011-10-03 13:57:23 -07003105 Fail(VERIFY_ERROR_NO_METHOD) << "invalid invoke-super from " << PrettyMethod(method_)
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003106 << " to super " << PrettyDescriptor(super)
3107 << "." << mh.GetName()
3108 << mh.GetSignature();
Ian Rogersd81871c2011-10-03 13:57:23 -07003109 }
3110 return NULL;
3111 }
3112 }
3113 // We use vAA as our expected arg count, rather than res_method->insSize, because we need to
3114 // match the call to the signature. Also, we might might be calling through an abstract method
3115 // definition (which doesn't have register count values).
3116 int expected_args = dec_insn.vA_;
3117 /* caught by static verifier */
3118 DCHECK(is_range || expected_args <= 5);
3119 if (expected_args > code_item_->outs_size_) {
3120 Fail(VERIFY_ERROR_GENERIC) << "invalid arg count (" << expected_args
3121 << ") exceeds outsSize (" << code_item_->outs_size_ << ")";
3122 return NULL;
3123 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003124 std::string sig(MethodHelper(res_method).GetSignature());
Ian Rogersd81871c2011-10-03 13:57:23 -07003125 if (sig[0] != '(') {
3126 Fail(VERIFY_ERROR_GENERIC) << "rejecting call to " << res_method
3127 << " as descriptor doesn't start with '(': " << sig;
3128 return NULL;
3129 }
jeffhaobdb76512011-09-07 11:43:16 -07003130 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07003131 * Check the "this" argument, which must be an instance of the class
3132 * that declared the method. For an interface class, we don't do the
3133 * full interface merge, so we can't do a rigorous check here (which
3134 * is okay since we have to do it at runtime).
jeffhaobdb76512011-09-07 11:43:16 -07003135 */
Ian Rogersd81871c2011-10-03 13:57:23 -07003136 int actual_args = 0;
3137 if (!res_method->IsStatic()) {
3138 const RegType& actual_arg_type = work_line_->GetInvocationThis(dec_insn);
3139 if (failure_ != VERIFY_ERROR_NONE) {
3140 return NULL;
3141 }
3142 if (actual_arg_type.IsUninitializedReference() && !res_method->IsConstructor()) {
3143 Fail(VERIFY_ERROR_GENERIC) << "'this' arg must be initialized";
3144 return NULL;
3145 }
3146 if (method_type != METHOD_INTERFACE && !actual_arg_type.IsZero()) {
Ian Rogers9074b992011-10-26 17:41:55 -07003147 const RegType& res_method_class = reg_types_.FromClass(res_method->GetDeclaringClass());
3148 if (!res_method_class.IsAssignableFrom(actual_arg_type)) {
3149 Fail(VERIFY_ERROR_GENERIC) << "'this' arg '" << actual_arg_type << "' not instance of '"
3150 << res_method_class << "'";
Ian Rogersd81871c2011-10-03 13:57:23 -07003151 return NULL;
3152 }
3153 }
3154 actual_args++;
3155 }
3156 /*
3157 * Process the target method's signature. This signature may or may not
3158 * have been verified, so we can't assume it's properly formed.
3159 */
3160 size_t sig_offset = 0;
3161 for (sig_offset = 1; sig_offset < sig.size() && sig[sig_offset] != ')'; sig_offset++) {
3162 if (actual_args >= expected_args) {
3163 Fail(VERIFY_ERROR_GENERIC) << "Rejecting invalid call to '" << PrettyMethod(res_method)
3164 << "'. Expected " << expected_args << " args, found more ("
3165 << sig.substr(sig_offset) << ")";
3166 return NULL;
3167 }
3168 std::string descriptor;
3169 if ((sig[sig_offset] == 'L') || (sig[sig_offset] == '[')) {
3170 size_t end;
3171 if (sig[sig_offset] == 'L') {
3172 end = sig.find(';', sig_offset);
3173 } else {
3174 for(end = sig_offset + 1; sig[end] == '['; end++) ;
3175 if (sig[end] == 'L') {
3176 end = sig.find(';', end);
3177 }
3178 }
3179 if (end == std::string::npos) {
3180 Fail(VERIFY_ERROR_GENERIC) << "Rejecting invocation of " << PrettyMethod(res_method)
3181 << "bad signature component '" << sig << "' (missing ';')";
3182 return NULL;
3183 }
3184 descriptor = sig.substr(sig_offset, end - sig_offset + 1);
3185 sig_offset = end;
3186 } else {
3187 descriptor = sig[sig_offset];
3188 }
3189 const RegType& reg_type =
3190 reg_types_.FromDescriptor(method_->GetDeclaringClass()->GetClassLoader(), descriptor);
Ian Rogers84fa0742011-10-25 18:13:30 -07003191 uint32_t get_reg = is_range ? dec_insn.vC_ + actual_args : dec_insn.arg_[actual_args];
3192 if (!work_line_->VerifyRegisterType(get_reg, reg_type)) {
3193 return NULL;
Ian Rogersd81871c2011-10-03 13:57:23 -07003194 }
3195 actual_args = reg_type.IsLongOrDoubleTypes() ? actual_args + 2 : actual_args + 1;
3196 }
3197 if (sig[sig_offset] != ')') {
3198 Fail(VERIFY_ERROR_GENERIC) << "invocation target: bad signature" << PrettyMethod(res_method);
3199 return NULL;
3200 }
3201 if (actual_args != expected_args) {
3202 Fail(VERIFY_ERROR_GENERIC) << "Rejecting invocation of " << PrettyMethod(res_method)
3203 << " expected " << expected_args << " args, found " << actual_args;
3204 return NULL;
3205 } else {
3206 return res_method;
3207 }
3208}
3209
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003210const RegType& DexVerifier::GetMethodReturnType() {
3211 return reg_types_.FromDescriptor(method_->GetDeclaringClass()->GetClassLoader(),
3212 MethodHelper(method_).GetReturnTypeDescriptor());
3213}
3214
Ian Rogersd81871c2011-10-03 13:57:23 -07003215void DexVerifier::VerifyAGet(const Instruction::DecodedInstruction& dec_insn,
3216 const RegType& insn_type, bool is_primitive) {
3217 const RegType& index_type = work_line_->GetRegisterType(dec_insn.vC_);
3218 if (!index_type.IsArrayIndexTypes()) {
3219 Fail(VERIFY_ERROR_GENERIC) << "Invalid reg type for array index (" << index_type << ")";
3220 } else {
3221 Class* array_class = work_line_->GetClassFromRegister(dec_insn.vB_);
3222 if (failure_ == VERIFY_ERROR_NONE) {
3223 if (array_class == NULL) {
3224 // Null array class; this code path will fail at runtime. Infer a merge-able type from the
3225 // instruction type. TODO: have a proper notion of bottom here.
3226 if (!is_primitive || insn_type.IsCategory1Types()) {
3227 // Reference or category 1
3228 work_line_->SetRegisterType(dec_insn.vA_, reg_types_.Zero());
3229 } else {
3230 // Category 2
3231 work_line_->SetRegisterType(dec_insn.vA_, reg_types_.ConstLo());
3232 }
3233 } else {
3234 /* verify the class */
3235 Class* component_class = array_class->GetComponentType();
3236 const RegType& component_type = reg_types_.FromClass(component_class);
3237 if (!array_class->IsArrayClass()) {
3238 Fail(VERIFY_ERROR_GENERIC) << "not array type "
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003239 << PrettyDescriptor(array_class) << " with aget";
Ian Rogersd81871c2011-10-03 13:57:23 -07003240 } else if (component_class->IsPrimitive() && !is_primitive) {
3241 Fail(VERIFY_ERROR_GENERIC) << "primitive array type "
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003242 << PrettyDescriptor(array_class)
Ian Rogersd81871c2011-10-03 13:57:23 -07003243 << " source for aget-object";
3244 } else if (!component_class->IsPrimitive() && is_primitive) {
3245 Fail(VERIFY_ERROR_GENERIC) << "reference array type "
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003246 << PrettyDescriptor(array_class)
Ian Rogersd81871c2011-10-03 13:57:23 -07003247 << " source for category 1 aget";
3248 } else if (is_primitive && !insn_type.Equals(component_type) &&
3249 !((insn_type.IsInteger() && component_type.IsFloat()) ||
3250 (insn_type.IsLong() && component_type.IsDouble()))) {
3251 Fail(VERIFY_ERROR_GENERIC) << "array type "
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003252 << PrettyDescriptor(array_class)
Ian Rogersd81871c2011-10-03 13:57:23 -07003253 << " incompatible with aget of type " << insn_type;
3254 } else {
3255 // Use knowledge of the field type which is stronger than the type inferred from the
3256 // instruction, which can't differentiate object types and ints from floats, longs from
3257 // doubles.
3258 work_line_->SetRegisterType(dec_insn.vA_, component_type);
3259 }
3260 }
3261 }
3262 }
3263}
3264
3265void DexVerifier::VerifyAPut(const Instruction::DecodedInstruction& dec_insn,
3266 const RegType& insn_type, bool is_primitive) {
3267 const RegType& index_type = work_line_->GetRegisterType(dec_insn.vC_);
3268 if (!index_type.IsArrayIndexTypes()) {
3269 Fail(VERIFY_ERROR_GENERIC) << "Invalid reg type for array index (" << index_type << ")";
3270 } else {
3271 Class* array_class = work_line_->GetClassFromRegister(dec_insn.vB_);
3272 if (failure_ == VERIFY_ERROR_NONE) {
3273 if (array_class == NULL) {
3274 // Null array class; this code path will fail at runtime. Infer a merge-able type from the
3275 // instruction type.
3276 } else {
3277 /* verify the class */
3278 Class* component_class = array_class->GetComponentType();
3279 const RegType& component_type = reg_types_.FromClass(component_class);
3280 if (!array_class->IsArrayClass()) {
3281 Fail(VERIFY_ERROR_GENERIC) << "not array type "
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003282 << PrettyDescriptor(array_class) << " with aput";
Ian Rogersd81871c2011-10-03 13:57:23 -07003283 } else if (component_class->IsPrimitive() && !is_primitive) {
3284 Fail(VERIFY_ERROR_GENERIC) << "primitive array type "
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003285 << PrettyDescriptor(array_class)
Ian Rogersd81871c2011-10-03 13:57:23 -07003286 << " source for aput-object";
3287 } else if (!component_class->IsPrimitive() && is_primitive) {
3288 Fail(VERIFY_ERROR_GENERIC) << "reference array type "
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003289 << PrettyDescriptor(array_class)
Ian Rogersd81871c2011-10-03 13:57:23 -07003290 << " source for category 1 aput";
3291 } else if (is_primitive && !insn_type.Equals(component_type) &&
3292 !((insn_type.IsInteger() && component_type.IsFloat()) ||
3293 (insn_type.IsLong() && component_type.IsDouble()))) {
3294 Fail(VERIFY_ERROR_GENERIC) << "array type "
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003295 << PrettyDescriptor(array_class)
Ian Rogersd81871c2011-10-03 13:57:23 -07003296 << " incompatible with aput of type " << insn_type;
3297 } else {
3298 // The instruction agrees with the type of array, confirm the value to be stored does too
Ian Rogers26fee742011-12-13 13:28:31 -08003299 // Note: we use the instruction type (rather than the component type) for aput-object as
3300 // incompatible classes will be caught at runtime as an array store exception
3301 work_line_->VerifyRegisterType(dec_insn.vA_, is_primitive ? component_type : insn_type);
Ian Rogersd81871c2011-10-03 13:57:23 -07003302 }
3303 }
3304 }
3305 }
3306}
3307
3308Field* DexVerifier::GetStaticField(int field_idx) {
Ian Rogersb067ac22011-12-13 18:05:09 -08003309 Field* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(field_idx, method_);
Ian Rogersd81871c2011-10-03 13:57:23 -07003310 if (field == NULL) {
3311 const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx);
Ian Rogersf4028cc2011-11-02 14:56:39 -07003312 LOG(INFO) << "unable to resolve static field " << field_idx << " ("
3313 << dex_file_->GetFieldName(field_id) << ") in "
3314 << dex_file_->GetFieldDeclaringClassDescriptor(field_id);
Ian Rogersd81871c2011-10-03 13:57:23 -07003315 DCHECK(Thread::Current()->IsExceptionPending());
3316 Thread::Current()->ClearException();
3317 return NULL;
3318 } else if (!method_->GetDeclaringClass()->CanAccessMember(field->GetDeclaringClass(),
3319 field->GetAccessFlags())) {
3320 Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot access static field " << PrettyField(field)
3321 << " from " << PrettyClass(method_->GetDeclaringClass());
3322 return NULL;
3323 } else if (!field->IsStatic()) {
3324 Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected field " << PrettyField(field) << " to be static";
3325 return NULL;
3326 } else {
3327 return field;
3328 }
3329}
3330
Ian Rogersd81871c2011-10-03 13:57:23 -07003331Field* DexVerifier::GetInstanceField(const RegType& obj_type, int field_idx) {
Ian Rogersb067ac22011-12-13 18:05:09 -08003332 Field* field = Runtime::Current()->GetClassLinker()->ResolveFieldJLS(field_idx, method_);
Ian Rogersd81871c2011-10-03 13:57:23 -07003333 if (field == NULL) {
3334 const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx);
Ian Rogersf4028cc2011-11-02 14:56:39 -07003335 LOG(INFO) << "unable to resolve instance field " << field_idx << " ("
3336 << dex_file_->GetFieldName(field_id) << ") in "
3337 << dex_file_->GetFieldDeclaringClassDescriptor(field_id);
Ian Rogersd81871c2011-10-03 13:57:23 -07003338 DCHECK(Thread::Current()->IsExceptionPending());
3339 Thread::Current()->ClearException();
3340 return NULL;
3341 } else if (!method_->GetDeclaringClass()->CanAccessMember(field->GetDeclaringClass(),
3342 field->GetAccessFlags())) {
3343 Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot access instance field " << PrettyField(field)
3344 << " from " << PrettyClass(method_->GetDeclaringClass());
3345 return NULL;
3346 } else if (field->IsStatic()) {
3347 Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected field " << PrettyField(field)
3348 << " to not be static";
3349 return NULL;
3350 } else if (obj_type.IsZero()) {
3351 // Cannot infer and check type, however, access will cause null pointer exception
3352 return field;
3353 } else if(obj_type.IsUninitializedReference() &&
3354 (!method_->IsConstructor() || method_->GetDeclaringClass() != obj_type.GetClass() ||
3355 field->GetDeclaringClass() != method_->GetDeclaringClass())) {
3356 // Field accesses through uninitialized references are only allowable for constructors where
3357 // the field is declared in this class
3358 Fail(VERIFY_ERROR_GENERIC) << "cannot access instance field " << PrettyField(field)
3359 << " of a not fully initialized object within the context of "
3360 << PrettyMethod(method_);
3361 return NULL;
3362 } else if(!field->GetDeclaringClass()->IsAssignableFrom(obj_type.GetClass())) {
3363 // Trying to access C1.field1 using reference of type C2, which is neither C1 or a sub-class
3364 // of C1. For resolution to occur the declared class of the field must be compatible with
3365 // obj_type, we've discovered this wasn't so, so report the field didn't exist.
3366 Fail(VERIFY_ERROR_NO_FIELD) << "cannot access instance field " << PrettyField(field)
3367 << " from object of type " << PrettyClass(obj_type.GetClass());
3368 return NULL;
3369 } else {
3370 return field;
3371 }
3372}
3373
Ian Rogersb94a27b2011-10-26 00:33:41 -07003374void DexVerifier::VerifyISGet(const Instruction::DecodedInstruction& dec_insn,
3375 const RegType& insn_type, bool is_primitive, bool is_static) {
Ian Rogersf4028cc2011-11-02 14:56:39 -07003376 uint32_t field_idx = is_static ? dec_insn.vB_ : dec_insn.vC_;
Ian Rogersb94a27b2011-10-26 00:33:41 -07003377 Field* field;
3378 if (is_static) {
Ian Rogersf4028cc2011-11-02 14:56:39 -07003379 field = GetStaticField(field_idx);
Ian Rogersb94a27b2011-10-26 00:33:41 -07003380 } else {
3381 const RegType& object_type = work_line_->GetRegisterType(dec_insn.vB_);
Ian Rogersf4028cc2011-11-02 14:56:39 -07003382 field = GetInstanceField(object_type, field_idx);
Ian Rogersb94a27b2011-10-26 00:33:41 -07003383 }
Ian Rogersf4028cc2011-11-02 14:56:39 -07003384 if (failure_ != VERIFY_ERROR_NONE) {
3385 work_line_->SetRegisterType(dec_insn.vA_, reg_types_.Unknown());
3386 } else {
3387 const char* descriptor;
3388 const ClassLoader* loader;
3389 if (field != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003390 descriptor = FieldHelper(field).GetTypeDescriptor();
Ian Rogersf4028cc2011-11-02 14:56:39 -07003391 loader = field->GetDeclaringClass()->GetClassLoader();
3392 } else {
3393 const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx);
3394 descriptor = dex_file_->GetFieldTypeDescriptor(field_id);
3395 loader = method_->GetDeclaringClass()->GetClassLoader();
3396 }
3397 const RegType& field_type = reg_types_.FromDescriptor(loader, descriptor);
Ian Rogersd81871c2011-10-03 13:57:23 -07003398 if (is_primitive) {
Ian Rogersb5e95b92011-10-25 23:28:55 -07003399 if (field_type.Equals(insn_type) ||
3400 (field_type.IsFloat() && insn_type.IsIntegralTypes()) ||
3401 (field_type.IsDouble() && insn_type.IsLongTypes())) {
Ian Rogersd81871c2011-10-03 13:57:23 -07003402 // expected that read is of the correct primitive type or that int reads are reading
3403 // floats or long reads are reading doubles
3404 } else {
3405 // This is a global failure rather than a class change failure as the instructions and
3406 // the descriptors for the type should have been consistent within the same file at
3407 // compile time
3408 Fail(VERIFY_ERROR_GENERIC) << "expected field " << PrettyField(field)
Ian Rogersb5e95b92011-10-25 23:28:55 -07003409 << " to be of type '" << insn_type
Ian Rogersb94a27b2011-10-26 00:33:41 -07003410 << "' but found type '" << field_type << "' in get";
Ian Rogersd81871c2011-10-03 13:57:23 -07003411 return;
3412 }
3413 } else {
Ian Rogersb5e95b92011-10-25 23:28:55 -07003414 if (!insn_type.IsAssignableFrom(field_type)) {
Ian Rogersd81871c2011-10-03 13:57:23 -07003415 Fail(VERIFY_ERROR_GENERIC) << "expected field " << PrettyField(field)
Ian Rogersb5e95b92011-10-25 23:28:55 -07003416 << " to be compatible with type '" << insn_type
3417 << "' but found type '" << field_type
Ian Rogersb94a27b2011-10-26 00:33:41 -07003418 << "' in get-object";
Ian Rogersd81871c2011-10-03 13:57:23 -07003419 return;
3420 }
3421 }
Ian Rogersb5e95b92011-10-25 23:28:55 -07003422 work_line_->SetRegisterType(dec_insn.vA_, field_type);
Ian Rogersd81871c2011-10-03 13:57:23 -07003423 }
3424}
3425
Ian Rogersb94a27b2011-10-26 00:33:41 -07003426void DexVerifier::VerifyISPut(const Instruction::DecodedInstruction& dec_insn,
3427 const RegType& insn_type, bool is_primitive, bool is_static) {
Ian Rogers55d249f2011-11-02 16:48:09 -07003428 uint32_t field_idx = is_static ? dec_insn.vB_ : dec_insn.vC_;
Ian Rogersb94a27b2011-10-26 00:33:41 -07003429 Field* field;
3430 if (is_static) {
Ian Rogers55d249f2011-11-02 16:48:09 -07003431 field = GetStaticField(field_idx);
Ian Rogersb94a27b2011-10-26 00:33:41 -07003432 } else {
3433 const RegType& object_type = work_line_->GetRegisterType(dec_insn.vB_);
Ian Rogers55d249f2011-11-02 16:48:09 -07003434 field = GetInstanceField(object_type, field_idx);
Ian Rogersb94a27b2011-10-26 00:33:41 -07003435 }
Ian Rogers55d249f2011-11-02 16:48:09 -07003436 if (failure_ != VERIFY_ERROR_NONE) {
3437 work_line_->SetRegisterType(dec_insn.vA_, reg_types_.Unknown());
3438 } else {
3439 const char* descriptor;
3440 const ClassLoader* loader;
3441 if (field != NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003442 descriptor = FieldHelper(field).GetTypeDescriptor();
Ian Rogers55d249f2011-11-02 16:48:09 -07003443 loader = field->GetDeclaringClass()->GetClassLoader();
3444 } else {
3445 const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx);
3446 descriptor = dex_file_->GetFieldTypeDescriptor(field_id);
3447 loader = method_->GetDeclaringClass()->GetClassLoader();
Ian Rogersd81871c2011-10-03 13:57:23 -07003448 }
Ian Rogers55d249f2011-11-02 16:48:09 -07003449 const RegType& field_type = reg_types_.FromDescriptor(loader, descriptor);
3450 if (field != NULL) {
3451 if (field->IsFinal() && field->GetDeclaringClass() != method_->GetDeclaringClass()) {
3452 Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot modify final field " << PrettyField(field)
3453 << " from other class " << PrettyClass(method_->GetDeclaringClass());
3454 return;
3455 }
3456 }
Ian Rogersd81871c2011-10-03 13:57:23 -07003457 if (is_primitive) {
Ian Rogers2c8a8572011-10-24 17:11:36 -07003458 // Primitive field assignability rules are weaker than regular assignability rules
3459 bool instruction_compatible;
3460 bool value_compatible;
3461 const RegType& value_type = work_line_->GetRegisterType(dec_insn.vA_);
3462 if (field_type.IsIntegralTypes()) {
3463 instruction_compatible = insn_type.IsIntegralTypes();
3464 value_compatible = value_type.IsIntegralTypes();
3465 } else if (field_type.IsFloat()) {
Ian Rogersb94a27b2011-10-26 00:33:41 -07003466 instruction_compatible = insn_type.IsInteger(); // no [is]put-float, so expect [is]put-int
Ian Rogers2c8a8572011-10-24 17:11:36 -07003467 value_compatible = value_type.IsFloatTypes();
3468 } else if (field_type.IsLong()) {
3469 instruction_compatible = insn_type.IsLong();
3470 value_compatible = value_type.IsLongTypes();
3471 } else if (field_type.IsDouble()) {
Ian Rogersb94a27b2011-10-26 00:33:41 -07003472 instruction_compatible = insn_type.IsLong(); // no [is]put-double, so expect [is]put-long
Ian Rogers2c8a8572011-10-24 17:11:36 -07003473 value_compatible = value_type.IsDoubleTypes();
Ian Rogersd81871c2011-10-03 13:57:23 -07003474 } else {
Ian Rogers2c8a8572011-10-24 17:11:36 -07003475 instruction_compatible = false; // reference field with primitive store
3476 value_compatible = false; // unused
3477 }
3478 if (!instruction_compatible) {
Ian Rogersd81871c2011-10-03 13:57:23 -07003479 // This is a global failure rather than a class change failure as the instructions and
3480 // the descriptors for the type should have been consistent within the same file at
3481 // compile time
3482 Fail(VERIFY_ERROR_GENERIC) << "expected field " << PrettyField(field)
Ian Rogersb5e95b92011-10-25 23:28:55 -07003483 << " to be of type '" << insn_type
3484 << "' but found type '" << field_type
Ian Rogersb94a27b2011-10-26 00:33:41 -07003485 << "' in put";
Ian Rogersd81871c2011-10-03 13:57:23 -07003486 return;
3487 }
Ian Rogers2c8a8572011-10-24 17:11:36 -07003488 if (!value_compatible) {
3489 Fail(VERIFY_ERROR_GENERIC) << "unexpected value in v" << dec_insn.vA_
3490 << " of type " << value_type
3491 << " but expected " << field_type
Ian Rogersb94a27b2011-10-26 00:33:41 -07003492 << " for store to " << PrettyField(field) << " in put";
Ian Rogers2c8a8572011-10-24 17:11:36 -07003493 return;
3494 }
Ian Rogersd81871c2011-10-03 13:57:23 -07003495 } else {
Ian Rogersb5e95b92011-10-25 23:28:55 -07003496 if (!insn_type.IsAssignableFrom(field_type)) {
Ian Rogersd81871c2011-10-03 13:57:23 -07003497 Fail(VERIFY_ERROR_GENERIC) << "expected field " << PrettyField(field)
Ian Rogersb5e95b92011-10-25 23:28:55 -07003498 << " to be compatible with type '" << insn_type
3499 << "' but found type '" << field_type
Ian Rogersb94a27b2011-10-26 00:33:41 -07003500 << "' in put-object";
Ian Rogersd81871c2011-10-03 13:57:23 -07003501 return;
3502 }
Ian Rogers2c8a8572011-10-24 17:11:36 -07003503 work_line_->VerifyRegisterType(dec_insn.vA_, field_type);
Ian Rogersd81871c2011-10-03 13:57:23 -07003504 }
Ian Rogersd81871c2011-10-03 13:57:23 -07003505 }
3506}
3507
3508bool DexVerifier::CheckMoveException(const uint16_t* insns, int insn_idx) {
3509 if ((insns[insn_idx] & 0xff) == Instruction::MOVE_EXCEPTION) {
3510 Fail(VERIFY_ERROR_GENERIC) << "invalid use of move-exception";
3511 return false;
3512 }
3513 return true;
3514}
3515
3516void DexVerifier::VerifyFilledNewArrayRegs(const Instruction::DecodedInstruction& dec_insn,
Ian Rogers28ad40d2011-10-27 15:19:26 -07003517 const RegType& res_type, bool is_range) {
3518 DCHECK(res_type.IsArrayClass()) << res_type; // Checked before calling.
Ian Rogersd81871c2011-10-03 13:57:23 -07003519 /*
3520 * Verify each register. If "arg_count" is bad, VerifyRegisterType() will run off the end of the
3521 * list and fail. It's legal, if silly, for arg_count to be zero.
3522 */
Ian Rogers28ad40d2011-10-27 15:19:26 -07003523 const RegType& expected_type = reg_types_.GetComponentType(res_type,
3524 method_->GetDeclaringClass()->GetClassLoader());
Ian Rogersd81871c2011-10-03 13:57:23 -07003525 uint32_t arg_count = dec_insn.vA_;
3526 for (size_t ui = 0; ui < arg_count; ui++) {
3527 uint32_t get_reg;
3528
3529 if (is_range)
3530 get_reg = dec_insn.vC_ + ui;
3531 else
3532 get_reg = dec_insn.arg_[ui];
3533
3534 if (!work_line_->VerifyRegisterType(get_reg, expected_type)) {
3535 Fail(VERIFY_ERROR_GENERIC) << "filled-new-array arg " << ui << "(" << get_reg
3536 << ") not valid";
3537 return;
3538 }
3539 }
3540}
3541
3542void DexVerifier::ReplaceFailingInstruction() {
Ian Rogersf1864ef2011-12-09 12:39:48 -08003543 if (Runtime::Current()->IsStarted()) {
3544 LOG(ERROR) << "Verification attempting to replacing instructions in " << PrettyMethod(method_)
3545 << " " << fail_messages_.str();
3546 return;
3547 }
Ian Rogersd81871c2011-10-03 13:57:23 -07003548 const Instruction* inst = Instruction::At(code_item_->insns_ + work_insn_idx_);
3549 DCHECK(inst->IsThrow()) << "Expected instruction that will throw " << inst->Name();
3550 VerifyErrorRefType ref_type;
3551 switch (inst->Opcode()) {
3552 case Instruction::CONST_CLASS: // insn[1] == class ref, 2 code units (4 bytes)
jeffhaobdb76512011-09-07 11:43:16 -07003553 case Instruction::CHECK_CAST:
3554 case Instruction::INSTANCE_OF:
3555 case Instruction::NEW_INSTANCE:
3556 case Instruction::NEW_ARRAY:
Ian Rogersd81871c2011-10-03 13:57:23 -07003557 case Instruction::FILLED_NEW_ARRAY: // insn[1] == class ref, 3 code units (6 bytes)
jeffhaobdb76512011-09-07 11:43:16 -07003558 case Instruction::FILLED_NEW_ARRAY_RANGE:
3559 ref_type = VERIFY_ERROR_REF_CLASS;
3560 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07003561 case Instruction::IGET: // insn[1] == field ref, 2 code units (4 bytes)
jeffhaobdb76512011-09-07 11:43:16 -07003562 case Instruction::IGET_BOOLEAN:
3563 case Instruction::IGET_BYTE:
3564 case Instruction::IGET_CHAR:
3565 case Instruction::IGET_SHORT:
3566 case Instruction::IGET_WIDE:
3567 case Instruction::IGET_OBJECT:
3568 case Instruction::IPUT:
3569 case Instruction::IPUT_BOOLEAN:
3570 case Instruction::IPUT_BYTE:
3571 case Instruction::IPUT_CHAR:
3572 case Instruction::IPUT_SHORT:
3573 case Instruction::IPUT_WIDE:
3574 case Instruction::IPUT_OBJECT:
3575 case Instruction::SGET:
3576 case Instruction::SGET_BOOLEAN:
3577 case Instruction::SGET_BYTE:
3578 case Instruction::SGET_CHAR:
3579 case Instruction::SGET_SHORT:
3580 case Instruction::SGET_WIDE:
3581 case Instruction::SGET_OBJECT:
3582 case Instruction::SPUT:
3583 case Instruction::SPUT_BOOLEAN:
3584 case Instruction::SPUT_BYTE:
3585 case Instruction::SPUT_CHAR:
3586 case Instruction::SPUT_SHORT:
3587 case Instruction::SPUT_WIDE:
3588 case Instruction::SPUT_OBJECT:
3589 ref_type = VERIFY_ERROR_REF_FIELD;
3590 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07003591 case Instruction::INVOKE_VIRTUAL: // insn[1] == method ref, 3 code units (6 bytes)
jeffhaobdb76512011-09-07 11:43:16 -07003592 case Instruction::INVOKE_VIRTUAL_RANGE:
3593 case Instruction::INVOKE_SUPER:
3594 case Instruction::INVOKE_SUPER_RANGE:
3595 case Instruction::INVOKE_DIRECT:
3596 case Instruction::INVOKE_DIRECT_RANGE:
3597 case Instruction::INVOKE_STATIC:
3598 case Instruction::INVOKE_STATIC_RANGE:
3599 case Instruction::INVOKE_INTERFACE:
3600 case Instruction::INVOKE_INTERFACE_RANGE:
3601 ref_type = VERIFY_ERROR_REF_METHOD;
3602 break;
jeffhaobdb76512011-09-07 11:43:16 -07003603 default:
Ian Rogers2c8a8572011-10-24 17:11:36 -07003604 LOG(FATAL) << "Error: verifier asked to replace instruction " << inst->DumpString(dex_file_);
jeffhaobdb76512011-09-07 11:43:16 -07003605 return;
jeffhaoba5ebb92011-08-25 17:24:37 -07003606 }
Ian Rogersd81871c2011-10-03 13:57:23 -07003607 uint16_t* insns = const_cast<uint16_t*>(code_item_->insns_);
3608 // THROW_VERIFICATION_ERROR is a 2 code unit instruction. We shouldn't be rewriting a 1 code unit
3609 // instruction, so assert it.
3610 size_t width = inst->SizeInCodeUnits();
3611 CHECK_GT(width, 1u);
Ian Rogersf1864ef2011-12-09 12:39:48 -08003612 // If the instruction is larger than 2 code units, rewrite subsequent code unit sized chunks with
Ian Rogersd81871c2011-10-03 13:57:23 -07003613 // NOPs
3614 for (size_t i = 2; i < width; i++) {
3615 insns[work_insn_idx_ + i] = Instruction::NOP;
3616 }
3617 // Encode the opcode, with the failure code in the high byte
3618 uint16_t new_instruction = Instruction::THROW_VERIFICATION_ERROR |
3619 (failure_ << 8) | // AA - component
3620 (ref_type << (8 + kVerifyErrorRefTypeShift));
3621 insns[work_insn_idx_] = new_instruction;
3622 // The 2nd code unit (higher in memory) with the reference in, comes from the instruction we
3623 // rewrote, so nothing to do here.
Ian Rogers9fdfc182011-10-26 23:12:52 -07003624 LOG(INFO) << "Verification error, replacing instructions in " << PrettyMethod(method_) << " "
3625 << fail_messages_.str();
3626 if (gDebugVerify) {
3627 std::cout << std::endl << info_messages_.str();
3628 Dump(std::cout);
3629 }
jeffhaobdb76512011-09-07 11:43:16 -07003630}
jeffhaoba5ebb92011-08-25 17:24:37 -07003631
Ian Rogersd81871c2011-10-03 13:57:23 -07003632bool DexVerifier::UpdateRegisters(uint32_t next_insn, const RegisterLine* merge_line) {
3633 const bool merge_debug = true;
3634 bool changed = true;
3635 RegisterLine* target_line = reg_table_.GetLine(next_insn);
3636 if (!insn_flags_[next_insn].IsVisitedOrChanged()) {
jeffhaobdb76512011-09-07 11:43:16 -07003637 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07003638 * We haven't processed this instruction before, and we haven't touched the registers here, so
3639 * there's nothing to "merge". Copy the registers over and mark it as changed. (This is the
3640 * only way a register can transition out of "unknown", so this is not just an optimization.)
jeffhaobdb76512011-09-07 11:43:16 -07003641 */
Ian Rogersd81871c2011-10-03 13:57:23 -07003642 target_line->CopyFromLine(merge_line);
jeffhaobdb76512011-09-07 11:43:16 -07003643 } else {
Ian Rogersd81871c2011-10-03 13:57:23 -07003644 UniquePtr<RegisterLine> copy(merge_debug ? new RegisterLine(target_line->NumRegs(), this) : NULL);
3645 copy->CopyFromLine(target_line);
3646 changed = target_line->MergeRegisters(merge_line);
3647 if (failure_ != VERIFY_ERROR_NONE) {
3648 return false;
jeffhaobdb76512011-09-07 11:43:16 -07003649 }
Ian Rogers2c8a8572011-10-24 17:11:36 -07003650 if (gDebugVerify && changed) {
Ian Rogersd81871c2011-10-03 13:57:23 -07003651 LogVerifyInfo() << "Merging at [" << (void*)work_insn_idx_ << "] to [" <<(void*)next_insn << "]: " << std::endl
3652 << *copy.get() << " MERGE" << std::endl
3653 << *merge_line << " ==" << std::endl
3654 << *target_line << std::endl;
jeffhaobdb76512011-09-07 11:43:16 -07003655 }
3656 }
Ian Rogersd81871c2011-10-03 13:57:23 -07003657 if (changed) {
3658 insn_flags_[next_insn].SetChanged();
jeffhaobdb76512011-09-07 11:43:16 -07003659 }
3660 return true;
3661}
3662
Ian Rogersd81871c2011-10-03 13:57:23 -07003663void DexVerifier::ComputeGcMapSizes(size_t* gc_points, size_t* ref_bitmap_bits,
3664 size_t* log2_max_gc_pc) {
3665 size_t local_gc_points = 0;
3666 size_t max_insn = 0;
3667 size_t max_ref_reg = -1;
3668 for (size_t i = 0; i < code_item_->insns_size_in_code_units_; i++) {
3669 if (insn_flags_[i].IsGcPoint()) {
3670 local_gc_points++;
3671 max_insn = i;
3672 RegisterLine* line = reg_table_.GetLine(i);
Ian Rogers84fa0742011-10-25 18:13:30 -07003673 max_ref_reg = line->GetMaxNonZeroReferenceReg(max_ref_reg);
jeffhaobdb76512011-09-07 11:43:16 -07003674 }
3675 }
Ian Rogersd81871c2011-10-03 13:57:23 -07003676 *gc_points = local_gc_points;
3677 *ref_bitmap_bits = max_ref_reg + 1; // if max register is 0 we need 1 bit to encode (ie +1)
3678 size_t i = 0;
3679 while ((1U << i) < max_insn) {
3680 i++;
3681 }
3682 *log2_max_gc_pc = i;
jeffhaobdb76512011-09-07 11:43:16 -07003683}
3684
Ian Rogersd81871c2011-10-03 13:57:23 -07003685ByteArray* DexVerifier::GenerateGcMap() {
3686 size_t num_entries, ref_bitmap_bits, pc_bits;
3687 ComputeGcMapSizes(&num_entries, &ref_bitmap_bits, &pc_bits);
3688 // There's a single byte to encode the size of each bitmap
3689 if (ref_bitmap_bits >= (8 /* bits per byte */ * 256 /* max unsigned byte + 1 */ )) {
3690 // TODO: either a better GC map format or per method failures
3691 Fail(VERIFY_ERROR_GENERIC) << "Cannot encode GC map for method with "
3692 << ref_bitmap_bits << " registers";
jeffhaobdb76512011-09-07 11:43:16 -07003693 return NULL;
3694 }
Ian Rogersd81871c2011-10-03 13:57:23 -07003695 size_t ref_bitmap_bytes = (ref_bitmap_bits + 7) / 8;
3696 // There are 2 bytes to encode the number of entries
3697 if (num_entries >= 65536) {
3698 // TODO: either a better GC map format or per method failures
3699 Fail(VERIFY_ERROR_GENERIC) << "Cannot encode GC map for method with "
3700 << num_entries << " entries";
jeffhaobdb76512011-09-07 11:43:16 -07003701 return NULL;
3702 }
Ian Rogersd81871c2011-10-03 13:57:23 -07003703 size_t pc_bytes;
jeffhaod1f0fde2011-09-08 17:25:33 -07003704 RegisterMapFormat format;
Ian Rogersd81871c2011-10-03 13:57:23 -07003705 if (pc_bits < 8) {
jeffhaod1f0fde2011-09-08 17:25:33 -07003706 format = kRegMapFormatCompact8;
Ian Rogersd81871c2011-10-03 13:57:23 -07003707 pc_bytes = 1;
3708 } else if (pc_bits < 16) {
jeffhaod1f0fde2011-09-08 17:25:33 -07003709 format = kRegMapFormatCompact16;
Ian Rogersd81871c2011-10-03 13:57:23 -07003710 pc_bytes = 2;
jeffhaoa0a764a2011-09-16 10:43:38 -07003711 } else {
Ian Rogersd81871c2011-10-03 13:57:23 -07003712 // TODO: either a better GC map format or per method failures
3713 Fail(VERIFY_ERROR_GENERIC) << "Cannot encode GC map for method with "
3714 << (1 << pc_bits) << " instructions (number is rounded up to nearest power of 2)";
3715 return NULL;
3716 }
3717 size_t table_size = ((pc_bytes + ref_bitmap_bytes) * num_entries ) + 4;
3718 ByteArray* table = ByteArray::Alloc(table_size);
3719 if (table == NULL) {
3720 Fail(VERIFY_ERROR_GENERIC) << "Failed to encode GC map (size=" << table_size << ")";
3721 return NULL;
3722 }
3723 // Write table header
3724 table->Set(0, format);
3725 table->Set(1, ref_bitmap_bytes);
3726 table->Set(2, num_entries & 0xFF);
3727 table->Set(3, (num_entries >> 8) & 0xFF);
3728 // Write table data
3729 size_t offset = 4;
3730 for (size_t i = 0; i < code_item_->insns_size_in_code_units_; i++) {
3731 if (insn_flags_[i].IsGcPoint()) {
3732 table->Set(offset, i & 0xFF);
3733 offset++;
3734 if (pc_bytes == 2) {
3735 table->Set(offset, (i >> 8) & 0xFF);
3736 offset++;
3737 }
3738 RegisterLine* line = reg_table_.GetLine(i);
3739 line->WriteReferenceBitMap(table->GetData() + offset, ref_bitmap_bytes);
3740 offset += ref_bitmap_bytes;
3741 }
3742 }
3743 DCHECK(offset == table_size);
3744 return table;
3745}
jeffhaoa0a764a2011-09-16 10:43:38 -07003746
Ian Rogersd81871c2011-10-03 13:57:23 -07003747void DexVerifier::VerifyGcMap() {
3748 // Check that for every GC point there is a map entry, there aren't entries for non-GC points,
3749 // that the table data is well formed and all references are marked (or not) in the bitmap
3750 PcToReferenceMap map(method_);
3751 size_t map_index = 0;
3752 for(size_t i = 0; i < code_item_->insns_size_in_code_units_; i++) {
3753 const uint8_t* reg_bitmap = map.FindBitMap(i, false);
3754 if (insn_flags_[i].IsGcPoint()) {
3755 CHECK_LT(map_index, map.NumEntries());
3756 CHECK_EQ(map.GetPC(map_index), i);
3757 CHECK_EQ(map.GetBitMap(map_index), reg_bitmap);
3758 map_index++;
3759 RegisterLine* line = reg_table_.GetLine(i);
3760 for(size_t j = 0; j < code_item_->registers_size_; j++) {
Ian Rogers84fa0742011-10-25 18:13:30 -07003761 if (line->GetRegisterType(j).IsNonZeroReferenceTypes()) {
Ian Rogersd81871c2011-10-03 13:57:23 -07003762 CHECK_LT(j / 8, map.RegWidth());
3763 CHECK_EQ((reg_bitmap[j / 8] >> (j % 8)) & 1, 1);
3764 } else if ((j / 8) < map.RegWidth()) {
3765 CHECK_EQ((reg_bitmap[j / 8] >> (j % 8)) & 1, 0);
3766 } else {
3767 // If a register doesn't contain a reference then the bitmap may be shorter than the line
3768 }
3769 }
3770 } else {
3771 CHECK(reg_bitmap == NULL);
3772 }
3773 }
3774}
jeffhaoa0a764a2011-09-16 10:43:38 -07003775
Ian Rogersd81871c2011-10-03 13:57:23 -07003776const uint8_t* PcToReferenceMap::FindBitMap(uint16_t dex_pc, bool error_if_not_present) const {
3777 size_t num_entries = NumEntries();
3778 // Do linear or binary search?
3779 static const size_t kSearchThreshold = 8;
3780 if (num_entries < kSearchThreshold) {
3781 for (size_t i = 0; i < num_entries; i++) {
3782 if (GetPC(i) == dex_pc) {
3783 return GetBitMap(i);
3784 }
3785 }
3786 } else {
3787 int lo = 0;
3788 int hi = num_entries -1;
jeffhaoa0a764a2011-09-16 10:43:38 -07003789 while (hi >= lo) {
Ian Rogersd81871c2011-10-03 13:57:23 -07003790 int mid = (hi + lo) / 2;
3791 int mid_pc = GetPC(mid);
3792 if (dex_pc > mid_pc) {
jeffhaoa0a764a2011-09-16 10:43:38 -07003793 lo = mid + 1;
Ian Rogersd81871c2011-10-03 13:57:23 -07003794 } else if (dex_pc < mid_pc) {
jeffhaoa0a764a2011-09-16 10:43:38 -07003795 hi = mid - 1;
3796 } else {
Ian Rogersd81871c2011-10-03 13:57:23 -07003797 return GetBitMap(mid);
jeffhaoa0a764a2011-09-16 10:43:38 -07003798 }
3799 }
3800 }
Ian Rogersd81871c2011-10-03 13:57:23 -07003801 if (error_if_not_present) {
3802 LOG(ERROR) << "Didn't find reference bit map for dex_pc " << dex_pc;
3803 }
jeffhaoa0a764a2011-09-16 10:43:38 -07003804 return NULL;
3805}
3806
Ian Rogersd81871c2011-10-03 13:57:23 -07003807} // namespace verifier
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003808} // namespace art