blob: de3d6760feb11676c34ef04f820f68ce05046253 [file] [log] [blame]
The Android Open Source Project2ad60cf2008-10-21 07:00:00 -07001/*
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 */
The Android Open Source Project89c1feb2008-12-17 18:03:55 -080016
The Android Open Source Project2ad60cf2008-10-21 07:00:00 -070017/*
18 * Main interpreter entry point and support functions.
19 *
20 * The entry point selects the "standard" or "debug" interpreter and
21 * facilitates switching between them. The standard interpreter may
22 * use the "fast" or "portable" implementation.
23 *
24 * Some debugger support functions are included here. Ideally their
25 * entire existence would be "#ifdef WITH_DEBUGGER", but we're not that
26 * aggressive in other parts of the code yet.
27 */
28#include "Dalvik.h"
29#include "interp/InterpDefs.h"
30
31
32/*
33 * ===========================================================================
34 * Debugger support
35 * ===========================================================================
36 */
37
38/*
39 * Initialize the breakpoint address lookup table when the debugger attaches.
40 *
41 * This shouldn't be necessary -- the global area is initially zeroed out,
42 * and the events should be cleaning up after themselves.
43 */
44void dvmInitBreakpoints(void)
45{
46#ifdef WITH_DEBUGGER
47 memset(gDvm.debugBreakAddr, 0, sizeof(gDvm.debugBreakAddr));
48#else
49 assert(false);
50#endif
51}
52
53/*
54 * Add an address to the list, putting it in the first non-empty slot.
55 *
56 * Sometimes the debugger likes to add two entries for one breakpoint.
57 * We add two entries here, so that we get the right behavior when it's
58 * removed twice.
59 *
60 * This will only be run from the JDWP thread, and it will happen while
61 * we are updating the event list, which is synchronized. We're guaranteed
62 * to be the only one adding entries, and the lock ensures that nobody
63 * will be trying to remove them while we're in here.
64 *
65 * "addr" is the absolute address of the breakpoint bytecode.
66 */
67void dvmAddBreakAddr(Method* method, int instrOffset)
68{
69#ifdef WITH_DEBUGGER
70 const u2* addr = method->insns + instrOffset;
71 const u2** ptr = gDvm.debugBreakAddr;
72 int i;
73
74 LOGV("BKP: add %p %s.%s (%s:%d)\n",
75 addr, method->clazz->descriptor, method->name,
76 dvmGetMethodSourceFile(method), dvmLineNumFromPC(method, instrOffset));
77
78 method->debugBreakpointCount++;
79 for (i = 0; i < MAX_BREAKPOINTS; i++, ptr++) {
80 if (*ptr == NULL) {
81 *ptr = addr;
82 break;
83 }
84 }
85 if (i == MAX_BREAKPOINTS) {
86 /* no room; size is too small or we're not cleaning up properly */
87 LOGE("ERROR: max breakpoints exceeded\n");
88 assert(false);
89 }
90#else
91 assert(false);
92#endif
93}
94
95/*
96 * Remove an address from the list by setting the entry to NULL.
97 *
98 * This can be called from the JDWP thread (because the debugger has
99 * cancelled the breakpoint) or from an event thread (because it's a
100 * single-shot breakpoint, e.g. "run to line"). We only get here as
101 * the result of removing an entry from the event list, which is
102 * synchronized, so it should not be possible for two threads to be
103 * updating breakpoints at the same time.
104 */
105void dvmClearBreakAddr(Method* method, int instrOffset)
106{
107#ifdef WITH_DEBUGGER
108 const u2* addr = method->insns + instrOffset;
109 const u2** ptr = gDvm.debugBreakAddr;
110 int i;
111
112 LOGV("BKP: clear %p %s.%s (%s:%d)\n",
113 addr, method->clazz->descriptor, method->name,
114 dvmGetMethodSourceFile(method), dvmLineNumFromPC(method, instrOffset));
115
116 method->debugBreakpointCount--;
117 assert(method->debugBreakpointCount >= 0);
118 for (i = 0; i < MAX_BREAKPOINTS; i++, ptr++) {
119 if (*ptr == addr) {
120 *ptr = NULL;
121 break;
122 }
123 }
124 if (i == MAX_BREAKPOINTS) {
125 /* didn't find it */
126 LOGE("ERROR: breakpoint on %p not found\n", addr);
127 assert(false);
128 }
129#else
130 assert(false);
131#endif
132}
133
134/*
135 * Add a single step event. Currently this is a global item.
136 *
137 * We set up some initial values based on the thread's current state. This
138 * won't work well if the thread is running, so it's up to the caller to
139 * verify that it's suspended.
140 *
141 * This is only called from the JDWP thread.
142 */
143bool dvmAddSingleStep(Thread* thread, int size, int depth)
144{
145#ifdef WITH_DEBUGGER
146 StepControl* pCtrl = &gDvm.stepControl;
147
148 if (pCtrl->active && thread != pCtrl->thread) {
149 LOGW("WARNING: single-step active for %p; adding %p\n",
150 pCtrl->thread, thread);
151
152 /*
153 * Keep going, overwriting previous. This can happen if you
154 * suspend a thread in Object.wait, hit the single-step key, then
155 * switch to another thread and do the same thing again.
156 * The first thread's step is still pending.
157 *
158 * TODO: consider making single-step per-thread. Adds to the
159 * overhead, but could be useful in rare situations.
160 */
161 }
162
163 pCtrl->size = size;
164 pCtrl->depth = depth;
165 pCtrl->thread = thread;
166
167 /*
168 * We may be stepping into or over method calls, or running until we
169 * return from the current method. To make this work we need to track
170 * the current line, current method, and current stack depth. We need
171 * to be checking these after most instructions, notably those that
172 * call methods, return from methods, or are on a different line from the
173 * previous instruction.
174 *
175 * We have to start with a snapshot of the current state. If we're in
176 * an interpreted method, everything we need is in the current frame. If
177 * we're in a native method, possibly with some extra JNI frames pushed
178 * on by PushLocalFrame, we want to use the topmost native method.
179 */
180 const StackSaveArea* saveArea;
181 void* fp;
182 void* prevFp = NULL;
183
184 for (fp = thread->curFrame; fp != NULL; fp = saveArea->prevFrame) {
185 const Method* method;
186
187 saveArea = SAVEAREA_FROM_FP(fp);
188 method = saveArea->method;
189
190 if (!dvmIsBreakFrame(fp) && !dvmIsNativeMethod(method))
191 break;
192 prevFp = fp;
193 }
194 if (fp == NULL) {
195 LOGW("Unexpected: step req in native-only threadid=%d\n",
196 thread->threadId);
197 return false;
198 }
199 if (prevFp != NULL) {
200 /*
201 * First interpreted frame wasn't the one at the bottom. Break
202 * frames are only inserted when calling from native->interp, so we
203 * don't need to worry about one being here.
204 */
205 LOGV("##### init step while in native method\n");
206 fp = prevFp;
207 assert(!dvmIsBreakFrame(fp));
208 assert(dvmIsNativeMethod(SAVEAREA_FROM_FP(fp)->method));
209 saveArea = SAVEAREA_FROM_FP(fp);
210 }
211
212 /*
213 * Pull the goodies out. "xtra.currentPc" should be accurate since
214 * we update it on every instruction while the debugger is connected.
215 */
216 pCtrl->method = saveArea->method;
217 // Clear out any old address set
218 if (pCtrl->pAddressSet != NULL) {
219 // (discard const)
220 free((void *)pCtrl->pAddressSet);
221 pCtrl->pAddressSet = NULL;
222 }
223 if (dvmIsNativeMethod(pCtrl->method)) {
224 pCtrl->line = -1;
225 } else {
226 pCtrl->line = dvmLineNumFromPC(saveArea->method,
227 saveArea->xtra.currentPc - saveArea->method->insns);
228 pCtrl->pAddressSet
229 = dvmAddressSetForLine(saveArea->method, pCtrl->line);
230 }
231 pCtrl->frameDepth = dvmComputeVagueFrameDepth(thread, thread->curFrame);
232 pCtrl->active = true;
233
234 LOGV("##### step init: thread=%p meth=%p '%s' line=%d frameDepth=%d depth=%s size=%s\n",
235 pCtrl->thread, pCtrl->method, pCtrl->method->name,
236 pCtrl->line, pCtrl->frameDepth,
237 dvmJdwpStepDepthStr(pCtrl->depth),
238 dvmJdwpStepSizeStr(pCtrl->size));
239
240 return true;
241#else
242 assert(false);
243 return false;
244#endif
245}
246
247/*
248 * Disable a single step event.
249 */
250void dvmClearSingleStep(Thread* thread)
251{
252#ifdef WITH_DEBUGGER
253 UNUSED_PARAMETER(thread);
254
255 gDvm.stepControl.active = false;
256#else
257 assert(false);
258#endif
259}
260
261
262/*
263 * Recover the "this" pointer from the current interpreted method. "this"
264 * is always in "in0" for non-static methods.
265 *
266 * The "ins" start at (#of registers - #of ins). Note in0 != v0.
267 *
268 * This works because "dx" guarantees that it will work. It's probably
269 * fairly common to have a virtual method that doesn't use its "this"
270 * pointer, in which case we're potentially wasting a register. However,
271 * the debugger doesn't treat "this" as just another argument. For
272 * example, events (such as breakpoints) can be enabled for specific
273 * values of "this". There is also a separate StackFrame.ThisObject call
274 * in JDWP that is expected to work for any non-native non-static method.
275 *
276 * Because we need it when setting up debugger event filters, we want to
277 * be able to do this quickly.
278 */
279Object* dvmGetThisPtr(const Method* method, const u4* fp)
280{
281 if (dvmIsStaticMethod(method))
282 return NULL;
283 return (Object*)fp[method->registersSize - method->insSize];
284}
285
286
287#if defined(WITH_TRACKREF_CHECKS)
288/*
289 * Verify that all internally-tracked references have been released. If
290 * they haven't, print them and abort the VM.
291 *
292 * "debugTrackedRefStart" indicates how many refs were on the list when
293 * we were first invoked.
294 */
295void dvmInterpCheckTrackedRefs(Thread* self, const Method* method,
296 int debugTrackedRefStart)
297{
298 if (dvmReferenceTableEntries(&self->internalLocalRefTable)
299 != (size_t) debugTrackedRefStart)
300 {
301 char* desc;
302 Object** top;
303 int count;
304
305 count = dvmReferenceTableEntries(&self->internalLocalRefTable);
306
307 LOGE("TRACK: unreleased internal reference (prev=%d total=%d)\n",
308 debugTrackedRefStart, count);
309 desc = dexProtoCopyMethodDescriptor(&method->prototype);
310 LOGE(" current method is %s.%s %s\n", method->clazz->descriptor,
311 method->name, desc);
312 free(desc);
313 top = self->internalLocalRefTable.table + debugTrackedRefStart;
314 while (top < self->internalLocalRefTable.nextEntry) {
315 LOGE(" %p (%s)\n",
316 *top,
317 ((*top)->clazz != NULL) ? (*top)->clazz->descriptor : "");
318 top++;
319 }
320 dvmDumpThread(self, false);
321
322 dvmAbort();
323 }
324 //LOGI("TRACK OK\n");
325}
326#endif
327
328
329#ifdef LOG_INSTR
330/*
331 * Dump the v-registers. Sent to the ILOG log tag.
332 */
333void dvmDumpRegs(const Method* method, const u4* framePtr, bool inOnly)
334{
335 int i, localCount;
336
337 localCount = method->registersSize - method->insSize;
338
339 LOG(LOG_VERBOSE, LOG_TAG"i", "Registers (fp=%p):\n", framePtr);
340 for (i = method->registersSize-1; i >= 0; i--) {
341 if (i >= localCount) {
342 LOG(LOG_VERBOSE, LOG_TAG"i", " v%-2d in%-2d : 0x%08x\n",
343 i, i-localCount, framePtr[i]);
344 } else {
345 if (inOnly) {
346 LOG(LOG_VERBOSE, LOG_TAG"i", " [...]\n");
347 break;
348 }
349 const char* name = "";
350 int j;
351#if 0 // "locals" structure has changed -- need to rewrite this
352 DexFile* pDexFile = method->clazz->pDexFile;
353 const DexCode* pDexCode = dvmGetMethodCode(method);
354 int localsSize = dexGetLocalsSize(pDexFile, pDexCode);
355 const DexLocal* locals = dvmDexGetLocals(pDexFile, pDexCode);
356 for (j = 0; j < localsSize, j++) {
357 if (locals[j].registerNum == (u4) i) {
358 name = dvmDexStringStr(locals[j].pName);
359 break;
360 }
361 }
362#endif
363 LOG(LOG_VERBOSE, LOG_TAG"i", " v%-2d : 0x%08x %s\n",
364 i, framePtr[i], name);
365 }
366 }
367}
368#endif
369
370
371/*
372 * ===========================================================================
373 * Entry point and general support functions
374 * ===========================================================================
375 */
376
377/*
378 * Construct an s4 from two consecutive half-words of switch data.
379 * This needs to check endianness because the DEX optimizer only swaps
380 * half-words in instruction stream.
381 *
382 * "switchData" must be 32-bit aligned.
383 */
384#if __BYTE_ORDER == __LITTLE_ENDIAN
385static inline s4 s4FromSwitchData(const void* switchData) {
386 return *(s4*) switchData;
387}
388#else
389static inline s4 s4FromSwitchData(const void* switchData) {
390 u2* data = switchData;
391 return data[0] | (((s4) data[1]) << 16);
Jay Freeman (saurik)ffa5c292008-11-16 13:51:51 +0000392}
The Android Open Source Project2ad60cf2008-10-21 07:00:00 -0700393#endif
394
395/*
396 * Find the matching case. Returns the offset to the handler instructions.
397 *
398 * Returns 3 if we don't find a match (it's the size of the packed-switch
399 * instruction).
400 */
401s4 dvmInterpHandlePackedSwitch(const u2* switchData, s4 testVal)
402{
403 const int kInstrLen = 3;
404 u2 size;
405 s4 firstKey;
406 const s4* entries;
407
408 /*
409 * Packed switch data format:
410 * ushort ident = 0x0100 magic value
411 * ushort size number of entries in the table
412 * int first_key first (and lowest) switch case value
413 * int targets[size] branch targets, relative to switch opcode
414 *
415 * Total size is (4+size*2) 16-bit code units.
416 */
417 if (*switchData++ != kPackedSwitchSignature) {
418 /* should have been caught by verifier */
419 dvmThrowException("Ljava/lang/InternalError;",
420 "bad packed switch magic");
421 return kInstrLen;
422 }
423
424 size = *switchData++;
425 assert(size > 0);
426
427 firstKey = *switchData++;
428 firstKey |= (*switchData++) << 16;
429
430 if (testVal < firstKey || testVal >= firstKey + size) {
431 LOGVV("Value %d not found in switch (%d-%d)\n",
432 testVal, firstKey, firstKey+size-1);
433 return kInstrLen;
434 }
435
436 /* The entries are guaranteed to be aligned on a 32-bit boundary;
437 * we can treat them as a native int array.
438 */
439 entries = (const s4*) switchData;
440 assert(((u4)entries & 0x3) == 0);
441
442 assert(testVal - firstKey >= 0 && testVal - firstKey < size);
443 LOGVV("Value %d found in slot %d (goto 0x%02x)\n",
444 testVal, testVal - firstKey,
445 s4FromSwitchData(&entries[testVal - firstKey]));
446 return s4FromSwitchData(&entries[testVal - firstKey]);
447}
448
449/*
450 * Find the matching case. Returns the offset to the handler instructions.
451 *
452 * Returns 3 if we don't find a match (it's the size of the sparse-switch
453 * instruction).
454 */
455s4 dvmInterpHandleSparseSwitch(const u2* switchData, s4 testVal)
456{
457 const int kInstrLen = 3;
458 u2 ident, size;
459 const s4* keys;
460 const s4* entries;
461 int i;
462
463 /*
464 * Sparse switch data format:
465 * ushort ident = 0x0200 magic value
466 * ushort size number of entries in the table; > 0
467 * int keys[size] keys, sorted low-to-high; 32-bit aligned
468 * int targets[size] branch targets, relative to switch opcode
469 *
470 * Total size is (2+size*4) 16-bit code units.
471 */
472
473 if (*switchData++ != kSparseSwitchSignature) {
474 /* should have been caught by verifier */
475 dvmThrowException("Ljava/lang/InternalError;",
476 "bad sparse switch magic");
477 return kInstrLen;
478 }
479
480 size = *switchData++;
481 assert(size > 0);
482
483 /* The keys are guaranteed to be aligned on a 32-bit boundary;
484 * we can treat them as a native int array.
485 */
486 keys = (const s4*) switchData;
487 assert(((u4)keys & 0x3) == 0);
488
489 /* The entries are guaranteed to be aligned on a 32-bit boundary;
490 * we can treat them as a native int array.
491 */
492 entries = keys + size;
493 assert(((u4)entries & 0x3) == 0);
494
495 /*
496 * Run through the list of keys, which are guaranteed to
497 * be sorted low-to-high.
498 *
499 * Most tables have 3-4 entries. Few have more than 10. A binary
500 * search here is probably not useful.
501 */
502 for (i = 0; i < size; i++) {
503 s4 k = s4FromSwitchData(&keys[i]);
504 if (k == testVal) {
505 LOGVV("Value %d found in entry %d (goto 0x%02x)\n",
506 testVal, i, s4FromSwitchData(&entries[i]));
507 return s4FromSwitchData(&entries[i]);
508 } else if (k > testVal) {
509 break;
510 }
511 }
512
513 LOGVV("Value %d not found in switch\n", testVal);
514 return kInstrLen;
515}
516
517/*
518 * Fill the array with predefined constant values.
519 *
520 * Returns true if job is completed, otherwise false to indicate that
521 * an exception has been thrown.
522 */
The Android Open Source Project89c1feb2008-12-17 18:03:55 -0800523bool dvmInterpHandleFillArrayData(ArrayObject* arrayObj, const u2* arrayData)
The Android Open Source Project2ad60cf2008-10-21 07:00:00 -0700524{
525 u2 width;
526 u4 size;
527
The Android Open Source Project89c1feb2008-12-17 18:03:55 -0800528 if (arrayObj == NULL) {
529 dvmThrowException("Ljava/lang/NullPointerException;", NULL);
The Android Open Source Project2ad60cf2008-10-21 07:00:00 -0700530 return false;
531 }
The Android Open Source Project89c1feb2008-12-17 18:03:55 -0800532
The Android Open Source Project2ad60cf2008-10-21 07:00:00 -0700533 /*
534 * Array data table format:
535 * ushort ident = 0x0300 magic value
536 * ushort width width of each element in the table
537 * uint size number of elements in the table
538 * ubyte data[size*width] table of data values (may contain a single-byte
539 * padding at the end)
540 *
541 * Total size is 4+(width * size + 1)/2 16-bit code units.
542 */
543 if (arrayData[0] != kArrayDataSignature) {
544 dvmThrowException("Ljava/lang/InternalError;", "bad array data magic");
545 return false;
546 }
547
548 width = arrayData[1];
549 size = arrayData[2] | (((u4)arrayData[3]) << 16);
550
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800551 if (size > arrayObj->length) {
The Android Open Source Project2ad60cf2008-10-21 07:00:00 -0700552 dvmThrowException("Ljava/lang/ArrayIndexOutOfBoundsException;", NULL);
553 return false;
554 }
555 memcpy(arrayObj->contents, &arrayData[4], size*width);
556 return true;
557}
558
559/*
560 * Find the concrete method that corresponds to "methodIdx". The code in
561 * "method" is executing invoke-method with "thisClass" as its first argument.
562 *
563 * Returns NULL with an exception raised on failure.
564 */
565Method* dvmInterpFindInterfaceMethod(ClassObject* thisClass, u4 methodIdx,
566 const Method* method, DvmDex* methodClassDex)
567{
568 Method* absMethod;
569 Method* methodToCall;
570 int i, vtableIndex;
571
572 /*
573 * Resolve the method. This gives us the abstract method from the
574 * interface class declaration.
575 */
576 absMethod = dvmDexGetResolvedMethod(methodClassDex, methodIdx);
577 if (absMethod == NULL) {
578 absMethod = dvmResolveInterfaceMethod(method->clazz, methodIdx);
579 if (absMethod == NULL) {
580 LOGV("+ unknown method\n");
581 return NULL;
582 }
583 }
584
585 /* make sure absMethod->methodIndex means what we think it means */
586 assert(dvmIsAbstractMethod(absMethod));
587
588 /*
589 * Run through the "this" object's iftable. Find the entry for
590 * absMethod's class, then use absMethod->methodIndex to find
591 * the method's entry. The value there is the offset into our
592 * vtable of the actual method to execute.
593 *
594 * The verifier does not guarantee that objects stored into
595 * interface references actually implement the interface, so this
596 * check cannot be eliminated.
597 */
598 for (i = 0; i < thisClass->iftableCount; i++) {
599 if (thisClass->iftable[i].clazz == absMethod->clazz)
600 break;
601 }
602 if (i == thisClass->iftableCount) {
603 /* impossible in verified DEX, need to check for it in unverified */
604 dvmThrowException("Ljava/lang/IncompatibleClassChangeError;",
605 "interface not implemented");
606 return NULL;
607 }
608
609 assert(absMethod->methodIndex <
610 thisClass->iftable[i].clazz->virtualMethodCount);
611
612 vtableIndex =
613 thisClass->iftable[i].methodIndexArray[absMethod->methodIndex];
614 assert(vtableIndex >= 0 && vtableIndex < thisClass->vtableCount);
615 methodToCall = thisClass->vtable[vtableIndex];
616
617#if 0
618 /* this can happen when there's a stale class file */
619 if (dvmIsAbstractMethod(methodToCall)) {
620 dvmThrowException("Ljava/lang/AbstractMethodError;",
621 "interface method not implemented");
622 return NULL;
623 }
624#else
625 assert(!dvmIsAbstractMethod(methodToCall) ||
626 methodToCall->nativeFunc != NULL);
627#endif
628
629 LOGVV("+++ interface=%s.%s concrete=%s.%s\n",
630 absMethod->clazz->descriptor, absMethod->name,
631 methodToCall->clazz->descriptor, methodToCall->name);
632 assert(methodToCall != NULL);
633
634 return methodToCall;
635}
636
637
Andy McFaddenb51ea112009-05-08 16:50:17 -0700638
639/*
640 * Helpers for dvmThrowVerificationError().
641 *
642 * Each returns a newly-allocated string.
643 */
644#define kThrowShow_accessFromClass 1
645static char* classNameFromIndex(const Method* method, int ref, int flags)
646{
647 static const int kBufLen = 256;
648 const DvmDex* pDvmDex = method->clazz->pDvmDex;
649 const char* className = dexStringByTypeIdx(pDvmDex->pDexFile, ref);
650 char* dotClassName = dvmDescriptorToDot(className);
651 if (flags == 0)
652 return dotClassName;
653
654 char* result = (char*) malloc(kBufLen);
655
656 if ((flags & kThrowShow_accessFromClass) != 0) {
657 char* dotFromName = dvmDescriptorToDot(method->clazz->descriptor);
658 snprintf(result, kBufLen, "tried to access class %s from class %s",
659 dotClassName, dotFromName);
660 free(dotFromName);
661 } else {
662 assert(false); // should've been caught above
663 result[0] = '\0';
664 }
665
666 free(dotClassName);
667 return result;
668}
669static char* fieldNameFromIndex(const Method* method, int ref, int flags)
670{
671 static const int kBufLen = 256;
672 const DvmDex* pDvmDex = method->clazz->pDvmDex;
673 const DexFieldId* pFieldId;
674 const char* className;
675 const char* fieldName;
676
677 pFieldId = dexGetFieldId(pDvmDex->pDexFile, ref);
678 className = dexStringByTypeIdx(pDvmDex->pDexFile, pFieldId->classIdx);
679 fieldName = dexStringById(pDvmDex->pDexFile, pFieldId->nameIdx);
680
681 char* dotName = dvmDescriptorToDot(className);
682 char* result = (char*) malloc(kBufLen);
683
684 if ((flags & kThrowShow_accessFromClass) != 0) {
685 char* dotFromName = dvmDescriptorToDot(method->clazz->descriptor);
686 snprintf(result, kBufLen, "tried to access field %s.%s from class %s",
687 dotName, fieldName, dotFromName);
688 free(dotFromName);
689 } else {
690 snprintf(result, kBufLen, "%s.%s", dotName, fieldName);
691 }
692
693 free(dotName);
694 return result;
695}
696static char* methodNameFromIndex(const Method* method, int ref, int flags)
697{
698 static const int kBufLen = 384;
699 const DvmDex* pDvmDex = method->clazz->pDvmDex;
700 const DexMethodId* pMethodId;
701 const char* className;
702 const char* methodName;
703
704 pMethodId = dexGetMethodId(pDvmDex->pDexFile, ref);
705 className = dexStringByTypeIdx(pDvmDex->pDexFile, pMethodId->classIdx);
706 methodName = dexStringById(pDvmDex->pDexFile, pMethodId->nameIdx);
707
708 char* dotName = dvmDescriptorToDot(className);
709 char* result = (char*) malloc(kBufLen);
710
711 if ((flags & kThrowShow_accessFromClass) != 0) {
712 char* dotFromName = dvmDescriptorToDot(method->clazz->descriptor);
713 char* desc = dexProtoCopyMethodDescriptor(&method->prototype);
714 snprintf(result, kBufLen,
715 "tried to access method %s.%s:%s from class %s",
716 dotName, methodName, desc, dotFromName);
717 free(dotFromName);
718 free(desc);
719 } else {
720 snprintf(result, kBufLen, "%s.%s", dotName, methodName);
721 }
722
723 free(dotName);
724 return result;
725}
726
The Android Open Source Project2ad60cf2008-10-21 07:00:00 -0700727/*
Andy McFadden3a1aedb2009-05-07 13:30:23 -0700728 * Throw an exception for a problem identified by the verifier.
729 *
730 * This is used by the invoke-verification-error instruction. It always
731 * throws an exception.
732 *
733 * "kind" indicates the kind of failure encountered by the verifier. The
734 * meaning of "ref" is kind-specific; it's usually an index to a
735 * class, field, or method reference.
736 */
Andy McFaddenb51ea112009-05-08 16:50:17 -0700737void dvmThrowVerificationError(const Method* method, int kind, int ref)
Andy McFadden3a1aedb2009-05-07 13:30:23 -0700738{
Andy McFaddenb51ea112009-05-08 16:50:17 -0700739 const char* exceptionName = "Ljava/lang/VerifyError;";
740 char* msg = NULL;
741
742 switch ((VerifyError) kind) {
743 case VERIFY_ERROR_NO_CLASS:
744 exceptionName = "Ljava/lang/NoClassDefFoundError;";
745 msg = classNameFromIndex(method, ref, 0);
746 break;
747 case VERIFY_ERROR_NO_FIELD:
748 exceptionName = "Ljava/lang/NoSuchFieldError;";
749 msg = fieldNameFromIndex(method, ref, 0);
750 break;
751 case VERIFY_ERROR_NO_METHOD:
752 exceptionName = "Ljava/lang/NoSuchMethodError;";
753 msg = methodNameFromIndex(method, ref, 0);
754 break;
755 case VERIFY_ERROR_ACCESS_CLASS:
756 exceptionName = "Ljava/lang/IllegalAccessError;";
757 msg = classNameFromIndex(method, ref, kThrowShow_accessFromClass);
758 break;
759 case VERIFY_ERROR_ACCESS_FIELD:
760 exceptionName = "Ljava/lang/IllegalAccessError;";
761 msg = fieldNameFromIndex(method, ref, kThrowShow_accessFromClass);
762 break;
763 case VERIFY_ERROR_ACCESS_METHOD:
764 exceptionName = "Ljava/lang/IllegalAccessError;";
765 msg = methodNameFromIndex(method, ref, kThrowShow_accessFromClass);
766 break;
767 case VERIFY_ERROR_CLASS_CHANGE:
768 exceptionName = "Ljava/lang/IncompatibleClassChangeError;";
769 msg = classNameFromIndex(method, ref, 0);
770 break;
771 case VERIFY_ERROR_INSTANTIATION:
772 exceptionName = "Ljava/lang/InstantiationError;";
773 msg = classNameFromIndex(method, ref, 0);
774 break;
775
776 case VERIFY_ERROR_GENERIC:
777 /* generic VerifyError; use default exception, no message */
778 break;
779 case VERIFY_ERROR_NONE:
780 /* should never happen; use default exception */
781 assert(false);
782 msg = strdup("weird - no error specified");
783 break;
784
785 /* no default clause -- want warning if enum updated */
786 }
787
788 dvmThrowException(exceptionName, msg);
789 free(msg);
Andy McFadden3a1aedb2009-05-07 13:30:23 -0700790}
791
792
793/*
The Android Open Source Project2ad60cf2008-10-21 07:00:00 -0700794 * Main interpreter loop entry point. Select "standard" or "debug"
795 * interpreter and switch between them as required.
796 *
797 * This begins executing code at the start of "method". On exit, "pResult"
798 * holds the return value of the method (or, if "method" returns NULL, it
799 * holds an undefined value).
800 *
801 * The interpreted stack frame, which holds the method arguments, has
802 * already been set up.
803 */
804void dvmInterpret(Thread* self, const Method* method, JValue* pResult)
805{
806 InterpState interpState;
807 bool change;
808
809#if defined(WITH_TRACKREF_CHECKS)
810 interpState.debugTrackedRefStart =
811 dvmReferenceTableEntries(&self->internalLocalRefTable);
812#endif
813#if defined(WITH_PROFILER) || defined(WITH_DEBUGGER)
814 interpState.debugIsMethodEntry = true;
815#endif
816
817 /*
818 * Initialize working state.
819 *
820 * No need to initialize "retval".
821 */
822 interpState.method = method;
823 interpState.fp = (u4*) self->curFrame;
824 interpState.pc = method->insns;
825 interpState.entryPoint = kInterpEntryInstr;
826
827 if (dvmDebuggerOrProfilerActive())
828 interpState.nextMode = INTERP_DBG;
829 else
830 interpState.nextMode = INTERP_STD;
831
832 assert(!dvmIsNativeMethod(method));
833
834 /*
835 * Make sure the class is ready to go. Shouldn't be possible to get
836 * here otherwise.
837 */
838 if (method->clazz->status < CLASS_INITIALIZING ||
839 method->clazz->status == CLASS_ERROR)
840 {
841 LOGE("ERROR: tried to execute code in unprepared class '%s' (%d)\n",
842 method->clazz->descriptor, method->clazz->status);
843 dvmDumpThread(self, false);
844 dvmAbort();
845 }
846
847 typedef bool (*Interpreter)(Thread*, InterpState*);
848 Interpreter stdInterp;
849 if (gDvm.executionMode == kExecutionModeInterpFast)
850 stdInterp = dvmMterpStd;
851 else
852 stdInterp = dvmInterpretStd;
853
854 change = true;
855 while (change) {
856 switch (interpState.nextMode) {
857 case INTERP_STD:
858 LOGVV("threadid=%d: interp STD\n", self->threadId);
859 change = (*stdInterp)(self, &interpState);
860 break;
861#if defined(WITH_PROFILER) || defined(WITH_DEBUGGER)
862 case INTERP_DBG:
863 LOGVV("threadid=%d: interp DBG\n", self->threadId);
864 change = dvmInterpretDbg(self, &interpState);
865 break;
866#endif
867 default:
868 dvmAbort();
869 }
870 }
871
872 *pResult = interpState.retval;
873}
The Android Open Source Project89c1feb2008-12-17 18:03:55 -0800874