blob: 103d2b4d986213397da4d9e51ac2087c3b4efa5c [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) {
354 LOGW("Status=%d on call to %s.%s -\n", self->status,
355 method->clazz->descriptor, method->name);
356 }
357#endif
358
359 assert(self != NULL);
360 assert(method != NULL);
361
362 if (obj != NULL)
363 clazz = obj->clazz;
364 else
365 clazz = method->clazz;
366
367 IF_LOGVV() {
368 char* desc = dexProtoCopyMethodDescriptor(&method->prototype);
369 LOGVV("thread=%d native code calling %s.%s %s\n", self->threadId,
370 clazz->descriptor, method->name, desc);
371 free(desc);
372 }
373
374 if (checkAccess) {
375 /* needed for java.lang.reflect.Method.invoke */
376 if (!dvmCheckMethodAccess(dvmGetCaller2Class(self->curFrame),
377 method))
378 {
379 /* note this throws IAException, not IAError */
380 dvmThrowException("Ljava/lang/IllegalAccessException;",
381 "access to method denied");
382 return NULL;
383 }
384 }
385
386 /*
387 * Push a call frame on. If there isn't enough room for ins, locals,
388 * outs, and the saved state, it will throw an exception.
389 *
390 * This updates self->curFrame.
391 */
392 if (dvmIsNativeMethod(method)) {
393 /* native code calling native code the hard way */
394 if (!dvmPushJNIFrame(self, method)) {
395 assert(dvmCheckException(self));
396 return NULL;
397 }
398 } else {
399 /* native code calling interpreted code */
400 if (!dvmPushInterpFrame(self, method)) {
401 assert(dvmCheckException(self));
402 return NULL;
403 }
404 }
405
406 return clazz;
407}
408
409/*
410 * Issue a method call.
411 *
412 * Pass in NULL for "obj" on calls to static methods.
413 *
414 * (Note this can't be inlined because it takes a variable number of args.)
415 */
416void dvmCallMethod(Thread* self, const Method* method, Object* obj,
417 JValue* pResult, ...)
418{
419 JValue result;
420
421 va_list args;
422 va_start(args, pResult);
423 dvmCallMethodV(self, method, obj, pResult, args);
424 va_end(args);
425}
426
427/*
428 * Issue a method call with a variable number of arguments. We process
429 * the contents of "args" by scanning the method signature.
430 *
431 * Pass in NULL for "obj" on calls to static methods.
432 *
433 * We don't need to take the class as an argument because, in Dalvik,
434 * we don't need to worry about static synchronized methods.
435 */
436void dvmCallMethodV(Thread* self, const Method* method, Object* obj,
437 JValue* pResult, va_list args)
438{
439 const char* desc = &(method->shorty[1]); // [0] is the return type.
440 int verifyCount = 0;
441 ClassObject* clazz;
442 u4* ins;
443
444 clazz = callPrep(self, method, obj, false);
445 if (clazz == NULL)
446 return;
447
448 /* "ins" for new frame start at frame pointer plus locals */
449 ins = ((u4*)self->curFrame) + (method->registersSize - method->insSize);
450
451 //LOGD(" FP is %p, INs live at >= %p\n", self->curFrame, ins);
452
453 /* put "this" pointer into in0 if appropriate */
454 if (!dvmIsStaticMethod(method)) {
455#ifdef WITH_EXTRA_OBJECT_VALIDATION
456 assert(obj != NULL && dvmIsValidObject(obj));
457#endif
458 *ins++ = (u4) obj;
459 verifyCount++;
460 }
461
462 while (*desc != '\0') {
463 switch (*(desc++)) {
464 case 'D': case 'J': {
465 u8 val = va_arg(args, u8);
466 memcpy(ins, &val, 8); // EABI prevents direct store
467 ins += 2;
468 verifyCount += 2;
469 break;
470 }
471 case 'F': {
472 /* floats were normalized to doubles; convert back */
473 float f = (float) va_arg(args, double);
474 *ins++ = dvmFloatToU4(f);
475 verifyCount++;
476 break;
477 }
478#ifdef WITH_EXTRA_OBJECT_VALIDATION
479 case 'L': { /* 'shorty' descr uses L for all refs, incl array */
480 Object* argObj = (Object*) va_arg(args, u4);
481 assert(obj == NULL || dvmIsValidObject(obj));
482 *ins++ = (u4) argObj;
483 verifyCount++;
484 break;
485 }
486#endif
487 default: {
488 *ins++ = va_arg(args, u4);
489 verifyCount++;
490 break;
491 }
492 }
493 }
494
495#ifndef NDEBUG
496 if (verifyCount != method->insSize) {
497 LOGE("Got vfycount=%d insSize=%d for %s.%s\n", verifyCount,
498 method->insSize, clazz->descriptor, method->name);
499 assert(false);
500 goto bail;
501 }
502#endif
503
504 //dvmDumpThreadStack(dvmThreadSelf());
505
506 if (dvmIsNativeMethod(method)) {
507 /*
508 * Because we leave no space for local variables, "curFrame" points
509 * directly at the method arguments.
510 */
511 (*method->nativeFunc)(self->curFrame, pResult, method, self);
512 } else {
513 dvmInterpret(self, method, pResult);
514 }
515
516bail:
517 dvmPopFrame(self);
518}
519
520/*
521 * Issue a method call with arguments provided in an array. We process
522 * the contents of "args" by scanning the method signature.
523 *
524 * The values were likely placed into an uninitialized jvalue array using
525 * the field specifiers, which means that sub-32-bit fields (e.g. short,
526 * boolean) may not have 32 or 64 bits of valid data. This is different
527 * from the varargs invocation where the C compiler does a widening
528 * conversion when calling a function. As a result, we have to be a
529 * little more precise when pulling stuff out.
530 */
531void dvmCallMethodA(Thread* self, const Method* method, Object* obj,
532 JValue* pResult, const jvalue* args)
533{
534 const char* desc = &(method->shorty[1]); // [0] is the return type.
535 int verifyCount = 0;
536 ClassObject* clazz;
537 u4* ins;
538
539 clazz = callPrep(self, method, obj, false);
540 if (clazz == NULL)
541 return;
542
543 /* "ins" for new frame start at frame pointer plus locals */
544 ins = ((u4*)self->curFrame) + (method->registersSize - method->insSize);
545
546 /* put "this" pointer into in0 if appropriate */
547 if (!dvmIsStaticMethod(method)) {
548 assert(obj != NULL);
549 *ins++ = (u4) obj;
550 verifyCount++;
551 }
552
553 while (*desc != '\0') {
554 switch (*(desc++)) {
555 case 'D': case 'J': {
556 memcpy(ins, &args->j, 8); /* EABI prevents direct store */
557 ins += 2;
558 verifyCount += 2;
559 args++;
560 break;
561 }
562 case 'F': case 'I': case 'L': { /* (no '[' in short signatures) */
563 *ins++ = args->i; /* get all 32 bits */
564 verifyCount++;
565 args++;
566 break;
567 }
568 case 'S': {
569 *ins++ = args->s; /* 16 bits, sign-extended */
570 verifyCount++;
571 args++;
572 break;
573 }
574 case 'C': {
575 *ins++ = args->c; /* 16 bits, unsigned */
576 verifyCount++;
577 args++;
578 break;
579 }
580 case 'B': {
581 *ins++ = args->b; /* 8 bits, sign-extended */
582 verifyCount++;
583 args++;
584 break;
585 }
586 case 'Z': {
587 *ins++ = args->z; /* 8 bits, zero or non-zero */
588 verifyCount++;
589 args++;
590 break;
591 }
592 default: {
593 LOGE("Invalid char %c in short signature of %s.%s\n",
594 *(desc-1), clazz->descriptor, method->name);
595 assert(false);
596 goto bail;
597 }
598 }
599 }
600
601#ifndef NDEBUG
602 if (verifyCount != method->insSize) {
603 LOGE("Got vfycount=%d insSize=%d for %s.%s\n", verifyCount,
604 method->insSize, clazz->descriptor, method->name);
605 assert(false);
606 goto bail;
607 }
608#endif
609
610 if (dvmIsNativeMethod(method)) {
611 /*
612 * Because we leave no space for local variables, "curFrame" points
613 * directly at the method arguments.
614 */
615 (*method->nativeFunc)(self->curFrame, pResult, method, self);
616 } else {
617 dvmInterpret(self, method, pResult);
618 }
619
620bail:
621 dvmPopFrame(self);
622}
623
624/*
625 * Invoke a method, using the specified arguments and return type, through
626 * one of the reflection interfaces. Could be a virtual or direct method
627 * (including constructors). Used for reflection.
628 *
629 * Deals with boxing/unboxing primitives and performs widening conversions.
630 *
631 * "invokeObj" will be null for a static method.
632 *
633 * If the invocation returns with an exception raised, we have to wrap it.
634 */
635Object* dvmInvokeMethod(Object* obj, const Method* method,
636 ArrayObject* argList, ArrayObject* params, ClassObject* returnType,
637 bool noAccessCheck)
638{
639 ClassObject* clazz;
640 Object* retObj = NULL;
641 Thread* self = dvmThreadSelf();
642 s4* ins;
643 int verifyCount, argListLength;
644 JValue retval;
645
646 /* verify arg count */
647 if (argList != NULL)
648 argListLength = argList->length;
649 else
650 argListLength = 0;
651 if (argListLength != (int) params->length) {
652 LOGI("invoke: expected %d args, received %d args\n",
653 params->length, argListLength);
654 dvmThrowException("Ljava/lang/IllegalArgumentException;",
655 "wrong number of arguments");
656 return NULL;
657 }
658
659 clazz = callPrep(self, method, obj, !noAccessCheck);
660 if (clazz == NULL)
661 return NULL;
662
663 /* "ins" for new frame start at frame pointer plus locals */
664 ins = ((s4*)self->curFrame) + (method->registersSize - method->insSize);
665 verifyCount = 0;
666
667 //LOGD(" FP is %p, INs live at >= %p\n", self->curFrame, ins);
668
669 /* put "this" pointer into in0 if appropriate */
670 if (!dvmIsStaticMethod(method)) {
671 assert(obj != NULL);
672 *ins++ = (s4) obj;
673 verifyCount++;
674 }
675
676 /*
677 * Copy the args onto the stack. Primitive types are converted when
678 * necessary, and object types are verified.
679 */
680 DataObject** args;
681 ClassObject** types;
682 int i;
683
684 args = (DataObject**) argList->contents;
685 types = (ClassObject**) params->contents;
686 for (i = 0; i < argListLength; i++) {
687 int width;
688
689 width = dvmConvertArgument(*args++, *types++, ins);
690 if (width < 0) {
691 if (*(args-1) != NULL) {
692 LOGV("invoke: type mismatch on arg %d ('%s' '%s')\n",
693 i, (*(args-1))->obj.clazz->descriptor,
694 (*(types-1))->descriptor);
695 }
696 dvmPopFrame(self); // throw wants to pull PC out of stack
697 dvmThrowException("Ljava/lang/IllegalArgumentException;",
698 "argument type mismatch");
699 goto bail_popped;
700 }
701
702 ins += width;
703 verifyCount += width;
704 }
705
706 if (verifyCount != method->insSize) {
707 LOGE("Got vfycount=%d insSize=%d for %s.%s\n", verifyCount,
708 method->insSize, clazz->descriptor, method->name);
709 assert(false);
710 goto bail;
711 }
712 //dvmDumpThreadStack(dvmThreadSelf());
713
714 if (dvmIsNativeMethod(method)) {
715 /*
716 * Because we leave no space for local variables, "curFrame" points
717 * directly at the method arguments.
718 */
719 (*method->nativeFunc)(self->curFrame, &retval, method, self);
720 } else {
721 dvmInterpret(self, method, &retval);
722 }
723
724 /*
725 * If an exception is raised, wrap and replace. This is necessary
726 * because the invoked method could have thrown a checked exception
727 * that the caller wasn't prepared for.
728 *
729 * We might be able to do this up in the interpreted code, but that will
730 * leave us with a shortened stack trace in the top-level exception.
731 */
732 if (dvmCheckException(self)) {
733 dvmWrapException("Ljava/lang/reflect/InvocationTargetException;");
734 } else {
735 /*
736 * If this isn't a void method or constructor, convert the return type
737 * to an appropriate object.
738 *
739 * We don't do this when an exception is raised because the value
740 * in "retval" is undefined.
741 */
742 if (returnType != NULL) {
743 retObj = (Object*)dvmWrapPrimitive(retval, returnType);
744 dvmReleaseTrackedAlloc(retObj, NULL);
745 }
746 }
747
748bail:
749 dvmPopFrame(self);
750bail_popped:
751 return retObj;
752}
753
754typedef struct LineNumFromPcContext {
755 u4 address;
756 u4 lineNum;
757} LineNumFromPcContext;
758
759static int lineNumForPcCb(void *cnxt, u4 address, u4 lineNum)
760{
761 LineNumFromPcContext *pContext = (LineNumFromPcContext *)cnxt;
762
763 // We know that this callback will be called in
764 // ascending address order, so keep going until we find
765 // a match or we've just gone past it.
766
767 if (address > pContext->address) {
768 // The line number from the previous positions callback
769 // wil be the final result.
770 return 1;
771 }
772
773 pContext->lineNum = lineNum;
774
775 return (address == pContext->address) ? 1 : 0;
776}
777
778/*
779 * Determine the source file line number based on the program counter.
780 * "pc" is an offset, in 16-bit units, from the start of the method's code.
781 *
782 * Returns -1 if no match was found (possibly because the source files were
783 * compiled without "-g", so no line number information is present).
784 * Returns -2 for native methods (as expected in exception traces).
785 */
786int dvmLineNumFromPC(const Method* method, u4 relPc)
787{
788 const DexCode* pDexCode = dvmGetMethodCode(method);
789
790 if (pDexCode == NULL) {
791 if (dvmIsNativeMethod(method) && !dvmIsAbstractMethod(method))
792 return -2;
793 return -1; /* can happen for abstract method stub */
794 }
795
796 LineNumFromPcContext context;
797 memset(&context, 0, sizeof(context));
798 context.address = relPc;
799 // A method with no line number info should return -1
800 context.lineNum = -1;
801
802 dexDecodeDebugInfo(method->clazz->pDvmDex->pDexFile, pDexCode,
803 method->clazz->descriptor,
804 method->prototype.protoIdx,
805 method->accessFlags,
806 lineNumForPcCb, NULL, &context);
807
808 return context.lineNum;
809}
810
811/*
812 * Compute the frame depth.
813 *
814 * Excludes "break" frames.
815 */
816int dvmComputeExactFrameDepth(const void* fp)
817{
818 int count = 0;
819
820 for ( ; fp != NULL; fp = SAVEAREA_FROM_FP(fp)->prevFrame) {
821 if (!dvmIsBreakFrame(fp))
822 count++;
823 }
824
825 return count;
826}
827
828/*
829 * Compute the "vague" frame depth, which is just a pointer subtraction.
830 * The result is NOT an overly generous assessment of the number of
831 * frames; the only meaningful use is to compare against the result of
832 * an earlier invocation.
833 *
834 * Useful for implementing single-step debugger modes, which may need to
835 * call this for every instruction.
836 */
837int dvmComputeVagueFrameDepth(Thread* thread, const void* fp)
838{
839 const u1* interpStackStart = thread->interpStackStart;
840 const u1* interpStackBottom = interpStackStart - thread->interpStackSize;
841
842 assert((u1*) fp >= interpStackBottom && (u1*) fp < interpStackStart);
843 return interpStackStart - (u1*) fp;
844}
845
846/*
847 * Get the calling frame. Pass in the current fp.
848 *
849 * Skip "break" frames and reflection invoke frames.
850 */
851void* dvmGetCallerFP(const void* curFrame)
852{
853 void* caller = SAVEAREA_FROM_FP(curFrame)->prevFrame;
854 StackSaveArea* saveArea;
855
856retry:
857 if (dvmIsBreakFrame(caller)) {
858 /* pop up one more */
859 caller = SAVEAREA_FROM_FP(caller)->prevFrame;
860 if (caller == NULL)
861 return NULL; /* hit the top */
862
863 /*
864 * If we got here by java.lang.reflect.Method.invoke(), we don't
865 * want to return Method's class loader. Shift up one and try
866 * again.
867 */
868 saveArea = SAVEAREA_FROM_FP(caller);
869 if (dvmIsReflectionMethod(saveArea->method)) {
870 caller = saveArea->prevFrame;
871 assert(caller != NULL);
872 goto retry;
873 }
874 }
875
876 return caller;
877}
878
879/*
880 * Get the caller's class. Pass in the current fp.
881 *
882 * This is used by e.g. java.lang.Class.
883 */
884ClassObject* dvmGetCallerClass(const void* curFrame)
885{
886 void* caller;
887
888 caller = dvmGetCallerFP(curFrame);
889 if (caller == NULL)
890 return NULL;
891
892 return SAVEAREA_FROM_FP(caller)->method->clazz;
893}
894
895/*
896 * Get the caller's caller's class. Pass in the current fp.
897 *
898 * This is used by e.g. java.lang.Class, which wants to know about the
899 * class loader of the method that called it.
900 */
901ClassObject* dvmGetCaller2Class(const void* curFrame)
902{
903 void* caller = SAVEAREA_FROM_FP(curFrame)->prevFrame;
904 void* callerCaller;
905
906 /* at the top? */
907 if (dvmIsBreakFrame(caller) && SAVEAREA_FROM_FP(caller)->prevFrame == NULL)
908 return NULL;
909
910 /* go one more */
911 callerCaller = dvmGetCallerFP(caller);
912 if (callerCaller == NULL)
913 return NULL;
914
915 return SAVEAREA_FROM_FP(callerCaller)->method->clazz;
916}
917
918/*
919 * Get the caller's caller's caller's class. Pass in the current fp.
920 *
921 * This is used by e.g. java.lang.Class, which wants to know about the
922 * class loader of the method that called it.
923 */
924ClassObject* dvmGetCaller3Class(const void* curFrame)
925{
926 void* caller = SAVEAREA_FROM_FP(curFrame)->prevFrame;
927 int i;
928
929 /* at the top? */
930 if (dvmIsBreakFrame(caller) && SAVEAREA_FROM_FP(caller)->prevFrame == NULL)
931 return NULL;
932
933 /* Walk up two frames if possible. */
934 for (i = 0; i < 2; i++) {
935 caller = dvmGetCallerFP(caller);
936 if (caller == NULL)
937 return NULL;
938 }
939
940 return SAVEAREA_FROM_FP(caller)->method->clazz;
941}
942
943/*
944 * Create a flat array of methods that comprise the current interpreter
945 * stack trace. Pass in the current frame ptr.
946 *
947 * Allocates a new array and fills it with method pointers. Break frames
948 * are skipped, but reflection invocations are not. The caller must free
949 * "*pArray".
950 *
951 * The current frame will be in element 0.
952 *
953 * Returns "true" on success, "false" on failure (e.g. malloc failed).
954 */
955bool dvmCreateStackTraceArray(const void* fp, const Method*** pArray,
956 int* pLength)
957{
958 const Method** array;
959 int idx, depth;
960
961 depth = dvmComputeExactFrameDepth(fp);
962 array = (const Method**) malloc(depth * sizeof(Method*));
963 if (array == NULL)
964 return false;
965
966 for (idx = 0; fp != NULL; fp = SAVEAREA_FROM_FP(fp)->prevFrame) {
967 if (!dvmIsBreakFrame(fp))
968 array[idx++] = SAVEAREA_FROM_FP(fp)->method;
969 }
970 assert(idx == depth);
971
972 *pArray = array;
973 *pLength = depth;
974 return true;
975}
976
977/*
978 * Open up the reserved area and throw an exception. The reserved area
979 * should only be needed to create and initialize the exception itself.
980 *
981 * If we already opened it and we're continuing to overflow, abort the VM.
982 *
983 * We have to leave the "reserved" area open until the "catch" handler has
984 * finished doing its processing. This is because the catch handler may
985 * need to resolve classes, which requires calling into the class loader if
986 * the classes aren't already in the "initiating loader" list.
987 */
988void dvmHandleStackOverflow(Thread* self)
989{
990 /*
991 * Can we make the reserved area available?
992 */
993 if (self->stackOverflowed) {
994 /*
995 * Already did, nothing to do but bail.
996 */
997 LOGE("DalvikVM: double-overflow of stack in threadid=%d; aborting\n",
998 self->threadId);
999 dvmDumpThread(self, false);
1000 dvmAbort();
1001 }
1002
1003 /* open it up to the full range */
1004 LOGI("Stack overflow, expanding (%p to %p)\n", self->interpStackEnd,
1005 self->interpStackStart - self->interpStackSize);
1006 //dvmDumpThread(self, false);
1007 self->interpStackEnd = self->interpStackStart - self->interpStackSize;
1008 self->stackOverflowed = true;
1009
1010 /*
1011 * If we were trying to throw an exception when the stack overflowed,
1012 * we will blow up when doing the class lookup on StackOverflowError
1013 * because of the pending exception. So, we clear it and make it
1014 * the cause of the SOE.
1015 */
1016 Object* excep = dvmGetException(self);
1017 if (excep != NULL) {
1018 LOGW("Stack overflow while throwing exception\n");
1019 dvmClearException(self);
1020 }
1021 dvmThrowChainedException("Ljava/lang/StackOverflowError;", NULL, excep);
1022}
1023
1024/*
1025 * Reduce the available stack size. By this point we should have finished
1026 * our overflow processing.
1027 */
1028void dvmCleanupStackOverflow(Thread* self)
1029{
1030 const u1* newStackEnd;
1031
1032 assert(self->stackOverflowed);
1033
1034 newStackEnd = (self->interpStackStart - self->interpStackSize)
1035 + STACK_OVERFLOW_RESERVE;
1036 if ((u1*)self->curFrame <= newStackEnd) {
1037 LOGE("Can't shrink stack: curFrame is in reserved area (%p %p)\n",
1038 self->interpStackEnd, self->curFrame);
1039 dvmDumpThread(self, false);
1040 dvmAbort();
1041 }
1042
1043 self->interpStackEnd = newStackEnd;
1044 self->stackOverflowed = false;
1045
1046 LOGI("Shrank stack (to %p, curFrame is %p)\n", self->interpStackEnd,
1047 self->curFrame);
1048}
1049
1050
1051/*
1052 * Dump stack frames, starting from the specified frame and moving down.
1053 *
1054 * Each frame holds a pointer to the currently executing method, and the
1055 * saved program counter from the caller ("previous" frame). This means
1056 * we don't have the PC for the current method on the stack, which is
1057 * pretty reasonable since it's in the "PC register" for the VM. Because
1058 * exceptions need to show the correct line number we actually *do* have
1059 * an updated version in the fame's "xtra.currentPc", but it's unreliable.
1060 *
1061 * Note "framePtr" could be NULL in rare circumstances.
1062 */
1063static void dumpFrames(const DebugOutputTarget* target, void* framePtr,
1064 Thread* thread)
1065{
1066 const StackSaveArea* saveArea;
1067 const Method* method;
1068 int checkCount = 0;
1069 const u2* currentPc = NULL;
1070 bool first = true;
1071
1072 /*
1073 * The "currentPc" is updated whenever we execute an instruction that
1074 * might throw an exception. Show it here.
1075 */
1076 if (framePtr != NULL && !dvmIsBreakFrame(framePtr)) {
1077 saveArea = SAVEAREA_FROM_FP(framePtr);
1078
1079 if (saveArea->xtra.currentPc != NULL)
1080 currentPc = saveArea->xtra.currentPc;
1081 }
1082
1083 while (framePtr != NULL) {
1084 saveArea = SAVEAREA_FROM_FP(framePtr);
1085 method = saveArea->method;
1086
1087 if (dvmIsBreakFrame(framePtr)) {
1088 //dvmPrintDebugMessage(target, " (break frame)\n");
1089 } else {
1090 int relPc;
1091
1092 if (currentPc != NULL)
1093 relPc = currentPc - saveArea->method->insns;
1094 else
1095 relPc = -1;
1096
1097 char* className = dvmDescriptorToDot(method->clazz->descriptor);
1098 if (dvmIsNativeMethod(method))
1099 dvmPrintDebugMessage(target,
1100 " at %s.%s(Native Method)\n", className, method->name);
1101 else {
1102 dvmPrintDebugMessage(target,
1103 " at %s.%s(%s:%s%d)\n",
1104 className, method->name, dvmGetMethodSourceFile(method),
1105 (relPc >= 0 && first) ? "~" : "",
1106 relPc < 0 ? -1 : dvmLineNumFromPC(method, relPc));
1107 }
1108 free(className);
1109
1110 if (first &&
1111 (thread->status == THREAD_WAIT ||
1112 thread->status == THREAD_TIMED_WAIT))
1113 {
1114 /* warning: wait status not stable, even in suspend */
1115 Monitor* mon = thread->waitMonitor;
1116 Object* obj = dvmGetMonitorObject(mon);
1117 if (obj != NULL) {
1118 className = dvmDescriptorToDot(obj->clazz->descriptor);
1119 dvmPrintDebugMessage(target,
1120 " - waiting on <%p> (a %s)\n", mon, className);
1121 free(className);
1122 }
1123 }
1124
1125 }
1126
1127 /*
1128 * Get saved PC for previous frame. There's no savedPc in a "break"
1129 * frame, because that represents native or interpreted code
1130 * invoked by the VM. The saved PC is sitting in the "PC register",
1131 * a local variable on the native stack.
1132 */
1133 currentPc = saveArea->savedPc;
1134
1135 first = false;
1136
1137 assert(framePtr != saveArea->prevFrame);
1138 framePtr = saveArea->prevFrame;
1139
1140 checkCount++;
1141 if (checkCount > 200) {
1142 dvmPrintDebugMessage(target,
1143 " ***** printed %d frames, not showing any more\n",
1144 checkCount);
1145 break;
1146 }
1147 }
1148 dvmPrintDebugMessage(target, "\n");
1149}
1150
1151
1152/*
1153 * Dump the stack for the specified thread.
1154 */
1155void dvmDumpThreadStack(const DebugOutputTarget* target, Thread* thread)
1156{
1157 dumpFrames(target, thread->curFrame, thread);
1158}
1159
1160/*
1161 * Dump the stack for the specified thread, which is still running.
1162 *
1163 * This is very dangerous, because stack frames are being pushed on and
1164 * popped off, and if the thread exits we'll be looking at freed memory.
1165 * The plan here is to take a snapshot of the stack and then dump that
1166 * to try to minimize the chances of catching it mid-update. This should
1167 * work reasonably well on a single-CPU system.
1168 *
1169 * There is a small chance that calling here will crash the VM.
1170 */
1171void dvmDumpRunningThreadStack(const DebugOutputTarget* target, Thread* thread)
1172{
1173 StackSaveArea* saveArea;
1174 const u1* origStack;
1175 u1* stackCopy = NULL;
1176 int origSize, fpOffset;
1177 void* fp;
1178 int depthLimit = 200;
1179
1180 if (thread == NULL || thread->curFrame == NULL) {
1181 dvmPrintDebugMessage(target,
1182 "DumpRunning: Thread at %p has no curFrame (threadid=%d)\n",
1183 thread, (thread != NULL) ? thread->threadId : 0);
1184 return;
1185 }
1186
1187 /* wait for a full quantum */
1188 sched_yield();
1189
1190 /* copy the info we need, then the stack itself */
1191 origSize = thread->interpStackSize;
1192 origStack = (const u1*) thread->interpStackStart - origSize;
1193 stackCopy = (u1*) malloc(origSize);
1194 fpOffset = (u1*) thread->curFrame - origStack;
1195 memcpy(stackCopy, origStack, origSize);
1196
1197 /*
1198 * Run through the stack and rewrite the "prev" pointers.
1199 */
1200 //LOGI("DR: fpOff=%d (from %p %p)\n",fpOffset, origStack, thread->curFrame);
1201 fp = stackCopy + fpOffset;
1202 while (true) {
1203 int prevOffset;
1204
1205 if (depthLimit-- < 0) {
1206 /* we're probably screwed */
1207 dvmPrintDebugMessage(target, "DumpRunning: depth limit hit\n");
1208 dvmAbort();
1209 }
1210 saveArea = SAVEAREA_FROM_FP(fp);
1211 if (saveArea->prevFrame == NULL)
1212 break;
1213
1214 prevOffset = (u1*) saveArea->prevFrame - origStack;
1215 if (prevOffset < 0 || prevOffset > origSize) {
1216 dvmPrintDebugMessage(target,
1217 "DumpRunning: bad offset found: %d (from %p %p)\n",
1218 prevOffset, origStack, saveArea->prevFrame);
1219 saveArea->prevFrame = NULL;
1220 break;
1221 }
1222
1223 saveArea->prevFrame = stackCopy + prevOffset;
1224 fp = saveArea->prevFrame;
1225 }
1226
1227 /*
1228 * We still need to pass the Thread for some monitor wait stuff.
1229 */
1230 dumpFrames(target, stackCopy + fpOffset, thread);
1231 free(stackCopy);
1232}
1233