blob: 16f128ec0efe2f16df2fed12d8e02a7d564e80d2 [file] [log] [blame]
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/*
18 * Dalvik verification subroutines.
19 */
20#include "Dalvik.h"
21#include "analysis/CodeVerify.h"
22#include "libdex/DexCatch.h"
23#include "libdex/InstrUtils.h"
24
25
26/*
27 * Compute the width of the instruction at each address in the instruction
28 * stream. Addresses that are in the middle of an instruction, or that
29 * are part of switch table data, are not set (so the caller should probably
30 * initialize "insnFlags" to zero).
31 *
32 * If "pNewInstanceCount" is not NULL, it will be set to the number of
33 * new-instance instructions in the method.
34 *
35 * Logs an error and returns "false" on failure.
36 */
37bool dvmComputeCodeWidths(const Method* meth, InsnFlags* insnFlags,
38 int* pNewInstanceCount)
39{
40 const int insnCount = dvmGetMethodInsnsSize(meth);
41 const u2* insns = meth->insns;
42 bool result = false;
43 int newInstanceCount = 0;
44 int i;
45
46
47 for (i = 0; i < insnCount; /**/) {
48 int width;
49
50 /*
51 * Switch tables and array data tables are identified with
52 * "extended NOP" opcodes. They contain no executable code,
53 * so we can just skip past them.
54 */
55 if (*insns == kPackedSwitchSignature) {
56 width = 4 + insns[1] * 2;
57 } else if (*insns == kSparseSwitchSignature) {
58 width = 2 + insns[1] * 4;
59 } else if (*insns == kArrayDataSignature) {
60 u4 size = insns[2] | (((u4)insns[3]) << 16);
61 width = 4 + (insns[1] * size + 1) / 2;
62 } else {
63 int instr = *insns & 0xff;
64 width = dexGetInstrWidthAbs(gDvm.instrWidth, instr);
65 if (width == 0) {
66 LOG_VFY_METH(meth,
67 "VFY: invalid post-opt instruction (0x%x)\n", instr);
David 'Digit' Turnerec628b52009-09-20 11:58:16 -070068 LOGI("### instr=%d width=%d table=%d\n",
69 instr, width, dexGetInstrWidthAbs(gDvm.instrWidth, instr));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080070 goto bail;
71 }
72 if (width < 0 || width > 5) {
73 LOGE("VFY: bizarre width value %d\n", width);
74 dvmAbort();
75 }
76
77 if (instr == OP_NEW_INSTANCE)
78 newInstanceCount++;
79 }
80
81 if (width > 65535) {
82 LOG_VFY_METH(meth, "VFY: insane width %d\n", width);
83 goto bail;
84 }
85
86 insnFlags[i] |= width;
87 i += width;
88 insns += width;
89 }
90 if (i != (int) dvmGetMethodInsnsSize(meth)) {
91 LOG_VFY_METH(meth, "VFY: code did not end where expected (%d vs. %d)\n",
92 i, dvmGetMethodInsnsSize(meth));
93 goto bail;
94 }
95
96 result = true;
97 if (pNewInstanceCount != NULL)
98 *pNewInstanceCount = newInstanceCount;
99
100bail:
101 return result;
102}
103
104/*
105 * Set the "in try" flags for all instructions protected by "try" statements.
106 * Also sets the "branch target" flags for exception handlers.
107 *
108 * Call this after widths have been set in "insnFlags".
109 *
110 * Returns "false" if something in the exception table looks fishy, but
111 * we're expecting the exception table to be somewhat sane.
112 */
113bool dvmSetTryFlags(const Method* meth, InsnFlags* insnFlags)
114{
115 u4 insnsSize = dvmGetMethodInsnsSize(meth);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800116 const DexCode* pCode = dvmGetMethodCode(meth);
117 u4 triesSize = pCode->triesSize;
118 const DexTry* pTries;
119 u4 handlersSize;
120 u4 offset;
121 u4 i;
122
123 if (triesSize == 0) {
124 return true;
125 }
126
127 pTries = dexGetTries(pCode);
128 handlersSize = dexGetHandlersSize(pCode);
129
130 for (i = 0; i < triesSize; i++) {
131 const DexTry* pTry = &pTries[i];
132 u4 start = pTry->startAddr;
133 u4 end = start + pTry->insnCount;
134 u4 addr;
135
136 if ((start >= end) || (start >= insnsSize) || (end > insnsSize)) {
137 LOG_VFY_METH(meth,
138 "VFY: bad exception entry: startAddr=%d endAddr=%d (size=%d)\n",
139 start, end, insnsSize);
140 return false;
141 }
142
143 if (dvmInsnGetWidth(insnFlags, start) == 0) {
144 LOG_VFY_METH(meth,
145 "VFY: 'try' block starts inside an instruction (%d)\n",
146 start);
147 return false;
148 }
149
150 for (addr = start; addr < end;
151 addr += dvmInsnGetWidth(insnFlags, addr))
152 {
153 assert(dvmInsnGetWidth(insnFlags, addr) != 0);
154 dvmInsnSetInTry(insnFlags, addr, true);
155 }
156 }
157
158 /* Iterate over each of the handlers to verify target addresses. */
159 offset = dexGetFirstHandlerOffset(pCode);
160 for (i = 0; i < handlersSize; i++) {
161 DexCatchIterator iterator;
162 dexCatchIteratorInit(&iterator, pCode, offset);
163
164 for (;;) {
165 DexCatchHandler* handler = dexCatchIteratorNext(&iterator);
166 u4 addr;
167
168 if (handler == NULL) {
169 break;
170 }
171
172 addr = handler->address;
173 if (dvmInsnGetWidth(insnFlags, addr) == 0) {
174 LOG_VFY_METH(meth,
175 "VFY: exception handler starts at bad address (%d)\n",
176 addr);
177 return false;
178 }
179
180 dvmInsnSetBranchTarget(insnFlags, addr, true);
181 }
182
183 offset = dexCatchIteratorGetEndOffset(&iterator, pCode);
184 }
185
186 return true;
187}
188
189/*
190 * Verify a switch table. "curOffset" is the offset of the switch
191 * instruction.
192 */
193bool dvmCheckSwitchTargets(const Method* meth, InsnFlags* insnFlags,
194 int curOffset)
195{
196 const int insnCount = dvmGetMethodInsnsSize(meth);
197 const u2* insns = meth->insns + curOffset;
198 const u2* switchInsns;
199 u2 expectedSignature;
200 int switchCount, tableSize;
201 int offsetToSwitch, offsetToKeys, offsetToTargets, targ;
202 int offset, absOffset;
203
204 assert(curOffset >= 0 && curOffset < insnCount);
205
206 /* make sure the start of the switch is in range */
207 offsetToSwitch = (s2) insns[1];
208 if (curOffset + offsetToSwitch < 0 ||
209 curOffset + offsetToSwitch + 2 >= insnCount)
210 {
211 LOG_VFY_METH(meth,
212 "VFY: invalid switch start: at %d, switch offset %d, count %d\n",
213 curOffset, offsetToSwitch, insnCount);
214 return false;
215 }
216
217 /* offset to switch table is a relative branch-style offset */
218 switchInsns = insns + offsetToSwitch;
219
220 /* make sure the table is 32-bit aligned */
221 if ((((u4) switchInsns) & 0x03) != 0) {
222 LOG_VFY_METH(meth,
223 "VFY: unaligned switch table: at %d, switch offset %d\n",
224 curOffset, offsetToSwitch);
225 return false;
226 }
227
228 switchCount = switchInsns[1];
229
230 if ((*insns & 0xff) == OP_PACKED_SWITCH) {
231 /* 0=sig, 1=count, 2/3=firstKey */
232 offsetToTargets = 4;
233 offsetToKeys = -1;
234 expectedSignature = kPackedSwitchSignature;
235 } else {
236 /* 0=sig, 1=count, 2..count*2 = keys */
237 offsetToKeys = 2;
238 offsetToTargets = 2 + 2*switchCount;
239 expectedSignature = kSparseSwitchSignature;
240 }
241 tableSize = offsetToTargets + switchCount*2;
242
243 if (switchInsns[0] != expectedSignature) {
244 LOG_VFY_METH(meth,
245 "VFY: wrong signature for switch table (0x%04x, wanted 0x%04x)\n",
246 switchInsns[0], expectedSignature);
247 return false;
248 }
249
250 /* make sure the end of the switch is in range */
251 if (curOffset + offsetToSwitch + tableSize > insnCount) {
252 LOG_VFY_METH(meth,
253 "VFY: invalid switch end: at %d, switch offset %d, end %d, count %d\n",
254 curOffset, offsetToSwitch, curOffset + offsetToSwitch + tableSize,
255 insnCount);
256 return false;
257 }
258
259 /* for a sparse switch, verify the keys are in ascending order */
260 if (offsetToKeys > 0 && switchCount > 1) {
261 s4 lastKey;
262
263 lastKey = switchInsns[offsetToKeys] |
264 (switchInsns[offsetToKeys+1] << 16);
265 for (targ = 1; targ < switchCount; targ++) {
266 s4 key = (s4) switchInsns[offsetToKeys + targ*2] |
267 (s4) (switchInsns[offsetToKeys + targ*2 +1] << 16);
268 if (key <= lastKey) {
269 LOG_VFY_METH(meth,
270 "VFY: invalid packed switch: last key=%d, this=%d\n",
271 lastKey, key);
272 return false;
273 }
274
275 lastKey = key;
276 }
277 }
278
279 /* verify each switch target */
280 for (targ = 0; targ < switchCount; targ++) {
281 offset = (s4) switchInsns[offsetToTargets + targ*2] |
282 (s4) (switchInsns[offsetToTargets + targ*2 +1] << 16);
283 absOffset = curOffset + offset;
284
285 if (absOffset < 0 || absOffset >= insnCount ||
286 !dvmInsnIsOpcode(insnFlags, absOffset))
287 {
288 LOG_VFY_METH(meth,
289 "VFY: invalid switch target %d (-> 0x%x) at 0x%x[%d]\n",
290 offset, absOffset, curOffset, targ);
291 return false;
292 }
293 dvmInsnSetBranchTarget(insnFlags, absOffset, true);
294 }
295
296 return true;
297}
298
299/*
300 * Verify that the target of a branch instruction is valid.
301 *
302 * We don't expect code to jump directly into an exception handler, but
303 * it's valid to do so as long as the target isn't a "move-exception"
304 * instruction. We verify that in a later stage.
305 *
306 * The VM spec doesn't forbid an instruction from branching to itself,
307 * but the Dalvik spec declares that only certain instructions can do so.
308 */
309bool dvmCheckBranchTarget(const Method* meth, InsnFlags* insnFlags,
310 int curOffset, bool selfOkay)
311{
312 const int insnCount = dvmGetMethodInsnsSize(meth);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800313 int offset, absOffset;
314 bool isConditional;
315
316 if (!dvmGetBranchTarget(meth, insnFlags, curOffset, &offset,
317 &isConditional))
318 return false;
319
320 if (!selfOkay && offset == 0) {
321 LOG_VFY_METH(meth, "VFY: branch offset of zero not allowed at 0x%x\n",
322 curOffset);
323 return false;
324 }
325
326 /*
327 * Check for 32-bit overflow. This isn't strictly necessary if we can
328 * depend on the VM to have identical "wrap-around" behavior, but
329 * it's unwise to depend on that.
330 */
331 if (((s8) curOffset + (s8) offset) != (s8)(curOffset + offset)) {
332 LOG_VFY_METH(meth, "VFY: branch target overflow 0x%x +%d\n",
333 curOffset, offset);
334 return false;
335 }
336 absOffset = curOffset + offset;
337 if (absOffset < 0 || absOffset >= insnCount ||
338 !dvmInsnIsOpcode(insnFlags, absOffset))
339 {
340 LOG_VFY_METH(meth,
341 "VFY: invalid branch target %d (-> 0x%x) at 0x%x\n",
342 offset, absOffset, curOffset);
343 return false;
344 }
345 dvmInsnSetBranchTarget(insnFlags, absOffset, true);
346
347 return true;
348}
349
350
351/*
352 * Output a code verifier warning message. For the pre-verifier it's not
353 * a big deal if something fails (and it may even be expected), but if
354 * we're doing just-in-time verification it's significant.
355 */
356void dvmLogVerifyFailure(const Method* meth, const char* format, ...)
357{
358 va_list ap;
359 int logLevel;
360
361 if (gDvm.optimizing) {
362 return;
363 //logLevel = ANDROID_LOG_DEBUG;
364 } else {
365 logLevel = ANDROID_LOG_WARN;
366 }
367
368 va_start(ap, format);
369 LOG_PRI_VA(logLevel, LOG_TAG, format, ap);
370 if (meth != NULL) {
371 char* desc = dexProtoCopyMethodDescriptor(&meth->prototype);
372 LOG_PRI(logLevel, LOG_TAG, "VFY: rejected %s.%s %s\n",
373 meth->clazz->descriptor, meth->name, desc);
374 free(desc);
375 }
376}
377
378/*
379 * Show a relatively human-readable message describing the failure to
380 * resolve a class.
381 *
382 * TODO: this is somewhat misleading when resolution fails because of
383 * illegal access rather than nonexistent class.
384 */
385void dvmLogUnableToResolveClass(const char* missingClassDescr,
386 const Method* meth)
387{
388 if (gDvm.optimizing)
389 return;
390
391 char* dotMissingClass = dvmDescriptorToDot(missingClassDescr);
392 char* dotFromClass = dvmDescriptorToDot(meth->clazz->descriptor);
393 //char* methodDescr = dexProtoCopyMethodDescriptor(&meth->prototype);
394
395 LOGE("Could not find class '%s', referenced from method %s.%s\n",
396 dotMissingClass, dotFromClass, meth->name/*, methodDescr*/);
397
398 free(dotMissingClass);
399 free(dotFromClass);
400 //free(methodDescr);
401}
402
403/*
404 * Extract the relative offset from a branch instruction.
405 *
406 * Returns "false" on failure (e.g. this isn't a branch instruction).
407 */
408bool dvmGetBranchTarget(const Method* meth, InsnFlags* insnFlags,
409 int curOffset, int* pOffset, bool* pConditional)
410{
411 const u2* insns = meth->insns + curOffset;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800412
413 switch (*insns & 0xff) {
414 case OP_GOTO:
415 *pOffset = ((s2) *insns) >> 8;
416 *pConditional = false;
417 break;
418 case OP_GOTO_32:
419 *pOffset = insns[1] | (((u4) insns[2]) << 16);
420 *pConditional = false;
421 break;
422 case OP_GOTO_16:
423 *pOffset = (s2) insns[1];
424 *pConditional = false;
425 break;
426 case OP_IF_EQ:
427 case OP_IF_NE:
428 case OP_IF_LT:
429 case OP_IF_GE:
430 case OP_IF_GT:
431 case OP_IF_LE:
432 case OP_IF_EQZ:
433 case OP_IF_NEZ:
434 case OP_IF_LTZ:
435 case OP_IF_GEZ:
436 case OP_IF_GTZ:
437 case OP_IF_LEZ:
438 *pOffset = (s2) insns[1];
439 *pConditional = true;
440 break;
441 default:
442 return false;
443 break;
444 }
445
446 return true;
447}
448
449/*
450 * Given a 32-bit constant, return the most-restricted RegType enum entry
451 * that can hold the value.
452 */
453char dvmDetermineCat1Const(s4 value)
454{
455 if (value < -32768)
456 return kRegTypeInteger;
457 else if (value < -128)
458 return kRegTypeShort;
459 else if (value < 0)
460 return kRegTypeByte;
461 else if (value == 0)
462 return kRegTypeZero;
463 else if (value == 1)
464 return kRegTypeOne;
465 else if (value < 128)
466 return kRegTypePosByte;
467 else if (value < 32768)
468 return kRegTypePosShort;
469 else if (value < 65536)
470 return kRegTypeChar;
471 else
472 return kRegTypeInteger;
473}
474