blob: d5c5fe99c0e8e58141e08c4ae9015f220e55535c [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 * Stacks and their uses (e.g. native --> interpreted method calls).
18 *
19 * See the majestic ASCII art in Stack.h.
20 */
21#include "Dalvik.h"
22#include "jni.h"
23
24#include <stdlib.h>
25#include <stdarg.h>
26
27/*
28 * Initialize the interpreter stack in a new thread.
29 *
30 * Currently this doesn't do much, since we don't need to zero out the
31 * stack (and we really don't want to if it was created with mmap).
32 */
33bool dvmInitInterpStack(Thread* thread, int stackSize)
34{
35 assert(thread->interpStackStart != NULL);
36
37 assert(thread->curFrame == NULL);
38
39 return true;
40}
41
42/*
43 * We're calling an interpreted method from an internal VM function or
44 * via reflection.
45 *
46 * Push a frame for an interpreted method onto the stack. This is only
47 * used when calling into interpreted code from native code. (The
48 * interpreter does its own stack frame manipulation for interp-->interp
49 * calls.)
50 *
51 * The size we need to reserve is the sum of parameters, local variables,
52 * saved goodies, and outbound parameters.
53 *
54 * We start by inserting a "break" frame, which ensures that the interpreter
55 * hands control back to us after the function we call returns or an
56 * uncaught exception is thrown.
57 */
58static bool dvmPushInterpFrame(Thread* self, const Method* method)
59{
60 StackSaveArea* saveBlock;
61 StackSaveArea* breakSaveBlock;
62 int stackReq;
63 u1* stackPtr;
64
65 assert(!dvmIsNativeMethod(method));
66 assert(!dvmIsAbstractMethod(method));
67
68 stackReq = method->registersSize * 4 // params + locals
69 + sizeof(StackSaveArea) * 2 // break frame + regular frame
70 + method->outsSize * 4; // args to other methods
71
72 if (self->curFrame != NULL)
73 stackPtr = (u1*) SAVEAREA_FROM_FP(self->curFrame);
74 else
75 stackPtr = self->interpStackStart;
76
77 if (stackPtr - stackReq < self->interpStackEnd) {
78 /* not enough space */
79 LOGW("Stack overflow on call to interp (top=%p cur=%p size=%d %s.%s)\n",
80 self->interpStackStart, self->curFrame, self->interpStackSize,
81 method->clazz->descriptor, method->name);
82 dvmHandleStackOverflow(self);
83 assert(dvmCheckException(self));
84 return false;
85 }
86
87 /*
88 * Shift the stack pointer down, leaving space for the function's
89 * args/registers and save area.
90 */
91 stackPtr -= sizeof(StackSaveArea);
92 breakSaveBlock = (StackSaveArea*)stackPtr;
93 stackPtr -= method->registersSize * 4 + sizeof(StackSaveArea);
94 saveBlock = (StackSaveArea*) stackPtr;
95
96#if !defined(NDEBUG) && !defined(PAD_SAVE_AREA)
97 /* debug -- memset the new stack, unless we want valgrind's help */
98 memset(stackPtr - (method->outsSize*4), 0xaf, stackReq);
99#endif
100#ifdef EASY_GDB
101 breakSaveBlock->prevSave = FP_FROM_SAVEAREA(self->curFrame);
102 saveBlock->prevSave = breakSaveBlock;
103#endif
104
105 breakSaveBlock->prevFrame = self->curFrame;
106 breakSaveBlock->savedPc = NULL; // not required
107 breakSaveBlock->xtra.localRefTop = NULL; // not required
108 breakSaveBlock->method = NULL;
109 saveBlock->prevFrame = FP_FROM_SAVEAREA(breakSaveBlock);
110 saveBlock->savedPc = NULL; // not required
111 saveBlock->xtra.currentPc = NULL; // not required?
112 saveBlock->method = method;
113
114 LOGVV("PUSH frame: old=%p new=%p (size=%d)\n",
115 self->curFrame, FP_FROM_SAVEAREA(saveBlock),
116 (u1*)self->curFrame - (u1*)FP_FROM_SAVEAREA(saveBlock));
117
118 self->curFrame = FP_FROM_SAVEAREA(saveBlock);
119
120 return true;
121}
122
123/*
124 * We're calling a JNI native method from an internal VM fuction or
125 * via reflection. This is also used to create the "fake" native-method
126 * frames at the top of the interpreted stack.
127 *
128 * This actually pushes two frames; the first is a "break" frame.
129 *
130 * The top frame has additional space for JNI local reference tracking.
131 */
132bool dvmPushJNIFrame(Thread* self, const Method* method)
133{
134 StackSaveArea* saveBlock;
135 StackSaveArea* breakSaveBlock;
136 int stackReq;
137 u1* stackPtr;
138
139 assert(dvmIsNativeMethod(method));
140
141 stackReq = method->registersSize * 4 // params only
142 + sizeof(StackSaveArea) * 2; // break frame + regular frame
143
144 if (self->curFrame != NULL)
145 stackPtr = (u1*) SAVEAREA_FROM_FP(self->curFrame);
146 else
147 stackPtr = self->interpStackStart;
148
149 if (stackPtr - stackReq < self->interpStackEnd) {
150 /* not enough space */
151 LOGW("Stack overflow on call to native (top=%p cur=%p size=%d '%s')\n",
152 self->interpStackStart, self->curFrame, self->interpStackSize,
153 method->name);
154 dvmHandleStackOverflow(self);
155 assert(dvmCheckException(self));
156 return false;
157 }
158
159 /*
160 * Shift the stack pointer down, leaving space for just the stack save
161 * area for the break frame, then shift down farther for the full frame.
162 * We leave space for the method args, which are copied in later.
163 */
164 stackPtr -= sizeof(StackSaveArea);
165 breakSaveBlock = (StackSaveArea*)stackPtr;
166 stackPtr -= method->registersSize * 4 + sizeof(StackSaveArea);
167 saveBlock = (StackSaveArea*) stackPtr;
168
169#if !defined(NDEBUG) && !defined(PAD_SAVE_AREA)
170 /* debug -- memset the new stack */
171 memset(stackPtr, 0xaf, stackReq);
172#endif
173#ifdef EASY_GDB
174 if (self->curFrame == NULL)
175 breakSaveBlock->prevSave = NULL;
176 else
177 breakSaveBlock->prevSave = FP_FROM_SAVEAREA(self->curFrame);
178 saveBlock->prevSave = breakSaveBlock;
179#endif
180
181 breakSaveBlock->prevFrame = self->curFrame;
182 breakSaveBlock->savedPc = NULL; // not required
183 breakSaveBlock->xtra.localRefTop = NULL; // not required
184 breakSaveBlock->method = NULL;
185 saveBlock->prevFrame = FP_FROM_SAVEAREA(breakSaveBlock);
186 saveBlock->savedPc = NULL; // not required
187 saveBlock->xtra.localRefTop = self->jniLocalRefTable.nextEntry;
188 saveBlock->method = method;
189
190 LOGVV("PUSH JNI frame: old=%p new=%p (size=%d)\n",
191 self->curFrame, FP_FROM_SAVEAREA(saveBlock),
192 (u1*)self->curFrame - (u1*)FP_FROM_SAVEAREA(saveBlock));
193
194 self->curFrame = FP_FROM_SAVEAREA(saveBlock);
195
196 return true;
197}
198
199/*
200 * This is used by the JNI PushLocalFrame call. We push a new frame onto
201 * the stack that has no ins, outs, or locals, and no break frame above it.
202 * It's strictly used for tracking JNI local refs, and will be popped off
203 * by dvmPopFrame if it's not removed explicitly.
204 */
205bool dvmPushLocalFrame(Thread* self, const Method* method)
206{
207 StackSaveArea* saveBlock;
208 int stackReq;
209 u1* stackPtr;
210
211 assert(dvmIsNativeMethod(method));
212
213 stackReq = sizeof(StackSaveArea); // regular frame
214
215 assert(self->curFrame != NULL);
216 stackPtr = (u1*) SAVEAREA_FROM_FP(self->curFrame);
217
218 if (stackPtr - stackReq < self->interpStackEnd) {
219 /* not enough space; let JNI throw the exception */
220 LOGW("Stack overflow on PushLocal (top=%p cur=%p size=%d '%s')\n",
221 self->interpStackStart, self->curFrame, self->interpStackSize,
222 method->name);
223 dvmHandleStackOverflow(self);
224 assert(dvmCheckException(self));
225 return false;
226 }
227
228 /*
229 * Shift the stack pointer down, leaving space for just the stack save
230 * area for the break frame, then shift down farther for the full frame.
231 */
232 stackPtr -= sizeof(StackSaveArea);
233 saveBlock = (StackSaveArea*) stackPtr;
234
235#if !defined(NDEBUG) && !defined(PAD_SAVE_AREA)
236 /* debug -- memset the new stack */
237 memset(stackPtr, 0xaf, stackReq);
238#endif
239#ifdef EASY_GDB
240 saveBlock->prevSave = FP_FROM_SAVEAREA(self->curFrame);
241#endif
242
243 saveBlock->prevFrame = self->curFrame;
244 saveBlock->savedPc = NULL; // not required
245 saveBlock->xtra.localRefTop = self->jniLocalRefTable.nextEntry;
246 saveBlock->method = method;
247
248 LOGVV("PUSH JNI local frame: old=%p new=%p (size=%d)\n",
249 self->curFrame, FP_FROM_SAVEAREA(saveBlock),
250 (u1*)self->curFrame - (u1*)FP_FROM_SAVEAREA(saveBlock));
251
252 self->curFrame = FP_FROM_SAVEAREA(saveBlock);
253
254 return true;
255}
256
257/*
258 * Pop one frame pushed on by JNI PushLocalFrame.
259 *
260 * If we've gone too far, the previous frame is either a break frame or
261 * an interpreted frame. Either way, the method pointer won't match.
262 */
263bool dvmPopLocalFrame(Thread* self)
264{
265 StackSaveArea* saveBlock = SAVEAREA_FROM_FP(self->curFrame);
266
267 assert(!dvmIsBreakFrame(self->curFrame));
268 if (saveBlock->method != SAVEAREA_FROM_FP(saveBlock->prevFrame)->method) {
269 /*
270 * The previous frame doesn't have the same method pointer -- we've
271 * been asked to pop too much.
272 */
273 assert(dvmIsBreakFrame(saveBlock->prevFrame) ||
274 !dvmIsNativeMethod(
275 SAVEAREA_FROM_FP(saveBlock->prevFrame)->method));
276 return false;
277 }
278
279 LOGVV("POP JNI local frame: removing %s, now %s\n",
280 saveBlock->method->name,
281 SAVEAREA_FROM_FP(saveBlock->prevFrame)->method->name);
282 dvmPopJniLocals(self, saveBlock);
283 self->curFrame = saveBlock->prevFrame;
284
285 return true;
286}
287
288/*
289 * Pop a frame we added. There should be one method frame and one break
290 * frame.
291 *
292 * If JNI Push/PopLocalFrame calls were mismatched, we might end up
293 * popping multiple method frames before we find the break.
294 *
295 * Returns "false" if there was no frame to pop.
296 */
297static bool dvmPopFrame(Thread* self)
298{
299 StackSaveArea* saveBlock;
300
301 if (self->curFrame == NULL)
302 return false;
303
304 saveBlock = SAVEAREA_FROM_FP(self->curFrame);
305 assert(!dvmIsBreakFrame(self->curFrame));
306
307 /*
308 * Remove everything up to the break frame. If this was a call into
309 * native code, pop the JNI local references table.
310 */
311 while (saveBlock->prevFrame != NULL && saveBlock->method != NULL) {
312 /* probably a native->native JNI call */
313
314 if (dvmIsNativeMethod(saveBlock->method)) {
315 LOGVV("Popping JNI stack frame for %s.%s%s\n",
316 saveBlock->method->clazz->descriptor,
317 saveBlock->method->name,
318 (SAVEAREA_FROM_FP(saveBlock->prevFrame)->method == NULL) ?
319 "" : " (JNI local)");
320 assert(saveBlock->xtra.localRefTop != NULL);
321 assert(saveBlock->xtra.localRefTop >=self->jniLocalRefTable.table &&
322 saveBlock->xtra.localRefTop <=self->jniLocalRefTable.nextEntry);
323
324 dvmPopJniLocals(self, saveBlock);
325 }
326
327 saveBlock = SAVEAREA_FROM_FP(saveBlock->prevFrame);
328 }
329 if (saveBlock->method != NULL) {
330 LOGE("PopFrame missed the break\n");
331 assert(false);
332 dvmAbort(); // stack trashed -- nowhere to go in this thread
333 }
334
335 LOGVV("POP frame: cur=%p new=%p\n",
336 self->curFrame, saveBlock->prevFrame);
337
338 self->curFrame = saveBlock->prevFrame;
339 return true;
340}
341
342/*
343 * Common code for dvmCallMethodV/A and dvmInvokeMethod.
344 *
345 * Pushes a call frame on, advancing self->curFrame.
346 */
347static ClassObject* callPrep(Thread* self, const Method* method, Object* obj,
348 bool checkAccess)
349{
350 ClassObject* clazz;
351
352#ifndef NDEBUG
353 if (self->status != THREAD_RUNNING) {
Andy McFaddenfea44ba2009-07-01 14:52:13 -0700354 LOGW("threadid=%d: status=%d on call to %s.%s -\n",
355 self->threadId, self->status,
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800356 method->clazz->descriptor, method->name);
357 }
358#endif
359
360 assert(self != NULL);
361 assert(method != NULL);
362
363 if (obj != NULL)
364 clazz = obj->clazz;
365 else
366 clazz = method->clazz;
367
368 IF_LOGVV() {
369 char* desc = dexProtoCopyMethodDescriptor(&method->prototype);
370 LOGVV("thread=%d native code calling %s.%s %s\n", self->threadId,
371 clazz->descriptor, method->name, desc);
372 free(desc);
373 }
374
375 if (checkAccess) {
376 /* needed for java.lang.reflect.Method.invoke */
377 if (!dvmCheckMethodAccess(dvmGetCaller2Class(self->curFrame),
378 method))
379 {
380 /* note this throws IAException, not IAError */
381 dvmThrowException("Ljava/lang/IllegalAccessException;",
382 "access to method denied");
383 return NULL;
384 }
385 }
386
387 /*
388 * Push a call frame on. If there isn't enough room for ins, locals,
389 * outs, and the saved state, it will throw an exception.
390 *
391 * This updates self->curFrame.
392 */
393 if (dvmIsNativeMethod(method)) {
394 /* native code calling native code the hard way */
395 if (!dvmPushJNIFrame(self, method)) {
396 assert(dvmCheckException(self));
397 return NULL;
398 }
399 } else {
400 /* native code calling interpreted code */
401 if (!dvmPushInterpFrame(self, method)) {
402 assert(dvmCheckException(self));
403 return NULL;
404 }
405 }
406
407 return clazz;
408}
409
410/*
411 * Issue a method call.
412 *
413 * Pass in NULL for "obj" on calls to static methods.
414 *
415 * (Note this can't be inlined because it takes a variable number of args.)
416 */
417void dvmCallMethod(Thread* self, const Method* method, Object* obj,
418 JValue* pResult, ...)
419{
420 JValue result;
421
422 va_list args;
423 va_start(args, pResult);
424 dvmCallMethodV(self, method, obj, pResult, args);
425 va_end(args);
426}
427
428/*
429 * Issue a method call with a variable number of arguments. We process
430 * the contents of "args" by scanning the method signature.
431 *
432 * Pass in NULL for "obj" on calls to static methods.
433 *
434 * We don't need to take the class as an argument because, in Dalvik,
435 * we don't need to worry about static synchronized methods.
436 */
437void dvmCallMethodV(Thread* self, const Method* method, Object* obj,
438 JValue* pResult, va_list args)
439{
440 const char* desc = &(method->shorty[1]); // [0] is the return type.
441 int verifyCount = 0;
442 ClassObject* clazz;
443 u4* ins;
444
445 clazz = callPrep(self, method, obj, false);
446 if (clazz == NULL)
447 return;
448
449 /* "ins" for new frame start at frame pointer plus locals */
450 ins = ((u4*)self->curFrame) + (method->registersSize - method->insSize);
451
452 //LOGD(" FP is %p, INs live at >= %p\n", self->curFrame, ins);
453
454 /* put "this" pointer into in0 if appropriate */
455 if (!dvmIsStaticMethod(method)) {
456#ifdef WITH_EXTRA_OBJECT_VALIDATION
457 assert(obj != NULL && dvmIsValidObject(obj));
458#endif
459 *ins++ = (u4) obj;
460 verifyCount++;
461 }
462
463 while (*desc != '\0') {
464 switch (*(desc++)) {
465 case 'D': case 'J': {
466 u8 val = va_arg(args, u8);
467 memcpy(ins, &val, 8); // EABI prevents direct store
468 ins += 2;
469 verifyCount += 2;
470 break;
471 }
472 case 'F': {
473 /* floats were normalized to doubles; convert back */
474 float f = (float) va_arg(args, double);
475 *ins++ = dvmFloatToU4(f);
476 verifyCount++;
477 break;
478 }
479#ifdef WITH_EXTRA_OBJECT_VALIDATION
480 case 'L': { /* 'shorty' descr uses L for all refs, incl array */
481 Object* argObj = (Object*) va_arg(args, u4);
482 assert(obj == NULL || dvmIsValidObject(obj));
483 *ins++ = (u4) argObj;
484 verifyCount++;
485 break;
486 }
487#endif
488 default: {
489 *ins++ = va_arg(args, u4);
490 verifyCount++;
491 break;
492 }
493 }
494 }
495
496#ifndef NDEBUG
497 if (verifyCount != method->insSize) {
498 LOGE("Got vfycount=%d insSize=%d for %s.%s\n", verifyCount,
499 method->insSize, clazz->descriptor, method->name);
500 assert(false);
501 goto bail;
502 }
503#endif
504
505 //dvmDumpThreadStack(dvmThreadSelf());
506
507 if (dvmIsNativeMethod(method)) {
508 /*
509 * Because we leave no space for local variables, "curFrame" points
510 * directly at the method arguments.
511 */
512 (*method->nativeFunc)(self->curFrame, pResult, method, self);
513 } else {
514 dvmInterpret(self, method, pResult);
515 }
516
517bail:
518 dvmPopFrame(self);
519}
520
521/*
522 * Issue a method call with arguments provided in an array. We process
523 * the contents of "args" by scanning the method signature.
524 *
525 * The values were likely placed into an uninitialized jvalue array using
526 * the field specifiers, which means that sub-32-bit fields (e.g. short,
527 * boolean) may not have 32 or 64 bits of valid data. This is different
528 * from the varargs invocation where the C compiler does a widening
529 * conversion when calling a function. As a result, we have to be a
530 * little more precise when pulling stuff out.
531 */
532void dvmCallMethodA(Thread* self, const Method* method, Object* obj,
533 JValue* pResult, const jvalue* args)
534{
535 const char* desc = &(method->shorty[1]); // [0] is the return type.
536 int verifyCount = 0;
537 ClassObject* clazz;
538 u4* ins;
539
540 clazz = callPrep(self, method, obj, false);
541 if (clazz == NULL)
542 return;
543
544 /* "ins" for new frame start at frame pointer plus locals */
545 ins = ((u4*)self->curFrame) + (method->registersSize - method->insSize);
546
547 /* put "this" pointer into in0 if appropriate */
548 if (!dvmIsStaticMethod(method)) {
549 assert(obj != NULL);
550 *ins++ = (u4) obj;
551 verifyCount++;
552 }
553
554 while (*desc != '\0') {
555 switch (*(desc++)) {
556 case 'D': case 'J': {
557 memcpy(ins, &args->j, 8); /* EABI prevents direct store */
558 ins += 2;
559 verifyCount += 2;
560 args++;
561 break;
562 }
563 case 'F': case 'I': case 'L': { /* (no '[' in short signatures) */
564 *ins++ = args->i; /* get all 32 bits */
565 verifyCount++;
566 args++;
567 break;
568 }
569 case 'S': {
570 *ins++ = args->s; /* 16 bits, sign-extended */
571 verifyCount++;
572 args++;
573 break;
574 }
575 case 'C': {
576 *ins++ = args->c; /* 16 bits, unsigned */
577 verifyCount++;
578 args++;
579 break;
580 }
581 case 'B': {
582 *ins++ = args->b; /* 8 bits, sign-extended */
583 verifyCount++;
584 args++;
585 break;
586 }
587 case 'Z': {
588 *ins++ = args->z; /* 8 bits, zero or non-zero */
589 verifyCount++;
590 args++;
591 break;
592 }
593 default: {
594 LOGE("Invalid char %c in short signature of %s.%s\n",
595 *(desc-1), clazz->descriptor, method->name);
596 assert(false);
597 goto bail;
598 }
599 }
600 }
601
602#ifndef NDEBUG
603 if (verifyCount != method->insSize) {
604 LOGE("Got vfycount=%d insSize=%d for %s.%s\n", verifyCount,
605 method->insSize, clazz->descriptor, method->name);
606 assert(false);
607 goto bail;
608 }
609#endif
610
611 if (dvmIsNativeMethod(method)) {
612 /*
613 * Because we leave no space for local variables, "curFrame" points
614 * directly at the method arguments.
615 */
616 (*method->nativeFunc)(self->curFrame, pResult, method, self);
617 } else {
618 dvmInterpret(self, method, pResult);
619 }
620
621bail:
622 dvmPopFrame(self);
623}
624
625/*
626 * Invoke a method, using the specified arguments and return type, through
627 * one of the reflection interfaces. Could be a virtual or direct method
628 * (including constructors). Used for reflection.
629 *
630 * Deals with boxing/unboxing primitives and performs widening conversions.
631 *
632 * "invokeObj" will be null for a static method.
633 *
634 * If the invocation returns with an exception raised, we have to wrap it.
635 */
636Object* dvmInvokeMethod(Object* obj, const Method* method,
637 ArrayObject* argList, ArrayObject* params, ClassObject* returnType,
638 bool noAccessCheck)
639{
640 ClassObject* clazz;
641 Object* retObj = NULL;
642 Thread* self = dvmThreadSelf();
643 s4* ins;
644 int verifyCount, argListLength;
645 JValue retval;
646
647 /* verify arg count */
648 if (argList != NULL)
649 argListLength = argList->length;
650 else
651 argListLength = 0;
652 if (argListLength != (int) params->length) {
653 LOGI("invoke: expected %d args, received %d args\n",
654 params->length, argListLength);
655 dvmThrowException("Ljava/lang/IllegalArgumentException;",
656 "wrong number of arguments");
657 return NULL;
658 }
659
660 clazz = callPrep(self, method, obj, !noAccessCheck);
661 if (clazz == NULL)
662 return NULL;
663
664 /* "ins" for new frame start at frame pointer plus locals */
665 ins = ((s4*)self->curFrame) + (method->registersSize - method->insSize);
666 verifyCount = 0;
667
668 //LOGD(" FP is %p, INs live at >= %p\n", self->curFrame, ins);
669
670 /* put "this" pointer into in0 if appropriate */
671 if (!dvmIsStaticMethod(method)) {
672 assert(obj != NULL);
673 *ins++ = (s4) obj;
674 verifyCount++;
675 }
676
677 /*
678 * Copy the args onto the stack. Primitive types are converted when
679 * necessary, and object types are verified.
680 */
681 DataObject** args;
682 ClassObject** types;
683 int i;
684
685 args = (DataObject**) argList->contents;
686 types = (ClassObject**) params->contents;
687 for (i = 0; i < argListLength; i++) {
688 int width;
689
690 width = dvmConvertArgument(*args++, *types++, ins);
691 if (width < 0) {
692 if (*(args-1) != NULL) {
693 LOGV("invoke: type mismatch on arg %d ('%s' '%s')\n",
694 i, (*(args-1))->obj.clazz->descriptor,
695 (*(types-1))->descriptor);
696 }
697 dvmPopFrame(self); // throw wants to pull PC out of stack
698 dvmThrowException("Ljava/lang/IllegalArgumentException;",
699 "argument type mismatch");
700 goto bail_popped;
701 }
702
703 ins += width;
704 verifyCount += width;
705 }
706
707 if (verifyCount != method->insSize) {
708 LOGE("Got vfycount=%d insSize=%d for %s.%s\n", verifyCount,
709 method->insSize, clazz->descriptor, method->name);
710 assert(false);
711 goto bail;
712 }
713 //dvmDumpThreadStack(dvmThreadSelf());
714
715 if (dvmIsNativeMethod(method)) {
716 /*
717 * Because we leave no space for local variables, "curFrame" points
718 * directly at the method arguments.
719 */
720 (*method->nativeFunc)(self->curFrame, &retval, method, self);
721 } else {
722 dvmInterpret(self, method, &retval);
723 }
724
725 /*
726 * If an exception is raised, wrap and replace. This is necessary
727 * because the invoked method could have thrown a checked exception
728 * that the caller wasn't prepared for.
729 *
730 * We might be able to do this up in the interpreted code, but that will
731 * leave us with a shortened stack trace in the top-level exception.
732 */
733 if (dvmCheckException(self)) {
734 dvmWrapException("Ljava/lang/reflect/InvocationTargetException;");
735 } else {
736 /*
737 * If this isn't a void method or constructor, convert the return type
738 * to an appropriate object.
739 *
740 * We don't do this when an exception is raised because the value
741 * in "retval" is undefined.
742 */
743 if (returnType != NULL) {
744 retObj = (Object*)dvmWrapPrimitive(retval, returnType);
745 dvmReleaseTrackedAlloc(retObj, NULL);
746 }
747 }
748
749bail:
750 dvmPopFrame(self);
751bail_popped:
752 return retObj;
753}
754
755typedef struct LineNumFromPcContext {
756 u4 address;
757 u4 lineNum;
758} LineNumFromPcContext;
759
760static int lineNumForPcCb(void *cnxt, u4 address, u4 lineNum)
761{
762 LineNumFromPcContext *pContext = (LineNumFromPcContext *)cnxt;
763
764 // We know that this callback will be called in
765 // ascending address order, so keep going until we find
766 // a match or we've just gone past it.
767
768 if (address > pContext->address) {
769 // The line number from the previous positions callback
770 // wil be the final result.
771 return 1;
772 }
773
774 pContext->lineNum = lineNum;
775
776 return (address == pContext->address) ? 1 : 0;
777}
778
779/*
780 * Determine the source file line number based on the program counter.
781 * "pc" is an offset, in 16-bit units, from the start of the method's code.
782 *
783 * Returns -1 if no match was found (possibly because the source files were
784 * compiled without "-g", so no line number information is present).
785 * Returns -2 for native methods (as expected in exception traces).
786 */
787int dvmLineNumFromPC(const Method* method, u4 relPc)
788{
789 const DexCode* pDexCode = dvmGetMethodCode(method);
790
791 if (pDexCode == NULL) {
792 if (dvmIsNativeMethod(method) && !dvmIsAbstractMethod(method))
793 return -2;
794 return -1; /* can happen for abstract method stub */
795 }
796
797 LineNumFromPcContext context;
798 memset(&context, 0, sizeof(context));
799 context.address = relPc;
800 // A method with no line number info should return -1
801 context.lineNum = -1;
802
803 dexDecodeDebugInfo(method->clazz->pDvmDex->pDexFile, pDexCode,
804 method->clazz->descriptor,
805 method->prototype.protoIdx,
806 method->accessFlags,
807 lineNumForPcCb, NULL, &context);
808
809 return context.lineNum;
810}
811
812/*
813 * Compute the frame depth.
814 *
815 * Excludes "break" frames.
816 */
817int dvmComputeExactFrameDepth(const void* fp)
818{
819 int count = 0;
820
821 for ( ; fp != NULL; fp = SAVEAREA_FROM_FP(fp)->prevFrame) {
822 if (!dvmIsBreakFrame(fp))
823 count++;
824 }
825
826 return count;
827}
828
829/*
830 * Compute the "vague" frame depth, which is just a pointer subtraction.
831 * The result is NOT an overly generous assessment of the number of
832 * frames; the only meaningful use is to compare against the result of
833 * an earlier invocation.
834 *
835 * Useful for implementing single-step debugger modes, which may need to
836 * call this for every instruction.
837 */
838int dvmComputeVagueFrameDepth(Thread* thread, const void* fp)
839{
840 const u1* interpStackStart = thread->interpStackStart;
841 const u1* interpStackBottom = interpStackStart - thread->interpStackSize;
842
843 assert((u1*) fp >= interpStackBottom && (u1*) fp < interpStackStart);
844 return interpStackStart - (u1*) fp;
845}
846
847/*
848 * Get the calling frame. Pass in the current fp.
849 *
850 * Skip "break" frames and reflection invoke frames.
851 */
852void* dvmGetCallerFP(const void* curFrame)
853{
854 void* caller = SAVEAREA_FROM_FP(curFrame)->prevFrame;
855 StackSaveArea* saveArea;
856
857retry:
858 if (dvmIsBreakFrame(caller)) {
859 /* pop up one more */
860 caller = SAVEAREA_FROM_FP(caller)->prevFrame;
861 if (caller == NULL)
862 return NULL; /* hit the top */
863
864 /*
865 * If we got here by java.lang.reflect.Method.invoke(), we don't
866 * want to return Method's class loader. Shift up one and try
867 * again.
868 */
869 saveArea = SAVEAREA_FROM_FP(caller);
870 if (dvmIsReflectionMethod(saveArea->method)) {
871 caller = saveArea->prevFrame;
872 assert(caller != NULL);
873 goto retry;
874 }
875 }
876
877 return caller;
878}
879
880/*
881 * Get the caller's class. Pass in the current fp.
882 *
883 * This is used by e.g. java.lang.Class.
884 */
885ClassObject* dvmGetCallerClass(const void* curFrame)
886{
887 void* caller;
888
889 caller = dvmGetCallerFP(curFrame);
890 if (caller == NULL)
891 return NULL;
892
893 return SAVEAREA_FROM_FP(caller)->method->clazz;
894}
895
896/*
897 * Get the caller's caller's class. Pass in the current fp.
898 *
899 * This is used by e.g. java.lang.Class, which wants to know about the
900 * class loader of the method that called it.
901 */
902ClassObject* dvmGetCaller2Class(const void* curFrame)
903{
904 void* caller = SAVEAREA_FROM_FP(curFrame)->prevFrame;
905 void* callerCaller;
906
907 /* at the top? */
908 if (dvmIsBreakFrame(caller) && SAVEAREA_FROM_FP(caller)->prevFrame == NULL)
909 return NULL;
910
911 /* go one more */
912 callerCaller = dvmGetCallerFP(caller);
913 if (callerCaller == NULL)
914 return NULL;
915
916 return SAVEAREA_FROM_FP(callerCaller)->method->clazz;
917}
918
919/*
920 * Get the caller's caller's caller's class. Pass in the current fp.
921 *
922 * This is used by e.g. java.lang.Class, which wants to know about the
923 * class loader of the method that called it.
924 */
925ClassObject* dvmGetCaller3Class(const void* curFrame)
926{
927 void* caller = SAVEAREA_FROM_FP(curFrame)->prevFrame;
928 int i;
929
930 /* at the top? */
931 if (dvmIsBreakFrame(caller) && SAVEAREA_FROM_FP(caller)->prevFrame == NULL)
932 return NULL;
933
934 /* Walk up two frames if possible. */
935 for (i = 0; i < 2; i++) {
936 caller = dvmGetCallerFP(caller);
937 if (caller == NULL)
938 return NULL;
939 }
940
941 return SAVEAREA_FROM_FP(caller)->method->clazz;
942}
943
944/*
945 * Create a flat array of methods that comprise the current interpreter
946 * stack trace. Pass in the current frame ptr.
947 *
948 * Allocates a new array and fills it with method pointers. Break frames
949 * are skipped, but reflection invocations are not. The caller must free
950 * "*pArray".
951 *
952 * The current frame will be in element 0.
953 *
954 * Returns "true" on success, "false" on failure (e.g. malloc failed).
955 */
956bool dvmCreateStackTraceArray(const void* fp, const Method*** pArray,
957 int* pLength)
958{
959 const Method** array;
960 int idx, depth;
961
962 depth = dvmComputeExactFrameDepth(fp);
963 array = (const Method**) malloc(depth * sizeof(Method*));
964 if (array == NULL)
965 return false;
966
967 for (idx = 0; fp != NULL; fp = SAVEAREA_FROM_FP(fp)->prevFrame) {
968 if (!dvmIsBreakFrame(fp))
969 array[idx++] = SAVEAREA_FROM_FP(fp)->method;
970 }
971 assert(idx == depth);
972
973 *pArray = array;
974 *pLength = depth;
975 return true;
976}
977
978/*
979 * Open up the reserved area and throw an exception. The reserved area
980 * should only be needed to create and initialize the exception itself.
981 *
982 * If we already opened it and we're continuing to overflow, abort the VM.
983 *
984 * We have to leave the "reserved" area open until the "catch" handler has
985 * finished doing its processing. This is because the catch handler may
986 * need to resolve classes, which requires calling into the class loader if
987 * the classes aren't already in the "initiating loader" list.
988 */
989void dvmHandleStackOverflow(Thread* self)
990{
991 /*
992 * Can we make the reserved area available?
993 */
994 if (self->stackOverflowed) {
995 /*
996 * Already did, nothing to do but bail.
997 */
998 LOGE("DalvikVM: double-overflow of stack in threadid=%d; aborting\n",
999 self->threadId);
1000 dvmDumpThread(self, false);
1001 dvmAbort();
1002 }
1003
1004 /* open it up to the full range */
1005 LOGI("Stack overflow, expanding (%p to %p)\n", self->interpStackEnd,
1006 self->interpStackStart - self->interpStackSize);
1007 //dvmDumpThread(self, false);
1008 self->interpStackEnd = self->interpStackStart - self->interpStackSize;
1009 self->stackOverflowed = true;
1010
1011 /*
1012 * If we were trying to throw an exception when the stack overflowed,
1013 * we will blow up when doing the class lookup on StackOverflowError
1014 * because of the pending exception. So, we clear it and make it
1015 * the cause of the SOE.
1016 */
1017 Object* excep = dvmGetException(self);
1018 if (excep != NULL) {
1019 LOGW("Stack overflow while throwing exception\n");
1020 dvmClearException(self);
1021 }
1022 dvmThrowChainedException("Ljava/lang/StackOverflowError;", NULL, excep);
1023}
1024
1025/*
1026 * Reduce the available stack size. By this point we should have finished
1027 * our overflow processing.
1028 */
1029void dvmCleanupStackOverflow(Thread* self)
1030{
1031 const u1* newStackEnd;
1032
1033 assert(self->stackOverflowed);
1034
1035 newStackEnd = (self->interpStackStart - self->interpStackSize)
1036 + STACK_OVERFLOW_RESERVE;
1037 if ((u1*)self->curFrame <= newStackEnd) {
1038 LOGE("Can't shrink stack: curFrame is in reserved area (%p %p)\n",
1039 self->interpStackEnd, self->curFrame);
1040 dvmDumpThread(self, false);
1041 dvmAbort();
1042 }
1043
1044 self->interpStackEnd = newStackEnd;
1045 self->stackOverflowed = false;
1046
1047 LOGI("Shrank stack (to %p, curFrame is %p)\n", self->interpStackEnd,
1048 self->curFrame);
1049}
1050
1051
1052/*
1053 * Dump stack frames, starting from the specified frame and moving down.
1054 *
1055 * Each frame holds a pointer to the currently executing method, and the
1056 * saved program counter from the caller ("previous" frame). This means
1057 * we don't have the PC for the current method on the stack, which is
1058 * pretty reasonable since it's in the "PC register" for the VM. Because
1059 * exceptions need to show the correct line number we actually *do* have
1060 * an updated version in the fame's "xtra.currentPc", but it's unreliable.
1061 *
1062 * Note "framePtr" could be NULL in rare circumstances.
1063 */
1064static void dumpFrames(const DebugOutputTarget* target, void* framePtr,
1065 Thread* thread)
1066{
1067 const StackSaveArea* saveArea;
1068 const Method* method;
1069 int checkCount = 0;
1070 const u2* currentPc = NULL;
1071 bool first = true;
1072
1073 /*
1074 * The "currentPc" is updated whenever we execute an instruction that
1075 * might throw an exception. Show it here.
1076 */
1077 if (framePtr != NULL && !dvmIsBreakFrame(framePtr)) {
1078 saveArea = SAVEAREA_FROM_FP(framePtr);
1079
1080 if (saveArea->xtra.currentPc != NULL)
1081 currentPc = saveArea->xtra.currentPc;
1082 }
1083
1084 while (framePtr != NULL) {
1085 saveArea = SAVEAREA_FROM_FP(framePtr);
1086 method = saveArea->method;
1087
1088 if (dvmIsBreakFrame(framePtr)) {
1089 //dvmPrintDebugMessage(target, " (break frame)\n");
1090 } else {
1091 int relPc;
1092
1093 if (currentPc != NULL)
1094 relPc = currentPc - saveArea->method->insns;
1095 else
1096 relPc = -1;
1097
1098 char* className = dvmDescriptorToDot(method->clazz->descriptor);
1099 if (dvmIsNativeMethod(method))
1100 dvmPrintDebugMessage(target,
1101 " at %s.%s(Native Method)\n", className, method->name);
1102 else {
1103 dvmPrintDebugMessage(target,
1104 " at %s.%s(%s:%s%d)\n",
1105 className, method->name, dvmGetMethodSourceFile(method),
1106 (relPc >= 0 && first) ? "~" : "",
1107 relPc < 0 ? -1 : dvmLineNumFromPC(method, relPc));
1108 }
1109 free(className);
1110
1111 if (first &&
1112 (thread->status == THREAD_WAIT ||
1113 thread->status == THREAD_TIMED_WAIT))
1114 {
1115 /* warning: wait status not stable, even in suspend */
1116 Monitor* mon = thread->waitMonitor;
1117 Object* obj = dvmGetMonitorObject(mon);
1118 if (obj != NULL) {
1119 className = dvmDescriptorToDot(obj->clazz->descriptor);
1120 dvmPrintDebugMessage(target,
1121 " - waiting on <%p> (a %s)\n", mon, className);
1122 free(className);
1123 }
1124 }
1125
1126 }
1127
1128 /*
1129 * Get saved PC for previous frame. There's no savedPc in a "break"
1130 * frame, because that represents native or interpreted code
1131 * invoked by the VM. The saved PC is sitting in the "PC register",
1132 * a local variable on the native stack.
1133 */
1134 currentPc = saveArea->savedPc;
1135
1136 first = false;
1137
1138 assert(framePtr != saveArea->prevFrame);
1139 framePtr = saveArea->prevFrame;
1140
1141 checkCount++;
1142 if (checkCount > 200) {
1143 dvmPrintDebugMessage(target,
1144 " ***** printed %d frames, not showing any more\n",
1145 checkCount);
1146 break;
1147 }
1148 }
1149 dvmPrintDebugMessage(target, "\n");
1150}
1151
1152
1153/*
1154 * Dump the stack for the specified thread.
1155 */
1156void dvmDumpThreadStack(const DebugOutputTarget* target, Thread* thread)
1157{
1158 dumpFrames(target, thread->curFrame, thread);
1159}
1160
1161/*
1162 * Dump the stack for the specified thread, which is still running.
1163 *
1164 * This is very dangerous, because stack frames are being pushed on and
1165 * popped off, and if the thread exits we'll be looking at freed memory.
1166 * The plan here is to take a snapshot of the stack and then dump that
1167 * to try to minimize the chances of catching it mid-update. This should
1168 * work reasonably well on a single-CPU system.
1169 *
1170 * There is a small chance that calling here will crash the VM.
1171 */
1172void dvmDumpRunningThreadStack(const DebugOutputTarget* target, Thread* thread)
1173{
1174 StackSaveArea* saveArea;
1175 const u1* origStack;
1176 u1* stackCopy = NULL;
1177 int origSize, fpOffset;
1178 void* fp;
1179 int depthLimit = 200;
1180
1181 if (thread == NULL || thread->curFrame == NULL) {
1182 dvmPrintDebugMessage(target,
1183 "DumpRunning: Thread at %p has no curFrame (threadid=%d)\n",
1184 thread, (thread != NULL) ? thread->threadId : 0);
1185 return;
1186 }
1187
1188 /* wait for a full quantum */
1189 sched_yield();
1190
1191 /* copy the info we need, then the stack itself */
1192 origSize = thread->interpStackSize;
1193 origStack = (const u1*) thread->interpStackStart - origSize;
1194 stackCopy = (u1*) malloc(origSize);
1195 fpOffset = (u1*) thread->curFrame - origStack;
1196 memcpy(stackCopy, origStack, origSize);
1197
1198 /*
1199 * Run through the stack and rewrite the "prev" pointers.
1200 */
1201 //LOGI("DR: fpOff=%d (from %p %p)\n",fpOffset, origStack, thread->curFrame);
1202 fp = stackCopy + fpOffset;
1203 while (true) {
1204 int prevOffset;
1205
1206 if (depthLimit-- < 0) {
1207 /* we're probably screwed */
1208 dvmPrintDebugMessage(target, "DumpRunning: depth limit hit\n");
1209 dvmAbort();
1210 }
1211 saveArea = SAVEAREA_FROM_FP(fp);
1212 if (saveArea->prevFrame == NULL)
1213 break;
1214
1215 prevOffset = (u1*) saveArea->prevFrame - origStack;
1216 if (prevOffset < 0 || prevOffset > origSize) {
1217 dvmPrintDebugMessage(target,
1218 "DumpRunning: bad offset found: %d (from %p %p)\n",
1219 prevOffset, origStack, saveArea->prevFrame);
1220 saveArea->prevFrame = NULL;
1221 break;
1222 }
1223
1224 saveArea->prevFrame = stackCopy + prevOffset;
1225 fp = saveArea->prevFrame;
1226 }
1227
1228 /*
1229 * We still need to pass the Thread for some monitor wait stuff.
1230 */
1231 dumpFrames(target, stackCopy + fpOffset, thread);
1232 free(stackCopy);
1233}
1234