blob: 79f90e7b11d8215f70a0369ac32606eb4f3f1a8a [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"
Elliott Hughes1f359b02011-07-17 14:27:17 -070014#include "logging.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070015#include "runtime.h"
Elliott Hughes1f359b02011-07-17 14:27:17 -070016#include "stringpiece.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070017
18namespace art {
Ian Rogersd81871c2011-10-03 13:57:23 -070019namespace verifier {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070020
Ian Rogers2c8a8572011-10-24 17:11:36 -070021static const bool gDebugVerify = false;
22
Ian Rogersd81871c2011-10-03 13:57:23 -070023std::ostream& operator<<(std::ostream& os, const VerifyError& rhs) {
24 return os << (int)rhs;
25}
jeffhaobdb76512011-09-07 11:43:16 -070026
Ian Rogers84fa0742011-10-25 18:13:30 -070027static const char* type_strings[] = {
28 "Unknown",
29 "Conflict",
30 "Boolean",
31 "Byte",
32 "Short",
33 "Char",
34 "Integer",
35 "Float",
36 "Long (Low Half)",
37 "Long (High Half)",
38 "Double (Low Half)",
39 "Double (High Half)",
40 "64-bit Constant (Low Half)",
41 "64-bit Constant (High Half)",
42 "32-bit Constant",
43 "Unresolved Reference",
44 "Uninitialized Reference",
45 "Uninitialized This Reference",
Ian Rogers28ad40d2011-10-27 15:19:26 -070046 "Unresolved And Uninitialized Reference",
Ian Rogers84fa0742011-10-25 18:13:30 -070047 "Reference",
48};
Ian Rogersd81871c2011-10-03 13:57:23 -070049
Ian Rogers2c8a8572011-10-24 17:11:36 -070050std::string RegType::Dump() const {
Ian Rogers84fa0742011-10-25 18:13:30 -070051 DCHECK(type_ >= kRegTypeUnknown && type_ <= kRegTypeReference);
52 std::string result;
53 if (IsConstant()) {
54 uint32_t val = ConstantValue();
55 if (val == 0) {
56 result = "Zero";
Ian Rogersd81871c2011-10-03 13:57:23 -070057 } else {
Ian Rogers84fa0742011-10-25 18:13:30 -070058 if(IsConstantShort()) {
59 result = StringPrintf("32-bit Constant: %d", val);
60 } else {
61 result = StringPrintf("32-bit Constant: 0x%x", val);
62 }
63 }
64 } else {
65 result = type_strings[type_];
66 if (IsReferenceTypes()) {
67 result += ": ";
Ian Rogers28ad40d2011-10-27 15:19:26 -070068 if (IsUnresolvedTypes()) {
Ian Rogers84fa0742011-10-25 18:13:30 -070069 result += PrettyDescriptor(GetDescriptor());
70 } else {
71 result += PrettyDescriptor(GetClass()->GetDescriptor());
72 }
Ian Rogersd81871c2011-10-03 13:57:23 -070073 }
74 }
Ian Rogers84fa0742011-10-25 18:13:30 -070075 return result;
Ian Rogersd81871c2011-10-03 13:57:23 -070076}
77
78const RegType& RegType::HighHalf(RegTypeCache* cache) const {
79 CHECK(IsLowHalf());
80 if (type_ == kRegTypeLongLo) {
81 return cache->FromType(kRegTypeLongHi);
82 } else if (type_ == kRegTypeDoubleLo) {
83 return cache->FromType(kRegTypeDoubleHi);
84 } else {
85 return cache->FromType(kRegTypeConstHi);
86 }
87}
88
89/*
90 * A basic Join operation on classes. For a pair of types S and T the Join, written S v T = J, is
91 * S <: J, T <: J and for-all U such that S <: U, T <: U then J <: U. That is J is the parent of
92 * 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
93 * is the deepest (lowest upper bound) parent of S and T).
94 *
95 * This operation applies for regular classes and arrays, however, for interface types there needn't
96 * be a partial ordering on the types. We could solve the problem of a lack of a partial order by
97 * introducing sets of types, however, the only operation permissible on an interface is
98 * invoke-interface. In the tradition of Java verifiers we defer the verification of interface
99 * types until an invoke-interface call on the interface typed reference at runtime and allow
Ian Rogers5ed29bf2011-10-26 12:22:21 -0700100 * the perversion of any Object being assignable to an interface type (note, however, that we don't
101 * allow assignment of Object or Interface to any concrete subclass of Object and are therefore type
102 * safe; further the Join on a Object cannot result in a sub-class by definition).
Ian Rogersd81871c2011-10-03 13:57:23 -0700103 */
104Class* RegType::ClassJoin(Class* s, Class* t) {
105 DCHECK(!s->IsPrimitive()) << PrettyClass(s);
106 DCHECK(!t->IsPrimitive()) << PrettyClass(t);
107 if (s == t) {
108 return s;
109 } else if (s->IsAssignableFrom(t)) {
110 return s;
111 } else if (t->IsAssignableFrom(s)) {
112 return t;
113 } else if (s->IsArrayClass() && t->IsArrayClass()) {
114 Class* s_ct = s->GetComponentType();
115 Class* t_ct = t->GetComponentType();
116 if (s_ct->IsPrimitive() || t_ct->IsPrimitive()) {
117 // Given the types aren't the same, if either array is of primitive types then the only
118 // common parent is java.lang.Object
119 Class* result = s->GetSuperClass(); // short-cut to java.lang.Object
120 DCHECK(result->IsObjectClass());
121 return result;
122 }
123 Class* common_elem = ClassJoin(s_ct, t_ct);
124 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
125 const ClassLoader* class_loader = s->GetClassLoader();
126 std::string descriptor = "[" + common_elem->GetDescriptor()->ToModifiedUtf8();
127 Class* array_class = class_linker->FindClass(descriptor.c_str(), class_loader);
128 DCHECK(array_class != NULL);
129 return array_class;
130 } else {
131 size_t s_depth = s->Depth();
132 size_t t_depth = t->Depth();
133 // Get s and t to the same depth in the hierarchy
134 if (s_depth > t_depth) {
135 while (s_depth > t_depth) {
136 s = s->GetSuperClass();
137 s_depth--;
138 }
139 } else {
140 while (t_depth > s_depth) {
141 t = t->GetSuperClass();
142 t_depth--;
143 }
144 }
145 // Go up the hierarchy until we get to the common parent
146 while (s != t) {
147 s = s->GetSuperClass();
148 t = t->GetSuperClass();
149 }
150 return s;
151 }
152}
153
Ian Rogersb5e95b92011-10-25 23:28:55 -0700154bool RegType::IsAssignableFrom(const RegType& src) const {
155 if (Equals(src)) {
156 return true;
Ian Rogersd81871c2011-10-03 13:57:23 -0700157 } else {
Ian Rogersb5e95b92011-10-25 23:28:55 -0700158 switch (GetType()) {
Ian Rogers9074b992011-10-26 17:41:55 -0700159 case RegType::kRegTypeBoolean: return src.IsBooleanTypes();
160 case RegType::kRegTypeByte: return src.IsByteTypes();
161 case RegType::kRegTypeShort: return src.IsShortTypes();
162 case RegType::kRegTypeChar: return src.IsCharTypes();
163 case RegType::kRegTypeInteger: return src.IsIntegralTypes();
164 case RegType::kRegTypeFloat: return src.IsFloatTypes();
165 case RegType::kRegTypeLongLo: return src.IsLongTypes();
166 case RegType::kRegTypeDoubleLo: return src.IsDoubleTypes();
Ian Rogers84fa0742011-10-25 18:13:30 -0700167 default:
Ian Rogersb5e95b92011-10-25 23:28:55 -0700168 if (!IsReferenceTypes()) {
169 LOG(FATAL) << "Unexpected register type in IsAssignableFrom: '" << src << "'";
Ian Rogers84fa0742011-10-25 18:13:30 -0700170 }
Ian Rogersb5e95b92011-10-25 23:28:55 -0700171 if (src.IsZero()) {
Ian Rogers9074b992011-10-26 17:41:55 -0700172 return true; // all reference types can be assigned null
173 } else if (!src.IsReferenceTypes()) {
174 return false; // expect src to be a reference type
175 } else if (IsJavaLangObject()) {
176 return true; // all reference types can be assigned to Object
177 } else if (!IsUnresolvedTypes() && GetClass()->IsInterface()) {
Ian Rogers5ed29bf2011-10-26 12:22:21 -0700178 return true; // We allow assignment to any interface, see comment in ClassJoin
Ian Rogers9074b992011-10-26 17:41:55 -0700179 } else if (!IsUnresolvedTypes() && !src.IsUnresolvedTypes() &&
Ian Rogers5ed29bf2011-10-26 12:22:21 -0700180 GetClass()->IsAssignableFrom(src.GetClass())) {
181 // We're assignable from the Class point-of-view
Ian Rogersb5e95b92011-10-25 23:28:55 -0700182 return true;
Ian Rogersd81871c2011-10-03 13:57:23 -0700183 } else {
Ian Rogersb5e95b92011-10-25 23:28:55 -0700184 return false;
Ian Rogersd81871c2011-10-03 13:57:23 -0700185 }
Ian Rogersd81871c2011-10-03 13:57:23 -0700186 }
187 }
188}
189
Ian Rogers84fa0742011-10-25 18:13:30 -0700190static const RegType& SelectNonConstant(const RegType& a, const RegType& b) {
191 return a.IsConstant() ? b : a;
192}
jeffhaobdb76512011-09-07 11:43:16 -0700193
Ian Rogersd81871c2011-10-03 13:57:23 -0700194const RegType& RegType::Merge(const RegType& incoming_type, RegTypeCache* reg_types) const {
195 DCHECK(!Equals(incoming_type)); // Trivial equality handled by caller
Ian Rogers84fa0742011-10-25 18:13:30 -0700196 if (IsUnknown() && incoming_type.IsUnknown()) {
197 return *this; // Unknown MERGE Unknown => Unknown
198 } else if (IsConflict()) {
199 return *this; // Conflict MERGE * => Conflict
200 } else if (incoming_type.IsConflict()) {
201 return incoming_type; // * MERGE Conflict => Conflict
202 } else if (IsUnknown() || incoming_type.IsUnknown()) {
203 return reg_types->Conflict(); // Unknown MERGE * => Conflict
204 } else if(IsConstant() && incoming_type.IsConstant()) {
205 int32_t val1 = ConstantValue();
206 int32_t val2 = incoming_type.ConstantValue();
207 if (val1 >= 0 && val2 >= 0) {
208 // +ve1 MERGE +ve2 => MAX(+ve1, +ve2)
209 if (val1 >= val2) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700210 return *this;
Ian Rogers84fa0742011-10-25 18:13:30 -0700211 } else {
212 return incoming_type;
213 }
214 } else if (val1 < 0 && val2 < 0) {
215 // -ve1 MERGE -ve2 => MIN(-ve1, -ve2)
216 if (val1 <= val2) {
217 return *this;
218 } else {
219 return incoming_type;
220 }
221 } else {
222 // Values are +ve and -ve, choose smallest signed type in which they both fit
223 if (IsConstantByte()) {
224 if (incoming_type.IsConstantByte()) {
225 return reg_types->ByteConstant();
226 } else if (incoming_type.IsConstantShort()) {
227 return reg_types->ShortConstant();
228 } else {
229 return reg_types->IntConstant();
230 }
231 } else if (IsConstantShort()) {
Ian Rogers1592bc72011-10-27 20:08:53 -0700232 if (incoming_type.IsConstantShort()) {
Ian Rogers84fa0742011-10-25 18:13:30 -0700233 return reg_types->ShortConstant();
234 } else {
235 return reg_types->IntConstant();
236 }
237 } else {
238 return reg_types->IntConstant();
239 }
240 }
241 } else if (IsIntegralTypes() && incoming_type.IsIntegralTypes()) {
242 if (IsBooleanTypes() && incoming_type.IsBooleanTypes()) {
243 return reg_types->Boolean(); // boolean MERGE boolean => boolean
244 }
245 if (IsByteTypes() && incoming_type.IsByteTypes()) {
246 return reg_types->Byte(); // byte MERGE byte => byte
247 }
248 if (IsShortTypes() && incoming_type.IsShortTypes()) {
249 return reg_types->Short(); // short MERGE short => short
250 }
251 if (IsCharTypes() && incoming_type.IsCharTypes()) {
252 return reg_types->Char(); // char MERGE char => char
253 }
254 return reg_types->Integer(); // int MERGE * => int
255 } else if ((IsFloatTypes() && incoming_type.IsFloatTypes()) ||
256 (IsLongTypes() && incoming_type.IsLongTypes()) ||
257 (IsLongHighTypes() && incoming_type.IsLongHighTypes()) ||
258 (IsDoubleTypes() && incoming_type.IsDoubleTypes()) ||
259 (IsDoubleHighTypes() && incoming_type.IsDoubleHighTypes())) {
260 // check constant case was handled prior to entry
261 DCHECK(!IsConstant() || !incoming_type.IsConstant());
262 // float/long/double MERGE float/long/double_constant => float/long/double
263 return SelectNonConstant(*this, incoming_type);
264 } else if (IsReferenceTypes() && incoming_type.IsReferenceTypes()) {
Ian Rogers9074b992011-10-26 17:41:55 -0700265 if (IsZero() || incoming_type.IsZero()) {
Ian Rogers84fa0742011-10-25 18:13:30 -0700266 return SelectNonConstant(*this, incoming_type); // 0 MERGE ref => ref
Ian Rogers9074b992011-10-26 17:41:55 -0700267 } else if (IsJavaLangObject() || incoming_type.IsJavaLangObject()) {
268 return reg_types->JavaLangObject(); // Object MERGE ref => Object
269 } else if (IsUninitializedTypes() || incoming_type.IsUninitializedTypes() ||
270 IsUnresolvedTypes() || incoming_type.IsUnresolvedTypes()) {
271 // Can only merge an unresolved or uninitialized type with itself, 0 or Object, we've already
272 // checked these so => Conflict
Ian Rogers84fa0742011-10-25 18:13:30 -0700273 return reg_types->Conflict();
274 } else { // Two reference types, compute Join
275 Class* c1 = GetClass();
276 Class* c2 = incoming_type.GetClass();
277 DCHECK(c1 != NULL && !c1->IsPrimitive());
278 DCHECK(c2 != NULL && !c2->IsPrimitive());
279 Class* join_class = ClassJoin(c1, c2);
280 if (c1 == join_class) {
281 return *this;
282 } else if (c2 == join_class) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700283 return incoming_type;
284 } else {
Ian Rogers84fa0742011-10-25 18:13:30 -0700285 return reg_types->FromClass(join_class);
Ian Rogersd81871c2011-10-03 13:57:23 -0700286 }
Ian Rogersd81871c2011-10-03 13:57:23 -0700287 }
Ian Rogers84fa0742011-10-25 18:13:30 -0700288 } else {
289 return reg_types->Conflict(); // Unexpected types => Conflict
Ian Rogersd81871c2011-10-03 13:57:23 -0700290 }
291}
292
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700293static RegType::Type RegTypeFromPrimitiveType(Primitive::Type prim_type) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700294 switch (prim_type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700295 case Primitive::kPrimBoolean: return RegType::kRegTypeBoolean;
296 case Primitive::kPrimByte: return RegType::kRegTypeByte;
297 case Primitive::kPrimShort: return RegType::kRegTypeShort;
298 case Primitive::kPrimChar: return RegType::kRegTypeChar;
299 case Primitive::kPrimInt: return RegType::kRegTypeInteger;
300 case Primitive::kPrimLong: return RegType::kRegTypeLongLo;
301 case Primitive::kPrimFloat: return RegType::kRegTypeFloat;
302 case Primitive::kPrimDouble: return RegType::kRegTypeDoubleLo;
303 case Primitive::kPrimVoid:
304 default: return RegType::kRegTypeUnknown;
Ian Rogersd81871c2011-10-03 13:57:23 -0700305 }
306}
307
308static RegType::Type RegTypeFromDescriptor(const std::string& descriptor) {
309 if (descriptor.length() == 1) {
310 switch (descriptor[0]) {
311 case 'Z': return RegType::kRegTypeBoolean;
312 case 'B': return RegType::kRegTypeByte;
313 case 'S': return RegType::kRegTypeShort;
314 case 'C': return RegType::kRegTypeChar;
315 case 'I': return RegType::kRegTypeInteger;
316 case 'J': return RegType::kRegTypeLongLo;
317 case 'F': return RegType::kRegTypeFloat;
318 case 'D': return RegType::kRegTypeDoubleLo;
319 case 'V':
320 default: return RegType::kRegTypeUnknown;
321 }
322 } else if(descriptor[0] == 'L' || descriptor[0] == '[') {
323 return RegType::kRegTypeReference;
324 } else {
325 return RegType::kRegTypeUnknown;
326 }
327}
328
329std::ostream& operator<<(std::ostream& os, const RegType& rhs) {
Ian Rogers2c8a8572011-10-24 17:11:36 -0700330 os << rhs.Dump();
Ian Rogersd81871c2011-10-03 13:57:23 -0700331 return os;
332}
333
334const RegType& RegTypeCache::FromDescriptor(const ClassLoader* loader,
335 const std::string& descriptor) {
336 return From(RegTypeFromDescriptor(descriptor), loader, descriptor);
337}
338
339const RegType& RegTypeCache::From(RegType::Type type, const ClassLoader* loader,
340 const std::string& descriptor) {
Ian Rogers84fa0742011-10-25 18:13:30 -0700341 if (type <= RegType::kRegTypeLastFixedLocation) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700342 // entries should be sized greater than primitive types
343 DCHECK_GT(entries_.size(), static_cast<size_t>(type));
344 RegType* entry = entries_[type];
345 if (entry == NULL) {
Ian Rogers84fa0742011-10-25 18:13:30 -0700346 Class* klass = NULL;
Ian Rogersd81871c2011-10-03 13:57:23 -0700347 if (descriptor.size() != 0) {
348 klass = Runtime::Current()->GetClassLinker()->FindSystemClass(descriptor);
349 }
Ian Rogers84fa0742011-10-25 18:13:30 -0700350 entry = new RegType(type, klass, 0, type);
Ian Rogersd81871c2011-10-03 13:57:23 -0700351 entries_[type] = entry;
352 }
353 return *entry;
354 } else {
355 DCHECK (type == RegType::kRegTypeReference);
Ian Rogers84fa0742011-10-25 18:13:30 -0700356 for (size_t i = RegType::kRegTypeLastFixedLocation + 1; i < entries_.size(); i++) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700357 RegType* cur_entry = entries_[i];
Ian Rogers84fa0742011-10-25 18:13:30 -0700358 // check resolved and unresolved references, ignore uninitialized references
359 if (cur_entry->IsReference() && cur_entry->GetClass()->GetDescriptor()->Equals(descriptor)) {
360 return *cur_entry;
361 } else if (cur_entry->IsUnresolvedReference() &&
362 cur_entry->GetDescriptor()->Equals(descriptor)) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700363 return *cur_entry;
364 }
365 }
366 Class* klass = Runtime::Current()->GetClassLinker()->FindClass(descriptor, loader);
Ian Rogers2c8a8572011-10-24 17:11:36 -0700367 if (klass != NULL) {
Ian Rogers84fa0742011-10-25 18:13:30 -0700368 // Able to resolve so create resolved register type
369 RegType* entry = new RegType(type, klass, 0, entries_.size());
Ian Rogers2c8a8572011-10-24 17:11:36 -0700370 entries_.push_back(entry);
371 return *entry;
372 } else {
Ian Rogers28ad40d2011-10-27 15:19:26 -0700373 // TODO: we assume unresolved, but we may be able to do better by validating whether the
374 // descriptor string is valid
Ian Rogers84fa0742011-10-25 18:13:30 -0700375 // Unable to resolve so create unresolved register type
Ian Rogers2c8a8572011-10-24 17:11:36 -0700376 DCHECK(Thread::Current()->IsExceptionPending());
Ian Rogers84fa0742011-10-25 18:13:30 -0700377 Thread::Current()->ClearException();
Ian Rogers28ad40d2011-10-27 15:19:26 -0700378 if (IsValidDescriptor(descriptor.c_str())) {
379 String* string_descriptor =
380 Runtime::Current()->GetInternTable()->InternStrong(descriptor.c_str());
381 RegType* entry = new RegType(RegType::kRegTypeUnresolvedReference, string_descriptor, 0,
382 entries_.size());
383 entries_.push_back(entry);
384 return *entry;
385 } else {
386 // The descriptor is broken return the unknown type as there's nothing sensible that
387 // could be done at runtime
388 return Unknown();
389 }
Ian Rogers2c8a8572011-10-24 17:11:36 -0700390 }
Ian Rogersd81871c2011-10-03 13:57:23 -0700391 }
392}
393
394const RegType& RegTypeCache::FromClass(Class* klass) {
395 if (klass->IsPrimitive()) {
396 RegType::Type type = RegTypeFromPrimitiveType(klass->GetPrimitiveType());
397 // entries should be sized greater than primitive types
398 DCHECK_GT(entries_.size(), static_cast<size_t>(type));
399 RegType* entry = entries_[type];
400 if (entry == NULL) {
Ian Rogers84fa0742011-10-25 18:13:30 -0700401 entry = new RegType(type, klass, 0, type);
Ian Rogersd81871c2011-10-03 13:57:23 -0700402 entries_[type] = entry;
403 }
404 return *entry;
405 } else {
Ian Rogers84fa0742011-10-25 18:13:30 -0700406 for (size_t i = RegType::kRegTypeLastFixedLocation + 1; i < entries_.size(); i++) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700407 RegType* cur_entry = entries_[i];
Ian Rogers84fa0742011-10-25 18:13:30 -0700408 if (cur_entry->IsReference() && cur_entry->GetClass() == klass) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700409 return *cur_entry;
410 }
411 }
Ian Rogers84fa0742011-10-25 18:13:30 -0700412 RegType* entry = new RegType(RegType::kRegTypeReference, klass, 0, entries_.size());
Ian Rogersd81871c2011-10-03 13:57:23 -0700413 entries_.push_back(entry);
414 return *entry;
415 }
416}
417
Ian Rogers28ad40d2011-10-27 15:19:26 -0700418const RegType& RegTypeCache::Uninitialized(const RegType& type, uint32_t allocation_pc) {
419 RegType* entry;
420 if (type.IsUnresolvedTypes()) {
421 String* descriptor = type.GetDescriptor();
422 for (size_t i = RegType::kRegTypeLastFixedLocation + 1; i < entries_.size(); i++) {
423 RegType* cur_entry = entries_[i];
424 if (cur_entry->IsUnresolvedAndUninitializedReference() &&
425 cur_entry->GetAllocationPc() == allocation_pc &&
426 cur_entry->GetDescriptor() == descriptor) {
427 return *cur_entry;
428 }
Ian Rogersd81871c2011-10-03 13:57:23 -0700429 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700430 entry = new RegType(RegType::kRegTypeUnresolvedAndUninitializedReference,
431 descriptor, allocation_pc, entries_.size());
432 } else {
433 Class* klass = type.GetClass();
434 for (size_t i = RegType::kRegTypeLastFixedLocation + 1; i < entries_.size(); i++) {
435 RegType* cur_entry = entries_[i];
436 if (cur_entry->IsUninitializedReference() &&
437 cur_entry->GetAllocationPc() == allocation_pc &&
438 cur_entry->GetClass() == klass) {
439 return *cur_entry;
440 }
441 }
442 entry = new RegType(RegType::kRegTypeUninitializedReference,
443 klass, allocation_pc, entries_.size());
Ian Rogersd81871c2011-10-03 13:57:23 -0700444 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700445 entries_.push_back(entry);
446 return *entry;
447}
448
449const RegType& RegTypeCache::FromUninitialized(const RegType& uninit_type) {
450 RegType* entry;
451 if (uninit_type.IsUnresolvedTypes()) {
452 String* descriptor = uninit_type.GetDescriptor();
453 for (size_t i = RegType::kRegTypeLastFixedLocation + 1; i < entries_.size(); i++) {
454 RegType* cur_entry = entries_[i];
455 if (cur_entry->IsUnresolvedReference() && cur_entry->GetDescriptor() == descriptor) {
456 return *cur_entry;
457 }
458 }
459 entry = new RegType(RegType::kRegTypeUnresolvedReference, descriptor, 0, entries_.size());
460 } else {
461 Class* klass = uninit_type.GetClass();
462 for (size_t i = RegType::kRegTypeLastFixedLocation + 1; i < entries_.size(); i++) {
463 RegType* cur_entry = entries_[i];
464 if (cur_entry->IsReference() && cur_entry->GetClass() == klass) {
465 return *cur_entry;
466 }
467 }
468 entry = new RegType(RegType::kRegTypeReference, klass, 0, entries_.size());
469 }
Ian Rogersd81871c2011-10-03 13:57:23 -0700470 entries_.push_back(entry);
471 return *entry;
472}
473
474const RegType& RegTypeCache::UninitializedThisArgument(Class* klass) {
Ian Rogers84fa0742011-10-25 18:13:30 -0700475 for (size_t i = RegType::kRegTypeLastFixedLocation + 1; i < entries_.size(); i++) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700476 RegType* cur_entry = entries_[i];
477 if (cur_entry->IsUninitializedThisReference() && cur_entry->GetClass() == klass) {
478 return *cur_entry;
479 }
480 }
Ian Rogers84fa0742011-10-25 18:13:30 -0700481 RegType* entry = new RegType(RegType::kRegTypeUninitializedThisReference, klass, 0,
Ian Rogersd81871c2011-10-03 13:57:23 -0700482 entries_.size());
483 entries_.push_back(entry);
484 return *entry;
485}
486
487const RegType& RegTypeCache::FromType(RegType::Type type) {
488 CHECK(type < RegType::kRegTypeReference);
489 switch (type) {
490 case RegType::kRegTypeBoolean: return From(type, NULL, "Z");
491 case RegType::kRegTypeByte: return From(type, NULL, "B");
492 case RegType::kRegTypeShort: return From(type, NULL, "S");
493 case RegType::kRegTypeChar: return From(type, NULL, "C");
494 case RegType::kRegTypeInteger: return From(type, NULL, "I");
495 case RegType::kRegTypeFloat: return From(type, NULL, "F");
496 case RegType::kRegTypeLongLo:
497 case RegType::kRegTypeLongHi: return From(type, NULL, "J");
498 case RegType::kRegTypeDoubleLo:
499 case RegType::kRegTypeDoubleHi: return From(type, NULL, "D");
500 default: return From(type, NULL, "");
501 }
502}
503
504const RegType& RegTypeCache::FromCat1Const(int32_t value) {
Ian Rogers84fa0742011-10-25 18:13:30 -0700505 for (size_t i = RegType::kRegTypeLastFixedLocation + 1; i < entries_.size(); i++) {
506 RegType* cur_entry = entries_[i];
507 if (cur_entry->IsConstant() && cur_entry->ConstantValue() == value) {
508 return *cur_entry;
509 }
Ian Rogersd81871c2011-10-03 13:57:23 -0700510 }
Ian Rogers84fa0742011-10-25 18:13:30 -0700511 RegType* entry = new RegType(RegType::kRegTypeConst, NULL, value, entries_.size());
512 entries_.push_back(entry);
513 return *entry;
Ian Rogersd81871c2011-10-03 13:57:23 -0700514}
515
Ian Rogers28ad40d2011-10-27 15:19:26 -0700516const RegType& RegTypeCache::GetComponentType(const RegType& array, const ClassLoader* loader) {
517 CHECK(array.IsArrayClass());
518 if (array.IsUnresolvedTypes()) {
519 std::string descriptor = array.GetDescriptor()->ToModifiedUtf8();
520 std::string component = descriptor.substr(1, descriptor.size() - 1);
521 return FromDescriptor(loader, component);
522 } else {
523 return FromClass(array.GetClass()->GetComponentType());
524 }
525}
526
527
Ian Rogersd81871c2011-10-03 13:57:23 -0700528bool RegisterLine::CheckConstructorReturn() const {
529 for (size_t i = 0; i < num_regs_; i++) {
530 if (GetRegisterType(i).IsUninitializedThisReference()) {
531 verifier_->Fail(VERIFY_ERROR_GENERIC)
532 << "Constructor returning without calling superclass constructor";
533 return false;
534 }
535 }
536 return true;
537}
538
539void RegisterLine::SetRegisterType(uint32_t vdst, const RegType& new_type) {
540 DCHECK(vdst < num_regs_);
541 if (new_type.IsLowHalf()) {
542 line_[vdst] = new_type.GetId();
543 line_[vdst + 1] = new_type.HighHalf(verifier_->GetRegTypeCache()).GetId();
544 } else if (new_type.IsHighHalf()) {
545 /* should never set these explicitly */
546 verifier_->Fail(VERIFY_ERROR_GENERIC) << "Explicit set of high register type";
547 } else if (new_type.IsConflict()) { // should only be set during a merge
548 verifier_->Fail(VERIFY_ERROR_GENERIC) << "Set register to unknown type " << new_type;
549 } else {
550 line_[vdst] = new_type.GetId();
551 }
552 // Clear the monitor entry bits for this register.
553 ClearAllRegToLockDepths(vdst);
554}
555
556void RegisterLine::SetResultTypeToUnknown() {
557 uint16_t unknown_id = verifier_->GetRegTypeCache()->Unknown().GetId();
558 result_[0] = unknown_id;
559 result_[1] = unknown_id;
560}
561
562void RegisterLine::SetResultRegisterType(const RegType& new_type) {
563 result_[0] = new_type.GetId();
564 if(new_type.IsLowHalf()) {
565 DCHECK_EQ(new_type.HighHalf(verifier_->GetRegTypeCache()).GetId(), new_type.GetId() + 1);
566 result_[1] = new_type.GetId() + 1;
567 } else {
568 result_[1] = verifier_->GetRegTypeCache()->Unknown().GetId();
569 }
570}
571
572const RegType& RegisterLine::GetRegisterType(uint32_t vsrc) const {
573 // The register index was validated during the static pass, so we don't need to check it here.
574 DCHECK_LT(vsrc, num_regs_);
575 return verifier_->GetRegTypeCache()->GetFromId(line_[vsrc]);
576}
577
578const RegType& RegisterLine::GetInvocationThis(const Instruction::DecodedInstruction& dec_insn) {
579 if (dec_insn.vA_ < 1) {
580 verifier_->Fail(VERIFY_ERROR_GENERIC) << "invoke lacks 'this'";
581 return verifier_->GetRegTypeCache()->Unknown();
582 }
583 /* get the element type of the array held in vsrc */
584 const RegType& this_type = GetRegisterType(dec_insn.vC_);
585 if (!this_type.IsReferenceTypes()) {
586 verifier_->Fail(VERIFY_ERROR_GENERIC) << "tried to get class from non-reference register v"
587 << dec_insn.vC_ << " (type=" << this_type << ")";
588 return verifier_->GetRegTypeCache()->Unknown();
589 }
590 return this_type;
591}
592
593Class* RegisterLine::GetClassFromRegister(uint32_t vsrc) const {
594 /* get the element type of the array held in vsrc */
595 const RegType& type = GetRegisterType(vsrc);
596 /* if "always zero", we allow it to fail at runtime */
597 if (type.IsZero()) {
598 return NULL;
599 } else if (!type.IsReferenceTypes()) {
600 verifier_->Fail(VERIFY_ERROR_GENERIC) << "tried to get class from non-ref register v" << vsrc
601 << " (type=" << type << ")";
602 return NULL;
603 } else if (type.IsUninitializedReference()) {
604 verifier_->Fail(VERIFY_ERROR_GENERIC) << "register " << vsrc << " holds uninitialized reference";
605 return NULL;
606 } else {
607 return type.GetClass();
608 }
609}
610
611bool RegisterLine::VerifyRegisterType(uint32_t vsrc, const RegType& check_type) {
612 // Verify the src register type against the check type refining the type of the register
613 const RegType& src_type = GetRegisterType(vsrc);
Ian Rogersb5e95b92011-10-25 23:28:55 -0700614 if (!check_type.IsAssignableFrom(src_type)) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700615 verifier_->Fail(VERIFY_ERROR_GENERIC) << "register v" << vsrc << " has type " << src_type
616 << " but expected " << check_type;
617 return false;
618 }
619 // The register at vsrc has a defined type, we know the lower-upper-bound, but this is less
620 // precise than the subtype in vsrc so leave it for reference types. For primitive types
621 // if they are a defined type then they are as precise as we can get, however, for constant
622 // types we may wish to refine them. Unfortunately constant propagation has rendered this useless.
623 return true;
624}
625
626void RegisterLine::MarkRefsAsInitialized(const RegType& uninit_type) {
Ian Rogers28ad40d2011-10-27 15:19:26 -0700627 DCHECK(uninit_type.IsUninitializedTypes());
628 const RegType& init_type = verifier_->GetRegTypeCache()->FromUninitialized(uninit_type);
629 size_t changed = 0;
630 for (size_t i = 0; i < num_regs_; i++) {
631 if (GetRegisterType(i).Equals(uninit_type)) {
632 line_[i] = init_type.GetId();
633 changed++;
Ian Rogersd81871c2011-10-03 13:57:23 -0700634 }
Ian Rogersd81871c2011-10-03 13:57:23 -0700635 }
Ian Rogers28ad40d2011-10-27 15:19:26 -0700636 DCHECK_GT(changed, 0u);
Ian Rogersd81871c2011-10-03 13:57:23 -0700637}
638
639void RegisterLine::MarkUninitRefsAsInvalid(const RegType& uninit_type) {
640 for (size_t i = 0; i < num_regs_; i++) {
641 if (GetRegisterType(i).Equals(uninit_type)) {
642 line_[i] = verifier_->GetRegTypeCache()->Conflict().GetId();
643 ClearAllRegToLockDepths(i);
644 }
645 }
646}
647
648void RegisterLine::CopyRegister1(uint32_t vdst, uint32_t vsrc, TypeCategory cat) {
649 DCHECK(cat == kTypeCategory1nr || cat == kTypeCategoryRef);
650 const RegType& type = GetRegisterType(vsrc);
651 SetRegisterType(vdst, type);
652 if ((cat == kTypeCategory1nr && !type.IsCategory1Types()) ||
653 (cat == kTypeCategoryRef && !type.IsReferenceTypes())) {
654 verifier_->Fail(VERIFY_ERROR_GENERIC) << "copy1 v" << vdst << "<-v" << vsrc << " type=" << type
655 << " cat=" << static_cast<int>(cat);
656 } else if (cat == kTypeCategoryRef) {
657 CopyRegToLockDepth(vdst, vsrc);
658 }
659}
660
661void RegisterLine::CopyRegister2(uint32_t vdst, uint32_t vsrc) {
662 const RegType& type_l = GetRegisterType(vsrc);
663 const RegType& type_h = GetRegisterType(vsrc + 1);
664
665 if (!type_l.CheckWidePair(type_h)) {
666 verifier_->Fail(VERIFY_ERROR_GENERIC) << "copy2 v" << vdst << "<-v" << vsrc
667 << " type=" << type_l << "/" << type_h;
668 } else {
669 SetRegisterType(vdst, type_l); // implicitly sets the second half
670 }
671}
672
673void RegisterLine::CopyResultRegister1(uint32_t vdst, bool is_reference) {
674 const RegType& type = verifier_->GetRegTypeCache()->GetFromId(result_[0]);
675 if ((!is_reference && !type.IsCategory1Types()) ||
676 (is_reference && !type.IsReferenceTypes())) {
677 verifier_->Fail(VERIFY_ERROR_GENERIC)
678 << "copyRes1 v" << vdst << "<- result0" << " type=" << type;
679 } else {
680 DCHECK(verifier_->GetRegTypeCache()->GetFromId(result_[1]).IsUnknown());
681 SetRegisterType(vdst, type);
682 result_[0] = verifier_->GetRegTypeCache()->Unknown().GetId();
683 }
684}
685
686/*
687 * Implement "move-result-wide". Copy the category-2 value from the result
688 * register to another register, and reset the result register.
689 */
690void RegisterLine::CopyResultRegister2(uint32_t vdst) {
691 const RegType& type_l = verifier_->GetRegTypeCache()->GetFromId(result_[0]);
692 const RegType& type_h = verifier_->GetRegTypeCache()->GetFromId(result_[1]);
693 if (!type_l.IsCategory2Types()) {
694 verifier_->Fail(VERIFY_ERROR_GENERIC)
695 << "copyRes2 v" << vdst << "<- result0" << " type=" << type_l;
696 } else {
697 DCHECK(type_l.CheckWidePair(type_h)); // Set should never allow this case
698 SetRegisterType(vdst, type_l); // also sets the high
699 result_[0] = verifier_->GetRegTypeCache()->Unknown().GetId();
700 result_[1] = verifier_->GetRegTypeCache()->Unknown().GetId();
701 }
702}
703
704void RegisterLine::CheckUnaryOp(const Instruction::DecodedInstruction& dec_insn,
705 const RegType& dst_type, const RegType& src_type) {
706 if (VerifyRegisterType(dec_insn.vB_, src_type)) {
707 SetRegisterType(dec_insn.vA_, dst_type);
708 }
709}
710
711void RegisterLine::CheckBinaryOp(const Instruction::DecodedInstruction& dec_insn,
712 const RegType& dst_type,
713 const RegType& src_type1, const RegType& src_type2,
714 bool check_boolean_op) {
715 if (VerifyRegisterType(dec_insn.vB_, src_type1) &&
716 VerifyRegisterType(dec_insn.vC_, src_type2)) {
717 if (check_boolean_op) {
718 DCHECK(dst_type.IsInteger());
719 if (GetRegisterType(dec_insn.vB_).IsBooleanTypes() &&
720 GetRegisterType(dec_insn.vC_).IsBooleanTypes()) {
721 SetRegisterType(dec_insn.vA_, verifier_->GetRegTypeCache()->Boolean());
722 return;
723 }
724 }
725 SetRegisterType(dec_insn.vA_, dst_type);
726 }
727}
728
729void RegisterLine::CheckBinaryOp2addr(const Instruction::DecodedInstruction& dec_insn,
730 const RegType& dst_type, const RegType& src_type1,
731 const RegType& src_type2, bool check_boolean_op) {
732 if (VerifyRegisterType(dec_insn.vA_, src_type1) &&
733 VerifyRegisterType(dec_insn.vB_, src_type2)) {
734 if (check_boolean_op) {
735 DCHECK(dst_type.IsInteger());
736 if (GetRegisterType(dec_insn.vA_).IsBooleanTypes() &&
737 GetRegisterType(dec_insn.vB_).IsBooleanTypes()) {
738 SetRegisterType(dec_insn.vA_, verifier_->GetRegTypeCache()->Boolean());
739 return;
740 }
741 }
742 SetRegisterType(dec_insn.vA_, dst_type);
743 }
744}
745
746void RegisterLine::CheckLiteralOp(const Instruction::DecodedInstruction& dec_insn,
747 const RegType& dst_type, const RegType& src_type,
748 bool check_boolean_op) {
749 if (VerifyRegisterType(dec_insn.vB_, src_type)) {
750 if (check_boolean_op) {
751 DCHECK(dst_type.IsInteger());
752 /* check vB with the call, then check the constant manually */
753 if (GetRegisterType(dec_insn.vB_).IsBooleanTypes() &&
754 (dec_insn.vC_ == 0 || dec_insn.vC_ == 1)) {
755 SetRegisterType(dec_insn.vA_, verifier_->GetRegTypeCache()->Boolean());
756 return;
757 }
758 }
759 SetRegisterType(dec_insn.vA_, dst_type);
760 }
761}
762
763void RegisterLine::PushMonitor(uint32_t reg_idx, int32_t insn_idx) {
764 const RegType& reg_type = GetRegisterType(reg_idx);
765 if (!reg_type.IsReferenceTypes()) {
766 verifier_->Fail(VERIFY_ERROR_GENERIC) << "monitor-enter on non-object (" << reg_type << ")";
767 } else {
768 SetRegToLockDepth(reg_idx, monitors_.size());
769 monitors_.push(insn_idx);
770 }
771}
772
773void RegisterLine::PopMonitor(uint32_t reg_idx) {
774 const RegType& reg_type = GetRegisterType(reg_idx);
775 if (!reg_type.IsReferenceTypes()) {
776 verifier_->Fail(VERIFY_ERROR_GENERIC) << "monitor-exit on non-object (" << reg_type << ")";
777 } else if (monitors_.empty()) {
778 verifier_->Fail(VERIFY_ERROR_GENERIC) << "monitor-exit stack underflow";
779 } else {
780 monitors_.pop();
781 if(!IsSetLockDepth(reg_idx, monitors_.size())) {
782 // Bug 3215458: Locks and unlocks are on objects, if that object is a literal then before
783 // format "036" the constant collector may create unlocks on the same object but referenced
784 // via different registers.
785 ((verifier_->DexFileVersion() >= 36) ? verifier_->Fail(VERIFY_ERROR_GENERIC)
786 : verifier_->LogVerifyInfo())
787 << "monitor-exit not unlocking the top of the monitor stack";
788 } else {
789 // Record the register was unlocked
790 ClearRegToLockDepth(reg_idx, monitors_.size());
791 }
792 }
793}
794
795bool RegisterLine::VerifyMonitorStackEmpty() {
796 if (MonitorStackDepth() != 0) {
797 verifier_->Fail(VERIFY_ERROR_GENERIC) << "expected empty monitor stack";
798 return false;
799 } else {
800 return true;
801 }
802}
803
804bool RegisterLine::MergeRegisters(const RegisterLine* incoming_line) {
805 bool changed = false;
806 for (size_t idx = 0; idx < num_regs_; idx++) {
807 if (line_[idx] != incoming_line->line_[idx]) {
808 const RegType& incoming_reg_type = incoming_line->GetRegisterType(idx);
809 const RegType& cur_type = GetRegisterType(idx);
810 const RegType& new_type = cur_type.Merge(incoming_reg_type, verifier_->GetRegTypeCache());
811 changed = changed || !cur_type.Equals(new_type);
812 line_[idx] = new_type.GetId();
813 }
814 }
815 if(monitors_ != incoming_line->monitors_) {
816 verifier_->Fail(VERIFY_ERROR_GENERIC) << "mismatched stack depths (depth="
817 << MonitorStackDepth() << ", incoming depth=" << incoming_line->MonitorStackDepth() << ")";
818 } else if (reg_to_lock_depths_ != incoming_line->reg_to_lock_depths_) {
819 for (uint32_t idx = 0; idx < num_regs_; idx++) {
820 size_t depths = reg_to_lock_depths_.count(idx);
821 size_t incoming_depths = incoming_line->reg_to_lock_depths_.count(idx);
822 if (depths != incoming_depths) {
823 if (depths == 0 || incoming_depths == 0) {
824 reg_to_lock_depths_.erase(idx);
825 } else {
826 verifier_->Fail(VERIFY_ERROR_GENERIC) << "mismatched stack depths for register v" << idx
827 << ": " << depths << " != " << incoming_depths;
828 break;
829 }
830 }
831 }
832 }
833 return changed;
834}
835
836void RegisterLine::WriteReferenceBitMap(int8_t* data, size_t max_bytes) {
837 for (size_t i = 0; i < num_regs_; i += 8) {
838 uint8_t val = 0;
839 for (size_t j = 0; j < 8 && (i + j) < num_regs_; j++) {
840 // Note: we write 1 for a Reference but not for Null
Ian Rogers84fa0742011-10-25 18:13:30 -0700841 if (GetRegisterType(i + j).IsNonZeroReferenceTypes()) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700842 val |= 1 << j;
843 }
844 }
845 if (val != 0) {
846 DCHECK_LT(i / 8, max_bytes);
847 data[i / 8] = val;
848 }
849 }
850}
851
852std::ostream& operator<<(std::ostream& os, const RegisterLine& rhs) {
Ian Rogers2c8a8572011-10-24 17:11:36 -0700853 os << rhs.Dump();
Ian Rogersd81871c2011-10-03 13:57:23 -0700854 return os;
855}
856
857
858void PcToRegisterLineTable::Init(RegisterTrackingMode mode, InsnFlags* flags,
859 uint32_t insns_size, uint16_t registers_size,
860 DexVerifier* verifier) {
861 DCHECK_GT(insns_size, 0U);
862
863 for (uint32_t i = 0; i < insns_size; i++) {
864 bool interesting = false;
865 switch (mode) {
866 case kTrackRegsAll:
867 interesting = flags[i].IsOpcode();
868 break;
869 case kTrackRegsGcPoints:
870 interesting = flags[i].IsGcPoint() || flags[i].IsBranchTarget();
871 break;
872 case kTrackRegsBranches:
873 interesting = flags[i].IsBranchTarget();
874 break;
875 default:
876 break;
877 }
878 if (interesting) {
879 pc_to_register_line_[i] = new RegisterLine(registers_size, verifier);
880 }
881 }
882}
883
884bool DexVerifier::VerifyClass(const Class* klass) {
jeffhaobdb76512011-09-07 11:43:16 -0700885 if (klass->IsVerified()) {
886 return true;
887 }
Ian Rogersd81871c2011-10-03 13:57:23 -0700888 Class* super = klass->GetSuperClass();
889 if (super == NULL && !klass->GetDescriptor()->Equals("Ljava/lang/Object;")) {
890 LOG(ERROR) << "Verifier rejected class " << PrettyClass(klass) << " that has no super class";
891 return false;
892 }
893 if (super != NULL) {
894 if (!super->IsVerified() && !super->IsErroneous()) {
895 Runtime::Current()->GetClassLinker()->VerifyClass(super);
896 }
897 if (!super->IsVerified()) {
898 LOG(ERROR) << "Verifier rejected class " << PrettyClass(klass)
899 << " that attempts to sub-class corrupt class " << PrettyClass(super);
900 return false;
901 } else if (super->IsFinal()) {
902 LOG(ERROR) << "Verifier rejected class " << PrettyClass(klass)
903 << " that attempts to sub-class final class " << PrettyClass(super);
904 return false;
905 }
906 }
jeffhaobdb76512011-09-07 11:43:16 -0700907 for (size_t i = 0; i < klass->NumDirectMethods(); ++i) {
908 Method* method = klass->GetDirectMethod(i);
909 if (!VerifyMethod(method)) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700910 LOG(ERROR) << "Verifier rejected class " << PrettyClass(klass) << " due to bad method "
911 << PrettyMethod(method, true);
jeffhaobdb76512011-09-07 11:43:16 -0700912 return false;
913 }
914 }
915 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
916 Method* method = klass->GetVirtualMethod(i);
917 if (!VerifyMethod(method)) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700918 LOG(ERROR) << "Verifier rejected class " << PrettyClass(klass) << " due to bad method "
919 << PrettyMethod(method, true);
jeffhaobdb76512011-09-07 11:43:16 -0700920 return false;
921 }
922 }
923 return true;
jeffhaoba5ebb92011-08-25 17:24:37 -0700924}
925
jeffhaobdb76512011-09-07 11:43:16 -0700926bool DexVerifier::VerifyMethod(Method* method) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700927 DexVerifier verifier(method);
928 bool success = verifier.Verify();
929 // We expect either success and no verification error, or failure and a generic failure to
930 // reject the class.
931 if (success) {
932 if (verifier.failure_ != VERIFY_ERROR_NONE) {
933 LOG(FATAL) << "Unhandled failure in verification of " << PrettyMethod(method) << std::endl
934 << verifier.fail_messages_;
935 }
936 } else {
937 LOG(INFO) << "Verification error in " << PrettyMethod(method) << " "
Ian Rogers5ed29bf2011-10-26 12:22:21 -0700938 << verifier.fail_messages_.str();
Ian Rogers2c8a8572011-10-24 17:11:36 -0700939 if (gDebugVerify) {
Ian Rogers5ed29bf2011-10-26 12:22:21 -0700940 std::cout << std::endl << verifier.info_messages_.str();
Ian Rogers2c8a8572011-10-24 17:11:36 -0700941 verifier.Dump(std::cout);
942 }
Ian Rogersd81871c2011-10-03 13:57:23 -0700943 DCHECK_EQ(verifier.failure_, VERIFY_ERROR_GENERIC);
944 }
945 return success;
946}
947
Shih-wei Liao371814f2011-10-27 16:52:10 -0700948void DexVerifier::VerifyMethodAndDump(Method* method) {
949 DexVerifier verifier(method);
950 verifier.Verify();
951
Elliott Hughese0918552011-10-28 17:18:29 -0700952 LOG(INFO) << "Dump of method " << PrettyMethod(method) << " "
953 << verifier.fail_messages_.str() << std::endl
954 << verifier.info_messages_.str() << Dumpable<DexVerifier>(verifier);
Shih-wei Liao371814f2011-10-27 16:52:10 -0700955}
956
Ian Rogers28ad40d2011-10-27 15:19:26 -0700957DexVerifier::DexVerifier(Method* method) : work_insn_idx_(-1), method_(method),
958 failure_(VERIFY_ERROR_NONE),
959
Ian Rogersd81871c2011-10-03 13:57:23 -0700960 new_instance_count_(0), monitor_enter_count_(0) {
jeffhaobdb76512011-09-07 11:43:16 -0700961 const DexCache* dex_cache = method->GetDeclaringClass()->GetDexCache();
962 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogersd81871c2011-10-03 13:57:23 -0700963 dex_file_ = &class_linker->FindDexFile(dex_cache);
964 code_item_ = dex_file_->GetCodeItem(method->GetCodeItemOffset());
jeffhaoba5ebb92011-08-25 17:24:37 -0700965}
966
Ian Rogersd81871c2011-10-03 13:57:23 -0700967bool DexVerifier::Verify() {
968 // If there aren't any instructions, make sure that's expected, then exit successfully.
969 if (code_item_ == NULL) {
970 if (!method_->IsNative() && !method_->IsAbstract()) {
971 Fail(VERIFY_ERROR_GENERIC) << "zero-length code in concrete non-native method";
jeffhaobdb76512011-09-07 11:43:16 -0700972 return false;
Ian Rogersd81871c2011-10-03 13:57:23 -0700973 } else {
974 return true;
jeffhaobdb76512011-09-07 11:43:16 -0700975 }
jeffhaobdb76512011-09-07 11:43:16 -0700976 }
Ian Rogersd81871c2011-10-03 13:57:23 -0700977 // Sanity-check the register counts. ins + locals = registers, so make sure that ins <= registers.
978 if (code_item_->ins_size_ > code_item_->registers_size_) {
979 Fail(VERIFY_ERROR_GENERIC) << "bad register counts (ins=" << code_item_->ins_size_
980 << " regs=" << code_item_->registers_size_;
981 return false;
jeffhaobdb76512011-09-07 11:43:16 -0700982 }
Ian Rogersd81871c2011-10-03 13:57:23 -0700983 // Allocate and initialize an array to hold instruction data.
984 insn_flags_.reset(new InsnFlags[code_item_->insns_size_in_code_units_]());
985 // Run through the instructions and see if the width checks out.
986 bool result = ComputeWidthsAndCountOps();
987 // Flag instructions guarded by a "try" block and check exception handlers.
988 result = result && ScanTryCatchBlocks();
989 // Perform static instruction verification.
990 result = result && VerifyInstructions();
991 // Perform code flow analysis.
992 result = result && VerifyCodeFlow();
jeffhaobdb76512011-09-07 11:43:16 -0700993 return result;
jeffhaoba5ebb92011-08-25 17:24:37 -0700994}
995
Ian Rogersd81871c2011-10-03 13:57:23 -0700996bool DexVerifier::ComputeWidthsAndCountOps() {
997 const uint16_t* insns = code_item_->insns_;
998 size_t insns_size = code_item_->insns_size_in_code_units_;
999 const Instruction* inst = Instruction::At(insns);
jeffhaobdb76512011-09-07 11:43:16 -07001000 size_t new_instance_count = 0;
1001 size_t monitor_enter_count = 0;
Ian Rogersd81871c2011-10-03 13:57:23 -07001002 size_t dex_pc = 0;
jeffhaobdb76512011-09-07 11:43:16 -07001003
Ian Rogersd81871c2011-10-03 13:57:23 -07001004 while (dex_pc < insns_size) {
jeffhaobdb76512011-09-07 11:43:16 -07001005 Instruction::Code opcode = inst->Opcode();
1006 if (opcode == Instruction::NEW_INSTANCE) {
1007 new_instance_count++;
1008 } else if (opcode == Instruction::MONITOR_ENTER) {
1009 monitor_enter_count++;
1010 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001011 size_t inst_size = inst->SizeInCodeUnits();
1012 insn_flags_[dex_pc].SetLengthInCodeUnits(inst_size);
1013 dex_pc += inst_size;
jeffhaobdb76512011-09-07 11:43:16 -07001014 inst = inst->Next();
1015 }
1016
Ian Rogersd81871c2011-10-03 13:57:23 -07001017 if (dex_pc != insns_size) {
1018 Fail(VERIFY_ERROR_GENERIC) << "code did not end where expected ("
1019 << dex_pc << " vs. " << insns_size << ")";
jeffhaobdb76512011-09-07 11:43:16 -07001020 return false;
1021 }
1022
Ian Rogersd81871c2011-10-03 13:57:23 -07001023 new_instance_count_ = new_instance_count;
1024 monitor_enter_count_ = monitor_enter_count;
jeffhaobdb76512011-09-07 11:43:16 -07001025 return true;
1026}
1027
Ian Rogersd81871c2011-10-03 13:57:23 -07001028bool DexVerifier::ScanTryCatchBlocks() {
1029 uint32_t tries_size = code_item_->tries_size_;
jeffhaobdb76512011-09-07 11:43:16 -07001030 if (tries_size == 0) {
1031 return true;
1032 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001033 uint32_t insns_size = code_item_->insns_size_in_code_units_;
1034 const DexFile::TryItem* tries = DexFile::dexGetTryItems(*code_item_, 0);
jeffhaobdb76512011-09-07 11:43:16 -07001035
1036 for (uint32_t idx = 0; idx < tries_size; idx++) {
1037 const DexFile::TryItem* try_item = &tries[idx];
1038 uint32_t start = try_item->start_addr_;
1039 uint32_t end = start + try_item->insn_count_;
jeffhaobdb76512011-09-07 11:43:16 -07001040 if ((start >= end) || (start >= insns_size) || (end > insns_size)) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001041 Fail(VERIFY_ERROR_GENERIC) << "bad exception entry: startAddr=" << start
1042 << " endAddr=" << end << " (size=" << insns_size << ")";
jeffhaobdb76512011-09-07 11:43:16 -07001043 return false;
1044 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001045 if (!insn_flags_[start].IsOpcode()) {
1046 Fail(VERIFY_ERROR_GENERIC) << "'try' block starts inside an instruction (" << start << ")";
jeffhaobdb76512011-09-07 11:43:16 -07001047 return false;
1048 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001049 for (uint32_t dex_pc = start; dex_pc < end;
1050 dex_pc += insn_flags_[dex_pc].GetLengthInCodeUnits()) {
1051 insn_flags_[dex_pc].SetInTry();
jeffhaobdb76512011-09-07 11:43:16 -07001052 }
1053 }
jeffhaobdb76512011-09-07 11:43:16 -07001054 /* Iterate over each of the handlers to verify target addresses. */
Ian Rogersd81871c2011-10-03 13:57:23 -07001055 const byte* handlers_ptr = DexFile::dexGetCatchHandlerData(*code_item_, 0);
jeffhaobdb76512011-09-07 11:43:16 -07001056 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Ian Rogers28ad40d2011-10-27 15:19:26 -07001057 ClassLinker* linker = Runtime::Current()->GetClassLinker();
jeffhaobdb76512011-09-07 11:43:16 -07001058 for (uint32_t idx = 0; idx < handlers_size; idx++) {
1059 DexFile::CatchHandlerIterator iterator(handlers_ptr);
jeffhaobdb76512011-09-07 11:43:16 -07001060 for (; !iterator.HasNext(); iterator.Next()) {
Ian Rogers28ad40d2011-10-27 15:19:26 -07001061 const DexFile::CatchHandlerItem& handler = iterator.Get();
1062 uint32_t dex_pc= handler.address_;
Ian Rogersd81871c2011-10-03 13:57:23 -07001063 if (!insn_flags_[dex_pc].IsOpcode()) {
1064 Fail(VERIFY_ERROR_GENERIC) << "exception handler starts at bad address (" << dex_pc << ")";
jeffhaobdb76512011-09-07 11:43:16 -07001065 return false;
1066 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001067 insn_flags_[dex_pc].SetBranchTarget();
Ian Rogers28ad40d2011-10-27 15:19:26 -07001068 // Ensure exception types are resolved so that they don't need resolution to be delivered,
1069 // unresolved exception types will be ignored by exception delivery
1070 if (handler.type_idx_ != DexFile::kDexNoIndex) {
1071 Class* exception_type = linker->ResolveType(handler.type_idx_, method_);
1072 if (exception_type == NULL) {
1073 DCHECK(Thread::Current()->IsExceptionPending());
1074 Thread::Current()->ClearException();
1075 }
1076 }
jeffhaobdb76512011-09-07 11:43:16 -07001077 }
jeffhaobdb76512011-09-07 11:43:16 -07001078 handlers_ptr = iterator.GetData();
1079 }
jeffhaobdb76512011-09-07 11:43:16 -07001080 return true;
1081}
1082
Ian Rogersd81871c2011-10-03 13:57:23 -07001083bool DexVerifier::VerifyInstructions() {
1084 const Instruction* inst = Instruction::At(code_item_->insns_);
jeffhaoba5ebb92011-08-25 17:24:37 -07001085
Ian Rogersd81871c2011-10-03 13:57:23 -07001086 /* Flag the start of the method as a branch target. */
1087 insn_flags_[0].SetBranchTarget();
1088
1089 uint32_t insns_size = code_item_->insns_size_in_code_units_;
1090 for(uint32_t dex_pc = 0; dex_pc < insns_size;) {
1091 if (!VerifyInstruction(inst, dex_pc)) {
Ian Rogers2c8a8572011-10-24 17:11:36 -07001092 DCHECK_NE(failure_, VERIFY_ERROR_NONE);
1093 fail_messages_ << "Rejecting opcode " << inst->DumpString(dex_file_) << " at " << dex_pc;
Ian Rogersd81871c2011-10-03 13:57:23 -07001094 return false;
1095 }
1096 /* Flag instructions that are garbage collection points */
1097 if (inst->IsBranch() || inst->IsSwitch() || inst->IsThrow() || inst->IsReturn()) {
1098 insn_flags_[dex_pc].SetGcPoint();
1099 }
1100 dex_pc += inst->SizeInCodeUnits();
1101 inst = inst->Next();
1102 }
1103 return true;
1104}
1105
1106bool DexVerifier::VerifyInstruction(const Instruction* inst, uint32_t code_offset) {
1107 Instruction::DecodedInstruction dec_insn(inst);
1108 bool result = true;
1109 switch (inst->GetVerifyTypeArgumentA()) {
1110 case Instruction::kVerifyRegA:
1111 result = result && CheckRegisterIndex(dec_insn.vA_);
1112 break;
1113 case Instruction::kVerifyRegAWide:
1114 result = result && CheckWideRegisterIndex(dec_insn.vA_);
1115 break;
1116 }
1117 switch (inst->GetVerifyTypeArgumentB()) {
1118 case Instruction::kVerifyRegB:
1119 result = result && CheckRegisterIndex(dec_insn.vB_);
1120 break;
1121 case Instruction::kVerifyRegBField:
1122 result = result && CheckFieldIndex(dec_insn.vB_);
1123 break;
1124 case Instruction::kVerifyRegBMethod:
1125 result = result && CheckMethodIndex(dec_insn.vB_);
1126 break;
1127 case Instruction::kVerifyRegBNewInstance:
1128 result = result && CheckNewInstance(dec_insn.vB_);
1129 break;
1130 case Instruction::kVerifyRegBString:
1131 result = result && CheckStringIndex(dec_insn.vB_);
1132 break;
1133 case Instruction::kVerifyRegBType:
1134 result = result && CheckTypeIndex(dec_insn.vB_);
1135 break;
1136 case Instruction::kVerifyRegBWide:
1137 result = result && CheckWideRegisterIndex(dec_insn.vB_);
1138 break;
1139 }
1140 switch (inst->GetVerifyTypeArgumentC()) {
1141 case Instruction::kVerifyRegC:
1142 result = result && CheckRegisterIndex(dec_insn.vC_);
1143 break;
1144 case Instruction::kVerifyRegCField:
1145 result = result && CheckFieldIndex(dec_insn.vC_);
1146 break;
1147 case Instruction::kVerifyRegCNewArray:
1148 result = result && CheckNewArray(dec_insn.vC_);
1149 break;
1150 case Instruction::kVerifyRegCType:
1151 result = result && CheckTypeIndex(dec_insn.vC_);
1152 break;
1153 case Instruction::kVerifyRegCWide:
1154 result = result && CheckWideRegisterIndex(dec_insn.vC_);
1155 break;
1156 }
1157 switch (inst->GetVerifyExtraFlags()) {
1158 case Instruction::kVerifyArrayData:
1159 result = result && CheckArrayData(code_offset);
1160 break;
1161 case Instruction::kVerifyBranchTarget:
1162 result = result && CheckBranchTarget(code_offset);
1163 break;
1164 case Instruction::kVerifySwitchTargets:
1165 result = result && CheckSwitchTargets(code_offset);
1166 break;
1167 case Instruction::kVerifyVarArg:
1168 result = result && CheckVarArgRegs(dec_insn.vA_, dec_insn.arg_);
1169 break;
1170 case Instruction::kVerifyVarArgRange:
1171 result = result && CheckVarArgRangeRegs(dec_insn.vA_, dec_insn.vC_);
1172 break;
1173 case Instruction::kVerifyError:
1174 Fail(VERIFY_ERROR_GENERIC) << "unexpected opcode " << inst->Name();
1175 result = false;
1176 break;
1177 }
1178 return result;
1179}
1180
1181bool DexVerifier::CheckRegisterIndex(uint32_t idx) {
1182 if (idx >= code_item_->registers_size_) {
1183 Fail(VERIFY_ERROR_GENERIC) << "register index out of range (" << idx << " >= "
1184 << code_item_->registers_size_ << ")";
1185 return false;
1186 }
1187 return true;
1188}
1189
1190bool DexVerifier::CheckWideRegisterIndex(uint32_t idx) {
1191 if (idx + 1 >= code_item_->registers_size_) {
1192 Fail(VERIFY_ERROR_GENERIC) << "wide register index out of range (" << idx
1193 << "+1 >= " << code_item_->registers_size_ << ")";
1194 return false;
1195 }
1196 return true;
1197}
1198
1199bool DexVerifier::CheckFieldIndex(uint32_t idx) {
1200 if (idx >= dex_file_->GetHeader().field_ids_size_) {
1201 Fail(VERIFY_ERROR_GENERIC) << "bad field index " << idx << " (max "
1202 << dex_file_->GetHeader().field_ids_size_ << ")";
1203 return false;
1204 }
1205 return true;
1206}
1207
1208bool DexVerifier::CheckMethodIndex(uint32_t idx) {
1209 if (idx >= dex_file_->GetHeader().method_ids_size_) {
1210 Fail(VERIFY_ERROR_GENERIC) << "bad method index " << idx << " (max "
1211 << dex_file_->GetHeader().method_ids_size_ << ")";
1212 return false;
1213 }
1214 return true;
1215}
1216
1217bool DexVerifier::CheckNewInstance(uint32_t idx) {
1218 if (idx >= dex_file_->GetHeader().type_ids_size_) {
1219 Fail(VERIFY_ERROR_GENERIC) << "bad type index " << idx << " (max "
1220 << dex_file_->GetHeader().type_ids_size_ << ")";
1221 return false;
1222 }
1223 // We don't need the actual class, just a pointer to the class name.
1224 const char* descriptor = dex_file_->dexStringByTypeIdx(idx);
1225 if (descriptor[0] != 'L') {
1226 Fail(VERIFY_ERROR_GENERIC) << "can't call new-instance on type '" << descriptor << "'";
1227 return false;
1228 }
1229 return true;
1230}
1231
1232bool DexVerifier::CheckStringIndex(uint32_t idx) {
1233 if (idx >= dex_file_->GetHeader().string_ids_size_) {
1234 Fail(VERIFY_ERROR_GENERIC) << "bad string index " << idx << " (max "
1235 << dex_file_->GetHeader().string_ids_size_ << ")";
1236 return false;
1237 }
1238 return true;
1239}
1240
1241bool DexVerifier::CheckTypeIndex(uint32_t idx) {
1242 if (idx >= dex_file_->GetHeader().type_ids_size_) {
1243 Fail(VERIFY_ERROR_GENERIC) << "bad type index " << idx << " (max "
1244 << dex_file_->GetHeader().type_ids_size_ << ")";
1245 return false;
1246 }
1247 return true;
1248}
1249
1250bool DexVerifier::CheckNewArray(uint32_t idx) {
1251 if (idx >= dex_file_->GetHeader().type_ids_size_) {
1252 Fail(VERIFY_ERROR_GENERIC) << "bad type index " << idx << " (max "
1253 << dex_file_->GetHeader().type_ids_size_ << ")";
1254 return false;
1255 }
1256 int bracket_count = 0;
1257 const char* descriptor = dex_file_->dexStringByTypeIdx(idx);
1258 const char* cp = descriptor;
1259 while (*cp++ == '[') {
1260 bracket_count++;
1261 }
1262 if (bracket_count == 0) {
1263 /* The given class must be an array type. */
1264 Fail(VERIFY_ERROR_GENERIC) << "can't new-array class '" << descriptor << "' (not an array)";
1265 return false;
1266 } else if (bracket_count > 255) {
1267 /* It is illegal to create an array of more than 255 dimensions. */
1268 Fail(VERIFY_ERROR_GENERIC) << "can't new-array class '" << descriptor << "' (exceeds limit)";
1269 return false;
1270 }
1271 return true;
1272}
1273
1274bool DexVerifier::CheckArrayData(uint32_t cur_offset) {
1275 const uint32_t insn_count = code_item_->insns_size_in_code_units_;
1276 const uint16_t* insns = code_item_->insns_ + cur_offset;
1277 const uint16_t* array_data;
1278 int32_t array_data_offset;
1279
1280 DCHECK_LT(cur_offset, insn_count);
1281 /* make sure the start of the array data table is in range */
1282 array_data_offset = insns[1] | (((int32_t) insns[2]) << 16);
1283 if ((int32_t) cur_offset + array_data_offset < 0 ||
1284 cur_offset + array_data_offset + 2 >= insn_count) {
1285 Fail(VERIFY_ERROR_GENERIC) << "invalid array data start: at " << cur_offset
1286 << ", data offset " << array_data_offset << ", count " << insn_count;
1287 return false;
1288 }
1289 /* offset to array data table is a relative branch-style offset */
1290 array_data = insns + array_data_offset;
1291 /* make sure the table is 32-bit aligned */
1292 if ((((uint32_t) array_data) & 0x03) != 0) {
1293 Fail(VERIFY_ERROR_GENERIC) << "unaligned array data table: at " << cur_offset
1294 << ", data offset " << array_data_offset;
1295 return false;
1296 }
1297 uint32_t value_width = array_data[1];
1298 uint32_t value_count = *(uint32_t*) (&array_data[2]);
1299 uint32_t table_size = 4 + (value_width * value_count + 1) / 2;
1300 /* make sure the end of the switch is in range */
1301 if (cur_offset + array_data_offset + table_size > insn_count) {
1302 Fail(VERIFY_ERROR_GENERIC) << "invalid array data end: at " << cur_offset
1303 << ", data offset " << array_data_offset << ", end "
1304 << cur_offset + array_data_offset + table_size
1305 << ", count " << insn_count;
1306 return false;
1307 }
1308 return true;
1309}
1310
1311bool DexVerifier::CheckBranchTarget(uint32_t cur_offset) {
1312 int32_t offset;
1313 bool isConditional, selfOkay;
1314 if (!GetBranchOffset(cur_offset, &offset, &isConditional, &selfOkay)) {
1315 return false;
1316 }
1317 if (!selfOkay && offset == 0) {
1318 Fail(VERIFY_ERROR_GENERIC) << "branch offset of zero not allowed at" << (void*) cur_offset;
1319 return false;
1320 }
1321 // Check for 32-bit overflow. This isn't strictly necessary if we can depend on the VM to have
1322 // identical "wrap-around" behavior, but it's unwise to depend on that.
1323 if (((int64_t) cur_offset + (int64_t) offset) != (int64_t) (cur_offset + offset)) {
1324 Fail(VERIFY_ERROR_GENERIC) << "branch target overflow " << (void*) cur_offset << " +" << offset;
1325 return false;
1326 }
1327 const uint32_t insn_count = code_item_->insns_size_in_code_units_;
1328 int32_t abs_offset = cur_offset + offset;
1329 if (abs_offset < 0 || (uint32_t) abs_offset >= insn_count || !insn_flags_[abs_offset].IsOpcode()) {
1330 Fail(VERIFY_ERROR_GENERIC) << "invalid branch target " << offset << " (-> "
1331 << (void*) abs_offset << ") at " << (void*) cur_offset;
1332 return false;
1333 }
1334 insn_flags_[abs_offset].SetBranchTarget();
1335 return true;
1336}
1337
1338bool DexVerifier::GetBranchOffset(uint32_t cur_offset, int32_t* pOffset, bool* pConditional,
1339 bool* selfOkay) {
1340 const uint16_t* insns = code_item_->insns_ + cur_offset;
1341 *pConditional = false;
1342 *selfOkay = false;
jeffhaoba5ebb92011-08-25 17:24:37 -07001343 switch (*insns & 0xff) {
1344 case Instruction::GOTO:
1345 *pOffset = ((int16_t) *insns) >> 8;
jeffhaoba5ebb92011-08-25 17:24:37 -07001346 break;
1347 case Instruction::GOTO_32:
1348 *pOffset = insns[1] | (((uint32_t) insns[2]) << 16);
jeffhaoba5ebb92011-08-25 17:24:37 -07001349 *selfOkay = true;
1350 break;
1351 case Instruction::GOTO_16:
1352 *pOffset = (int16_t) insns[1];
jeffhaoba5ebb92011-08-25 17:24:37 -07001353 break;
1354 case Instruction::IF_EQ:
1355 case Instruction::IF_NE:
1356 case Instruction::IF_LT:
1357 case Instruction::IF_GE:
1358 case Instruction::IF_GT:
1359 case Instruction::IF_LE:
1360 case Instruction::IF_EQZ:
1361 case Instruction::IF_NEZ:
1362 case Instruction::IF_LTZ:
1363 case Instruction::IF_GEZ:
1364 case Instruction::IF_GTZ:
1365 case Instruction::IF_LEZ:
1366 *pOffset = (int16_t) insns[1];
1367 *pConditional = true;
jeffhaoba5ebb92011-08-25 17:24:37 -07001368 break;
1369 default:
1370 return false;
1371 break;
1372 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001373 return true;
1374}
1375
Ian Rogersd81871c2011-10-03 13:57:23 -07001376bool DexVerifier::CheckSwitchTargets(uint32_t cur_offset) {
1377 const uint32_t insn_count = code_item_->insns_size_in_code_units_;
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001378 DCHECK_LT(cur_offset, insn_count);
Ian Rogersd81871c2011-10-03 13:57:23 -07001379 const uint16_t* insns = code_item_->insns_ + cur_offset;
jeffhaoba5ebb92011-08-25 17:24:37 -07001380 /* make sure the start of the switch is in range */
Ian Rogersd81871c2011-10-03 13:57:23 -07001381 int32_t switch_offset = insns[1] | ((int32_t) insns[2]) << 16;
1382 if ((int32_t) cur_offset + switch_offset < 0 || cur_offset + switch_offset + 2 >= insn_count) {
1383 Fail(VERIFY_ERROR_GENERIC) << "invalid switch start: at " << cur_offset
1384 << ", switch offset " << switch_offset << ", count " << insn_count;
jeffhaoba5ebb92011-08-25 17:24:37 -07001385 return false;
1386 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001387 /* offset to switch table is a relative branch-style offset */
Ian Rogersd81871c2011-10-03 13:57:23 -07001388 const uint16_t* switch_insns = insns + switch_offset;
jeffhaoba5ebb92011-08-25 17:24:37 -07001389 /* make sure the table is 32-bit aligned */
1390 if ((((uint32_t) switch_insns) & 0x03) != 0) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001391 Fail(VERIFY_ERROR_GENERIC) << "unaligned switch table: at " << cur_offset
1392 << ", switch offset " << switch_offset;
jeffhaoba5ebb92011-08-25 17:24:37 -07001393 return false;
1394 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001395 uint32_t switch_count = switch_insns[1];
1396 int32_t keys_offset, targets_offset;
1397 uint16_t expected_signature;
jeffhaoba5ebb92011-08-25 17:24:37 -07001398 if ((*insns & 0xff) == Instruction::PACKED_SWITCH) {
1399 /* 0=sig, 1=count, 2/3=firstKey */
1400 targets_offset = 4;
1401 keys_offset = -1;
1402 expected_signature = Instruction::kPackedSwitchSignature;
1403 } else {
1404 /* 0=sig, 1=count, 2..count*2 = keys */
1405 keys_offset = 2;
1406 targets_offset = 2 + 2 * switch_count;
1407 expected_signature = Instruction::kSparseSwitchSignature;
1408 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001409 uint32_t table_size = targets_offset + switch_count * 2;
jeffhaoba5ebb92011-08-25 17:24:37 -07001410 if (switch_insns[0] != expected_signature) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001411 Fail(VERIFY_ERROR_GENERIC) << "wrong signature for switch table (" << (void*) switch_insns[0]
1412 << ", wanted " << (void*) expected_signature << ")";
jeffhaoba5ebb92011-08-25 17:24:37 -07001413 return false;
1414 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001415 /* make sure the end of the switch is in range */
1416 if (cur_offset + switch_offset + table_size > (uint32_t) insn_count) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001417 Fail(VERIFY_ERROR_GENERIC) << "invalid switch end: at " << cur_offset << ", switch offset "
1418 << switch_offset << ", end "
1419 << (cur_offset + switch_offset + table_size)
1420 << ", count " << insn_count;
jeffhaoba5ebb92011-08-25 17:24:37 -07001421 return false;
1422 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001423 /* for a sparse switch, verify the keys are in ascending order */
1424 if (keys_offset > 0 && switch_count > 1) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001425 int32_t last_key = switch_insns[keys_offset] | (switch_insns[keys_offset + 1] << 16);
1426 for (uint32_t targ = 1; targ < switch_count; targ++) {
jeffhaoba5ebb92011-08-25 17:24:37 -07001427 int32_t key = (int32_t) switch_insns[keys_offset + targ * 2] |
1428 (int32_t) (switch_insns[keys_offset + targ * 2 + 1] << 16);
1429 if (key <= last_key) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001430 Fail(VERIFY_ERROR_GENERIC) << "invalid packed switch: last key=" << last_key
1431 << ", this=" << key;
jeffhaoba5ebb92011-08-25 17:24:37 -07001432 return false;
1433 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001434 last_key = key;
1435 }
1436 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001437 /* verify each switch target */
Ian Rogersd81871c2011-10-03 13:57:23 -07001438 for (uint32_t targ = 0; targ < switch_count; targ++) {
1439 int32_t offset = (int32_t) switch_insns[targets_offset + targ * 2] |
1440 (int32_t) (switch_insns[targets_offset + targ * 2 + 1] << 16);
1441 int32_t abs_offset = cur_offset + offset;
1442 if (abs_offset < 0 || abs_offset >= (int32_t) insn_count || !insn_flags_[abs_offset].IsOpcode()) {
1443 Fail(VERIFY_ERROR_GENERIC) << "invalid switch target " << offset << " (-> "
1444 << (void*) abs_offset << ") at "
1445 << (void*) cur_offset << "[" << targ << "]";
jeffhaoba5ebb92011-08-25 17:24:37 -07001446 return false;
1447 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001448 insn_flags_[abs_offset].SetBranchTarget();
1449 }
1450 return true;
1451}
1452
1453bool DexVerifier::CheckVarArgRegs(uint32_t vA, uint32_t arg[]) {
1454 if (vA > 5) {
1455 Fail(VERIFY_ERROR_GENERIC) << "invalid arg count (" << vA << ") in non-range invoke)";
1456 return false;
1457 }
1458 uint16_t registers_size = code_item_->registers_size_;
1459 for (uint32_t idx = 0; idx < vA; idx++) {
1460 if (arg[idx] > registers_size) {
1461 Fail(VERIFY_ERROR_GENERIC) << "invalid reg index (" << arg[idx]
1462 << ") in non-range invoke (> " << registers_size << ")";
1463 return false;
1464 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001465 }
1466
1467 return true;
1468}
1469
Ian Rogersd81871c2011-10-03 13:57:23 -07001470bool DexVerifier::CheckVarArgRangeRegs(uint32_t vA, uint32_t vC) {
1471 uint16_t registers_size = code_item_->registers_size_;
1472 // vA/vC are unsigned 8-bit/16-bit quantities for /range instructions, so there's no risk of
1473 // integer overflow when adding them here.
1474 if (vA + vC > registers_size) {
1475 Fail(VERIFY_ERROR_GENERIC) << "invalid reg index " << vA << "+" << vC << " in range invoke (> "
1476 << registers_size << ")";
jeffhaoba5ebb92011-08-25 17:24:37 -07001477 return false;
1478 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001479 return true;
1480}
1481
Ian Rogersd81871c2011-10-03 13:57:23 -07001482bool DexVerifier::VerifyCodeFlow() {
1483 uint16_t registers_size = code_item_->registers_size_;
1484 uint32_t insns_size = code_item_->insns_size_in_code_units_;
jeffhaobdb76512011-09-07 11:43:16 -07001485
Ian Rogersd81871c2011-10-03 13:57:23 -07001486 if (registers_size * insns_size > 4*1024*1024) {
1487 Fail(VERIFY_ERROR_GENERIC) << "warning: method is huge (regs=" << registers_size
1488 << " insns_size=" << insns_size << ")";
1489 }
1490 /* Create and initialize table holding register status */
1491 reg_table_.Init(PcToRegisterLineTable::kTrackRegsGcPoints, insn_flags_.get(), insns_size,
1492 registers_size, this);
jeffhaobdb76512011-09-07 11:43:16 -07001493
Ian Rogersd81871c2011-10-03 13:57:23 -07001494 work_line_.reset(new RegisterLine(registers_size, this));
1495 saved_line_.reset(new RegisterLine(registers_size, this));
jeffhaobdb76512011-09-07 11:43:16 -07001496
Ian Rogersd81871c2011-10-03 13:57:23 -07001497 /* Initialize register types of method arguments. */
1498 if (!SetTypesFromSignature()) {
Ian Rogers2c8a8572011-10-24 17:11:36 -07001499 DCHECK_NE(failure_, VERIFY_ERROR_NONE);
1500 fail_messages_ << "Bad signature in " << PrettyMethod(method_);
Ian Rogersd81871c2011-10-03 13:57:23 -07001501 return false;
1502 }
1503 /* Perform code flow verification. */
1504 if (!CodeFlowVerifyMethod()) {
1505 return false;
jeffhaobdb76512011-09-07 11:43:16 -07001506 }
1507
Ian Rogersd81871c2011-10-03 13:57:23 -07001508 /* Generate a register map and add it to the method. */
1509 ByteArray* map = GenerateGcMap();
1510 if (map == NULL) {
1511 return false; // Not a real failure, but a failure to encode
1512 }
1513 method_->SetGcMap(map);
1514#ifndef NDEBUG
1515 VerifyGcMap();
1516#endif
jeffhaobdb76512011-09-07 11:43:16 -07001517 return true;
1518}
1519
Ian Rogersd81871c2011-10-03 13:57:23 -07001520void DexVerifier::Dump(std::ostream& os) {
1521 if (method_->IsNative()) {
1522 os << "Native method" << std::endl;
1523 return;
jeffhaobdb76512011-09-07 11:43:16 -07001524 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001525 DCHECK(code_item_ != NULL);
1526 const Instruction* inst = Instruction::At(code_item_->insns_);
1527 for (size_t dex_pc = 0; dex_pc < code_item_->insns_size_in_code_units_;
1528 dex_pc += insn_flags_[dex_pc].GetLengthInCodeUnits()) {
Ian Rogers2c8a8572011-10-24 17:11:36 -07001529 os << StringPrintf("0x%04x", dex_pc) << ": " << insn_flags_[dex_pc].Dump()
1530 << " " << inst->DumpHex(5) << " " << inst->DumpString(dex_file_) << std::endl;
Ian Rogersd81871c2011-10-03 13:57:23 -07001531 RegisterLine* reg_line = reg_table_.GetLine(dex_pc);
1532 if (reg_line != NULL) {
Ian Rogers2c8a8572011-10-24 17:11:36 -07001533 os << reg_line->Dump() << std::endl;
jeffhaobdb76512011-09-07 11:43:16 -07001534 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001535 inst = inst->Next();
1536 }
jeffhaobdb76512011-09-07 11:43:16 -07001537}
1538
Ian Rogersd81871c2011-10-03 13:57:23 -07001539static bool IsPrimitiveDescriptor(char descriptor) {
1540 switch (descriptor) {
jeffhaobdb76512011-09-07 11:43:16 -07001541 case 'I':
1542 case 'C':
1543 case 'S':
1544 case 'B':
1545 case 'Z':
jeffhaobdb76512011-09-07 11:43:16 -07001546 case 'F':
1547 case 'D':
1548 case 'J':
Ian Rogersd81871c2011-10-03 13:57:23 -07001549 return true;
jeffhaobdb76512011-09-07 11:43:16 -07001550 default:
1551 return false;
1552 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001553}
1554
Ian Rogersd81871c2011-10-03 13:57:23 -07001555bool DexVerifier::SetTypesFromSignature() {
1556 RegisterLine* reg_line = reg_table_.GetLine(0);
1557 int arg_start = code_item_->registers_size_ - code_item_->ins_size_;
1558 size_t expected_args = code_item_->ins_size_; /* long/double count as two */
jeffhaobdb76512011-09-07 11:43:16 -07001559
Ian Rogersd81871c2011-10-03 13:57:23 -07001560 DCHECK_GE(arg_start, 0); /* should have been verified earlier */
1561 //Include the "this" pointer.
1562 size_t cur_arg = 0;
1563 if (!method_->IsStatic()) {
1564 // If this is a constructor for a class other than java.lang.Object, mark the first ("this")
1565 // argument as uninitialized. This restricts field access until the superclass constructor is
1566 // called.
1567 Class* declaring_class = method_->GetDeclaringClass();
1568 if (method_->IsConstructor() && !declaring_class->IsObjectClass()) {
1569 reg_line->SetRegisterType(arg_start + cur_arg,
1570 reg_types_.UninitializedThisArgument(declaring_class));
1571 } else {
1572 reg_line->SetRegisterType(arg_start + cur_arg, reg_types_.FromClass(declaring_class));
jeffhaobdb76512011-09-07 11:43:16 -07001573 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001574 cur_arg++;
jeffhaobdb76512011-09-07 11:43:16 -07001575 }
1576
Ian Rogersd81871c2011-10-03 13:57:23 -07001577 const DexFile::ProtoId& proto_id = dex_file_->GetProtoId(method_->GetProtoIdx());
1578 DexFile::ParameterIterator iterator(*dex_file_, proto_id);
1579
1580 for (; iterator.HasNext(); iterator.Next()) {
1581 const char* descriptor = iterator.GetDescriptor();
1582 if (descriptor == NULL) {
1583 LOG(FATAL) << "Null descriptor";
1584 }
1585 if (cur_arg >= expected_args) {
1586 Fail(VERIFY_ERROR_GENERIC) << "expected " << expected_args
1587 << " args, found more (" << descriptor << ")";
1588 return false;
1589 }
1590 switch (descriptor[0]) {
1591 case 'L':
1592 case '[':
1593 // We assume that reference arguments are initialized. The only way it could be otherwise
1594 // (assuming the caller was verified) is if the current method is <init>, but in that case
1595 // it's effectively considered initialized the instant we reach here (in the sense that we
1596 // can return without doing anything or call virtual methods).
1597 {
1598 const RegType& reg_type =
1599 reg_types_.FromDescriptor(method_->GetDeclaringClass()->GetClassLoader(), descriptor);
Ian Rogers84fa0742011-10-25 18:13:30 -07001600 reg_line->SetRegisterType(arg_start + cur_arg, reg_type);
Ian Rogersd81871c2011-10-03 13:57:23 -07001601 }
1602 break;
1603 case 'Z':
1604 reg_line->SetRegisterType(arg_start + cur_arg, reg_types_.Boolean());
1605 break;
1606 case 'C':
1607 reg_line->SetRegisterType(arg_start + cur_arg, reg_types_.Char());
1608 break;
1609 case 'B':
1610 reg_line->SetRegisterType(arg_start + cur_arg, reg_types_.Byte());
1611 break;
1612 case 'I':
1613 reg_line->SetRegisterType(arg_start + cur_arg, reg_types_.Integer());
1614 break;
1615 case 'S':
1616 reg_line->SetRegisterType(arg_start + cur_arg, reg_types_.Short());
1617 break;
1618 case 'F':
1619 reg_line->SetRegisterType(arg_start + cur_arg, reg_types_.Float());
1620 break;
1621 case 'J':
1622 case 'D': {
1623 const RegType& low_half = descriptor[0] == 'J' ? reg_types_.Long() : reg_types_.Double();
1624 reg_line->SetRegisterType(arg_start + cur_arg, low_half); // implicitly sets high-register
1625 cur_arg++;
1626 break;
1627 }
1628 default:
1629 Fail(VERIFY_ERROR_GENERIC) << "unexpected signature type char '" << descriptor << "'";
1630 return false;
1631 }
1632 cur_arg++;
1633 }
1634 if (cur_arg != expected_args) {
1635 Fail(VERIFY_ERROR_GENERIC) << "expected " << expected_args << " arguments, found " << cur_arg;
1636 return false;
1637 }
1638 const char* descriptor = dex_file_->GetReturnTypeDescriptor(proto_id);
1639 // Validate return type. We don't do the type lookup; just want to make sure that it has the right
1640 // format. Only major difference from the method argument format is that 'V' is supported.
1641 bool result;
1642 if (IsPrimitiveDescriptor(descriptor[0]) || descriptor[0] == 'V') {
1643 result = descriptor[1] == '\0';
1644 } else if (descriptor[0] == '[') { // single/multi-dimensional array of object/primitive
1645 size_t i = 0;
1646 do {
1647 i++;
1648 } while (descriptor[i] == '['); // process leading [
1649 if (descriptor[i] == 'L') { // object array
1650 do {
1651 i++; // find closing ;
1652 } while (descriptor[i] != ';' && descriptor[i] != '\0');
1653 result = descriptor[i] == ';';
1654 } else { // primitive array
1655 result = IsPrimitiveDescriptor(descriptor[i]) && descriptor[i + 1] == '\0';
1656 }
1657 } else if (descriptor[0] == 'L') {
1658 // could be more thorough here, but shouldn't be required
1659 size_t i = 0;
1660 do {
1661 i++;
1662 } while (descriptor[i] != ';' && descriptor[i] != '\0');
1663 result = descriptor[i] == ';';
1664 } else {
1665 result = false;
1666 }
1667 if (!result) {
1668 Fail(VERIFY_ERROR_GENERIC) << "unexpected char in return type descriptor '"
1669 << descriptor << "'";
1670 }
1671 return result;
jeffhaobdb76512011-09-07 11:43:16 -07001672}
1673
Ian Rogersd81871c2011-10-03 13:57:23 -07001674bool DexVerifier::CodeFlowVerifyMethod() {
1675 const uint16_t* insns = code_item_->insns_;
1676 const uint32_t insns_size = code_item_->insns_size_in_code_units_;
jeffhaoba5ebb92011-08-25 17:24:37 -07001677
jeffhaobdb76512011-09-07 11:43:16 -07001678 /* Begin by marking the first instruction as "changed". */
Ian Rogersd81871c2011-10-03 13:57:23 -07001679 insn_flags_[0].SetChanged();
1680 uint32_t start_guess = 0;
jeffhaoba5ebb92011-08-25 17:24:37 -07001681
jeffhaobdb76512011-09-07 11:43:16 -07001682 /* Continue until no instructions are marked "changed". */
1683 while (true) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001684 // Find the first marked one. Use "start_guess" as a way to find one quickly.
1685 uint32_t insn_idx = start_guess;
1686 for (; insn_idx < insns_size; insn_idx++) {
1687 if (insn_flags_[insn_idx].IsChanged())
jeffhaobdb76512011-09-07 11:43:16 -07001688 break;
1689 }
jeffhaobdb76512011-09-07 11:43:16 -07001690 if (insn_idx == insns_size) {
1691 if (start_guess != 0) {
1692 /* try again, starting from the top */
1693 start_guess = 0;
1694 continue;
1695 } else {
1696 /* all flags are clear */
1697 break;
1698 }
1699 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001700 // We carry the working set of registers from instruction to instruction. If this address can
1701 // be the target of a branch (or throw) instruction, or if we're skipping around chasing
1702 // "changed" flags, we need to load the set of registers from the table.
1703 // Because we always prefer to continue on to the next instruction, we should never have a
1704 // situation where we have a stray "changed" flag set on an instruction that isn't a branch
1705 // target.
1706 work_insn_idx_ = insn_idx;
1707 if (insn_flags_[insn_idx].IsBranchTarget()) {
1708 work_line_->CopyFromLine(reg_table_.GetLine(insn_idx));
jeffhaobdb76512011-09-07 11:43:16 -07001709 } else {
1710#ifndef NDEBUG
1711 /*
1712 * Sanity check: retrieve the stored register line (assuming
1713 * a full table) and make sure it actually matches.
1714 */
Ian Rogersd81871c2011-10-03 13:57:23 -07001715 RegisterLine* register_line = reg_table_.GetLine(insn_idx);
1716 if (register_line != NULL) {
1717 if (work_line_->CompareLine(register_line) != 0) {
1718 Dump(std::cout);
1719 std::cout << info_messages_.str();
1720 LOG(FATAL) << "work_line diverged in " << PrettyMethod(method_)
1721 << "@" << (void*)work_insn_idx_ << std::endl
1722 << " work_line=" << *work_line_ << std::endl
1723 << " expected=" << *register_line;
1724 }
jeffhaobdb76512011-09-07 11:43:16 -07001725 }
1726#endif
1727 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001728 if (!CodeFlowVerifyInstruction(&start_guess)) {
1729 fail_messages_ << std::endl << PrettyMethod(method_) << " failed to verify";
jeffhaoba5ebb92011-08-25 17:24:37 -07001730 return false;
1731 }
jeffhaobdb76512011-09-07 11:43:16 -07001732 /* Clear "changed" and mark as visited. */
Ian Rogersd81871c2011-10-03 13:57:23 -07001733 insn_flags_[insn_idx].SetVisited();
1734 insn_flags_[insn_idx].ClearChanged();
jeffhaobdb76512011-09-07 11:43:16 -07001735 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001736
Ian Rogersd81871c2011-10-03 13:57:23 -07001737 if (DEAD_CODE_SCAN && ((method_->GetAccessFlags() & kAccWritable) == 0)) {
jeffhaobdb76512011-09-07 11:43:16 -07001738 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001739 * Scan for dead code. There's nothing "evil" about dead code
jeffhaobdb76512011-09-07 11:43:16 -07001740 * (besides the wasted space), but it indicates a flaw somewhere
1741 * down the line, possibly in the verifier.
1742 *
1743 * If we've substituted "always throw" instructions into the stream,
1744 * we are almost certainly going to have some dead code.
1745 */
1746 int dead_start = -1;
Ian Rogersd81871c2011-10-03 13:57:23 -07001747 uint32_t insn_idx = 0;
1748 for (; insn_idx < insns_size; insn_idx += insn_flags_[insn_idx].GetLengthInCodeUnits()) {
jeffhaobdb76512011-09-07 11:43:16 -07001749 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001750 * Switch-statement data doesn't get "visited" by scanner. It
jeffhaobdb76512011-09-07 11:43:16 -07001751 * may or may not be preceded by a padding NOP (for alignment).
1752 */
1753 if (insns[insn_idx] == Instruction::kPackedSwitchSignature ||
1754 insns[insn_idx] == Instruction::kSparseSwitchSignature ||
1755 insns[insn_idx] == Instruction::kArrayDataSignature ||
1756 (insns[insn_idx] == Instruction::NOP &&
1757 (insns[insn_idx + 1] == Instruction::kPackedSwitchSignature ||
1758 insns[insn_idx + 1] == Instruction::kSparseSwitchSignature ||
1759 insns[insn_idx + 1] == Instruction::kArrayDataSignature))) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001760 insn_flags_[insn_idx].SetVisited();
jeffhaobdb76512011-09-07 11:43:16 -07001761 }
1762
Ian Rogersd81871c2011-10-03 13:57:23 -07001763 if (!insn_flags_[insn_idx].IsVisited()) {
jeffhaobdb76512011-09-07 11:43:16 -07001764 if (dead_start < 0)
1765 dead_start = insn_idx;
1766 } else if (dead_start >= 0) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001767 LogVerifyInfo() << "dead code " << (void*) dead_start << "-" << (void*) (insn_idx - 1);
jeffhaobdb76512011-09-07 11:43:16 -07001768 dead_start = -1;
1769 }
1770 }
1771 if (dead_start >= 0) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001772 LogVerifyInfo() << "dead code " << (void*) dead_start << "-" << (void*) (insn_idx - 1);
jeffhaoba5ebb92011-08-25 17:24:37 -07001773 }
1774 }
jeffhaobdb76512011-09-07 11:43:16 -07001775 return true;
1776}
1777
Ian Rogersd81871c2011-10-03 13:57:23 -07001778bool DexVerifier::CodeFlowVerifyInstruction(uint32_t* start_guess) {
jeffhaobdb76512011-09-07 11:43:16 -07001779#ifdef VERIFIER_STATS
Ian Rogersd81871c2011-10-03 13:57:23 -07001780 if (CurrentInsnFlags().IsVisited()) {
jeffhaobdb76512011-09-07 11:43:16 -07001781 gDvm.verifierStats.instrsReexamined++;
1782 } else {
1783 gDvm.verifierStats.instrsExamined++;
1784 }
1785#endif
1786
1787 /*
1788 * Once we finish decoding the instruction, we need to figure out where
jeffhaod1f0fde2011-09-08 17:25:33 -07001789 * we can go from here. There are three possible ways to transfer
jeffhaobdb76512011-09-07 11:43:16 -07001790 * control to another statement:
1791 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001792 * (1) Continue to the next instruction. Applies to all but
jeffhaobdb76512011-09-07 11:43:16 -07001793 * unconditional branches, method returns, and exception throws.
jeffhaod1f0fde2011-09-08 17:25:33 -07001794 * (2) Branch to one or more possible locations. Applies to branches
jeffhaobdb76512011-09-07 11:43:16 -07001795 * and switch statements.
jeffhaod1f0fde2011-09-08 17:25:33 -07001796 * (3) Exception handlers. Applies to any instruction that can
jeffhaobdb76512011-09-07 11:43:16 -07001797 * throw an exception that is handled by an encompassing "try"
1798 * block.
1799 *
1800 * We can also return, in which case there is no successor instruction
1801 * from this point.
1802 *
1803 * The behavior can be determined from the OpcodeFlags.
1804 */
Ian Rogersd81871c2011-10-03 13:57:23 -07001805 const uint16_t* insns = code_item_->insns_ + work_insn_idx_;
1806 const Instruction* inst = Instruction::At(insns);
jeffhaobdb76512011-09-07 11:43:16 -07001807 Instruction::DecodedInstruction dec_insn(inst);
1808 int opcode_flag = inst->Flag();
1809
jeffhaobdb76512011-09-07 11:43:16 -07001810 int32_t branch_target = 0;
jeffhaobdb76512011-09-07 11:43:16 -07001811 bool just_set_result = false;
Ian Rogers2c8a8572011-10-24 17:11:36 -07001812 if (gDebugVerify) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001813 // Generate processing back trace to debug verifier
Ian Rogers5ed29bf2011-10-26 12:22:21 -07001814 LogVerifyInfo() << "Processing " << inst->DumpString(dex_file_) << std::endl
1815 << *work_line_.get() << std::endl;
Ian Rogersd81871c2011-10-03 13:57:23 -07001816 }
jeffhaobdb76512011-09-07 11:43:16 -07001817
1818 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001819 * Make a copy of the previous register state. If the instruction
jeffhaobdb76512011-09-07 11:43:16 -07001820 * can throw an exception, we will copy/merge this into the "catch"
1821 * address rather than work_line, because we don't want the result
1822 * from the "successful" code path (e.g. a check-cast that "improves"
1823 * a type) to be visible to the exception handler.
1824 */
Ian Rogersd81871c2011-10-03 13:57:23 -07001825 if ((opcode_flag & Instruction::kThrow) != 0 && CurrentInsnFlags().IsInTry()) {
1826 saved_line_->CopyFromLine(work_line_.get());
jeffhaobdb76512011-09-07 11:43:16 -07001827 } else {
1828#ifndef NDEBUG
Ian Rogersd81871c2011-10-03 13:57:23 -07001829 saved_line_->FillWithGarbage();
jeffhaobdb76512011-09-07 11:43:16 -07001830#endif
1831 }
1832
1833 switch (dec_insn.opcode_) {
1834 case Instruction::NOP:
1835 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001836 * A "pure" NOP has no effect on anything. Data tables start with
jeffhaobdb76512011-09-07 11:43:16 -07001837 * a signature that looks like a NOP; if we see one of these in
1838 * the course of executing code then we have a problem.
1839 */
1840 if (dec_insn.vA_ != 0) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001841 Fail(VERIFY_ERROR_GENERIC) << "encountered data table in instruction stream";
jeffhaobdb76512011-09-07 11:43:16 -07001842 }
1843 break;
1844
1845 case Instruction::MOVE:
1846 case Instruction::MOVE_FROM16:
1847 case Instruction::MOVE_16:
Ian Rogersd81871c2011-10-03 13:57:23 -07001848 work_line_->CopyRegister1(dec_insn.vA_, dec_insn.vB_, kTypeCategory1nr);
jeffhaobdb76512011-09-07 11:43:16 -07001849 break;
1850 case Instruction::MOVE_WIDE:
1851 case Instruction::MOVE_WIDE_FROM16:
1852 case Instruction::MOVE_WIDE_16:
Ian Rogersd81871c2011-10-03 13:57:23 -07001853 work_line_->CopyRegister2(dec_insn.vA_, dec_insn.vB_);
jeffhaobdb76512011-09-07 11:43:16 -07001854 break;
1855 case Instruction::MOVE_OBJECT:
1856 case Instruction::MOVE_OBJECT_FROM16:
1857 case Instruction::MOVE_OBJECT_16:
Ian Rogersd81871c2011-10-03 13:57:23 -07001858 work_line_->CopyRegister1(dec_insn.vA_, dec_insn.vB_, kTypeCategoryRef);
jeffhaobdb76512011-09-07 11:43:16 -07001859 break;
1860
1861 /*
1862 * The move-result instructions copy data out of a "pseudo-register"
jeffhaod1f0fde2011-09-08 17:25:33 -07001863 * with the results from the last method invocation. In practice we
jeffhaobdb76512011-09-07 11:43:16 -07001864 * might want to hold the result in an actual CPU register, so the
1865 * Dalvik spec requires that these only appear immediately after an
1866 * invoke or filled-new-array.
1867 *
jeffhaod1f0fde2011-09-08 17:25:33 -07001868 * These calls invalidate the "result" register. (This is now
jeffhaobdb76512011-09-07 11:43:16 -07001869 * redundant with the reset done below, but it can make the debug info
1870 * easier to read in some cases.)
1871 */
1872 case Instruction::MOVE_RESULT:
Ian Rogersd81871c2011-10-03 13:57:23 -07001873 work_line_->CopyResultRegister1(dec_insn.vA_, false);
jeffhaobdb76512011-09-07 11:43:16 -07001874 break;
1875 case Instruction::MOVE_RESULT_WIDE:
Ian Rogersd81871c2011-10-03 13:57:23 -07001876 work_line_->CopyResultRegister2(dec_insn.vA_);
jeffhaobdb76512011-09-07 11:43:16 -07001877 break;
1878 case Instruction::MOVE_RESULT_OBJECT:
Ian Rogersd81871c2011-10-03 13:57:23 -07001879 work_line_->CopyResultRegister1(dec_insn.vA_, true);
jeffhaobdb76512011-09-07 11:43:16 -07001880 break;
1881
Ian Rogersd81871c2011-10-03 13:57:23 -07001882 case Instruction::MOVE_EXCEPTION: {
jeffhaobdb76512011-09-07 11:43:16 -07001883 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07001884 * This statement can only appear as the first instruction in an exception handler (though not
1885 * all exception handlers need to have one of these). We verify that as part of extracting the
jeffhaobdb76512011-09-07 11:43:16 -07001886 * exception type from the catch block list.
jeffhaobdb76512011-09-07 11:43:16 -07001887 */
Ian Rogers28ad40d2011-10-27 15:19:26 -07001888 const RegType& res_type = GetCaughtExceptionType();
1889 work_line_->SetRegisterType(dec_insn.vA_, res_type);
jeffhaobdb76512011-09-07 11:43:16 -07001890 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07001891 }
jeffhaobdb76512011-09-07 11:43:16 -07001892 case Instruction::RETURN_VOID:
Ian Rogersd81871c2011-10-03 13:57:23 -07001893 if (!method_->IsConstructor() || work_line_->CheckConstructorReturn()) {
1894 if (!GetMethodReturnType().IsUnknown()) {
1895 Fail(VERIFY_ERROR_GENERIC) << "return-void not expected";
1896 }
jeffhaobdb76512011-09-07 11:43:16 -07001897 }
1898 break;
1899 case Instruction::RETURN:
Ian Rogersd81871c2011-10-03 13:57:23 -07001900 if (!method_->IsConstructor() || work_line_->CheckConstructorReturn()) {
jeffhaobdb76512011-09-07 11:43:16 -07001901 /* check the method signature */
Ian Rogersd81871c2011-10-03 13:57:23 -07001902 const RegType& return_type = GetMethodReturnType();
1903 if (!return_type.IsCategory1Types()) {
1904 Fail(VERIFY_ERROR_GENERIC) << "unexpected non-category 1 return type " << return_type;
1905 } else {
1906 // Compilers may generate synthetic functions that write byte values into boolean fields.
1907 // Also, it may use integer values for boolean, byte, short, and character return types.
1908 const RegType& src_type = work_line_->GetRegisterType(dec_insn.vA_);
1909 bool use_src = ((return_type.IsBoolean() && src_type.IsByte()) ||
1910 ((return_type.IsBoolean() || return_type.IsByte() ||
1911 return_type.IsShort() || return_type.IsChar()) &&
1912 src_type.IsInteger()));
1913 /* check the register contents */
1914 work_line_->VerifyRegisterType(dec_insn.vA_, use_src ? src_type : return_type);
1915 if (failure_ != VERIFY_ERROR_NONE) {
Ian Rogers84fa0742011-10-25 18:13:30 -07001916 fail_messages_ << " return-1nr on invalid register v" << dec_insn.vA_;
Ian Rogersd81871c2011-10-03 13:57:23 -07001917 }
jeffhaobdb76512011-09-07 11:43:16 -07001918 }
1919 }
1920 break;
1921 case Instruction::RETURN_WIDE:
Ian Rogersd81871c2011-10-03 13:57:23 -07001922 if (!method_->IsConstructor() || work_line_->CheckConstructorReturn()) {
jeffhaobdb76512011-09-07 11:43:16 -07001923 /* check the method signature */
Ian Rogersd81871c2011-10-03 13:57:23 -07001924 const RegType& return_type = GetMethodReturnType();
1925 if (!return_type.IsCategory2Types()) {
1926 Fail(VERIFY_ERROR_GENERIC) << "return-wide not expected";
1927 } else {
1928 /* check the register contents */
1929 work_line_->VerifyRegisterType(dec_insn.vA_, return_type);
1930 if (failure_ != VERIFY_ERROR_NONE) {
Ian Rogers84fa0742011-10-25 18:13:30 -07001931 fail_messages_ << " return-wide on invalid register pair v" << dec_insn.vA_;
Ian Rogersd81871c2011-10-03 13:57:23 -07001932 }
jeffhaobdb76512011-09-07 11:43:16 -07001933 }
1934 }
1935 break;
1936 case Instruction::RETURN_OBJECT:
Ian Rogersd81871c2011-10-03 13:57:23 -07001937 if (!method_->IsConstructor() || work_line_->CheckConstructorReturn()) {
1938 const RegType& return_type = GetMethodReturnType();
1939 if (!return_type.IsReferenceTypes()) {
1940 Fail(VERIFY_ERROR_GENERIC) << "return-object not expected";
1941 } else {
1942 /* return_type is the *expected* return type, not register value */
1943 DCHECK(!return_type.IsZero());
1944 DCHECK(!return_type.IsUninitializedReference());
Ian Rogers9074b992011-10-26 17:41:55 -07001945 const RegType& reg_type = work_line_->GetRegisterType(dec_insn.vA_);
1946 // Disallow returning uninitialized values and verify that the reference in vAA is an
1947 // instance of the "return_type"
1948 if (reg_type.IsUninitializedTypes()) {
1949 Fail(VERIFY_ERROR_GENERIC) << "returning uninitialized object '" << reg_type << "'";
1950 } else if (!return_type.IsAssignableFrom(reg_type)) {
1951 Fail(VERIFY_ERROR_GENERIC) << "returning '" << reg_type
1952 << "', but expected from declaration '" << return_type << "'";
jeffhaobdb76512011-09-07 11:43:16 -07001953 }
1954 }
1955 }
1956 break;
1957
1958 case Instruction::CONST_4:
1959 case Instruction::CONST_16:
1960 case Instruction::CONST:
1961 /* could be boolean, int, float, or a null reference */
Ian Rogersd81871c2011-10-03 13:57:23 -07001962 work_line_->SetRegisterType(dec_insn.vA_, reg_types_.FromCat1Const((int32_t) dec_insn.vB_));
jeffhaobdb76512011-09-07 11:43:16 -07001963 break;
1964 case Instruction::CONST_HIGH16:
1965 /* could be boolean, int, float, or a null reference */
Ian Rogersd81871c2011-10-03 13:57:23 -07001966 work_line_->SetRegisterType(dec_insn.vA_,
1967 reg_types_.FromCat1Const((int32_t) dec_insn.vB_ << 16));
jeffhaobdb76512011-09-07 11:43:16 -07001968 break;
1969 case Instruction::CONST_WIDE_16:
1970 case Instruction::CONST_WIDE_32:
1971 case Instruction::CONST_WIDE:
1972 case Instruction::CONST_WIDE_HIGH16:
1973 /* could be long or double; resolved upon use */
Ian Rogersd81871c2011-10-03 13:57:23 -07001974 work_line_->SetRegisterType(dec_insn.vA_, reg_types_.ConstLo());
jeffhaobdb76512011-09-07 11:43:16 -07001975 break;
1976 case Instruction::CONST_STRING:
1977 case Instruction::CONST_STRING_JUMBO:
Ian Rogersd81871c2011-10-03 13:57:23 -07001978 work_line_->SetRegisterType(dec_insn.vA_, reg_types_.JavaLangString());
jeffhaobdb76512011-09-07 11:43:16 -07001979 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07001980 case Instruction::CONST_CLASS: {
Ian Rogers28ad40d2011-10-27 15:19:26 -07001981 // Get type from instruction if unresolved then we need an access check
1982 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved
1983 const RegType& res_type = ResolveClassAndCheckAccess(dec_insn.vB_);
1984 // Register holds class, ie its type is class, but on error we keep it Unknown
1985 work_line_->SetRegisterType(dec_insn.vA_,
1986 res_type.IsUnknown() ? res_type : reg_types_.JavaLangClass());
jeffhaobdb76512011-09-07 11:43:16 -07001987 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07001988 }
jeffhaobdb76512011-09-07 11:43:16 -07001989 case Instruction::MONITOR_ENTER:
Ian Rogersd81871c2011-10-03 13:57:23 -07001990 work_line_->PushMonitor(dec_insn.vA_, work_insn_idx_);
jeffhaobdb76512011-09-07 11:43:16 -07001991 break;
1992 case Instruction::MONITOR_EXIT:
1993 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001994 * monitor-exit instructions are odd. They can throw exceptions,
jeffhaobdb76512011-09-07 11:43:16 -07001995 * but when they do they act as if they succeeded and the PC is
jeffhaod1f0fde2011-09-08 17:25:33 -07001996 * pointing to the following instruction. (This behavior goes back
jeffhaobdb76512011-09-07 11:43:16 -07001997 * to the need to handle asynchronous exceptions, a now-deprecated
1998 * feature that Dalvik doesn't support.)
1999 *
jeffhaod1f0fde2011-09-08 17:25:33 -07002000 * In practice we don't need to worry about this. The only
jeffhaobdb76512011-09-07 11:43:16 -07002001 * exceptions that can be thrown from monitor-exit are for a
jeffhaod1f0fde2011-09-08 17:25:33 -07002002 * null reference and -exit without a matching -enter. If the
jeffhaobdb76512011-09-07 11:43:16 -07002003 * structured locking checks are working, the former would have
2004 * failed on the -enter instruction, and the latter is impossible.
2005 *
2006 * This is fortunate, because issue 3221411 prevents us from
2007 * chasing the "can throw" path when monitor verification is
jeffhaod1f0fde2011-09-08 17:25:33 -07002008 * enabled. If we can fully verify the locking we can ignore
jeffhaobdb76512011-09-07 11:43:16 -07002009 * some catch blocks (which will show up as "dead" code when
2010 * we skip them here); if we can't, then the code path could be
2011 * "live" so we still need to check it.
2012 */
Ian Rogersd81871c2011-10-03 13:57:23 -07002013 opcode_flag &= ~Instruction::kThrow;
2014 work_line_->PopMonitor(dec_insn.vA_);
jeffhaobdb76512011-09-07 11:43:16 -07002015 break;
2016
Ian Rogers28ad40d2011-10-27 15:19:26 -07002017 case Instruction::CHECK_CAST:
Ian Rogersd81871c2011-10-03 13:57:23 -07002018 case Instruction::INSTANCE_OF: {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002019 /*
2020 * If this instruction succeeds, we will "downcast" register vA to the type in vB. (This
2021 * could be a "upcast" -- not expected, so we don't try to address it.)
2022 *
2023 * If it fails, an exception is thrown, which we deal with later by ignoring the update to
2024 * dec_insn.vA_ when branching to a handler.
2025 */
2026 bool is_checkcast = dec_insn.opcode_ == Instruction::CHECK_CAST;
2027 const RegType& res_type =
2028 ResolveClassAndCheckAccess(is_checkcast ? dec_insn.vB_ : dec_insn.vC_);
2029 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved
2030 const RegType& orig_type =
2031 work_line_->GetRegisterType(is_checkcast ? dec_insn.vA_ : dec_insn.vB_);
2032 if (!res_type.IsNonZeroReferenceTypes()) {
2033 Fail(VERIFY_ERROR_GENERIC) << "check-cast on unexpected class " << res_type;
2034 } else if (!orig_type.IsReferenceTypes()) {
2035 Fail(VERIFY_ERROR_GENERIC) << "check-cast on non-reference in v" << dec_insn.vA_;
jeffhao2a8a90e2011-09-26 14:25:31 -07002036 } else {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002037 if (is_checkcast) {
2038 work_line_->SetRegisterType(dec_insn.vA_, res_type);
Ian Rogersd81871c2011-10-03 13:57:23 -07002039 } else {
Ian Rogersd81871c2011-10-03 13:57:23 -07002040 work_line_->SetRegisterType(dec_insn.vA_, reg_types_.Boolean());
jeffhaobdb76512011-09-07 11:43:16 -07002041 }
jeffhaobdb76512011-09-07 11:43:16 -07002042 }
jeffhao2a8a90e2011-09-26 14:25:31 -07002043 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002044 }
2045 case Instruction::ARRAY_LENGTH: {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002046 const RegType& res_type = work_line_->GetRegisterType(dec_insn.vB_);
2047 if (res_type.IsReferenceTypes()) {
2048 if (!res_type.IsArrayClass()) {
2049 Fail(VERIFY_ERROR_GENERIC) << "array-length on non-array " << res_type;
Ian Rogersd81871c2011-10-03 13:57:23 -07002050 } else {
2051 work_line_->SetRegisterType(dec_insn.vA_, reg_types_.Integer());
2052 }
2053 }
2054 break;
2055 }
2056 case Instruction::NEW_INSTANCE: {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002057 const RegType& res_type = ResolveClassAndCheckAccess(dec_insn.vB_);
2058 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved
2059 // can't create an instance of an interface or abstract class */
2060 if (!res_type.IsInstantiableTypes()) {
2061 Fail(VERIFY_ERROR_INSTANTIATION)
2062 << "new-instance on primitive, interface or abstract class" << res_type;
Ian Rogersd81871c2011-10-03 13:57:23 -07002063 } else {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002064 const RegType& uninit_type = reg_types_.Uninitialized(res_type, work_insn_idx_);
2065 // Any registers holding previous allocations from this address that have not yet been
2066 // initialized must be marked invalid.
2067 work_line_->MarkUninitRefsAsInvalid(uninit_type);
2068 // add the new uninitialized reference to the register state
2069 work_line_->SetRegisterType(dec_insn.vA_, uninit_type);
Ian Rogersd81871c2011-10-03 13:57:23 -07002070 }
2071 break;
2072 }
2073 case Instruction::NEW_ARRAY: {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002074 const RegType& res_type = ResolveClassAndCheckAccess(dec_insn.vC_);
2075 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved
2076 if (!res_type.IsArrayClass()) {
2077 Fail(VERIFY_ERROR_GENERIC) << "new-array on non-array class " << res_type;
jeffhaobdb76512011-09-07 11:43:16 -07002078 } else {
2079 /* make sure "size" register is valid type */
Ian Rogersd81871c2011-10-03 13:57:23 -07002080 work_line_->VerifyRegisterType(dec_insn.vB_, reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07002081 /* set register type to array class */
Ian Rogers28ad40d2011-10-27 15:19:26 -07002082 work_line_->SetRegisterType(dec_insn.vA_, res_type);
jeffhaobdb76512011-09-07 11:43:16 -07002083 }
2084 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002085 }
jeffhaobdb76512011-09-07 11:43:16 -07002086 case Instruction::FILLED_NEW_ARRAY:
Ian Rogersd81871c2011-10-03 13:57:23 -07002087 case Instruction::FILLED_NEW_ARRAY_RANGE: {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002088 const RegType& res_type = ResolveClassAndCheckAccess(dec_insn.vB_);
2089 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved
2090 if (!res_type.IsArrayClass()) {
Ian Rogersd81871c2011-10-03 13:57:23 -07002091 Fail(VERIFY_ERROR_GENERIC) << "filled-new-array on non-array class";
jeffhaobdb76512011-09-07 11:43:16 -07002092 } else {
jeffhaoe0cfb6f2011-09-22 16:42:56 -07002093 bool is_range = (dec_insn.opcode_ == Instruction::FILLED_NEW_ARRAY_RANGE);
jeffhaobdb76512011-09-07 11:43:16 -07002094 /* check the arguments to the instruction */
Ian Rogers28ad40d2011-10-27 15:19:26 -07002095 VerifyFilledNewArrayRegs(dec_insn, res_type, is_range);
jeffhaobdb76512011-09-07 11:43:16 -07002096 /* filled-array result goes into "result" register */
Ian Rogers28ad40d2011-10-27 15:19:26 -07002097 work_line_->SetResultRegisterType(res_type);
jeffhaobdb76512011-09-07 11:43:16 -07002098 just_set_result = true;
2099 }
2100 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002101 }
jeffhaobdb76512011-09-07 11:43:16 -07002102 case Instruction::CMPL_FLOAT:
2103 case Instruction::CMPG_FLOAT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002104 work_line_->VerifyRegisterType(dec_insn.vB_, reg_types_.Float());
2105 work_line_->VerifyRegisterType(dec_insn.vC_, reg_types_.Float());
2106 work_line_->SetRegisterType(dec_insn.vA_, reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07002107 break;
2108 case Instruction::CMPL_DOUBLE:
2109 case Instruction::CMPG_DOUBLE:
Ian Rogersd81871c2011-10-03 13:57:23 -07002110 work_line_->VerifyRegisterType(dec_insn.vB_, reg_types_.Double());
2111 work_line_->VerifyRegisterType(dec_insn.vC_, reg_types_.Double());
2112 work_line_->SetRegisterType(dec_insn.vA_, reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07002113 break;
2114 case Instruction::CMP_LONG:
Ian Rogersd81871c2011-10-03 13:57:23 -07002115 work_line_->VerifyRegisterType(dec_insn.vB_, reg_types_.Long());
2116 work_line_->VerifyRegisterType(dec_insn.vC_, reg_types_.Long());
2117 work_line_->SetRegisterType(dec_insn.vA_, reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07002118 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002119 case Instruction::THROW: {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002120 const RegType& res_type = work_line_->GetRegisterType(dec_insn.vA_);
2121 if (!reg_types_.JavaLangThrowable().IsAssignableFrom(res_type)) {
2122 Fail(VERIFY_ERROR_GENERIC) << "thrown class " << res_type << " not instanceof Throwable";
jeffhaobdb76512011-09-07 11:43:16 -07002123 }
2124 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002125 }
jeffhaobdb76512011-09-07 11:43:16 -07002126 case Instruction::GOTO:
2127 case Instruction::GOTO_16:
2128 case Instruction::GOTO_32:
2129 /* no effect on or use of registers */
2130 break;
2131
2132 case Instruction::PACKED_SWITCH:
2133 case Instruction::SPARSE_SWITCH:
2134 /* verify that vAA is an integer, or can be converted to one */
Ian Rogersd81871c2011-10-03 13:57:23 -07002135 work_line_->VerifyRegisterType(dec_insn.vA_, reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07002136 break;
2137
Ian Rogersd81871c2011-10-03 13:57:23 -07002138 case Instruction::FILL_ARRAY_DATA: {
2139 /* Similar to the verification done for APUT */
2140 Class* res_class = work_line_->GetClassFromRegister(dec_insn.vA_);
2141 if (failure_ == VERIFY_ERROR_NONE) {
jeffhaobdb76512011-09-07 11:43:16 -07002142 /* res_class can be null if the reg type is Zero */
Ian Rogersd81871c2011-10-03 13:57:23 -07002143 if (res_class != NULL) {
2144 Class* component_type = res_class->GetComponentType();
2145 if (!res_class->IsArrayClass() || !component_type->IsPrimitive() ||
2146 component_type->IsPrimitiveVoid()) {
2147 Fail(VERIFY_ERROR_GENERIC) << "invalid fill-array-data on "
2148 << PrettyDescriptor(res_class->GetDescriptor());
2149 } else {
2150 const RegType& value_type = reg_types_.FromClass(component_type);
2151 DCHECK(!value_type.IsUnknown());
2152 // Now verify if the element width in the table matches the element width declared in
2153 // the array
2154 const uint16_t* array_data = insns + (insns[1] | (((int32_t) insns[2]) << 16));
2155 if (array_data[0] != Instruction::kArrayDataSignature) {
2156 Fail(VERIFY_ERROR_GENERIC) << "invalid magic for array-data";
2157 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002158 size_t elem_width = Primitive::ComponentSize(component_type->GetPrimitiveType());
Ian Rogersd81871c2011-10-03 13:57:23 -07002159 // Since we don't compress the data in Dex, expect to see equal width of data stored
2160 // in the table and expected from the array class.
2161 if (array_data[1] != elem_width) {
2162 Fail(VERIFY_ERROR_GENERIC) << "array-data size mismatch (" << array_data[1]
2163 << " vs " << elem_width << ")";
2164 }
2165 }
2166 }
jeffhaobdb76512011-09-07 11:43:16 -07002167 }
2168 }
2169 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002170 }
jeffhaobdb76512011-09-07 11:43:16 -07002171 case Instruction::IF_EQ:
Ian Rogersd81871c2011-10-03 13:57:23 -07002172 case Instruction::IF_NE: {
2173 const RegType& reg_type1 = work_line_->GetRegisterType(dec_insn.vA_);
2174 const RegType& reg_type2 = work_line_->GetRegisterType(dec_insn.vB_);
2175 bool mismatch = false;
2176 if (reg_type1.IsZero()) { // zero then integral or reference expected
2177 mismatch = !reg_type2.IsReferenceTypes() && !reg_type2.IsIntegralTypes();
2178 } else if (reg_type1.IsReferenceTypes()) { // both references?
2179 mismatch = !reg_type2.IsReferenceTypes();
2180 } else { // both integral?
2181 mismatch = !reg_type1.IsIntegralTypes() || !reg_type2.IsIntegralTypes();
2182 }
2183 if (mismatch) {
2184 Fail(VERIFY_ERROR_GENERIC) << "args to if-eq/if-ne (" << reg_type1 << "," << reg_type2
2185 << ") must both be references or integral";
jeffhaobdb76512011-09-07 11:43:16 -07002186 }
2187 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002188 }
jeffhaobdb76512011-09-07 11:43:16 -07002189 case Instruction::IF_LT:
2190 case Instruction::IF_GE:
2191 case Instruction::IF_GT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002192 case Instruction::IF_LE: {
2193 const RegType& reg_type1 = work_line_->GetRegisterType(dec_insn.vA_);
2194 const RegType& reg_type2 = work_line_->GetRegisterType(dec_insn.vB_);
2195 if (!reg_type1.IsIntegralTypes() || !reg_type2.IsIntegralTypes()) {
2196 Fail(VERIFY_ERROR_GENERIC) << "args to 'if' (" << reg_type1 << ","
2197 << reg_type2 << ") must be integral";
jeffhaobdb76512011-09-07 11:43:16 -07002198 }
2199 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002200 }
jeffhaobdb76512011-09-07 11:43:16 -07002201 case Instruction::IF_EQZ:
Ian Rogersd81871c2011-10-03 13:57:23 -07002202 case Instruction::IF_NEZ: {
2203 const RegType& reg_type = work_line_->GetRegisterType(dec_insn.vA_);
2204 if (!reg_type.IsReferenceTypes() && !reg_type.IsIntegralTypes()) {
2205 Fail(VERIFY_ERROR_GENERIC) << "type " << reg_type << " unexpected as arg to if-eqz/if-nez";
2206 }
jeffhaobdb76512011-09-07 11:43:16 -07002207 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002208 }
jeffhaobdb76512011-09-07 11:43:16 -07002209 case Instruction::IF_LTZ:
2210 case Instruction::IF_GEZ:
2211 case Instruction::IF_GTZ:
Ian Rogersd81871c2011-10-03 13:57:23 -07002212 case Instruction::IF_LEZ: {
2213 const RegType& reg_type = work_line_->GetRegisterType(dec_insn.vA_);
2214 if (!reg_type.IsIntegralTypes()) {
2215 Fail(VERIFY_ERROR_GENERIC) << "type " << reg_type
2216 << " unexpected as arg to if-ltz/if-gez/if-gtz/if-lez";
2217 }
jeffhaobdb76512011-09-07 11:43:16 -07002218 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002219 }
jeffhaobdb76512011-09-07 11:43:16 -07002220 case Instruction::AGET_BOOLEAN:
Ian Rogersd81871c2011-10-03 13:57:23 -07002221 VerifyAGet(dec_insn, reg_types_.Boolean(), true);
2222 break;
jeffhaobdb76512011-09-07 11:43:16 -07002223 case Instruction::AGET_BYTE:
Ian Rogersd81871c2011-10-03 13:57:23 -07002224 VerifyAGet(dec_insn, reg_types_.Byte(), true);
2225 break;
jeffhaobdb76512011-09-07 11:43:16 -07002226 case Instruction::AGET_CHAR:
Ian Rogersd81871c2011-10-03 13:57:23 -07002227 VerifyAGet(dec_insn, reg_types_.Char(), true);
2228 break;
jeffhaobdb76512011-09-07 11:43:16 -07002229 case Instruction::AGET_SHORT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002230 VerifyAGet(dec_insn, reg_types_.Short(), true);
jeffhaobdb76512011-09-07 11:43:16 -07002231 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002232 case Instruction::AGET:
2233 VerifyAGet(dec_insn, reg_types_.Integer(), true);
2234 break;
jeffhaobdb76512011-09-07 11:43:16 -07002235 case Instruction::AGET_WIDE:
Ian Rogersd81871c2011-10-03 13:57:23 -07002236 VerifyAGet(dec_insn, reg_types_.Long(), true);
2237 break;
2238 case Instruction::AGET_OBJECT:
2239 VerifyAGet(dec_insn, reg_types_.JavaLangObject(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002240 break;
2241
Ian Rogersd81871c2011-10-03 13:57:23 -07002242 case Instruction::APUT_BOOLEAN:
2243 VerifyAPut(dec_insn, reg_types_.Boolean(), true);
2244 break;
2245 case Instruction::APUT_BYTE:
2246 VerifyAPut(dec_insn, reg_types_.Byte(), true);
2247 break;
2248 case Instruction::APUT_CHAR:
2249 VerifyAPut(dec_insn, reg_types_.Char(), true);
2250 break;
2251 case Instruction::APUT_SHORT:
2252 VerifyAPut(dec_insn, reg_types_.Short(), true);
jeffhaobdb76512011-09-07 11:43:16 -07002253 break;
2254 case Instruction::APUT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002255 VerifyAPut(dec_insn, reg_types_.Integer(), true);
jeffhaobdb76512011-09-07 11:43:16 -07002256 break;
2257 case Instruction::APUT_WIDE:
Ian Rogersd81871c2011-10-03 13:57:23 -07002258 VerifyAPut(dec_insn, reg_types_.Long(), true);
jeffhaobdb76512011-09-07 11:43:16 -07002259 break;
2260 case Instruction::APUT_OBJECT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002261 VerifyAPut(dec_insn, reg_types_.JavaLangObject(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002262 break;
2263
jeffhaobdb76512011-09-07 11:43:16 -07002264 case Instruction::IGET_BOOLEAN:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002265 VerifyISGet(dec_insn, reg_types_.Boolean(), true, false);
Ian Rogersd81871c2011-10-03 13:57:23 -07002266 break;
jeffhaobdb76512011-09-07 11:43:16 -07002267 case Instruction::IGET_BYTE:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002268 VerifyISGet(dec_insn, reg_types_.Byte(), true, false);
Ian Rogersd81871c2011-10-03 13:57:23 -07002269 break;
jeffhaobdb76512011-09-07 11:43:16 -07002270 case Instruction::IGET_CHAR:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002271 VerifyISGet(dec_insn, reg_types_.Char(), true, false);
Ian Rogersd81871c2011-10-03 13:57:23 -07002272 break;
jeffhaobdb76512011-09-07 11:43:16 -07002273 case Instruction::IGET_SHORT:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002274 VerifyISGet(dec_insn, reg_types_.Short(), true, false);
Ian Rogersd81871c2011-10-03 13:57:23 -07002275 break;
2276 case Instruction::IGET:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002277 VerifyISGet(dec_insn, reg_types_.Integer(), true, false);
jeffhaobdb76512011-09-07 11:43:16 -07002278 break;
2279 case Instruction::IGET_WIDE:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002280 VerifyISGet(dec_insn, reg_types_.Long(), true, false);
jeffhaobdb76512011-09-07 11:43:16 -07002281 break;
2282 case Instruction::IGET_OBJECT:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002283 VerifyISGet(dec_insn, reg_types_.JavaLangObject(), false, false);
Ian Rogersd81871c2011-10-03 13:57:23 -07002284 break;
jeffhaobdb76512011-09-07 11:43:16 -07002285
Ian Rogersd81871c2011-10-03 13:57:23 -07002286 case Instruction::IPUT_BOOLEAN:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002287 VerifyISPut(dec_insn, reg_types_.Boolean(), true, false);
Ian Rogersd81871c2011-10-03 13:57:23 -07002288 break;
2289 case Instruction::IPUT_BYTE:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002290 VerifyISPut(dec_insn, reg_types_.Byte(), true, false);
Ian Rogersd81871c2011-10-03 13:57:23 -07002291 break;
2292 case Instruction::IPUT_CHAR:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002293 VerifyISPut(dec_insn, reg_types_.Char(), true, false);
Ian Rogersd81871c2011-10-03 13:57:23 -07002294 break;
2295 case Instruction::IPUT_SHORT:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002296 VerifyISPut(dec_insn, reg_types_.Short(), true, false);
jeffhaobdb76512011-09-07 11:43:16 -07002297 break;
2298 case Instruction::IPUT:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002299 VerifyISPut(dec_insn, reg_types_.Integer(), true, false);
jeffhaobdb76512011-09-07 11:43:16 -07002300 break;
2301 case Instruction::IPUT_WIDE:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002302 VerifyISPut(dec_insn, reg_types_.Long(), true, false);
Ian Rogersd81871c2011-10-03 13:57:23 -07002303 break;
jeffhaobdb76512011-09-07 11:43:16 -07002304 case Instruction::IPUT_OBJECT:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002305 VerifyISPut(dec_insn, reg_types_.JavaLangObject(), false, false);
jeffhaobdb76512011-09-07 11:43:16 -07002306 break;
2307
jeffhaobdb76512011-09-07 11:43:16 -07002308 case Instruction::SGET_BOOLEAN:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002309 VerifyISGet(dec_insn, reg_types_.Boolean(), true, true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002310 break;
jeffhaobdb76512011-09-07 11:43:16 -07002311 case Instruction::SGET_BYTE:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002312 VerifyISGet(dec_insn, reg_types_.Byte(), true, true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002313 break;
jeffhaobdb76512011-09-07 11:43:16 -07002314 case Instruction::SGET_CHAR:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002315 VerifyISGet(dec_insn, reg_types_.Char(), true, true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002316 break;
jeffhaobdb76512011-09-07 11:43:16 -07002317 case Instruction::SGET_SHORT:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002318 VerifyISGet(dec_insn, reg_types_.Short(), true, true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002319 break;
2320 case Instruction::SGET:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002321 VerifyISGet(dec_insn, reg_types_.Integer(), true, true);
jeffhaobdb76512011-09-07 11:43:16 -07002322 break;
2323 case Instruction::SGET_WIDE:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002324 VerifyISGet(dec_insn, reg_types_.Long(), true, true);
jeffhaobdb76512011-09-07 11:43:16 -07002325 break;
2326 case Instruction::SGET_OBJECT:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002327 VerifyISGet(dec_insn, reg_types_.JavaLangObject(), false, true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002328 break;
2329
2330 case Instruction::SPUT_BOOLEAN:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002331 VerifyISPut(dec_insn, reg_types_.Boolean(), true, true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002332 break;
2333 case Instruction::SPUT_BYTE:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002334 VerifyISPut(dec_insn, reg_types_.Byte(), true, true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002335 break;
2336 case Instruction::SPUT_CHAR:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002337 VerifyISPut(dec_insn, reg_types_.Char(), true, true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002338 break;
2339 case Instruction::SPUT_SHORT:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002340 VerifyISPut(dec_insn, reg_types_.Short(), true, true);
jeffhaobdb76512011-09-07 11:43:16 -07002341 break;
2342 case Instruction::SPUT:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002343 VerifyISPut(dec_insn, reg_types_.Integer(), true, true);
jeffhaobdb76512011-09-07 11:43:16 -07002344 break;
2345 case Instruction::SPUT_WIDE:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002346 VerifyISPut(dec_insn, reg_types_.Long(), true, true);
jeffhaobdb76512011-09-07 11:43:16 -07002347 break;
2348 case Instruction::SPUT_OBJECT:
Ian Rogersb94a27b2011-10-26 00:33:41 -07002349 VerifyISPut(dec_insn, reg_types_.JavaLangObject(), false, true);
jeffhaobdb76512011-09-07 11:43:16 -07002350 break;
2351
2352 case Instruction::INVOKE_VIRTUAL:
2353 case Instruction::INVOKE_VIRTUAL_RANGE:
2354 case Instruction::INVOKE_SUPER:
Ian Rogersd81871c2011-10-03 13:57:23 -07002355 case Instruction::INVOKE_SUPER_RANGE: {
2356 bool is_range = (dec_insn.opcode_ == Instruction::INVOKE_VIRTUAL_RANGE ||
2357 dec_insn.opcode_ == Instruction::INVOKE_SUPER_RANGE);
2358 bool is_super = (dec_insn.opcode_ == Instruction::INVOKE_SUPER ||
2359 dec_insn.opcode_ == Instruction::INVOKE_SUPER_RANGE);
2360 Method* called_method = VerifyInvocationArgs(dec_insn, METHOD_VIRTUAL, is_range, is_super);
2361 if (failure_ == VERIFY_ERROR_NONE) {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002362 const char* descriptor;
2363 if (called_method == NULL) {
2364 uint32_t method_idx = dec_insn.vB_;
2365 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx);
2366 uint32_t return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_;
2367 descriptor = dex_file_->dexStringByTypeIdx(return_type_idx);
2368 } else {
2369 descriptor = called_method->GetReturnTypeDescriptor();
2370 }
Ian Rogers9074b992011-10-26 17:41:55 -07002371 const RegType& return_type =
Ian Rogers28ad40d2011-10-27 15:19:26 -07002372 reg_types_.FromDescriptor(method_->GetDeclaringClass()->GetClassLoader(), descriptor);
Ian Rogersd81871c2011-10-03 13:57:23 -07002373 work_line_->SetResultRegisterType(return_type);
jeffhaobdb76512011-09-07 11:43:16 -07002374 just_set_result = true;
2375 }
2376 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002377 }
jeffhaobdb76512011-09-07 11:43:16 -07002378 case Instruction::INVOKE_DIRECT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002379 case Instruction::INVOKE_DIRECT_RANGE: {
2380 bool is_range = (dec_insn.opcode_ == Instruction::INVOKE_DIRECT_RANGE);
2381 Method* called_method = VerifyInvocationArgs(dec_insn, METHOD_DIRECT, is_range, false);
2382 if (failure_ == VERIFY_ERROR_NONE) {
jeffhaobdb76512011-09-07 11:43:16 -07002383 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07002384 * Some additional checks when calling a constructor. We know from the invocation arg check
2385 * that the "this" argument is an instance of called_method->klass. Now we further restrict
2386 * that to require that called_method->klass is the same as this->klass or this->super,
2387 * allowing the latter only if the "this" argument is the same as the "this" argument to
2388 * this method (which implies that we're in a constructor ourselves).
jeffhaobdb76512011-09-07 11:43:16 -07002389 */
Ian Rogers28ad40d2011-10-27 15:19:26 -07002390 bool is_constructor;
2391 if (called_method != NULL) {
2392 is_constructor = called_method->IsConstructor();
2393 } else {
2394 uint32_t method_idx = dec_insn.vB_;
2395 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx);
2396 const char* name = dex_file_->GetMethodName(method_id);
2397 is_constructor = strcmp(name, "<init>") == 0;
2398 }
2399 if (is_constructor) {
Ian Rogersd81871c2011-10-03 13:57:23 -07002400 const RegType& this_type = work_line_->GetInvocationThis(dec_insn);
2401 if (failure_ != VERIFY_ERROR_NONE)
jeffhaobdb76512011-09-07 11:43:16 -07002402 break;
2403
2404 /* no null refs allowed (?) */
Ian Rogersd81871c2011-10-03 13:57:23 -07002405 if (this_type.IsZero()) {
2406 Fail(VERIFY_ERROR_GENERIC) << "unable to initialize null ref";
jeffhaobdb76512011-09-07 11:43:16 -07002407 break;
2408 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07002409 if (called_method != NULL) {
2410 Class* this_class = this_type.GetClass();
2411 DCHECK(this_class != NULL);
2412 /* must be in same class or in superclass */
2413 if (called_method->GetDeclaringClass() == this_class->GetSuperClass()) {
2414 if (this_class != method_->GetDeclaringClass()) {
2415 Fail(VERIFY_ERROR_GENERIC)
2416 << "invoke-direct <init> on super only allowed for 'this' in <init>";
2417 break;
2418 }
2419 } else if (called_method->GetDeclaringClass() != this_class) {
2420 Fail(VERIFY_ERROR_GENERIC) << "invoke-direct <init> must be on current class or super";
jeffhaobdb76512011-09-07 11:43:16 -07002421 break;
2422 }
jeffhaobdb76512011-09-07 11:43:16 -07002423 }
2424
2425 /* arg must be an uninitialized reference */
Ian Rogers84fa0742011-10-25 18:13:30 -07002426 if (!this_type.IsUninitializedTypes()) {
Ian Rogersd81871c2011-10-03 13:57:23 -07002427 Fail(VERIFY_ERROR_GENERIC) << "Expected initialization on uninitialized reference "
2428 << this_type;
jeffhaobdb76512011-09-07 11:43:16 -07002429 break;
2430 }
2431
2432 /*
Ian Rogers84fa0742011-10-25 18:13:30 -07002433 * Replace the uninitialized reference with an initialized one. We need to do this for all
2434 * registers that have the same object instance in them, not just the "this" register.
jeffhaobdb76512011-09-07 11:43:16 -07002435 */
Ian Rogersd81871c2011-10-03 13:57:23 -07002436 work_line_->MarkRefsAsInitialized(this_type);
2437 if (failure_ != VERIFY_ERROR_NONE)
jeffhaobdb76512011-09-07 11:43:16 -07002438 break;
jeffhao2a8a90e2011-09-26 14:25:31 -07002439 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07002440 const char* descriptor;
2441 if (called_method == NULL) {
2442 uint32_t method_idx = dec_insn.vB_;
2443 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx);
2444 uint32_t return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_;
2445 descriptor = dex_file_->dexStringByTypeIdx(return_type_idx);
2446 } else {
2447 descriptor = called_method->GetReturnTypeDescriptor();
2448 }
Ian Rogers9074b992011-10-26 17:41:55 -07002449 const RegType& return_type =
Ian Rogers28ad40d2011-10-27 15:19:26 -07002450 reg_types_.FromDescriptor(method_->GetDeclaringClass()->GetClassLoader(), descriptor);
Ian Rogersd81871c2011-10-03 13:57:23 -07002451 work_line_->SetResultRegisterType(return_type);
jeffhaobdb76512011-09-07 11:43:16 -07002452 just_set_result = true;
2453 }
2454 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002455 }
jeffhaobdb76512011-09-07 11:43:16 -07002456 case Instruction::INVOKE_STATIC:
Ian Rogersd81871c2011-10-03 13:57:23 -07002457 case Instruction::INVOKE_STATIC_RANGE: {
2458 bool is_range = (dec_insn.opcode_ == Instruction::INVOKE_STATIC_RANGE);
2459 Method* called_method = VerifyInvocationArgs(dec_insn, METHOD_STATIC, is_range, false);
2460 if (failure_ == VERIFY_ERROR_NONE) {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002461 const char* descriptor;
2462 if (called_method == NULL) {
2463 uint32_t method_idx = dec_insn.vB_;
2464 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx);
2465 uint32_t return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_;
2466 descriptor = dex_file_->dexStringByTypeIdx(return_type_idx);
2467 } else {
2468 descriptor = called_method->GetReturnTypeDescriptor();
2469 }
Ian Rogers9074b992011-10-26 17:41:55 -07002470 const RegType& return_type =
Ian Rogers28ad40d2011-10-27 15:19:26 -07002471 reg_types_.FromDescriptor(method_->GetDeclaringClass()->GetClassLoader(), descriptor);
Ian Rogersd81871c2011-10-03 13:57:23 -07002472 work_line_->SetResultRegisterType(return_type);
2473 just_set_result = true;
2474 }
jeffhaobdb76512011-09-07 11:43:16 -07002475 }
2476 break;
2477 case Instruction::INVOKE_INTERFACE:
Ian Rogersd81871c2011-10-03 13:57:23 -07002478 case Instruction::INVOKE_INTERFACE_RANGE: {
2479 bool is_range = (dec_insn.opcode_ == Instruction::INVOKE_INTERFACE_RANGE);
2480 Method* abs_method = VerifyInvocationArgs(dec_insn, METHOD_INTERFACE, is_range, false);
2481 if (failure_ == VERIFY_ERROR_NONE) {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002482 if (abs_method != NULL) {
2483 Class* called_interface = abs_method->GetDeclaringClass();
2484 if (!called_interface->IsInterface()) {
2485 Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected interface class in invoke-interface '"
2486 << PrettyMethod(abs_method) << "'";
2487 break;
2488 }
2489 }
2490 /* Get the type of the "this" arg, which should either be a sub-interface of called
2491 * interface or Object (see comments in RegType::JoinClass).
2492 */
2493 const RegType& this_type = work_line_->GetInvocationThis(dec_insn);
2494 if (failure_ == VERIFY_ERROR_NONE) {
2495 if (this_type.IsZero()) {
2496 /* null pointer always passes (and always fails at runtime) */
2497 } else {
2498 if (this_type.IsUninitializedTypes()) {
2499 Fail(VERIFY_ERROR_GENERIC) << "interface call on uninitialized object "
2500 << this_type;
2501 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002502 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07002503 // In the past we have tried to assert that "called_interface" is assignable
2504 // from "this_type.GetClass()", however, as we do an imprecise Join
2505 // (RegType::JoinClass) we don't have full information on what interfaces are
2506 // implemented by "this_type". For example, two classes may implement the same
2507 // interfaces and have a common parent that doesn't implement the interface. The
2508 // join will set "this_type" to the parent class and a test that this implements
2509 // the interface will incorrectly fail.
jeffhaobdb76512011-09-07 11:43:16 -07002510 }
2511 }
jeffhaobdb76512011-09-07 11:43:16 -07002512 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07002513 * We don't have an object instance, so we can't find the concrete method. However, all of
2514 * the type information is in the abstract method, so we're good.
jeffhaobdb76512011-09-07 11:43:16 -07002515 */
Ian Rogers28ad40d2011-10-27 15:19:26 -07002516 const char* descriptor;
2517 if (abs_method == NULL) {
2518 uint32_t method_idx = dec_insn.vB_;
2519 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx);
2520 uint32_t return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_;
2521 descriptor = dex_file_->dexStringByTypeIdx(return_type_idx);
2522 } else {
2523 descriptor = abs_method->GetReturnTypeDescriptor();
2524 }
Ian Rogers9074b992011-10-26 17:41:55 -07002525 const RegType& return_type =
Ian Rogers28ad40d2011-10-27 15:19:26 -07002526 reg_types_.FromDescriptor(method_->GetDeclaringClass()->GetClassLoader(), descriptor);
2527 work_line_->SetResultRegisterType(return_type);
Ian Rogersd81871c2011-10-03 13:57:23 -07002528 work_line_->SetResultRegisterType(return_type);
jeffhaobdb76512011-09-07 11:43:16 -07002529 just_set_result = true;
2530 }
2531 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002532 }
jeffhaobdb76512011-09-07 11:43:16 -07002533 case Instruction::NEG_INT:
2534 case Instruction::NOT_INT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002535 work_line_->CheckUnaryOp(dec_insn, reg_types_.Integer(), reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07002536 break;
2537 case Instruction::NEG_LONG:
2538 case Instruction::NOT_LONG:
Ian Rogersd81871c2011-10-03 13:57:23 -07002539 work_line_->CheckUnaryOp(dec_insn, reg_types_.Long(), reg_types_.Long());
jeffhaobdb76512011-09-07 11:43:16 -07002540 break;
2541 case Instruction::NEG_FLOAT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002542 work_line_->CheckUnaryOp(dec_insn, reg_types_.Float(), reg_types_.Float());
jeffhaobdb76512011-09-07 11:43:16 -07002543 break;
2544 case Instruction::NEG_DOUBLE:
Ian Rogersd81871c2011-10-03 13:57:23 -07002545 work_line_->CheckUnaryOp(dec_insn, reg_types_.Double(), reg_types_.Double());
jeffhaobdb76512011-09-07 11:43:16 -07002546 break;
2547 case Instruction::INT_TO_LONG:
Ian Rogersd81871c2011-10-03 13:57:23 -07002548 work_line_->CheckUnaryOp(dec_insn, reg_types_.Long(), reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07002549 break;
2550 case Instruction::INT_TO_FLOAT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002551 work_line_->CheckUnaryOp(dec_insn, reg_types_.Float(), reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07002552 break;
2553 case Instruction::INT_TO_DOUBLE:
Ian Rogersd81871c2011-10-03 13:57:23 -07002554 work_line_->CheckUnaryOp(dec_insn, reg_types_.Double(), reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07002555 break;
2556 case Instruction::LONG_TO_INT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002557 work_line_->CheckUnaryOp(dec_insn, reg_types_.Integer(), reg_types_.Long());
jeffhaobdb76512011-09-07 11:43:16 -07002558 break;
2559 case Instruction::LONG_TO_FLOAT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002560 work_line_->CheckUnaryOp(dec_insn, reg_types_.Float(), reg_types_.Long());
jeffhaobdb76512011-09-07 11:43:16 -07002561 break;
2562 case Instruction::LONG_TO_DOUBLE:
Ian Rogersd81871c2011-10-03 13:57:23 -07002563 work_line_->CheckUnaryOp(dec_insn, reg_types_.Double(), reg_types_.Long());
jeffhaobdb76512011-09-07 11:43:16 -07002564 break;
2565 case Instruction::FLOAT_TO_INT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002566 work_line_->CheckUnaryOp(dec_insn, reg_types_.Integer(), reg_types_.Float());
jeffhaobdb76512011-09-07 11:43:16 -07002567 break;
2568 case Instruction::FLOAT_TO_LONG:
Ian Rogersd81871c2011-10-03 13:57:23 -07002569 work_line_->CheckUnaryOp(dec_insn, reg_types_.Long(), reg_types_.Float());
jeffhaobdb76512011-09-07 11:43:16 -07002570 break;
2571 case Instruction::FLOAT_TO_DOUBLE:
Ian Rogersd81871c2011-10-03 13:57:23 -07002572 work_line_->CheckUnaryOp(dec_insn, reg_types_.Double(), reg_types_.Float());
jeffhaobdb76512011-09-07 11:43:16 -07002573 break;
2574 case Instruction::DOUBLE_TO_INT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002575 work_line_->CheckUnaryOp(dec_insn, reg_types_.Integer(), reg_types_.Double());
jeffhaobdb76512011-09-07 11:43:16 -07002576 break;
2577 case Instruction::DOUBLE_TO_LONG:
Ian Rogersd81871c2011-10-03 13:57:23 -07002578 work_line_->CheckUnaryOp(dec_insn, reg_types_.Long(), reg_types_.Double());
jeffhaobdb76512011-09-07 11:43:16 -07002579 break;
2580 case Instruction::DOUBLE_TO_FLOAT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002581 work_line_->CheckUnaryOp(dec_insn, reg_types_.Float(), reg_types_.Double());
jeffhaobdb76512011-09-07 11:43:16 -07002582 break;
2583 case Instruction::INT_TO_BYTE:
Ian Rogersd81871c2011-10-03 13:57:23 -07002584 work_line_->CheckUnaryOp(dec_insn, reg_types_.Byte(), reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07002585 break;
2586 case Instruction::INT_TO_CHAR:
Ian Rogersd81871c2011-10-03 13:57:23 -07002587 work_line_->CheckUnaryOp(dec_insn, reg_types_.Char(), reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07002588 break;
2589 case Instruction::INT_TO_SHORT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002590 work_line_->CheckUnaryOp(dec_insn, reg_types_.Short(), reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07002591 break;
2592
2593 case Instruction::ADD_INT:
2594 case Instruction::SUB_INT:
2595 case Instruction::MUL_INT:
2596 case Instruction::REM_INT:
2597 case Instruction::DIV_INT:
2598 case Instruction::SHL_INT:
2599 case Instruction::SHR_INT:
2600 case Instruction::USHR_INT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002601 work_line_->CheckBinaryOp(dec_insn, reg_types_.Integer(), reg_types_.Integer(), reg_types_.Integer(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002602 break;
2603 case Instruction::AND_INT:
2604 case Instruction::OR_INT:
2605 case Instruction::XOR_INT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002606 work_line_->CheckBinaryOp(dec_insn, reg_types_.Integer(), reg_types_.Integer(), reg_types_.Integer(), true);
jeffhaobdb76512011-09-07 11:43:16 -07002607 break;
2608 case Instruction::ADD_LONG:
2609 case Instruction::SUB_LONG:
2610 case Instruction::MUL_LONG:
2611 case Instruction::DIV_LONG:
2612 case Instruction::REM_LONG:
2613 case Instruction::AND_LONG:
2614 case Instruction::OR_LONG:
2615 case Instruction::XOR_LONG:
Ian Rogersd81871c2011-10-03 13:57:23 -07002616 work_line_->CheckBinaryOp(dec_insn, reg_types_.Long(), reg_types_.Long(), reg_types_.Long(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002617 break;
2618 case Instruction::SHL_LONG:
2619 case Instruction::SHR_LONG:
2620 case Instruction::USHR_LONG:
Ian Rogersd81871c2011-10-03 13:57:23 -07002621 /* shift distance is Int, making these different from other binary operations */
2622 work_line_->CheckBinaryOp(dec_insn, reg_types_.Long(), reg_types_.Long(), reg_types_.Integer(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002623 break;
2624 case Instruction::ADD_FLOAT:
2625 case Instruction::SUB_FLOAT:
2626 case Instruction::MUL_FLOAT:
2627 case Instruction::DIV_FLOAT:
2628 case Instruction::REM_FLOAT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002629 work_line_->CheckBinaryOp(dec_insn, reg_types_.Float(), reg_types_.Float(), reg_types_.Float(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002630 break;
2631 case Instruction::ADD_DOUBLE:
2632 case Instruction::SUB_DOUBLE:
2633 case Instruction::MUL_DOUBLE:
2634 case Instruction::DIV_DOUBLE:
2635 case Instruction::REM_DOUBLE:
Ian Rogersd81871c2011-10-03 13:57:23 -07002636 work_line_->CheckBinaryOp(dec_insn, reg_types_.Double(), reg_types_.Double(), reg_types_.Double(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002637 break;
2638 case Instruction::ADD_INT_2ADDR:
2639 case Instruction::SUB_INT_2ADDR:
2640 case Instruction::MUL_INT_2ADDR:
2641 case Instruction::REM_INT_2ADDR:
2642 case Instruction::SHL_INT_2ADDR:
2643 case Instruction::SHR_INT_2ADDR:
2644 case Instruction::USHR_INT_2ADDR:
Ian Rogersd81871c2011-10-03 13:57:23 -07002645 work_line_->CheckBinaryOp2addr(dec_insn, reg_types_.Integer(), reg_types_.Integer(), reg_types_.Integer(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002646 break;
2647 case Instruction::AND_INT_2ADDR:
2648 case Instruction::OR_INT_2ADDR:
2649 case Instruction::XOR_INT_2ADDR:
Ian Rogersd81871c2011-10-03 13:57:23 -07002650 work_line_->CheckBinaryOp2addr(dec_insn, reg_types_.Integer(), reg_types_.Integer(), reg_types_.Integer(), true);
jeffhaobdb76512011-09-07 11:43:16 -07002651 break;
2652 case Instruction::DIV_INT_2ADDR:
Ian Rogersd81871c2011-10-03 13:57:23 -07002653 work_line_->CheckBinaryOp2addr(dec_insn, reg_types_.Integer(), reg_types_.Integer(), reg_types_.Integer(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002654 break;
2655 case Instruction::ADD_LONG_2ADDR:
2656 case Instruction::SUB_LONG_2ADDR:
2657 case Instruction::MUL_LONG_2ADDR:
2658 case Instruction::DIV_LONG_2ADDR:
2659 case Instruction::REM_LONG_2ADDR:
2660 case Instruction::AND_LONG_2ADDR:
2661 case Instruction::OR_LONG_2ADDR:
2662 case Instruction::XOR_LONG_2ADDR:
Ian Rogersd81871c2011-10-03 13:57:23 -07002663 work_line_->CheckBinaryOp2addr(dec_insn, reg_types_.Long(), reg_types_.Long(), reg_types_.Long(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002664 break;
2665 case Instruction::SHL_LONG_2ADDR:
2666 case Instruction::SHR_LONG_2ADDR:
2667 case Instruction::USHR_LONG_2ADDR:
Ian Rogersd81871c2011-10-03 13:57:23 -07002668 work_line_->CheckBinaryOp2addr(dec_insn, reg_types_.Long(), reg_types_.Long(), reg_types_.Integer(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002669 break;
2670 case Instruction::ADD_FLOAT_2ADDR:
2671 case Instruction::SUB_FLOAT_2ADDR:
2672 case Instruction::MUL_FLOAT_2ADDR:
2673 case Instruction::DIV_FLOAT_2ADDR:
2674 case Instruction::REM_FLOAT_2ADDR:
Ian Rogersd81871c2011-10-03 13:57:23 -07002675 work_line_->CheckBinaryOp2addr(dec_insn, reg_types_.Float(), reg_types_.Float(), reg_types_.Float(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002676 break;
2677 case Instruction::ADD_DOUBLE_2ADDR:
2678 case Instruction::SUB_DOUBLE_2ADDR:
2679 case Instruction::MUL_DOUBLE_2ADDR:
2680 case Instruction::DIV_DOUBLE_2ADDR:
2681 case Instruction::REM_DOUBLE_2ADDR:
Ian Rogersd81871c2011-10-03 13:57:23 -07002682 work_line_->CheckBinaryOp2addr(dec_insn, reg_types_.Double(), reg_types_.Double(), reg_types_.Double(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002683 break;
2684 case Instruction::ADD_INT_LIT16:
2685 case Instruction::RSUB_INT:
2686 case Instruction::MUL_INT_LIT16:
2687 case Instruction::DIV_INT_LIT16:
2688 case Instruction::REM_INT_LIT16:
Ian Rogersd81871c2011-10-03 13:57:23 -07002689 work_line_->CheckLiteralOp(dec_insn, reg_types_.Integer(), reg_types_.Integer(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002690 break;
2691 case Instruction::AND_INT_LIT16:
2692 case Instruction::OR_INT_LIT16:
2693 case Instruction::XOR_INT_LIT16:
Ian Rogersd81871c2011-10-03 13:57:23 -07002694 work_line_->CheckLiteralOp(dec_insn, reg_types_.Integer(), reg_types_.Integer(), true);
jeffhaobdb76512011-09-07 11:43:16 -07002695 break;
2696 case Instruction::ADD_INT_LIT8:
2697 case Instruction::RSUB_INT_LIT8:
2698 case Instruction::MUL_INT_LIT8:
2699 case Instruction::DIV_INT_LIT8:
2700 case Instruction::REM_INT_LIT8:
2701 case Instruction::SHL_INT_LIT8:
jeffhaobdb76512011-09-07 11:43:16 -07002702 case Instruction::SHR_INT_LIT8:
jeffhaobdb76512011-09-07 11:43:16 -07002703 case Instruction::USHR_INT_LIT8:
Ian Rogersd81871c2011-10-03 13:57:23 -07002704 work_line_->CheckLiteralOp(dec_insn, reg_types_.Integer(), reg_types_.Integer(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002705 break;
2706 case Instruction::AND_INT_LIT8:
2707 case Instruction::OR_INT_LIT8:
2708 case Instruction::XOR_INT_LIT8:
Ian Rogersd81871c2011-10-03 13:57:23 -07002709 work_line_->CheckLiteralOp(dec_insn, reg_types_.Integer(), reg_types_.Integer(), true);
jeffhaobdb76512011-09-07 11:43:16 -07002710 break;
2711
2712 /*
2713 * This falls into the general category of "optimized" instructions,
jeffhaod1f0fde2011-09-08 17:25:33 -07002714 * which don't generally appear during verification. Because it's
jeffhaobdb76512011-09-07 11:43:16 -07002715 * inserted in the course of verification, we can expect to see it here.
2716 */
jeffhaob4df5142011-09-19 20:25:32 -07002717 case Instruction::THROW_VERIFICATION_ERROR:
jeffhaobdb76512011-09-07 11:43:16 -07002718 break;
2719
Ian Rogersd81871c2011-10-03 13:57:23 -07002720 /* These should never appear during verification. */
jeffhaobdb76512011-09-07 11:43:16 -07002721 case Instruction::UNUSED_EE:
2722 case Instruction::UNUSED_EF:
2723 case Instruction::UNUSED_F2:
2724 case Instruction::UNUSED_F3:
2725 case Instruction::UNUSED_F4:
2726 case Instruction::UNUSED_F5:
2727 case Instruction::UNUSED_F6:
2728 case Instruction::UNUSED_F7:
2729 case Instruction::UNUSED_F8:
2730 case Instruction::UNUSED_F9:
2731 case Instruction::UNUSED_FA:
2732 case Instruction::UNUSED_FB:
jeffhaobdb76512011-09-07 11:43:16 -07002733 case Instruction::UNUSED_F0:
2734 case Instruction::UNUSED_F1:
2735 case Instruction::UNUSED_E3:
2736 case Instruction::UNUSED_E8:
2737 case Instruction::UNUSED_E7:
2738 case Instruction::UNUSED_E4:
2739 case Instruction::UNUSED_E9:
2740 case Instruction::UNUSED_FC:
2741 case Instruction::UNUSED_E5:
2742 case Instruction::UNUSED_EA:
2743 case Instruction::UNUSED_FD:
2744 case Instruction::UNUSED_E6:
2745 case Instruction::UNUSED_EB:
2746 case Instruction::UNUSED_FE:
jeffhaobdb76512011-09-07 11:43:16 -07002747 case Instruction::UNUSED_3E:
2748 case Instruction::UNUSED_3F:
2749 case Instruction::UNUSED_40:
2750 case Instruction::UNUSED_41:
2751 case Instruction::UNUSED_42:
2752 case Instruction::UNUSED_43:
2753 case Instruction::UNUSED_73:
2754 case Instruction::UNUSED_79:
2755 case Instruction::UNUSED_7A:
2756 case Instruction::UNUSED_EC:
2757 case Instruction::UNUSED_FF:
Ian Rogers2c8a8572011-10-24 17:11:36 -07002758 Fail(VERIFY_ERROR_GENERIC) << "Unexpected opcode " << inst->DumpString(dex_file_);
jeffhaobdb76512011-09-07 11:43:16 -07002759 break;
2760
2761 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07002762 * DO NOT add a "default" clause here. Without it the compiler will
jeffhaobdb76512011-09-07 11:43:16 -07002763 * complain if an instruction is missing (which is desirable).
2764 */
Ian Rogersd81871c2011-10-03 13:57:23 -07002765 } // end - switch (dec_insn.opcode_)
jeffhaobdb76512011-09-07 11:43:16 -07002766
Ian Rogersd81871c2011-10-03 13:57:23 -07002767 if (failure_ != VERIFY_ERROR_NONE) {
2768 if (failure_ == VERIFY_ERROR_GENERIC) {
jeffhaobdb76512011-09-07 11:43:16 -07002769 /* immediate failure, reject class */
Ian Rogers2c8a8572011-10-24 17:11:36 -07002770 fail_messages_ << std::endl << "Rejecting opcode " << inst->DumpString(dex_file_);
jeffhaobdb76512011-09-07 11:43:16 -07002771 return false;
2772 } else {
2773 /* replace opcode and continue on */
Ian Rogers2c8a8572011-10-24 17:11:36 -07002774 fail_messages_ << std::endl << "Replacing opcode " << inst->DumpString(dex_file_);
Ian Rogersd81871c2011-10-03 13:57:23 -07002775 ReplaceFailingInstruction();
jeffhaobdb76512011-09-07 11:43:16 -07002776 /* IMPORTANT: method->insns may have been changed */
Ian Rogersd81871c2011-10-03 13:57:23 -07002777 insns = code_item_->insns_ + work_insn_idx_;
jeffhaobdb76512011-09-07 11:43:16 -07002778 /* continue on as if we just handled a throw-verification-error */
Ian Rogersd81871c2011-10-03 13:57:23 -07002779 failure_ = VERIFY_ERROR_NONE;
jeffhaobdb76512011-09-07 11:43:16 -07002780 opcode_flag = Instruction::kThrow;
2781 }
2782 }
jeffhaobdb76512011-09-07 11:43:16 -07002783 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07002784 * If we didn't just set the result register, clear it out. This ensures that you can only use
2785 * "move-result" immediately after the result is set. (We could check this statically, but it's
2786 * not expensive and it makes our debugging output cleaner.)
jeffhaobdb76512011-09-07 11:43:16 -07002787 */
2788 if (!just_set_result) {
Ian Rogersd81871c2011-10-03 13:57:23 -07002789 work_line_->SetResultTypeToUnknown();
jeffhaobdb76512011-09-07 11:43:16 -07002790 }
2791
jeffhaoa0a764a2011-09-16 10:43:38 -07002792 /* Handle "continue". Tag the next consecutive instruction. */
jeffhaobdb76512011-09-07 11:43:16 -07002793 if ((opcode_flag & Instruction::kContinue) != 0) {
Ian Rogersd81871c2011-10-03 13:57:23 -07002794 uint32_t next_insn_idx = work_insn_idx_ + CurrentInsnFlags().GetLengthInCodeUnits();
2795 if (next_insn_idx >= code_item_->insns_size_in_code_units_) {
2796 Fail(VERIFY_ERROR_GENERIC) << "Execution can walk off end of code area";
jeffhaobdb76512011-09-07 11:43:16 -07002797 return false;
2798 }
Ian Rogersd81871c2011-10-03 13:57:23 -07002799 // The only way to get to a move-exception instruction is to get thrown there. Make sure the
2800 // next instruction isn't one.
2801 if (!CheckMoveException(code_item_->insns_, next_insn_idx)) {
jeffhaobdb76512011-09-07 11:43:16 -07002802 return false;
Ian Rogersd81871c2011-10-03 13:57:23 -07002803 }
2804 RegisterLine* next_line = reg_table_.GetLine(next_insn_idx);
2805 if (next_line != NULL) {
2806 // Merge registers into what we have for the next instruction, and set the "changed" flag if
2807 // needed.
2808 if (!UpdateRegisters(next_insn_idx, work_line_.get())) {
jeffhaobdb76512011-09-07 11:43:16 -07002809 return false;
Ian Rogersd81871c2011-10-03 13:57:23 -07002810 }
jeffhaobdb76512011-09-07 11:43:16 -07002811 } else {
2812 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07002813 * We're not recording register data for the next instruction, so we don't know what the prior
2814 * state was. We have to assume that something has changed and re-evaluate it.
jeffhaobdb76512011-09-07 11:43:16 -07002815 */
Ian Rogersd81871c2011-10-03 13:57:23 -07002816 insn_flags_[next_insn_idx].SetChanged();
jeffhaobdb76512011-09-07 11:43:16 -07002817 }
2818 }
2819
2820 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07002821 * Handle "branch". Tag the branch target.
jeffhaobdb76512011-09-07 11:43:16 -07002822 *
2823 * NOTE: instructions like Instruction::EQZ provide information about the
jeffhaod1f0fde2011-09-08 17:25:33 -07002824 * state of the register when the branch is taken or not taken. For example,
jeffhaobdb76512011-09-07 11:43:16 -07002825 * somebody could get a reference field, check it for zero, and if the
2826 * branch is taken immediately store that register in a boolean field
jeffhaod1f0fde2011-09-08 17:25:33 -07002827 * since the value is known to be zero. We do not currently account for
jeffhaobdb76512011-09-07 11:43:16 -07002828 * that, and will reject the code.
2829 *
2830 * TODO: avoid re-fetching the branch target
2831 */
2832 if ((opcode_flag & Instruction::kBranch) != 0) {
2833 bool isConditional, selfOkay;
Ian Rogersd81871c2011-10-03 13:57:23 -07002834 if (!GetBranchOffset(work_insn_idx_, &branch_target, &isConditional, &selfOkay)) {
jeffhaobdb76512011-09-07 11:43:16 -07002835 /* should never happen after static verification */
Ian Rogersd81871c2011-10-03 13:57:23 -07002836 Fail(VERIFY_ERROR_GENERIC) << "bad branch";
jeffhaobdb76512011-09-07 11:43:16 -07002837 return false;
2838 }
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002839 DCHECK_EQ(isConditional, (opcode_flag & Instruction::kContinue) != 0);
Ian Rogersd81871c2011-10-03 13:57:23 -07002840 if (!CheckMoveException(code_item_->insns_, work_insn_idx_ + branch_target)) {
jeffhaobdb76512011-09-07 11:43:16 -07002841 return false;
Ian Rogersd81871c2011-10-03 13:57:23 -07002842 }
jeffhaobdb76512011-09-07 11:43:16 -07002843 /* update branch target, set "changed" if appropriate */
Ian Rogersd81871c2011-10-03 13:57:23 -07002844 if (!UpdateRegisters(work_insn_idx_ + branch_target, work_line_.get())) {
jeffhaobdb76512011-09-07 11:43:16 -07002845 return false;
Ian Rogersd81871c2011-10-03 13:57:23 -07002846 }
jeffhaobdb76512011-09-07 11:43:16 -07002847 }
2848
2849 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07002850 * Handle "switch". Tag all possible branch targets.
jeffhaobdb76512011-09-07 11:43:16 -07002851 *
2852 * We've already verified that the table is structurally sound, so we
2853 * just need to walk through and tag the targets.
2854 */
2855 if ((opcode_flag & Instruction::kSwitch) != 0) {
2856 int offset_to_switch = insns[1] | (((int32_t) insns[2]) << 16);
2857 const uint16_t* switch_insns = insns + offset_to_switch;
2858 int switch_count = switch_insns[1];
2859 int offset_to_targets, targ;
2860
2861 if ((*insns & 0xff) == Instruction::PACKED_SWITCH) {
2862 /* 0 = sig, 1 = count, 2/3 = first key */
2863 offset_to_targets = 4;
2864 } else {
2865 /* 0 = sig, 1 = count, 2..count * 2 = keys */
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002866 DCHECK((*insns & 0xff) == Instruction::SPARSE_SWITCH);
jeffhaobdb76512011-09-07 11:43:16 -07002867 offset_to_targets = 2 + 2 * switch_count;
2868 }
2869
2870 /* verify each switch target */
2871 for (targ = 0; targ < switch_count; targ++) {
2872 int offset;
2873 uint32_t abs_offset;
2874
2875 /* offsets are 32-bit, and only partly endian-swapped */
2876 offset = switch_insns[offset_to_targets + targ * 2] |
2877 (((int32_t) switch_insns[offset_to_targets + targ * 2 + 1]) << 16);
Ian Rogersd81871c2011-10-03 13:57:23 -07002878 abs_offset = work_insn_idx_ + offset;
2879 DCHECK_LT(abs_offset, code_item_->insns_size_in_code_units_);
2880 if (!CheckMoveException(code_item_->insns_, abs_offset)) {
jeffhaobdb76512011-09-07 11:43:16 -07002881 return false;
Ian Rogersd81871c2011-10-03 13:57:23 -07002882 }
2883 if (!UpdateRegisters(abs_offset, work_line_.get()))
jeffhaobdb76512011-09-07 11:43:16 -07002884 return false;
2885 }
2886 }
2887
2888 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07002889 * Handle instructions that can throw and that are sitting in a "try" block. (If they're not in a
2890 * "try" block when they throw, control transfers out of the method.)
jeffhaobdb76512011-09-07 11:43:16 -07002891 */
Ian Rogersd81871c2011-10-03 13:57:23 -07002892 if ((opcode_flag & Instruction::kThrow) != 0 && insn_flags_[work_insn_idx_].IsInTry()) {
2893 bool within_catch_all = false;
2894 DexFile::CatchHandlerIterator iterator =
2895 DexFile::dexFindCatchHandler(*code_item_, work_insn_idx_);
jeffhaobdb76512011-09-07 11:43:16 -07002896
2897 for (; !iterator.HasNext(); iterator.Next()) {
Ian Rogersd81871c2011-10-03 13:57:23 -07002898 if (iterator.Get().type_idx_ == DexFile::kDexNoIndex) {
2899 within_catch_all = true;
2900 }
jeffhaobdb76512011-09-07 11:43:16 -07002901 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07002902 * Merge registers into the "catch" block. We want to use the "savedRegs" rather than
2903 * "work_regs", because at runtime the exception will be thrown before the instruction
2904 * modifies any registers.
jeffhaobdb76512011-09-07 11:43:16 -07002905 */
Ian Rogersd81871c2011-10-03 13:57:23 -07002906 if (!UpdateRegisters(iterator.Get().address_, saved_line_.get())) {
jeffhaobdb76512011-09-07 11:43:16 -07002907 return false;
Ian Rogersd81871c2011-10-03 13:57:23 -07002908 }
jeffhaobdb76512011-09-07 11:43:16 -07002909 }
2910
2911 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07002912 * If the monitor stack depth is nonzero, there must be a "catch all" handler for this
2913 * instruction. This does apply to monitor-exit because of async exception handling.
jeffhaobdb76512011-09-07 11:43:16 -07002914 */
Ian Rogersd81871c2011-10-03 13:57:23 -07002915 if (work_line_->MonitorStackDepth() > 0 && !within_catch_all) {
jeffhaobdb76512011-09-07 11:43:16 -07002916 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07002917 * The state in work_line reflects the post-execution state. If the current instruction is a
2918 * monitor-enter and the monitor stack was empty, we don't need a catch-all (if it throws,
jeffhaobdb76512011-09-07 11:43:16 -07002919 * it will do so before grabbing the lock).
2920 */
Ian Rogersd81871c2011-10-03 13:57:23 -07002921 if (dec_insn.opcode_ != Instruction::MONITOR_ENTER || work_line_->MonitorStackDepth() != 1) {
2922 Fail(VERIFY_ERROR_GENERIC)
2923 << "expected to be within a catch-all for an instruction where a monitor is held";
jeffhaobdb76512011-09-07 11:43:16 -07002924 return false;
2925 }
2926 }
2927 }
2928
jeffhaod1f0fde2011-09-08 17:25:33 -07002929 /* If we're returning from the method, make sure monitor stack is empty. */
Ian Rogersd81871c2011-10-03 13:57:23 -07002930 if ((opcode_flag & Instruction::kReturn) != 0) {
2931 if(!work_line_->VerifyMonitorStackEmpty()) {
2932 return false;
2933 }
jeffhaobdb76512011-09-07 11:43:16 -07002934 }
2935
2936 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07002937 * Update start_guess. Advance to the next instruction of that's
2938 * possible, otherwise use the branch target if one was found. If
jeffhaobdb76512011-09-07 11:43:16 -07002939 * neither of those exists we're in a return or throw; leave start_guess
2940 * alone and let the caller sort it out.
2941 */
2942 if ((opcode_flag & Instruction::kContinue) != 0) {
Ian Rogersd81871c2011-10-03 13:57:23 -07002943 *start_guess = work_insn_idx_ + insn_flags_[work_insn_idx_].GetLengthInCodeUnits();
jeffhaobdb76512011-09-07 11:43:16 -07002944 } else if ((opcode_flag & Instruction::kBranch) != 0) {
2945 /* we're still okay if branch_target is zero */
Ian Rogersd81871c2011-10-03 13:57:23 -07002946 *start_guess = work_insn_idx_ + branch_target;
jeffhaobdb76512011-09-07 11:43:16 -07002947 }
2948
Ian Rogersd81871c2011-10-03 13:57:23 -07002949 DCHECK_LT(*start_guess, code_item_->insns_size_in_code_units_);
2950 DCHECK(insn_flags_[*start_guess].IsOpcode());
jeffhaobdb76512011-09-07 11:43:16 -07002951
2952 return true;
2953}
2954
Ian Rogers28ad40d2011-10-27 15:19:26 -07002955const RegType& DexVerifier::ResolveClassAndCheckAccess(uint32_t class_idx) {
2956 const char* descriptor = dex_file_->dexStringByTypeIdx(class_idx);
2957 Class* referrer = method_->GetDeclaringClass();
2958 Class* klass = method_->GetDexCacheResolvedTypes()->Get(class_idx);
2959 const RegType& result =
2960 klass != NULL ? reg_types_.FromClass(klass)
2961 : reg_types_.FromDescriptor(referrer->GetClassLoader(), descriptor);
2962 if (klass == NULL && !result.IsUnresolvedTypes()) {
2963 method_->GetDexCacheResolvedTypes()->Set(class_idx, result.GetClass());
Ian Rogersd81871c2011-10-03 13:57:23 -07002964 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07002965 // Check if access is allowed. Unresolved types use AllocObjectFromCodeWithAccessCheck to
2966 // check at runtime if access is allowed and so pass here.
2967 if (!result.IsUnresolvedTypes() && !referrer->CanAccess(result.GetClass())) {
2968 Fail(VERIFY_ERROR_ACCESS_CLASS) << "illegal class access: '"
2969 << PrettyDescriptor(referrer->GetDescriptor()) << "' -> '"
2970 << result << "'";
2971 return reg_types_.Unknown();
2972 } else {
2973 return result;
2974 }
Ian Rogersd81871c2011-10-03 13:57:23 -07002975}
2976
Ian Rogers28ad40d2011-10-27 15:19:26 -07002977const RegType& DexVerifier::GetCaughtExceptionType() {
2978 const RegType* common_super = NULL;
Ian Rogersd81871c2011-10-03 13:57:23 -07002979 if (code_item_->tries_size_ != 0) {
2980 const byte* handlers_ptr = DexFile::dexGetCatchHandlerData(*code_item_, 0);
2981 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
2982 for (uint32_t i = 0; i < handlers_size; i++) {
2983 DexFile::CatchHandlerIterator iterator(handlers_ptr);
2984 for (; !iterator.HasNext(); iterator.Next()) {
2985 DexFile::CatchHandlerItem handler = iterator.Get();
2986 if (handler.address_ == (uint32_t) work_insn_idx_) {
2987 if (handler.type_idx_ == DexFile::kDexNoIndex) {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002988 common_super = &reg_types_.JavaLangThrowable();
Ian Rogersd81871c2011-10-03 13:57:23 -07002989 } else {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002990 const RegType& exception = ResolveClassAndCheckAccess(handler.type_idx_);
Ian Rogersd81871c2011-10-03 13:57:23 -07002991 /* TODO: on error do we want to keep going? If we don't fail this we run the risk of
2992 * having a non-Throwable introduced at runtime. However, that won't pass an instanceof
2993 * test, so is essentially harmless.
2994 */
Ian Rogers28ad40d2011-10-27 15:19:26 -07002995 if(!reg_types_.JavaLangThrowable().IsAssignableFrom(exception)) {
2996 Fail(VERIFY_ERROR_GENERIC) << "unexpected non-exception class " << exception;
2997 return reg_types_.Unknown();
Ian Rogersd81871c2011-10-03 13:57:23 -07002998 } else if (common_super == NULL) {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002999 common_super = &exception;
3000 } else if (common_super->Equals(exception)) {
3001 // nothing to do
Ian Rogersd81871c2011-10-03 13:57:23 -07003002 } else {
Ian Rogers28ad40d2011-10-27 15:19:26 -07003003 common_super = &common_super->Merge(exception, &reg_types_);
3004 CHECK(reg_types_.JavaLangThrowable().IsAssignableFrom(*common_super));
Ian Rogersd81871c2011-10-03 13:57:23 -07003005 }
3006 }
3007 }
3008 }
3009 handlers_ptr = iterator.GetData();
3010 }
3011 }
3012 if (common_super == NULL) {
3013 /* no catch blocks, or no catches with classes we can find */
3014 Fail(VERIFY_ERROR_GENERIC) << "unable to find exception handler";
3015 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07003016 return *common_super;
Ian Rogersd81871c2011-10-03 13:57:23 -07003017}
3018
3019Method* DexVerifier::ResolveMethodAndCheckAccess(uint32_t method_idx, bool is_direct) {
3020 Class* referrer = method_->GetDeclaringClass();
3021 DexCache* dex_cache = referrer->GetDexCache();
3022 Method* res_method = dex_cache->GetResolvedMethod(method_idx);
3023 if (res_method == NULL) {
3024 const DexFile::MethodId& method_id = dex_file_->GetMethodId(method_idx);
Ian Rogers28ad40d2011-10-27 15:19:26 -07003025 const RegType& klass_type = ResolveClassAndCheckAccess(method_id.class_idx_);
3026 if(klass_type.IsUnresolvedTypes()) {
3027 return NULL; // Can't resolve Class so no more to do here
Ian Rogersd81871c2011-10-03 13:57:23 -07003028 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07003029 Class* klass = klass_type.GetClass();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003030 const char* name = dex_file_->GetMethodName(method_id);
Ian Rogersd81871c2011-10-03 13:57:23 -07003031 std::string signature(dex_file_->CreateMethodDescriptor(method_id.proto_idx_, NULL));
3032 if (is_direct) {
3033 res_method = klass->FindDirectMethod(name, signature);
3034 } else if (klass->IsInterface()) {
3035 res_method = klass->FindInterfaceMethod(name, signature);
3036 } else {
3037 res_method = klass->FindVirtualMethod(name, signature);
3038 }
3039 if (res_method != NULL) {
3040 dex_cache->SetResolvedMethod(method_idx, res_method);
3041 } else {
3042 Fail(VERIFY_ERROR_NO_METHOD) << "couldn't find method "
3043 << PrettyDescriptor(klass->GetDescriptor()) << "." << name
3044 << " " << signature;
3045 return NULL;
3046 }
3047 }
3048 /* Check if access is allowed. */
3049 if (!referrer->CanAccessMember(res_method->GetDeclaringClass(), res_method->GetAccessFlags())) {
3050 Fail(VERIFY_ERROR_ACCESS_METHOD) << "illegal method access (call " << PrettyMethod(res_method)
3051 << " from " << PrettyDescriptor(referrer->GetDescriptor()) << ")";
3052 return NULL;
3053 }
3054 return res_method;
3055}
3056
3057Method* DexVerifier::VerifyInvocationArgs(const Instruction::DecodedInstruction& dec_insn,
3058 MethodType method_type, bool is_range, bool is_super) {
3059 // Resolve the method. This could be an abstract or concrete method depending on what sort of call
3060 // we're making.
3061 Method* res_method = ResolveMethodAndCheckAccess(dec_insn.vB_,
3062 (method_type == METHOD_DIRECT || method_type == METHOD_STATIC));
Ian Rogers28ad40d2011-10-27 15:19:26 -07003063 if (res_method == NULL) { // error or class is unresolved
Ian Rogersd81871c2011-10-03 13:57:23 -07003064 return NULL;
3065 }
3066 // Make sure calls to constructors are "direct". There are additional restrictions but we don't
3067 // enforce them here.
3068 if (res_method->IsConstructor() && method_type != METHOD_DIRECT) {
3069 Fail(VERIFY_ERROR_GENERIC) << "rejecting non-direct call to constructor "
3070 << PrettyMethod(res_method);
3071 return NULL;
3072 }
3073 // See if the method type implied by the invoke instruction matches the access flags for the
3074 // target method.
3075 if ((method_type == METHOD_DIRECT && !res_method->IsDirect()) ||
3076 (method_type == METHOD_STATIC && !res_method->IsStatic()) ||
3077 ((method_type == METHOD_VIRTUAL || method_type == METHOD_INTERFACE) && res_method->IsDirect())
3078 ) {
3079 Fail(VERIFY_ERROR_GENERIC) << "invoke type does not match method type of "
3080 << PrettyMethod(res_method);
3081 return NULL;
3082 }
3083 // If we're using invoke-super(method), make sure that the executing method's class' superclass
3084 // has a vtable entry for the target method.
3085 if (is_super) {
3086 DCHECK(method_type == METHOD_VIRTUAL);
3087 Class* super = method_->GetDeclaringClass()->GetSuperClass();
3088 if (super == NULL || res_method->GetMethodIndex() > super->GetVTable()->GetLength()) {
3089 if (super == NULL) { // Only Object has no super class
3090 Fail(VERIFY_ERROR_NO_METHOD) << "invalid invoke-super from " << PrettyMethod(method_)
3091 << " to super " << PrettyMethod(res_method);
3092 } else {
3093 Fail(VERIFY_ERROR_NO_METHOD) << "invalid invoke-super from " << PrettyMethod(method_)
3094 << " to super " << PrettyDescriptor(super->GetDescriptor())
3095 << "." << res_method->GetName()->ToModifiedUtf8()
3096 << " " << res_method->GetSignature()->ToModifiedUtf8();
3097
3098 }
3099 return NULL;
3100 }
3101 }
3102 // We use vAA as our expected arg count, rather than res_method->insSize, because we need to
3103 // match the call to the signature. Also, we might might be calling through an abstract method
3104 // definition (which doesn't have register count values).
3105 int expected_args = dec_insn.vA_;
3106 /* caught by static verifier */
3107 DCHECK(is_range || expected_args <= 5);
3108 if (expected_args > code_item_->outs_size_) {
3109 Fail(VERIFY_ERROR_GENERIC) << "invalid arg count (" << expected_args
3110 << ") exceeds outsSize (" << code_item_->outs_size_ << ")";
3111 return NULL;
3112 }
3113 std::string sig = res_method->GetSignature()->ToModifiedUtf8();
3114 if (sig[0] != '(') {
3115 Fail(VERIFY_ERROR_GENERIC) << "rejecting call to " << res_method
3116 << " as descriptor doesn't start with '(': " << sig;
3117 return NULL;
3118 }
jeffhaobdb76512011-09-07 11:43:16 -07003119 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07003120 * Check the "this" argument, which must be an instance of the class
3121 * that declared the method. For an interface class, we don't do the
3122 * full interface merge, so we can't do a rigorous check here (which
3123 * is okay since we have to do it at runtime).
jeffhaobdb76512011-09-07 11:43:16 -07003124 */
Ian Rogersd81871c2011-10-03 13:57:23 -07003125 int actual_args = 0;
3126 if (!res_method->IsStatic()) {
3127 const RegType& actual_arg_type = work_line_->GetInvocationThis(dec_insn);
3128 if (failure_ != VERIFY_ERROR_NONE) {
3129 return NULL;
3130 }
3131 if (actual_arg_type.IsUninitializedReference() && !res_method->IsConstructor()) {
3132 Fail(VERIFY_ERROR_GENERIC) << "'this' arg must be initialized";
3133 return NULL;
3134 }
3135 if (method_type != METHOD_INTERFACE && !actual_arg_type.IsZero()) {
Ian Rogers9074b992011-10-26 17:41:55 -07003136 const RegType& res_method_class = reg_types_.FromClass(res_method->GetDeclaringClass());
3137 if (!res_method_class.IsAssignableFrom(actual_arg_type)) {
3138 Fail(VERIFY_ERROR_GENERIC) << "'this' arg '" << actual_arg_type << "' not instance of '"
3139 << res_method_class << "'";
Ian Rogersd81871c2011-10-03 13:57:23 -07003140 return NULL;
3141 }
3142 }
3143 actual_args++;
3144 }
3145 /*
3146 * Process the target method's signature. This signature may or may not
3147 * have been verified, so we can't assume it's properly formed.
3148 */
3149 size_t sig_offset = 0;
3150 for (sig_offset = 1; sig_offset < sig.size() && sig[sig_offset] != ')'; sig_offset++) {
3151 if (actual_args >= expected_args) {
3152 Fail(VERIFY_ERROR_GENERIC) << "Rejecting invalid call to '" << PrettyMethod(res_method)
3153 << "'. Expected " << expected_args << " args, found more ("
3154 << sig.substr(sig_offset) << ")";
3155 return NULL;
3156 }
3157 std::string descriptor;
3158 if ((sig[sig_offset] == 'L') || (sig[sig_offset] == '[')) {
3159 size_t end;
3160 if (sig[sig_offset] == 'L') {
3161 end = sig.find(';', sig_offset);
3162 } else {
3163 for(end = sig_offset + 1; sig[end] == '['; end++) ;
3164 if (sig[end] == 'L') {
3165 end = sig.find(';', end);
3166 }
3167 }
3168 if (end == std::string::npos) {
3169 Fail(VERIFY_ERROR_GENERIC) << "Rejecting invocation of " << PrettyMethod(res_method)
3170 << "bad signature component '" << sig << "' (missing ';')";
3171 return NULL;
3172 }
3173 descriptor = sig.substr(sig_offset, end - sig_offset + 1);
3174 sig_offset = end;
3175 } else {
3176 descriptor = sig[sig_offset];
3177 }
3178 const RegType& reg_type =
3179 reg_types_.FromDescriptor(method_->GetDeclaringClass()->GetClassLoader(), descriptor);
Ian Rogers84fa0742011-10-25 18:13:30 -07003180 uint32_t get_reg = is_range ? dec_insn.vC_ + actual_args : dec_insn.arg_[actual_args];
3181 if (!work_line_->VerifyRegisterType(get_reg, reg_type)) {
3182 return NULL;
Ian Rogersd81871c2011-10-03 13:57:23 -07003183 }
3184 actual_args = reg_type.IsLongOrDoubleTypes() ? actual_args + 2 : actual_args + 1;
3185 }
3186 if (sig[sig_offset] != ')') {
3187 Fail(VERIFY_ERROR_GENERIC) << "invocation target: bad signature" << PrettyMethod(res_method);
3188 return NULL;
3189 }
3190 if (actual_args != expected_args) {
3191 Fail(VERIFY_ERROR_GENERIC) << "Rejecting invocation of " << PrettyMethod(res_method)
3192 << " expected " << expected_args << " args, found " << actual_args;
3193 return NULL;
3194 } else {
3195 return res_method;
3196 }
3197}
3198
3199void DexVerifier::VerifyAGet(const Instruction::DecodedInstruction& dec_insn,
3200 const RegType& insn_type, bool is_primitive) {
3201 const RegType& index_type = work_line_->GetRegisterType(dec_insn.vC_);
3202 if (!index_type.IsArrayIndexTypes()) {
3203 Fail(VERIFY_ERROR_GENERIC) << "Invalid reg type for array index (" << index_type << ")";
3204 } else {
3205 Class* array_class = work_line_->GetClassFromRegister(dec_insn.vB_);
3206 if (failure_ == VERIFY_ERROR_NONE) {
3207 if (array_class == NULL) {
3208 // Null array class; this code path will fail at runtime. Infer a merge-able type from the
3209 // instruction type. TODO: have a proper notion of bottom here.
3210 if (!is_primitive || insn_type.IsCategory1Types()) {
3211 // Reference or category 1
3212 work_line_->SetRegisterType(dec_insn.vA_, reg_types_.Zero());
3213 } else {
3214 // Category 2
3215 work_line_->SetRegisterType(dec_insn.vA_, reg_types_.ConstLo());
3216 }
3217 } else {
3218 /* verify the class */
3219 Class* component_class = array_class->GetComponentType();
3220 const RegType& component_type = reg_types_.FromClass(component_class);
3221 if (!array_class->IsArrayClass()) {
3222 Fail(VERIFY_ERROR_GENERIC) << "not array type "
3223 << PrettyDescriptor(array_class->GetDescriptor()) << " with aget";
3224 } else if (component_class->IsPrimitive() && !is_primitive) {
3225 Fail(VERIFY_ERROR_GENERIC) << "primitive array type "
3226 << PrettyDescriptor(array_class->GetDescriptor())
3227 << " source for aget-object";
3228 } else if (!component_class->IsPrimitive() && is_primitive) {
3229 Fail(VERIFY_ERROR_GENERIC) << "reference array type "
3230 << PrettyDescriptor(array_class->GetDescriptor())
3231 << " source for category 1 aget";
3232 } else if (is_primitive && !insn_type.Equals(component_type) &&
3233 !((insn_type.IsInteger() && component_type.IsFloat()) ||
3234 (insn_type.IsLong() && component_type.IsDouble()))) {
3235 Fail(VERIFY_ERROR_GENERIC) << "array type "
3236 << PrettyDescriptor(array_class->GetDescriptor())
3237 << " incompatible with aget of type " << insn_type;
3238 } else {
3239 // Use knowledge of the field type which is stronger than the type inferred from the
3240 // instruction, which can't differentiate object types and ints from floats, longs from
3241 // doubles.
3242 work_line_->SetRegisterType(dec_insn.vA_, component_type);
3243 }
3244 }
3245 }
3246 }
3247}
3248
3249void DexVerifier::VerifyAPut(const Instruction::DecodedInstruction& dec_insn,
3250 const RegType& insn_type, bool is_primitive) {
3251 const RegType& index_type = work_line_->GetRegisterType(dec_insn.vC_);
3252 if (!index_type.IsArrayIndexTypes()) {
3253 Fail(VERIFY_ERROR_GENERIC) << "Invalid reg type for array index (" << index_type << ")";
3254 } else {
3255 Class* array_class = work_line_->GetClassFromRegister(dec_insn.vB_);
3256 if (failure_ == VERIFY_ERROR_NONE) {
3257 if (array_class == NULL) {
3258 // Null array class; this code path will fail at runtime. Infer a merge-able type from the
3259 // instruction type.
3260 } else {
3261 /* verify the class */
3262 Class* component_class = array_class->GetComponentType();
3263 const RegType& component_type = reg_types_.FromClass(component_class);
3264 if (!array_class->IsArrayClass()) {
3265 Fail(VERIFY_ERROR_GENERIC) << "not array type "
3266 << PrettyDescriptor(array_class->GetDescriptor()) << " with aput";
3267 } else if (component_class->IsPrimitive() && !is_primitive) {
3268 Fail(VERIFY_ERROR_GENERIC) << "primitive array type "
3269 << PrettyDescriptor(array_class->GetDescriptor())
3270 << " source for aput-object";
3271 } else if (!component_class->IsPrimitive() && is_primitive) {
3272 Fail(VERIFY_ERROR_GENERIC) << "reference array type "
3273 << PrettyDescriptor(array_class->GetDescriptor())
3274 << " source for category 1 aput";
3275 } else if (is_primitive && !insn_type.Equals(component_type) &&
3276 !((insn_type.IsInteger() && component_type.IsFloat()) ||
3277 (insn_type.IsLong() && component_type.IsDouble()))) {
3278 Fail(VERIFY_ERROR_GENERIC) << "array type "
3279 << PrettyDescriptor(array_class->GetDescriptor())
3280 << " incompatible with aput of type " << insn_type;
3281 } else {
3282 // The instruction agrees with the type of array, confirm the value to be stored does too
3283 work_line_->VerifyRegisterType(dec_insn.vA_, component_type);
3284 }
3285 }
3286 }
3287 }
3288}
3289
3290Field* DexVerifier::GetStaticField(int field_idx) {
3291 Field* field = Runtime::Current()->GetClassLinker()->ResolveField(field_idx, method_, true);
3292 if (field == NULL) {
3293 const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx);
3294 Fail(VERIFY_ERROR_NO_FIELD) << "unable to resolve static field " << field_idx << " ("
3295 << dex_file_->GetFieldName(field_id) << ") in "
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003296 << dex_file_->GetFieldDeclaringClassDescriptor(field_id);
Ian Rogersd81871c2011-10-03 13:57:23 -07003297 DCHECK(Thread::Current()->IsExceptionPending());
3298 Thread::Current()->ClearException();
3299 return NULL;
3300 } else if (!method_->GetDeclaringClass()->CanAccessMember(field->GetDeclaringClass(),
3301 field->GetAccessFlags())) {
3302 Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot access static field " << PrettyField(field)
3303 << " from " << PrettyClass(method_->GetDeclaringClass());
3304 return NULL;
3305 } else if (!field->IsStatic()) {
3306 Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected field " << PrettyField(field) << " to be static";
3307 return NULL;
3308 } else {
3309 return field;
3310 }
3311}
3312
Ian Rogersd81871c2011-10-03 13:57:23 -07003313Field* DexVerifier::GetInstanceField(const RegType& obj_type, int field_idx) {
3314 Field* field = Runtime::Current()->GetClassLinker()->ResolveField(field_idx, method_, false);
3315 if (field == NULL) {
3316 const DexFile::FieldId& field_id = dex_file_->GetFieldId(field_idx);
3317 Fail(VERIFY_ERROR_NO_FIELD) << "unable to resolve instance field " << field_idx << " ("
3318 << dex_file_->GetFieldName(field_id) << ") in "
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003319 << dex_file_->GetFieldDeclaringClassDescriptor(field_id);
Ian Rogersd81871c2011-10-03 13:57:23 -07003320 DCHECK(Thread::Current()->IsExceptionPending());
3321 Thread::Current()->ClearException();
3322 return NULL;
3323 } else if (!method_->GetDeclaringClass()->CanAccessMember(field->GetDeclaringClass(),
3324 field->GetAccessFlags())) {
3325 Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot access instance field " << PrettyField(field)
3326 << " from " << PrettyClass(method_->GetDeclaringClass());
3327 return NULL;
3328 } else if (field->IsStatic()) {
3329 Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected field " << PrettyField(field)
3330 << " to not be static";
3331 return NULL;
3332 } else if (obj_type.IsZero()) {
3333 // Cannot infer and check type, however, access will cause null pointer exception
3334 return field;
3335 } else if(obj_type.IsUninitializedReference() &&
3336 (!method_->IsConstructor() || method_->GetDeclaringClass() != obj_type.GetClass() ||
3337 field->GetDeclaringClass() != method_->GetDeclaringClass())) {
3338 // Field accesses through uninitialized references are only allowable for constructors where
3339 // the field is declared in this class
3340 Fail(VERIFY_ERROR_GENERIC) << "cannot access instance field " << PrettyField(field)
3341 << " of a not fully initialized object within the context of "
3342 << PrettyMethod(method_);
3343 return NULL;
3344 } else if(!field->GetDeclaringClass()->IsAssignableFrom(obj_type.GetClass())) {
3345 // Trying to access C1.field1 using reference of type C2, which is neither C1 or a sub-class
3346 // of C1. For resolution to occur the declared class of the field must be compatible with
3347 // obj_type, we've discovered this wasn't so, so report the field didn't exist.
3348 Fail(VERIFY_ERROR_NO_FIELD) << "cannot access instance field " << PrettyField(field)
3349 << " from object of type " << PrettyClass(obj_type.GetClass());
3350 return NULL;
3351 } else {
3352 return field;
3353 }
3354}
3355
Ian Rogersb94a27b2011-10-26 00:33:41 -07003356void DexVerifier::VerifyISGet(const Instruction::DecodedInstruction& dec_insn,
3357 const RegType& insn_type, bool is_primitive, bool is_static) {
3358 Field* field;
3359 if (is_static) {
3360 field = GetStaticField(dec_insn.vB_);
3361 } else {
3362 const RegType& object_type = work_line_->GetRegisterType(dec_insn.vB_);
3363 field = GetInstanceField(object_type, dec_insn.vC_);
3364 }
Ian Rogersd81871c2011-10-03 13:57:23 -07003365 if (field != NULL) {
Ian Rogersb5e95b92011-10-25 23:28:55 -07003366 const RegType& field_type =
3367 reg_types_.FromDescriptor(field->GetDeclaringClass()->GetClassLoader(),
3368 field->GetTypeDescriptor());
Ian Rogersd81871c2011-10-03 13:57:23 -07003369 if (is_primitive) {
Ian Rogersb5e95b92011-10-25 23:28:55 -07003370 if (field_type.Equals(insn_type) ||
3371 (field_type.IsFloat() && insn_type.IsIntegralTypes()) ||
3372 (field_type.IsDouble() && insn_type.IsLongTypes())) {
Ian Rogersd81871c2011-10-03 13:57:23 -07003373 // expected that read is of the correct primitive type or that int reads are reading
3374 // floats or long reads are reading doubles
3375 } else {
3376 // This is a global failure rather than a class change failure as the instructions and
3377 // the descriptors for the type should have been consistent within the same file at
3378 // compile time
3379 Fail(VERIFY_ERROR_GENERIC) << "expected field " << PrettyField(field)
Ian Rogersb5e95b92011-10-25 23:28:55 -07003380 << " to be of type '" << insn_type
Ian Rogersb94a27b2011-10-26 00:33:41 -07003381 << "' but found type '" << field_type << "' in get";
Ian Rogersd81871c2011-10-03 13:57:23 -07003382 return;
3383 }
3384 } else {
Ian Rogersb5e95b92011-10-25 23:28:55 -07003385 if (!insn_type.IsAssignableFrom(field_type)) {
Ian Rogersd81871c2011-10-03 13:57:23 -07003386 Fail(VERIFY_ERROR_GENERIC) << "expected field " << PrettyField(field)
Ian Rogersb5e95b92011-10-25 23:28:55 -07003387 << " to be compatible with type '" << insn_type
3388 << "' but found type '" << field_type
Ian Rogersb94a27b2011-10-26 00:33:41 -07003389 << "' in get-object";
Ian Rogersd81871c2011-10-03 13:57:23 -07003390 return;
3391 }
3392 }
Ian Rogersb5e95b92011-10-25 23:28:55 -07003393 work_line_->SetRegisterType(dec_insn.vA_, field_type);
Ian Rogersd81871c2011-10-03 13:57:23 -07003394 }
3395}
3396
Ian Rogersb94a27b2011-10-26 00:33:41 -07003397void DexVerifier::VerifyISPut(const Instruction::DecodedInstruction& dec_insn,
3398 const RegType& insn_type, bool is_primitive, bool is_static) {
3399 Field* field;
3400 if (is_static) {
3401 field = GetStaticField(dec_insn.vB_);
3402 } else {
3403 const RegType& object_type = work_line_->GetRegisterType(dec_insn.vB_);
3404 field = GetInstanceField(object_type, dec_insn.vC_);
3405 }
Ian Rogersd81871c2011-10-03 13:57:23 -07003406 if (field != NULL) {
Ian Rogersd81871c2011-10-03 13:57:23 -07003407 if (field->IsFinal() && field->GetDeclaringClass() != method_->GetDeclaringClass()) {
3408 Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot modify final field " << PrettyField(field)
3409 << " from other class " << PrettyClass(method_->GetDeclaringClass());
3410 return;
3411 }
Ian Rogersb5e95b92011-10-25 23:28:55 -07003412 const RegType& field_type =
3413 reg_types_.FromDescriptor(field->GetDeclaringClass()->GetClassLoader(),
3414 field->GetTypeDescriptor());
Ian Rogersd81871c2011-10-03 13:57:23 -07003415 if (is_primitive) {
Ian Rogers2c8a8572011-10-24 17:11:36 -07003416 // Primitive field assignability rules are weaker than regular assignability rules
3417 bool instruction_compatible;
3418 bool value_compatible;
3419 const RegType& value_type = work_line_->GetRegisterType(dec_insn.vA_);
3420 if (field_type.IsIntegralTypes()) {
3421 instruction_compatible = insn_type.IsIntegralTypes();
3422 value_compatible = value_type.IsIntegralTypes();
3423 } else if (field_type.IsFloat()) {
Ian Rogersb94a27b2011-10-26 00:33:41 -07003424 instruction_compatible = insn_type.IsInteger(); // no [is]put-float, so expect [is]put-int
Ian Rogers2c8a8572011-10-24 17:11:36 -07003425 value_compatible = value_type.IsFloatTypes();
3426 } else if (field_type.IsLong()) {
3427 instruction_compatible = insn_type.IsLong();
3428 value_compatible = value_type.IsLongTypes();
3429 } else if (field_type.IsDouble()) {
Ian Rogersb94a27b2011-10-26 00:33:41 -07003430 instruction_compatible = insn_type.IsLong(); // no [is]put-double, so expect [is]put-long
Ian Rogers2c8a8572011-10-24 17:11:36 -07003431 value_compatible = value_type.IsDoubleTypes();
Ian Rogersd81871c2011-10-03 13:57:23 -07003432 } else {
Ian Rogers2c8a8572011-10-24 17:11:36 -07003433 instruction_compatible = false; // reference field with primitive store
3434 value_compatible = false; // unused
3435 }
3436 if (!instruction_compatible) {
Ian Rogersd81871c2011-10-03 13:57:23 -07003437 // This is a global failure rather than a class change failure as the instructions and
3438 // the descriptors for the type should have been consistent within the same file at
3439 // compile time
3440 Fail(VERIFY_ERROR_GENERIC) << "expected field " << PrettyField(field)
Ian Rogersb5e95b92011-10-25 23:28:55 -07003441 << " to be of type '" << insn_type
3442 << "' but found type '" << field_type
Ian Rogersb94a27b2011-10-26 00:33:41 -07003443 << "' in put";
Ian Rogersd81871c2011-10-03 13:57:23 -07003444 return;
3445 }
Ian Rogers2c8a8572011-10-24 17:11:36 -07003446 if (!value_compatible) {
3447 Fail(VERIFY_ERROR_GENERIC) << "unexpected value in v" << dec_insn.vA_
3448 << " of type " << value_type
3449 << " but expected " << field_type
Ian Rogersb94a27b2011-10-26 00:33:41 -07003450 << " for store to " << PrettyField(field) << " in put";
Ian Rogers2c8a8572011-10-24 17:11:36 -07003451 return;
3452 }
Ian Rogersd81871c2011-10-03 13:57:23 -07003453 } else {
Ian Rogersb5e95b92011-10-25 23:28:55 -07003454 if (!insn_type.IsAssignableFrom(field_type)) {
Ian Rogersd81871c2011-10-03 13:57:23 -07003455 Fail(VERIFY_ERROR_GENERIC) << "expected field " << PrettyField(field)
Ian Rogersb5e95b92011-10-25 23:28:55 -07003456 << " to be compatible with type '" << insn_type
3457 << "' but found type '" << field_type
Ian Rogersb94a27b2011-10-26 00:33:41 -07003458 << "' in put-object";
Ian Rogersd81871c2011-10-03 13:57:23 -07003459 return;
3460 }
Ian Rogers2c8a8572011-10-24 17:11:36 -07003461 work_line_->VerifyRegisterType(dec_insn.vA_, field_type);
Ian Rogersd81871c2011-10-03 13:57:23 -07003462 }
Ian Rogersd81871c2011-10-03 13:57:23 -07003463 }
3464}
3465
3466bool DexVerifier::CheckMoveException(const uint16_t* insns, int insn_idx) {
3467 if ((insns[insn_idx] & 0xff) == Instruction::MOVE_EXCEPTION) {
3468 Fail(VERIFY_ERROR_GENERIC) << "invalid use of move-exception";
3469 return false;
3470 }
3471 return true;
3472}
3473
3474void DexVerifier::VerifyFilledNewArrayRegs(const Instruction::DecodedInstruction& dec_insn,
Ian Rogers28ad40d2011-10-27 15:19:26 -07003475 const RegType& res_type, bool is_range) {
3476 DCHECK(res_type.IsArrayClass()) << res_type; // Checked before calling.
Ian Rogersd81871c2011-10-03 13:57:23 -07003477 /*
3478 * Verify each register. If "arg_count" is bad, VerifyRegisterType() will run off the end of the
3479 * list and fail. It's legal, if silly, for arg_count to be zero.
3480 */
Ian Rogers28ad40d2011-10-27 15:19:26 -07003481 const RegType& expected_type = reg_types_.GetComponentType(res_type,
3482 method_->GetDeclaringClass()->GetClassLoader());
Ian Rogersd81871c2011-10-03 13:57:23 -07003483 uint32_t arg_count = dec_insn.vA_;
3484 for (size_t ui = 0; ui < arg_count; ui++) {
3485 uint32_t get_reg;
3486
3487 if (is_range)
3488 get_reg = dec_insn.vC_ + ui;
3489 else
3490 get_reg = dec_insn.arg_[ui];
3491
3492 if (!work_line_->VerifyRegisterType(get_reg, expected_type)) {
3493 Fail(VERIFY_ERROR_GENERIC) << "filled-new-array arg " << ui << "(" << get_reg
3494 << ") not valid";
3495 return;
3496 }
3497 }
3498}
3499
3500void DexVerifier::ReplaceFailingInstruction() {
3501 const Instruction* inst = Instruction::At(code_item_->insns_ + work_insn_idx_);
3502 DCHECK(inst->IsThrow()) << "Expected instruction that will throw " << inst->Name();
3503 VerifyErrorRefType ref_type;
3504 switch (inst->Opcode()) {
3505 case Instruction::CONST_CLASS: // insn[1] == class ref, 2 code units (4 bytes)
jeffhaobdb76512011-09-07 11:43:16 -07003506 case Instruction::CHECK_CAST:
3507 case Instruction::INSTANCE_OF:
3508 case Instruction::NEW_INSTANCE:
3509 case Instruction::NEW_ARRAY:
Ian Rogersd81871c2011-10-03 13:57:23 -07003510 case Instruction::FILLED_NEW_ARRAY: // insn[1] == class ref, 3 code units (6 bytes)
jeffhaobdb76512011-09-07 11:43:16 -07003511 case Instruction::FILLED_NEW_ARRAY_RANGE:
3512 ref_type = VERIFY_ERROR_REF_CLASS;
3513 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07003514 case Instruction::IGET: // insn[1] == field ref, 2 code units (4 bytes)
jeffhaobdb76512011-09-07 11:43:16 -07003515 case Instruction::IGET_BOOLEAN:
3516 case Instruction::IGET_BYTE:
3517 case Instruction::IGET_CHAR:
3518 case Instruction::IGET_SHORT:
3519 case Instruction::IGET_WIDE:
3520 case Instruction::IGET_OBJECT:
3521 case Instruction::IPUT:
3522 case Instruction::IPUT_BOOLEAN:
3523 case Instruction::IPUT_BYTE:
3524 case Instruction::IPUT_CHAR:
3525 case Instruction::IPUT_SHORT:
3526 case Instruction::IPUT_WIDE:
3527 case Instruction::IPUT_OBJECT:
3528 case Instruction::SGET:
3529 case Instruction::SGET_BOOLEAN:
3530 case Instruction::SGET_BYTE:
3531 case Instruction::SGET_CHAR:
3532 case Instruction::SGET_SHORT:
3533 case Instruction::SGET_WIDE:
3534 case Instruction::SGET_OBJECT:
3535 case Instruction::SPUT:
3536 case Instruction::SPUT_BOOLEAN:
3537 case Instruction::SPUT_BYTE:
3538 case Instruction::SPUT_CHAR:
3539 case Instruction::SPUT_SHORT:
3540 case Instruction::SPUT_WIDE:
3541 case Instruction::SPUT_OBJECT:
3542 ref_type = VERIFY_ERROR_REF_FIELD;
3543 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07003544 case Instruction::INVOKE_VIRTUAL: // insn[1] == method ref, 3 code units (6 bytes)
jeffhaobdb76512011-09-07 11:43:16 -07003545 case Instruction::INVOKE_VIRTUAL_RANGE:
3546 case Instruction::INVOKE_SUPER:
3547 case Instruction::INVOKE_SUPER_RANGE:
3548 case Instruction::INVOKE_DIRECT:
3549 case Instruction::INVOKE_DIRECT_RANGE:
3550 case Instruction::INVOKE_STATIC:
3551 case Instruction::INVOKE_STATIC_RANGE:
3552 case Instruction::INVOKE_INTERFACE:
3553 case Instruction::INVOKE_INTERFACE_RANGE:
3554 ref_type = VERIFY_ERROR_REF_METHOD;
3555 break;
jeffhaobdb76512011-09-07 11:43:16 -07003556 default:
Ian Rogers2c8a8572011-10-24 17:11:36 -07003557 LOG(FATAL) << "Error: verifier asked to replace instruction " << inst->DumpString(dex_file_);
jeffhaobdb76512011-09-07 11:43:16 -07003558 return;
jeffhaoba5ebb92011-08-25 17:24:37 -07003559 }
Ian Rogersd81871c2011-10-03 13:57:23 -07003560 uint16_t* insns = const_cast<uint16_t*>(code_item_->insns_);
3561 // THROW_VERIFICATION_ERROR is a 2 code unit instruction. We shouldn't be rewriting a 1 code unit
3562 // instruction, so assert it.
3563 size_t width = inst->SizeInCodeUnits();
3564 CHECK_GT(width, 1u);
3565 // If the instruction is larger than 2 code units, rewrite subqeuent code unit sized chunks with
3566 // NOPs
3567 for (size_t i = 2; i < width; i++) {
3568 insns[work_insn_idx_ + i] = Instruction::NOP;
3569 }
3570 // Encode the opcode, with the failure code in the high byte
3571 uint16_t new_instruction = Instruction::THROW_VERIFICATION_ERROR |
3572 (failure_ << 8) | // AA - component
3573 (ref_type << (8 + kVerifyErrorRefTypeShift));
3574 insns[work_insn_idx_] = new_instruction;
3575 // The 2nd code unit (higher in memory) with the reference in, comes from the instruction we
3576 // rewrote, so nothing to do here.
Ian Rogers9fdfc182011-10-26 23:12:52 -07003577 LOG(INFO) << "Verification error, replacing instructions in " << PrettyMethod(method_) << " "
3578 << fail_messages_.str();
3579 if (gDebugVerify) {
3580 std::cout << std::endl << info_messages_.str();
3581 Dump(std::cout);
3582 }
jeffhaobdb76512011-09-07 11:43:16 -07003583}
jeffhaoba5ebb92011-08-25 17:24:37 -07003584
Ian Rogersd81871c2011-10-03 13:57:23 -07003585bool DexVerifier::UpdateRegisters(uint32_t next_insn, const RegisterLine* merge_line) {
3586 const bool merge_debug = true;
3587 bool changed = true;
3588 RegisterLine* target_line = reg_table_.GetLine(next_insn);
3589 if (!insn_flags_[next_insn].IsVisitedOrChanged()) {
jeffhaobdb76512011-09-07 11:43:16 -07003590 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07003591 * We haven't processed this instruction before, and we haven't touched the registers here, so
3592 * there's nothing to "merge". Copy the registers over and mark it as changed. (This is the
3593 * only way a register can transition out of "unknown", so this is not just an optimization.)
jeffhaobdb76512011-09-07 11:43:16 -07003594 */
Ian Rogersd81871c2011-10-03 13:57:23 -07003595 target_line->CopyFromLine(merge_line);
jeffhaobdb76512011-09-07 11:43:16 -07003596 } else {
Ian Rogersd81871c2011-10-03 13:57:23 -07003597 UniquePtr<RegisterLine> copy(merge_debug ? new RegisterLine(target_line->NumRegs(), this) : NULL);
3598 copy->CopyFromLine(target_line);
3599 changed = target_line->MergeRegisters(merge_line);
3600 if (failure_ != VERIFY_ERROR_NONE) {
3601 return false;
jeffhaobdb76512011-09-07 11:43:16 -07003602 }
Ian Rogers2c8a8572011-10-24 17:11:36 -07003603 if (gDebugVerify && changed) {
Ian Rogersd81871c2011-10-03 13:57:23 -07003604 LogVerifyInfo() << "Merging at [" << (void*)work_insn_idx_ << "] to [" <<(void*)next_insn << "]: " << std::endl
3605 << *copy.get() << " MERGE" << std::endl
3606 << *merge_line << " ==" << std::endl
3607 << *target_line << std::endl;
jeffhaobdb76512011-09-07 11:43:16 -07003608 }
3609 }
Ian Rogersd81871c2011-10-03 13:57:23 -07003610 if (changed) {
3611 insn_flags_[next_insn].SetChanged();
jeffhaobdb76512011-09-07 11:43:16 -07003612 }
3613 return true;
3614}
3615
Ian Rogersd81871c2011-10-03 13:57:23 -07003616void DexVerifier::ComputeGcMapSizes(size_t* gc_points, size_t* ref_bitmap_bits,
3617 size_t* log2_max_gc_pc) {
3618 size_t local_gc_points = 0;
3619 size_t max_insn = 0;
3620 size_t max_ref_reg = -1;
3621 for (size_t i = 0; i < code_item_->insns_size_in_code_units_; i++) {
3622 if (insn_flags_[i].IsGcPoint()) {
3623 local_gc_points++;
3624 max_insn = i;
3625 RegisterLine* line = reg_table_.GetLine(i);
Ian Rogers84fa0742011-10-25 18:13:30 -07003626 max_ref_reg = line->GetMaxNonZeroReferenceReg(max_ref_reg);
jeffhaobdb76512011-09-07 11:43:16 -07003627 }
3628 }
Ian Rogersd81871c2011-10-03 13:57:23 -07003629 *gc_points = local_gc_points;
3630 *ref_bitmap_bits = max_ref_reg + 1; // if max register is 0 we need 1 bit to encode (ie +1)
3631 size_t i = 0;
3632 while ((1U << i) < max_insn) {
3633 i++;
3634 }
3635 *log2_max_gc_pc = i;
jeffhaobdb76512011-09-07 11:43:16 -07003636}
3637
Ian Rogersd81871c2011-10-03 13:57:23 -07003638ByteArray* DexVerifier::GenerateGcMap() {
3639 size_t num_entries, ref_bitmap_bits, pc_bits;
3640 ComputeGcMapSizes(&num_entries, &ref_bitmap_bits, &pc_bits);
3641 // There's a single byte to encode the size of each bitmap
3642 if (ref_bitmap_bits >= (8 /* bits per byte */ * 256 /* max unsigned byte + 1 */ )) {
3643 // TODO: either a better GC map format or per method failures
3644 Fail(VERIFY_ERROR_GENERIC) << "Cannot encode GC map for method with "
3645 << ref_bitmap_bits << " registers";
jeffhaobdb76512011-09-07 11:43:16 -07003646 return NULL;
3647 }
Ian Rogersd81871c2011-10-03 13:57:23 -07003648 size_t ref_bitmap_bytes = (ref_bitmap_bits + 7) / 8;
3649 // There are 2 bytes to encode the number of entries
3650 if (num_entries >= 65536) {
3651 // TODO: either a better GC map format or per method failures
3652 Fail(VERIFY_ERROR_GENERIC) << "Cannot encode GC map for method with "
3653 << num_entries << " entries";
jeffhaobdb76512011-09-07 11:43:16 -07003654 return NULL;
3655 }
Ian Rogersd81871c2011-10-03 13:57:23 -07003656 size_t pc_bytes;
jeffhaod1f0fde2011-09-08 17:25:33 -07003657 RegisterMapFormat format;
Ian Rogersd81871c2011-10-03 13:57:23 -07003658 if (pc_bits < 8) {
jeffhaod1f0fde2011-09-08 17:25:33 -07003659 format = kRegMapFormatCompact8;
Ian Rogersd81871c2011-10-03 13:57:23 -07003660 pc_bytes = 1;
3661 } else if (pc_bits < 16) {
jeffhaod1f0fde2011-09-08 17:25:33 -07003662 format = kRegMapFormatCompact16;
Ian Rogersd81871c2011-10-03 13:57:23 -07003663 pc_bytes = 2;
jeffhaoa0a764a2011-09-16 10:43:38 -07003664 } else {
Ian Rogersd81871c2011-10-03 13:57:23 -07003665 // TODO: either a better GC map format or per method failures
3666 Fail(VERIFY_ERROR_GENERIC) << "Cannot encode GC map for method with "
3667 << (1 << pc_bits) << " instructions (number is rounded up to nearest power of 2)";
3668 return NULL;
3669 }
3670 size_t table_size = ((pc_bytes + ref_bitmap_bytes) * num_entries ) + 4;
3671 ByteArray* table = ByteArray::Alloc(table_size);
3672 if (table == NULL) {
3673 Fail(VERIFY_ERROR_GENERIC) << "Failed to encode GC map (size=" << table_size << ")";
3674 return NULL;
3675 }
3676 // Write table header
3677 table->Set(0, format);
3678 table->Set(1, ref_bitmap_bytes);
3679 table->Set(2, num_entries & 0xFF);
3680 table->Set(3, (num_entries >> 8) & 0xFF);
3681 // Write table data
3682 size_t offset = 4;
3683 for (size_t i = 0; i < code_item_->insns_size_in_code_units_; i++) {
3684 if (insn_flags_[i].IsGcPoint()) {
3685 table->Set(offset, i & 0xFF);
3686 offset++;
3687 if (pc_bytes == 2) {
3688 table->Set(offset, (i >> 8) & 0xFF);
3689 offset++;
3690 }
3691 RegisterLine* line = reg_table_.GetLine(i);
3692 line->WriteReferenceBitMap(table->GetData() + offset, ref_bitmap_bytes);
3693 offset += ref_bitmap_bytes;
3694 }
3695 }
3696 DCHECK(offset == table_size);
3697 return table;
3698}
jeffhaoa0a764a2011-09-16 10:43:38 -07003699
Ian Rogersd81871c2011-10-03 13:57:23 -07003700void DexVerifier::VerifyGcMap() {
3701 // Check that for every GC point there is a map entry, there aren't entries for non-GC points,
3702 // that the table data is well formed and all references are marked (or not) in the bitmap
3703 PcToReferenceMap map(method_);
3704 size_t map_index = 0;
3705 for(size_t i = 0; i < code_item_->insns_size_in_code_units_; i++) {
3706 const uint8_t* reg_bitmap = map.FindBitMap(i, false);
3707 if (insn_flags_[i].IsGcPoint()) {
3708 CHECK_LT(map_index, map.NumEntries());
3709 CHECK_EQ(map.GetPC(map_index), i);
3710 CHECK_EQ(map.GetBitMap(map_index), reg_bitmap);
3711 map_index++;
3712 RegisterLine* line = reg_table_.GetLine(i);
3713 for(size_t j = 0; j < code_item_->registers_size_; j++) {
Ian Rogers84fa0742011-10-25 18:13:30 -07003714 if (line->GetRegisterType(j).IsNonZeroReferenceTypes()) {
Ian Rogersd81871c2011-10-03 13:57:23 -07003715 CHECK_LT(j / 8, map.RegWidth());
3716 CHECK_EQ((reg_bitmap[j / 8] >> (j % 8)) & 1, 1);
3717 } else if ((j / 8) < map.RegWidth()) {
3718 CHECK_EQ((reg_bitmap[j / 8] >> (j % 8)) & 1, 0);
3719 } else {
3720 // If a register doesn't contain a reference then the bitmap may be shorter than the line
3721 }
3722 }
3723 } else {
3724 CHECK(reg_bitmap == NULL);
3725 }
3726 }
3727}
jeffhaoa0a764a2011-09-16 10:43:38 -07003728
Ian Rogersd81871c2011-10-03 13:57:23 -07003729const uint8_t* PcToReferenceMap::FindBitMap(uint16_t dex_pc, bool error_if_not_present) const {
3730 size_t num_entries = NumEntries();
3731 // Do linear or binary search?
3732 static const size_t kSearchThreshold = 8;
3733 if (num_entries < kSearchThreshold) {
3734 for (size_t i = 0; i < num_entries; i++) {
3735 if (GetPC(i) == dex_pc) {
3736 return GetBitMap(i);
3737 }
3738 }
3739 } else {
3740 int lo = 0;
3741 int hi = num_entries -1;
jeffhaoa0a764a2011-09-16 10:43:38 -07003742 while (hi >= lo) {
Ian Rogersd81871c2011-10-03 13:57:23 -07003743 int mid = (hi + lo) / 2;
3744 int mid_pc = GetPC(mid);
3745 if (dex_pc > mid_pc) {
jeffhaoa0a764a2011-09-16 10:43:38 -07003746 lo = mid + 1;
Ian Rogersd81871c2011-10-03 13:57:23 -07003747 } else if (dex_pc < mid_pc) {
jeffhaoa0a764a2011-09-16 10:43:38 -07003748 hi = mid - 1;
3749 } else {
Ian Rogersd81871c2011-10-03 13:57:23 -07003750 return GetBitMap(mid);
jeffhaoa0a764a2011-09-16 10:43:38 -07003751 }
3752 }
3753 }
Ian Rogersd81871c2011-10-03 13:57:23 -07003754 if (error_if_not_present) {
3755 LOG(ERROR) << "Didn't find reference bit map for dex_pc " << dex_pc;
3756 }
jeffhaoa0a764a2011-09-16 10:43:38 -07003757 return NULL;
3758}
3759
Ian Rogersd81871c2011-10-03 13:57:23 -07003760} // namespace verifier
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003761} // namespace art