2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * Dalvik verification subroutines.
21 #include "analysis/CodeVerify.h"
22 #include "libdex/DexCatch.h"
23 #include "libdex/InstrUtils.h"
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).
32 * If "pNewInstanceCount" is not NULL, it will be set to the number of
33 * new-instance instructions in the method.
35 * Logs an error and returns "false" on failure.
37 bool dvmComputeCodeWidths(const Method* meth, InsnFlags* insnFlags,
38 int* pNewInstanceCount)
40 const int insnCount = dvmGetMethodInsnsSize(meth);
41 const u2* insns = meth->insns;
43 int newInstanceCount = 0;
47 for (i = 0; i < insnCount; /**/) {
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.
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;
63 int instr = *insns & 0xff;
64 width = dexGetInstrWidthAbs(gDvm.instrWidth, instr);
67 "VFY: invalid post-opt instruction (0x%x)\n", instr);
68 LOGI("### instr=%d width=%d table=%d\n",
69 instr, width, dexGetInstrWidthAbs(gDvm.instrWidth, instr));
72 if (width < 0 || width > 5) {
73 LOGE("VFY: bizarre width value %d\n", width);
77 if (instr == OP_NEW_INSTANCE)
82 LOG_VFY_METH(meth, "VFY: insane width %d\n", width);
86 insnFlags[i] |= width;
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));
97 if (pNewInstanceCount != NULL)
98 *pNewInstanceCount = newInstanceCount;
105 * Set the "in try" flags for all instructions protected by "try" statements.
106 * Also sets the "branch target" flags for exception handlers.
108 * Call this after widths have been set in "insnFlags".
110 * Returns "false" if something in the exception table looks fishy, but
111 * we're expecting the exception table to be somewhat sane.
113 bool dvmSetTryFlags(const Method* meth, InsnFlags* insnFlags)
115 u4 insnsSize = dvmGetMethodInsnsSize(meth);
116 DexFile* pDexFile = meth->clazz->pDvmDex->pDexFile;
117 const DexCode* pCode = dvmGetMethodCode(meth);
118 u4 triesSize = pCode->triesSize;
119 const DexTry* pTries;
124 if (triesSize == 0) {
128 pTries = dexGetTries(pCode);
129 handlersSize = dexGetHandlersSize(pCode);
131 for (i = 0; i < triesSize; i++) {
132 const DexTry* pTry = &pTries[i];
133 u4 start = pTry->startAddr;
134 u4 end = start + pTry->insnCount;
137 if ((start >= end) || (start >= insnsSize) || (end > insnsSize)) {
139 "VFY: bad exception entry: startAddr=%d endAddr=%d (size=%d)\n",
140 start, end, insnsSize);
144 if (dvmInsnGetWidth(insnFlags, start) == 0) {
146 "VFY: 'try' block starts inside an instruction (%d)\n",
151 for (addr = start; addr < end;
152 addr += dvmInsnGetWidth(insnFlags, addr))
154 assert(dvmInsnGetWidth(insnFlags, addr) != 0);
155 dvmInsnSetInTry(insnFlags, addr, true);
159 /* Iterate over each of the handlers to verify target addresses. */
160 offset = dexGetFirstHandlerOffset(pCode);
161 for (i = 0; i < handlersSize; i++) {
162 DexCatchIterator iterator;
163 dexCatchIteratorInit(&iterator, pCode, offset);
166 DexCatchHandler* handler = dexCatchIteratorNext(&iterator);
169 if (handler == NULL) {
173 addr = handler->address;
174 if (dvmInsnGetWidth(insnFlags, addr) == 0) {
176 "VFY: exception handler starts at bad address (%d)\n",
181 dvmInsnSetBranchTarget(insnFlags, addr, true);
184 offset = dexCatchIteratorGetEndOffset(&iterator, pCode);
191 * Verify a switch table. "curOffset" is the offset of the switch
194 bool dvmCheckSwitchTargets(const Method* meth, InsnFlags* insnFlags,
197 const int insnCount = dvmGetMethodInsnsSize(meth);
198 const u2* insns = meth->insns + curOffset;
199 const u2* switchInsns;
200 u2 expectedSignature;
201 int switchCount, tableSize;
202 int offsetToSwitch, offsetToKeys, offsetToTargets, targ;
203 int offset, absOffset;
205 assert(curOffset >= 0 && curOffset < insnCount);
207 /* make sure the start of the switch is in range */
208 offsetToSwitch = (s2) insns[1];
209 if (curOffset + offsetToSwitch < 0 ||
210 curOffset + offsetToSwitch + 2 >= insnCount)
213 "VFY: invalid switch start: at %d, switch offset %d, count %d\n",
214 curOffset, offsetToSwitch, insnCount);
218 /* offset to switch table is a relative branch-style offset */
219 switchInsns = insns + offsetToSwitch;
221 /* make sure the table is 32-bit aligned */
222 if ((((u4) switchInsns) & 0x03) != 0) {
224 "VFY: unaligned switch table: at %d, switch offset %d\n",
225 curOffset, offsetToSwitch);
229 switchCount = switchInsns[1];
231 if ((*insns & 0xff) == OP_PACKED_SWITCH) {
232 /* 0=sig, 1=count, 2/3=firstKey */
235 expectedSignature = kPackedSwitchSignature;
237 /* 0=sig, 1=count, 2..count*2 = keys */
239 offsetToTargets = 2 + 2*switchCount;
240 expectedSignature = kSparseSwitchSignature;
242 tableSize = offsetToTargets + switchCount*2;
244 if (switchInsns[0] != expectedSignature) {
246 "VFY: wrong signature for switch table (0x%04x, wanted 0x%04x)\n",
247 switchInsns[0], expectedSignature);
251 /* make sure the end of the switch is in range */
252 if (curOffset + offsetToSwitch + tableSize > insnCount) {
254 "VFY: invalid switch end: at %d, switch offset %d, end %d, count %d\n",
255 curOffset, offsetToSwitch, curOffset + offsetToSwitch + tableSize,
260 /* for a sparse switch, verify the keys are in ascending order */
261 if (offsetToKeys > 0 && switchCount > 1) {
264 lastKey = switchInsns[offsetToKeys] |
265 (switchInsns[offsetToKeys+1] << 16);
266 for (targ = 1; targ < switchCount; targ++) {
267 s4 key = (s4) switchInsns[offsetToKeys + targ*2] |
268 (s4) (switchInsns[offsetToKeys + targ*2 +1] << 16);
269 if (key <= lastKey) {
271 "VFY: invalid packed switch: last key=%d, this=%d\n",
280 /* verify each switch target */
281 for (targ = 0; targ < switchCount; targ++) {
282 offset = (s4) switchInsns[offsetToTargets + targ*2] |
283 (s4) (switchInsns[offsetToTargets + targ*2 +1] << 16);
284 absOffset = curOffset + offset;
286 if (absOffset < 0 || absOffset >= insnCount ||
287 !dvmInsnIsOpcode(insnFlags, absOffset))
290 "VFY: invalid switch target %d (-> 0x%x) at 0x%x[%d]\n",
291 offset, absOffset, curOffset, targ);
294 dvmInsnSetBranchTarget(insnFlags, absOffset, true);
301 * Verify that the target of a branch instruction is valid.
303 * We don't expect code to jump directly into an exception handler, but
304 * it's valid to do so as long as the target isn't a "move-exception"
305 * instruction. We verify that in a later stage.
307 * The VM spec doesn't forbid an instruction from branching to itself,
308 * but the Dalvik spec declares that only certain instructions can do so.
310 bool dvmCheckBranchTarget(const Method* meth, InsnFlags* insnFlags,
311 int curOffset, bool selfOkay)
313 const int insnCount = dvmGetMethodInsnsSize(meth);
314 const u2* insns = meth->insns + curOffset;
315 int offset, absOffset;
318 if (!dvmGetBranchTarget(meth, insnFlags, curOffset, &offset,
322 if (!selfOkay && offset == 0) {
323 LOG_VFY_METH(meth, "VFY: branch offset of zero not allowed at 0x%x\n",
329 * Check for 32-bit overflow. This isn't strictly necessary if we can
330 * depend on the VM to have identical "wrap-around" behavior, but
331 * it's unwise to depend on that.
333 if (((s8) curOffset + (s8) offset) != (s8)(curOffset + offset)) {
334 LOG_VFY_METH(meth, "VFY: branch target overflow 0x%x +%d\n",
338 absOffset = curOffset + offset;
339 if (absOffset < 0 || absOffset >= insnCount ||
340 !dvmInsnIsOpcode(insnFlags, absOffset))
343 "VFY: invalid branch target %d (-> 0x%x) at 0x%x\n",
344 offset, absOffset, curOffset);
347 dvmInsnSetBranchTarget(insnFlags, absOffset, true);
354 * Output a code verifier warning message. For the pre-verifier it's not
355 * a big deal if something fails (and it may even be expected), but if
356 * we're doing just-in-time verification it's significant.
358 void dvmLogVerifyFailure(const Method* meth, const char* format, ...)
363 if (gDvm.optimizing) {
365 //logLevel = ANDROID_LOG_DEBUG;
367 logLevel = ANDROID_LOG_WARN;
370 va_start(ap, format);
371 LOG_PRI_VA(logLevel, LOG_TAG, format, ap);
373 char* desc = dexProtoCopyMethodDescriptor(&meth->prototype);
374 LOG_PRI(logLevel, LOG_TAG, "VFY: rejected %s.%s %s\n",
375 meth->clazz->descriptor, meth->name, desc);
381 * Show a relatively human-readable message describing the failure to
384 * TODO: this is somewhat misleading when resolution fails because of
385 * illegal access rather than nonexistent class.
387 void dvmLogUnableToResolveClass(const char* missingClassDescr,
393 char* dotMissingClass = dvmDescriptorToDot(missingClassDescr);
394 char* dotFromClass = dvmDescriptorToDot(meth->clazz->descriptor);
395 //char* methodDescr = dexProtoCopyMethodDescriptor(&meth->prototype);
397 LOGE("Could not find class '%s', referenced from method %s.%s\n",
398 dotMissingClass, dotFromClass, meth->name/*, methodDescr*/);
400 free(dotMissingClass);
406 * Extract the relative offset from a branch instruction.
408 * Returns "false" on failure (e.g. this isn't a branch instruction).
410 bool dvmGetBranchTarget(const Method* meth, InsnFlags* insnFlags,
411 int curOffset, int* pOffset, bool* pConditional)
413 const u2* insns = meth->insns + curOffset;
416 switch (*insns & 0xff) {
418 *pOffset = ((s2) *insns) >> 8;
419 *pConditional = false;
422 *pOffset = insns[1] | (((u4) insns[2]) << 16);
423 *pConditional = false;
426 *pOffset = (s2) insns[1];
427 *pConditional = false;
441 *pOffset = (s2) insns[1];
442 *pConditional = true;
453 * Given a 32-bit constant, return the most-restricted RegType enum entry
454 * that can hold the value.
456 char dvmDetermineCat1Const(s4 value)
459 return kRegTypeInteger;
460 else if (value < -128)
461 return kRegTypeShort;
468 else if (value < 128)
469 return kRegTypePosByte;
470 else if (value < 32768)
471 return kRegTypePosShort;
472 else if (value < 65536)
475 return kRegTypeInteger;