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