2 * Copyright (C) 2008 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
20 #include "libdex/DexCatch.h"
25 Notes on Exception Handling
27 We have one fairly sticky issue to deal with: creating the exception stack
28 trace. The trouble is that we need the current value of the program
29 counter for the method now being executed, but that's only held in a local
30 variable or hardware register in the main interpreter loop.
32 The exception mechanism requires that the current stack trace be associated
33 with a Throwable at the time the Throwable is constructed. The construction
34 may or may not be associated with a throw. We have three situations to
37 (1) A Throwable is created with a "new Throwable" statement in the
38 application code, for immediate or deferred use with a "throw" statement.
39 (2) The VM throws an exception from within the interpreter core, e.g.
40 after an integer divide-by-zero.
41 (3) The VM throws an exception from somewhere deeper down, e.g. while
42 trying to link a class.
44 We need to have the current value for the PC, which means that for
45 situation (3) the interpreter loop must copy it to an externally-accessible
46 location before handling any opcode that could cause the VM to throw
47 an exception. We can't store it globally, because the various threads
48 would trample each other. We can't store it in the Thread structure,
49 because it'll get overwritten as soon as the Throwable constructor starts
50 executing. It needs to go on the stack, but our stack frames hold the
51 caller's *saved* PC, not the current PC.
53 Situation #1 doesn't require special handling. Situation #2 could be dealt
54 with by passing the PC into the exception creation function. The trick
55 is to solve situation #3 in a way that adds minimal overhead to common
56 operations. Making it more costly to throw an exception is acceptable.
58 There are a few ways to deal with this:
60 (a) Change "savedPc" to "currentPc" in the stack frame. All of the
61 stack logic gets offset by one frame. The current PC is written
62 to the current stack frame when necessary.
63 (b) Write the current PC into the current stack frame, but without
64 replacing "savedPc". The JNI local refs pointer, which is only
65 used for native code, can be overloaded to save space.
66 (c) In dvmThrowException(), push an extra stack frame on, with the
67 current PC in it. The current PC is written into the Thread struct
68 when necessary, and copied out when the VM throws.
69 (d) Before doing something that might throw an exception, push a
70 temporary frame on with the saved PC in it.
72 Solution (a) is the simplest, but breaks Dalvik's goal of mingling native
73 and interpreted stacks.
75 Solution (b) retains the simplicity of (a) without rearranging the stack,
76 but now in some cases we're storing the PC twice, which feels wrong.
78 Solution (c) usually works, because we push the saved PC onto the stack
79 before the Throwable construction can overwrite the copy in Thread. One
80 way solution (c) could break is:
81 - Interpreter saves the PC
82 - Execute some bytecode, which runs successfully (and alters the saved PC)
83 - Throw an exception before re-saving the PC (i.e in the same opcode)
84 This is a risk for anything that could cause <clinit> to execute, e.g.
85 executing a static method or accessing a static field. Attemping to access
86 a field that doesn't exist in a class that does exist might cause this.
87 It may be possible to simply bracket the dvmCallMethod*() functions to
90 Solution (d) incurs additional overhead, but may have other benefits (e.g.
91 it's easy to find the stack frames that should be removed before storage
94 Current plan is option (b), because it's simple, fast, and doesn't change
95 the way the stack works.
99 static bool initException(Object* exception, const char* msg, Object* cause,
102 void dvmThrowExceptionFmtV(ClassObject* exceptionClass,
103 const char* fmt, va_list args)
107 vsnprintf(msgBuf, sizeof(msgBuf), fmt, args);
108 dvmThrowChainedException(exceptionClass, msgBuf, NULL);
111 void dvmThrowChainedException(ClassObject* excepClass, const char* msg,
114 Thread* self = dvmThreadSelf();
117 if (excepClass == NULL) {
119 * The exception class was passed in as NULL. This might happen
120 * early on in VM initialization. There's nothing better to do
121 * than just log the message as an error and abort.
123 LOGE("Fatal error: %s", msg);
127 /* make sure the exception is initialized */
128 if (!dvmIsClassInitialized(excepClass) && !dvmInitClass(excepClass)) {
129 LOGE("ERROR: unable to initialize exception class '%s'",
130 excepClass->descriptor);
131 if (strcmp(excepClass->descriptor, "Ljava/lang/InternalError;") == 0)
133 dvmThrowChainedException(gDvm.exInternalError,
134 "failed to init original exception class", cause);
138 exception = dvmAllocObject(excepClass, ALLOC_DEFAULT);
139 if (exception == NULL) {
141 * We're in a lot of trouble. We might be in the process of
142 * throwing an out-of-memory exception, in which case the
143 * pre-allocated object will have been thrown when our object alloc
144 * failed. So long as there's an exception raised, return and
145 * allow the system to try to recover. If not, something is broken
146 * and we need to bail out.
148 if (dvmCheckException(self))
150 LOGE("FATAL: unable to allocate exception '%s' '%s'",
151 excepClass->descriptor, msg != NULL ? msg : "(no msg)");
156 * Init the exception.
158 if (gDvm.optimizing) {
159 /* need the exception object, but can't invoke interpreted code */
160 LOGV("Skipping init of exception %s '%s'",
161 excepClass->descriptor, msg);
163 assert(excepClass == exception->clazz);
164 if (!initException(exception, msg, cause, self)) {
166 * Whoops. If we can't initialize the exception, we can't use
167 * it. If there's an exception already set, the constructor
168 * probably threw an OutOfMemoryError.
170 if (!dvmCheckException(self)) {
172 * We're required to throw something, so we just
173 * throw the pre-constructed internal error.
175 self->exception = gDvm.internalErrorObj;
181 self->exception = exception;
184 dvmReleaseTrackedAlloc(exception, self);
187 void dvmThrowChainedExceptionWithClassMessage(
188 ClassObject* exceptionClass, const char* messageDescriptor,
191 char* message = dvmDescriptorToName(messageDescriptor);
193 dvmThrowChainedException(exceptionClass, message, cause);
198 * Find and return an exception constructor method that can take the
199 * indicated parameters, or return NULL if no such constructor exists.
201 static Method* findExceptionInitMethod(ClassObject* excepClass,
202 bool hasMessage, bool hasCause)
208 result = dvmFindDirectMethodByDescriptor(
209 excepClass, "<init>",
210 "(Ljava/lang/String;Ljava/lang/Throwable;)V");
212 result = dvmFindDirectMethodByDescriptor(
213 excepClass, "<init>", "(Ljava/lang/String;)V");
216 if (result != NULL) {
221 return dvmFindDirectMethodByDescriptor(
222 excepClass, "<init>",
223 "(Ljava/lang/Object;Ljava/lang/Throwable;)V");
225 return dvmFindDirectMethodByDescriptor(
226 excepClass, "<init>", "(Ljava/lang/Object;)V");
228 } else if (hasCause) {
229 return dvmFindDirectMethodByDescriptor(
230 excepClass, "<init>", "(Ljava/lang/Throwable;)V");
232 return dvmFindDirectMethodByDescriptor(excepClass, "<init>", "()V");
237 * Initialize an exception with an appropriate constructor.
239 * "exception" is the exception object to initialize.
240 * Either or both of "msg" and "cause" may be null.
241 * "self" is dvmThreadSelf(), passed in so we don't have to look it up again.
243 * If the process of initializing the exception causes another
244 * exception (e.g., OutOfMemoryError) to be thrown, return an error
245 * and leave self->exception intact.
247 static bool initException(Object* exception, const char* msg, Object* cause,
256 } initKind = kInitUnknown;
257 Method* initMethod = NULL;
258 ClassObject* excepClass = exception->clazz;
259 StringObject* msgStr = NULL;
261 bool needInitCause = false;
263 assert(self != NULL);
264 assert(self->exception == NULL);
266 /* if we have a message, create a String */
270 msgStr = dvmCreateStringFromCstr(msg);
271 if (msgStr == NULL) {
272 LOGW("Could not allocate message string \"%s\" while "
273 "throwing internal exception (%s)",
274 msg, excepClass->descriptor);
280 if (!dvmInstanceof(cause->clazz, gDvm.exThrowable)) {
281 LOGE("Tried to init exception with cause '%s'",
282 cause->clazz->descriptor);
288 * The Throwable class has four public constructors:
290 * (2) Throwable(String message)
291 * (3) Throwable(String message, Throwable cause) (added in 1.4)
292 * (4) Throwable(Throwable cause) (added in 1.4)
294 * The first two are part of the original design, and most exception
295 * classes should support them. The third prototype was used by
296 * individual exceptions. e.g. ClassNotFoundException added it in 1.2.
297 * The general "cause" mechanism was added in 1.4. Some classes,
298 * such as IllegalArgumentException, initially supported the first
299 * two, but added the second two in a later release.
301 * Exceptions may be picky about how their "cause" field is initialized.
302 * If you call ClassNotFoundException(String), it may choose to
303 * initialize its "cause" field to null. Doing so prevents future
304 * calls to Throwable.initCause().
306 * So, if "cause" is not NULL, we need to look for a constructor that
307 * takes a throwable. If we can't find one, we fall back on calling
308 * #1/#2 and making a separate call to initCause(). Passing a null ref
309 * for "message" into Throwable(String, Throwable) is allowed, but we
310 * prefer to use the Throwable-only version because it has different
313 * java.lang.TypeNotPresentException is a strange case -- it has #3 but
314 * not #2. (Some might argue that the constructor is actually not #3,
315 * because it doesn't take the message string as an argument, but it
316 * has the same effect and we can work with it here.)
318 * java.lang.AssertionError is also a strange case -- it has a
319 * constructor that takes an Object, but not one that takes a String.
320 * There may be other cases like this, as well, so we generally look
321 * for an Object-taking constructor if we can't find one that takes
325 if (msgStr == NULL) {
326 initMethod = findExceptionInitMethod(excepClass, false, false);
327 initKind = kInitNoarg;
329 initMethod = findExceptionInitMethod(excepClass, true, false);
330 if (initMethod != NULL) {
334 initMethod = findExceptionInitMethod(excepClass, true, true);
335 if (initMethod != NULL) {
336 initKind = kInitMsgThrow;
341 if (msgStr == NULL) {
342 initMethod = findExceptionInitMethod(excepClass, false, true);
343 if (initMethod != NULL) {
344 initKind = kInitThrow;
346 initMethod = findExceptionInitMethod(excepClass, false, false);
347 initKind = kInitNoarg;
348 needInitCause = true;
351 initMethod = findExceptionInitMethod(excepClass, true, true);
352 if (initMethod != NULL) {
353 initKind = kInitMsgThrow;
355 initMethod = findExceptionInitMethod(excepClass, true, false);
357 needInitCause = true;
362 if (initMethod == NULL) {
364 * We can't find the desired constructor. This can happen if a
365 * subclass of java/lang/Throwable doesn't define an expected
366 * constructor, e.g. it doesn't provide one that takes a string
367 * when a message has been provided.
369 LOGW("WARNING: exception class '%s' missing constructor "
370 "(msg='%s' kind=%d)",
371 excepClass->descriptor, msg, initKind);
372 assert(strcmp(excepClass->descriptor,
373 "Ljava/lang/RuntimeException;") != 0);
374 dvmThrowChainedException(gDvm.exRuntimeException,
375 "re-throw on exception class missing constructor", NULL);
380 * Call the constructor with the appropriate arguments.
385 LOGVV("+++ exc noarg (ic=%d)", needInitCause);
386 dvmCallMethod(self, initMethod, exception, &unused);
389 LOGVV("+++ exc msg (ic=%d)", needInitCause);
390 dvmCallMethod(self, initMethod, exception, &unused, msgStr);
393 LOGVV("+++ exc throw");
394 assert(!needInitCause);
395 dvmCallMethod(self, initMethod, exception, &unused, cause);
398 LOGVV("+++ exc msg+throw");
399 assert(!needInitCause);
400 dvmCallMethod(self, initMethod, exception, &unused, msgStr, cause);
408 * It's possible the constructor has thrown an exception. If so, we
409 * return an error and let our caller deal with it.
411 if (self->exception != NULL) {
412 LOGW("Exception thrown (%s) while throwing internal exception (%s)",
413 self->exception->clazz->descriptor, exception->clazz->descriptor);
418 * If this exception was caused by another exception, and we weren't
419 * able to find a cause-setting constructor, set the "cause" field
420 * with an explicit call.
424 initCause = dvmFindVirtualMethodHierByDescriptor(excepClass, "initCause",
425 "(Ljava/lang/Throwable;)Ljava/lang/Throwable;");
426 if (initCause != NULL) {
427 dvmCallMethod(self, initCause, exception, &unused, cause);
428 if (self->exception != NULL) {
429 /* initCause() threw an exception; return an error and
430 * let the caller deal with it.
432 LOGW("Exception thrown (%s) during initCause() "
433 "of internal exception (%s)",
434 self->exception->clazz->descriptor,
435 exception->clazz->descriptor);
439 LOGW("WARNING: couldn't find initCause in '%s'",
440 excepClass->descriptor);
448 dvmReleaseTrackedAlloc((Object*) msgStr, self); // NULL is ok
454 * Clear the pending exception. This is used by the optimization and
455 * verification code, which mostly happens during runs of dexopt.
457 * This can also be called when the VM is in a "normal" state, e.g. when
458 * verifying classes that couldn't be verified at optimization time.
460 void dvmClearOptException(Thread* self)
462 self->exception = NULL;
466 * Returns "true" if this is a "checked" exception, i.e. it's a subclass
467 * of Throwable (assumed) but not a subclass of RuntimeException or Error.
469 bool dvmIsCheckedException(const Object* exception)
471 if (dvmInstanceof(exception->clazz, gDvm.exError) ||
472 dvmInstanceof(exception->clazz, gDvm.exRuntimeException))
481 * Wrap the now-pending exception in a different exception. This is useful
482 * for reflection stuff that wants to hand a checked exception back from a
483 * method that doesn't declare it.
485 * If something fails, an (unchecked) exception related to that failure
486 * will be pending instead.
488 void dvmWrapException(const char* newExcepStr)
490 Thread* self = dvmThreadSelf();
492 ClassObject* iteClass;
494 origExcep = dvmGetException(self);
495 dvmAddTrackedAlloc(origExcep, self); // don't let the GC free it
497 dvmClearException(self); // clear before class lookup
498 iteClass = dvmFindSystemClass(newExcepStr);
499 if (iteClass != NULL) {
503 iteExcep = dvmAllocObject(iteClass, ALLOC_DEFAULT);
504 if (iteExcep != NULL) {
505 initMethod = dvmFindDirectMethodByDescriptor(iteClass, "<init>",
506 "(Ljava/lang/Throwable;)V");
507 if (initMethod != NULL) {
509 dvmCallMethod(self, initMethod, iteExcep, &unused,
512 /* if <init> succeeded, replace the old exception */
513 if (!dvmCheckException(self))
514 dvmSetException(self, iteExcep);
516 dvmReleaseTrackedAlloc(iteExcep, NULL);
518 /* if initMethod doesn't exist, or failed... */
519 if (!dvmCheckException(self))
520 dvmSetException(self, origExcep);
522 /* leave OutOfMemoryError pending */
525 /* leave ClassNotFoundException pending */
528 assert(dvmCheckException(self));
529 dvmReleaseTrackedAlloc(origExcep, self);
533 * Get the "cause" field from an exception.
535 * The Throwable class initializes the "cause" field to "this" to
536 * differentiate between being initialized to null and never being
537 * initialized. We check for that here and convert it to NULL.
539 Object* dvmGetExceptionCause(const Object* exception)
541 if (!dvmInstanceof(exception->clazz, gDvm.exThrowable)) {
542 LOGE("Tried to get cause from object of type '%s'",
543 exception->clazz->descriptor);
547 dvmGetFieldObject(exception, gDvm.offJavaLangThrowable_cause);
548 if (cause == exception)
555 * Print the stack trace of the current exception on stderr. This is called
556 * from the JNI ExceptionDescribe call.
558 * For consistency we just invoke the Throwable printStackTrace method,
559 * which might be overridden in the exception object.
561 * Exceptions thrown during the course of printing the stack trace are
564 void dvmPrintExceptionStackTrace()
566 Thread* self = dvmThreadSelf();
570 exception = self->exception;
571 if (exception == NULL)
574 dvmAddTrackedAlloc(exception, self);
575 self->exception = NULL;
576 printMethod = dvmFindVirtualMethodHierByDescriptor(exception->clazz,
577 "printStackTrace", "()V");
578 if (printMethod != NULL) {
580 dvmCallMethod(self, printMethod, exception, &unused);
582 LOGW("WARNING: could not find printStackTrace in %s",
583 exception->clazz->descriptor);
586 if (self->exception != NULL) {
587 LOGW("NOTE: exception thrown while printing stack trace: %s",
588 self->exception->clazz->descriptor);
591 self->exception = exception;
592 dvmReleaseTrackedAlloc(exception, self);
596 * Search the method's list of exceptions for a match.
598 * Returns the offset of the catch block on success, or -1 on failure.
600 static int findCatchInMethod(Thread* self, const Method* method, int relPc,
601 ClassObject* excepClass)
604 * Need to clear the exception before entry. Otherwise, dvmResolveClass
605 * might think somebody threw an exception while it was loading a class.
607 assert(!dvmCheckException(self));
608 assert(!dvmIsNativeMethod(method));
610 LOGVV("findCatchInMethod %s.%s excep=%s depth=%d",
611 method->clazz->descriptor, method->name, excepClass->descriptor,
612 dvmComputeExactFrameDepth(self->interpSave.curFrame));
614 DvmDex* pDvmDex = method->clazz->pDvmDex;
615 const DexCode* pCode = dvmGetMethodCode(method);
616 DexCatchIterator iterator;
618 if (dexFindCatchHandler(&iterator, pCode, relPc)) {
620 DexCatchHandler* handler = dexCatchIteratorNext(&iterator);
622 if (handler == NULL) {
626 if (handler->typeIdx == kDexNoIndex) {
628 LOGV("Match on catch-all block at 0x%02x in %s.%s for %s",
629 relPc, method->clazz->descriptor,
630 method->name, excepClass->descriptor);
631 return handler->address;
634 ClassObject* throwable =
635 dvmDexGetResolvedClass(pDvmDex, handler->typeIdx);
636 if (throwable == NULL) {
638 * TODO: this behaves badly if we run off the stack
639 * while trying to throw an exception. The problem is
640 * that, if we're in a class loaded by a class loader,
641 * the call to dvmResolveClass has to ask the class
642 * loader for help resolving any previously-unresolved
643 * classes. If this particular class loader hasn't
644 * resolved StackOverflowError, it will call into
645 * interpreted code, and blow up.
647 * We currently replace the previous exception with
648 * the StackOverflowError, which means they won't be
649 * catching it *unless* they explicitly catch
650 * StackOverflowError, in which case we'll be unable
651 * to resolve the class referred to by the "catch"
654 * We end up getting a huge pile of warnings if we do
655 * a simple synthetic test, because this method gets
656 * called on every stack frame up the tree, and it
659 * This eventually bails out, effectively becoming an
660 * uncatchable exception, so other than the flurry of
661 * warnings it's not really a problem. Still, we could
662 * probably handle this better.
664 throwable = dvmResolveClass(method->clazz, handler->typeIdx,
666 if (throwable == NULL) {
668 * We couldn't find the exception they wanted in
669 * our class files (or, perhaps, the stack blew up
670 * while we were querying a class loader). Cough
671 * up a warning, then move on to the next entry.
672 * Keep the exception status clear.
674 LOGW("Could not resolve class ref'ed in exception "
675 "catch list (class index %d, exception %s)",
677 (self->exception != NULL) ?
678 self->exception->clazz->descriptor : "(none)");
679 dvmClearException(self);
684 //LOGD("ADDR MATCH, check %s instanceof %s",
685 // excepClass->descriptor, pEntry->excepClass->descriptor);
687 if (dvmInstanceof(excepClass, throwable)) {
688 LOGV("Match on catch block at 0x%02x in %s.%s for %s",
689 relPc, method->clazz->descriptor,
690 method->name, excepClass->descriptor);
691 return handler->address;
696 LOGV("No matching catch block at 0x%02x in %s for %s",
697 relPc, method->name, excepClass->descriptor);
702 * Find a matching "catch" block. "pc" is the relative PC within the
703 * current method, indicating the offset from the start in 16-bit units.
705 * Returns the offset to the catch block, or -1 if we run up against a
706 * break frame without finding anything.
708 * The class resolution stuff we have to do while evaluating the "catch"
709 * blocks could cause an exception. The caller should clear the exception
710 * before calling here and restore it after.
712 * Sets *newFrame to the frame pointer of the frame with the catch block.
713 * If "scanOnly" is false, self->interpSave.curFrame is also set to this value.
715 int dvmFindCatchBlock(Thread* self, int relPc, Object* exception,
716 bool scanOnly, void** newFrame)
718 u4* fp = self->interpSave.curFrame;
721 assert(!dvmCheckException(self));
724 StackSaveArea* saveArea = SAVEAREA_FROM_FP(fp);
725 catchAddr = findCatchInMethod(self, saveArea->method, relPc,
731 * Normally we'd check for ACC_SYNCHRONIZED methods and unlock
732 * them as we unroll. Dalvik uses what amount to generated
733 * "finally" blocks to take care of this for us.
736 /* output method profiling info */
738 TRACE_METHOD_UNROLL(self, saveArea->method);
742 * Move up one frame. If the next thing up is a break frame,
743 * break out now so we're left unrolled to the last method frame.
744 * We need to point there so we can roll up the JNI local refs
745 * if this was a native method.
747 assert(saveArea->prevFrame != NULL);
748 if (dvmIsBreakFrame((u4*)saveArea->prevFrame)) {
750 break; // bail with catchAddr == -1
753 * We're scanning for the debugger. It needs to know if this
754 * exception is going to be caught or not, and we need to figure
755 * out if it will be caught *ever* not just between the current
756 * position and the next break frame. We can't tell what native
757 * code is going to do, so we assume it never catches exceptions.
759 * Start by finding an interpreted code frame.
761 fp = saveArea->prevFrame; // this is the break frame
762 saveArea = SAVEAREA_FROM_FP(fp);
763 fp = saveArea->prevFrame; // this may be a good one
765 if (!dvmIsBreakFrame((u4*)fp)) {
766 saveArea = SAVEAREA_FROM_FP(fp);
767 if (!dvmIsNativeMethod(saveArea->method))
771 fp = SAVEAREA_FROM_FP(fp)->prevFrame;
774 break; // bail with catchAddr == -1
777 * Now fp points to the "good" frame. When the interp code
778 * invoked the native code, it saved a copy of its current PC
779 * into xtra.currentPc. Pull it out of there.
782 saveArea->xtra.currentPc - SAVEAREA_FROM_FP(fp)->method->insns;
784 fp = saveArea->prevFrame;
786 /* savedPc in was-current frame goes with method in now-current */
787 relPc = saveArea->savedPc - SAVEAREA_FROM_FP(fp)->method->insns;
792 self->interpSave.curFrame = fp;
795 * The class resolution in findCatchInMethod() could cause an exception.
796 * Clear it to be safe.
798 self->exception = NULL;
805 * We have to carry the exception's stack trace around, but in many cases
806 * it will never be examined. It makes sense to keep it in a compact,
807 * VM-specific object, rather than an array of Objects with strings.
809 * Pass in the thread whose stack we're interested in. If "thread" is
810 * not self, the thread must be suspended. This implies that the thread
811 * list lock is held, which means we can't allocate objects or we risk
812 * jamming the GC. So, we allow this function to return different formats.
813 * (This shouldn't be called directly -- see the inline functions in the
816 * If "wantObject" is true, this returns a newly-allocated Object, which is
817 * presently an array of integers, but could become something else in the
818 * future. If "wantObject" is false, return plain malloc data.
820 * NOTE: if we support class unloading, we will need to scan the class
821 * object references out of these arrays.
823 void* dvmFillInStackTraceInternal(Thread* thread, bool wantObject, size_t* pCount)
825 ArrayObject* stackData = NULL;
826 int* simpleData = NULL;
834 fp = thread->interpSave.curFrame;
836 assert(thread == dvmThreadSelf() || dvmIsSuspended(thread));
839 * We're looking at a stack frame for code running below a Throwable
840 * constructor. We want to remove the Throwable methods and the
841 * superclass initializations so the user doesn't see them when they
842 * read the stack dump.
844 * TODO: this just scrapes off the top layers of Throwable. Might not do
845 * the right thing if we create an exception object or cause a VM
846 * exception while in a Throwable method.
849 const StackSaveArea* saveArea = SAVEAREA_FROM_FP(fp);
850 const Method* method = saveArea->method;
852 if (dvmIsBreakFrame((u4*)fp))
854 if (!dvmInstanceof(method->clazz, gDvm.exThrowable))
856 //LOGD("EXCEP: ignoring %s.%s",
857 // method->clazz->descriptor, method->name);
858 fp = saveArea->prevFrame;
863 * Compute the stack depth.
867 const StackSaveArea* saveArea = SAVEAREA_FROM_FP(fp);
869 if (!dvmIsBreakFrame((u4*)fp))
872 assert(fp != saveArea->prevFrame);
873 fp = saveArea->prevFrame;
875 //LOGD("EXCEP: stack depth is %d", stackDepth);
881 * We need to store a pointer to the Method and the program counter.
882 * We have 4-byte pointers, so we use '[I'.
885 assert(sizeof(Method*) == 4);
886 stackData = dvmAllocPrimitiveArray('I', stackDepth*2, ALLOC_DEFAULT);
887 if (stackData == NULL) {
888 assert(dvmCheckException(dvmThreadSelf()));
891 intPtr = (int*)(void*)stackData->contents;
893 /* array of ints; first entry is stack depth */
894 assert(sizeof(Method*) == sizeof(int));
895 simpleData = (int*) malloc(sizeof(int) * stackDepth*2);
896 if (simpleData == NULL)
899 assert(pCount != NULL);
903 *pCount = stackDepth;
907 const StackSaveArea* saveArea = SAVEAREA_FROM_FP(fp);
908 const Method* method = saveArea->method;
910 if (!dvmIsBreakFrame((u4*)fp)) {
911 //LOGD("EXCEP keeping %s.%s", method->clazz->descriptor,
914 *intPtr++ = (int) method;
915 if (dvmIsNativeMethod(method)) {
916 *intPtr++ = 0; /* no saved PC for native methods */
918 assert(saveArea->xtra.currentPc >= method->insns &&
919 saveArea->xtra.currentPc <
920 method->insns + dvmGetMethodInsnsSize(method));
921 *intPtr++ = (int) (saveArea->xtra.currentPc - method->insns);
924 stackDepth--; // for verification
927 assert(fp != saveArea->prevFrame);
928 fp = saveArea->prevFrame;
930 assert(stackDepth == 0);
934 dvmReleaseTrackedAlloc((Object*) stackData, dvmThreadSelf());
943 * Given an Object previously created by dvmFillInStackTrace(), use the
944 * contents of the saved stack trace to generate an array of
945 * java/lang/StackTraceElement objects.
947 * The returned array is not added to the "local refs" list.
949 ArrayObject* dvmGetStackTrace(const Object* ostackData)
951 const ArrayObject* stackData = (const ArrayObject*) ostackData;
952 size_t stackSize = stackData->length / 2;
953 const int* intVals = (const int*)(void*)stackData->contents;
954 return dvmGetStackTraceRaw(intVals, stackSize);
958 * Generate an array of StackTraceElement objects from the raw integer
959 * data encoded by dvmFillInStackTrace().
961 * "intVals" points to the first {method,pc} pair.
963 * The returned array is not added to the "local refs" list.
965 ArrayObject* dvmGetStackTraceRaw(const int* intVals, size_t stackDepth)
967 /* allocate a StackTraceElement array */
968 ClassObject* klass = gDvm.classJavaLangStackTraceElementArray;
969 ArrayObject* array = dvmAllocArrayByClass(klass, stackDepth, ALLOC_DEFAULT);
971 dvmFillStackTraceElements(intVals, stackDepth, array);
972 dvmReleaseTrackedAlloc((Object*) array, NULL);
978 * Fills the StackTraceElement array elements from the raw integer
979 * data encoded by dvmFillInStackTrace().
981 * "intVals" points to the first {method,pc} pair.
983 void dvmFillStackTraceElements(const int* intVals, size_t stackDepth, ArrayObject* steArray)
987 /* init this if we haven't yet */
988 if (!dvmIsClassInitialized(gDvm.classJavaLangStackTraceElement))
989 dvmInitClass(gDvm.classJavaLangStackTraceElement);
992 * Allocate and initialize a StackTraceElement for each stack frame.
993 * We use the standard constructor to configure the object.
995 for (i = 0; i < stackDepth; i++) {
996 Object* ste = dvmAllocObject(gDvm.classJavaLangStackTraceElement,ALLOC_DEFAULT);
1001 Method* meth = (Method*) *intVals++;
1002 int pc = *intVals++;
1005 if (pc == -1) // broken top frame?
1008 lineNumber = dvmLineNumFromPC(meth, pc);
1010 std::string dotName(dvmHumanReadableDescriptor(meth->clazz->descriptor));
1011 StringObject* className = dvmCreateStringFromCstr(dotName);
1013 StringObject* methodName = dvmCreateStringFromCstr(meth->name);
1015 const char* sourceFile = dvmGetMethodSourceFile(meth);
1016 StringObject* fileName = (sourceFile != NULL) ? dvmCreateStringFromCstr(sourceFile) : NULL;
1020 * public StackTraceElement(String declaringClass, String methodName,
1021 * String fileName, int lineNumber)
1022 * (where lineNumber==-2 means "native")
1025 dvmCallMethod(dvmThreadSelf(), gDvm.methJavaLangStackTraceElement_init,
1026 ste, &unused, className, methodName, fileName, lineNumber);
1028 dvmReleaseTrackedAlloc(ste, NULL);
1029 dvmReleaseTrackedAlloc((Object*) className, NULL);
1030 dvmReleaseTrackedAlloc((Object*) methodName, NULL);
1031 dvmReleaseTrackedAlloc((Object*) fileName, NULL);
1033 if (dvmCheckException(dvmThreadSelf())) {
1037 dvmSetObjectArrayElement(steArray, i, ste);
1042 * Dump the contents of a raw stack trace to the log.
1044 void dvmLogRawStackTrace(const int* intVals, int stackDepth) {
1046 * Run through the array of stack frame data.
1048 for (int i = 0; i < stackDepth; i++) {
1049 Method* meth = (Method*) *intVals++;
1050 int pc = *intVals++;
1053 if (pc == -1) // broken top frame?
1056 lineNumber = dvmLineNumFromPC(meth, pc);
1058 std::string dotName(dvmHumanReadableDescriptor(meth->clazz->descriptor));
1059 if (dvmIsNativeMethod(meth)) {
1060 LOGI("\tat %s.%s(Native Method)", dotName.c_str(), meth->name);
1062 LOGI("\tat %s.%s(%s:%d)",
1063 dotName.c_str(), meth->name, dvmGetMethodSourceFile(meth),
1064 dvmLineNumFromPC(meth, pc));
1070 * Get the message string. We'd like to just grab the field out of
1071 * Throwable, but the getMessage() function can be overridden by the
1074 * Returns the message string object, or NULL if it wasn't set or
1075 * we encountered a failure trying to retrieve it. The string will
1076 * be added to the tracked references table.
1078 static StringObject* getExceptionMessage(Object* exception)
1080 Thread* self = dvmThreadSelf();
1081 Method* getMessageMethod;
1082 StringObject* messageStr = NULL;
1083 Object* pendingException;
1086 * If an exception is pending, clear it while we work and restore
1087 * it when we're done.
1089 pendingException = dvmGetException(self);
1090 if (pendingException != NULL) {
1091 dvmAddTrackedAlloc(pendingException, self);
1092 dvmClearException(self);
1095 getMessageMethod = dvmFindVirtualMethodHierByDescriptor(exception->clazz,
1096 "getMessage", "()Ljava/lang/String;");
1097 if (getMessageMethod != NULL) {
1098 /* could be in NATIVE mode from CheckJNI, so switch state */
1099 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_RUNNING);
1102 dvmCallMethod(self, getMessageMethod, exception, &result);
1103 messageStr = (StringObject*) result.l;
1104 if (messageStr != NULL)
1105 dvmAddTrackedAlloc((Object*) messageStr, self);
1107 dvmChangeStatus(self, oldStatus);
1109 LOGW("WARNING: could not find getMessage in %s",
1110 exception->clazz->descriptor);
1113 if (dvmGetException(self) != NULL) {
1114 LOGW("NOTE: exception thrown while retrieving exception message: %s",
1115 dvmGetException(self)->clazz->descriptor);
1116 /* will be overwritten below */
1119 dvmSetException(self, pendingException);
1120 if (pendingException != NULL) {
1121 dvmReleaseTrackedAlloc(pendingException, self);
1127 * Print the direct stack trace of the given exception to the log.
1129 static void logStackTraceOf(Object* exception) {
1130 std::string className(dvmHumanReadableDescriptor(exception->clazz->descriptor));
1131 StringObject* messageStr = getExceptionMessage(exception);
1132 if (messageStr != NULL) {
1133 char* cp = dvmCreateCstrFromString(messageStr);
1134 dvmReleaseTrackedAlloc((Object*) messageStr, dvmThreadSelf());
1137 LOGI("%s: %s", className.c_str(), cp);
1140 LOGI("%s:", className.c_str());
1144 * This relies on the stackState field, which contains the "raw"
1145 * form of the stack. The Throwable class may clear this field
1146 * after it generates the "cooked" form, in which case we'll have
1149 const ArrayObject* stackData = (const ArrayObject*) dvmGetFieldObject(exception,
1150 gDvm.offJavaLangThrowable_stackState);
1151 if (stackData == NULL) {
1152 LOGI(" (raw stack trace not found)");
1156 int stackSize = stackData->length / 2;
1157 const int* intVals = (const int*)(void*)stackData->contents;
1159 dvmLogRawStackTrace(intVals, stackSize);
1163 * Print the stack trace of the current thread's exception, as well as
1164 * the stack traces of any chained exceptions, to the log. We extract
1165 * the stored stack trace and process it internally instead of calling
1168 void dvmLogExceptionStackTrace()
1170 Object* exception = dvmThreadSelf()->exception;
1173 if (exception == NULL) {
1174 LOGW("tried to log a null exception?");
1179 logStackTraceOf(exception);
1180 cause = dvmGetExceptionCause(exception);
1181 if (cause == NULL) {
1190 * Helper for a few of the throw functions defined below. This throws
1191 * the indicated exception, with a message based on a format in which
1192 * "%s" is used exactly twice, first for a received class and second
1193 * for the expected class.
1195 static void throwTypeError(ClassObject* exceptionClass, const char* fmt,
1196 ClassObject* actual, ClassObject* desired)
1198 std::string actualClassName(dvmHumanReadableDescriptor(actual->descriptor));
1199 std::string desiredClassName(dvmHumanReadableDescriptor(desired->descriptor));
1200 dvmThrowExceptionFmt(exceptionClass, fmt, actualClassName.c_str(), desiredClassName.c_str());
1203 void dvmThrowAbstractMethodError(const char* msg) {
1204 dvmThrowException(gDvm.exAbstractMethodError, msg);
1207 void dvmThrowArithmeticException(const char* msg) {
1208 dvmThrowException(gDvm.exArithmeticException, msg);
1211 void dvmThrowArrayIndexOutOfBoundsException(int length, int index)
1213 dvmThrowExceptionFmt(gDvm.exArrayIndexOutOfBoundsException,
1214 "length=%d; index=%d", length, index);
1217 void dvmThrowArrayStoreExceptionIncompatibleElement(ClassObject* objectType,
1218 ClassObject* arrayType)
1220 throwTypeError(gDvm.exArrayStoreException,
1221 "%s cannot be stored in an array of type %s",
1222 objectType, arrayType);
1225 void dvmThrowArrayStoreExceptionNotArray(ClassObject* actual, const char* label) {
1226 std::string actualClassName(dvmHumanReadableDescriptor(actual->descriptor));
1227 dvmThrowExceptionFmt(gDvm.exArrayStoreException, "%s of type %s is not an array",
1228 label, actualClassName.c_str());
1231 void dvmThrowArrayStoreExceptionIncompatibleArrays(ClassObject* source, ClassObject* destination)
1233 throwTypeError(gDvm.exArrayStoreException,
1234 "%s and %s are incompatible array types",
1235 source, destination);
1238 void dvmThrowArrayStoreExceptionIncompatibleArrayElement(s4 index, ClassObject* objectType,
1239 ClassObject* arrayType)
1241 std::string objectClassName(dvmHumanReadableDescriptor(objectType->descriptor));
1242 std::string arrayClassName(dvmHumanReadableDescriptor(arrayType->descriptor));
1243 dvmThrowExceptionFmt(gDvm.exArrayStoreException,
1244 "source[%d] of type %s cannot be stored in destination array of type %s",
1245 index, objectClassName.c_str(), arrayClassName.c_str());
1248 void dvmThrowClassCastException(ClassObject* actual, ClassObject* desired)
1250 throwTypeError(gDvm.exClassCastException,
1251 "%s cannot be cast to %s", actual, desired);
1254 void dvmThrowClassCircularityError(const char* descriptor) {
1255 dvmThrowExceptionWithClassMessage(gDvm.exClassCircularityError,
1259 void dvmThrowClassFormatError(const char* msg) {
1260 dvmThrowException(gDvm.exClassFormatError, msg);
1263 void dvmThrowClassNotFoundException(const char* name) {
1264 dvmThrowChainedClassNotFoundException(name, NULL);
1267 void dvmThrowChainedClassNotFoundException(const char* name, Object* cause) {
1269 * Note: This exception is thrown in response to a request coming
1270 * from client code for the name as given, so it is preferable to
1271 * make the exception message be that string, per se, instead of
1272 * trying to prettify it.
1274 dvmThrowChainedException(gDvm.exClassNotFoundException, name, cause);
1277 void dvmThrowExceptionInInitializerError()
1280 * TODO: Do we want to wrap it if the original is an Error rather than
1283 * TODO: Should this just use dvmWrapException()?
1286 if (gDvm.exExceptionInInitializerError == NULL) {
1288 * ExceptionInInitializerError isn't itself initialized. This
1289 * can happen very early during VM startup if there is a
1290 * problem with one of the corest-of-the-core classes, and it
1291 * can possibly happen during a dexopt run. Rather than do
1292 * anything fancier, we just abort here with a blatant
1295 LOGE("Fatal error during early class initialization:");
1296 dvmLogExceptionStackTrace();
1300 Thread* self = dvmThreadSelf();
1301 Object* exception = dvmGetException(self);
1303 dvmAddTrackedAlloc(exception, self);
1304 dvmClearException(self);
1306 dvmThrowChainedException(gDvm.exExceptionInInitializerError,
1308 dvmReleaseTrackedAlloc(exception, self);
1311 void dvmThrowFileNotFoundException(const char* msg) {
1312 dvmThrowException(gDvm.exFileNotFoundException, msg);
1315 void dvmThrowIOException(const char* msg) {
1316 dvmThrowException(gDvm.exIOException, msg);
1319 void dvmThrowIllegalAccessException(const char* msg) {
1320 dvmThrowException(gDvm.exIllegalAccessException, msg);
1323 void dvmThrowIllegalAccessError(const char* msg) {
1324 dvmThrowException(gDvm.exIllegalAccessError, msg);
1327 void dvmThrowIllegalArgumentException(const char* msg) {
1328 dvmThrowException(gDvm.exIllegalArgumentException, msg);
1331 void dvmThrowIllegalMonitorStateException(const char* msg) {
1332 dvmThrowException(gDvm.exIllegalMonitorStateException, msg);
1335 void dvmThrowIllegalStateException(const char* msg) {
1336 dvmThrowException(gDvm.exIllegalStateException, msg);
1339 void dvmThrowIllegalThreadStateException(const char* msg) {
1340 dvmThrowException(gDvm.exIllegalThreadStateException, msg);
1343 void dvmThrowIncompatibleClassChangeError(const char* msg) {
1344 dvmThrowException(gDvm.exIncompatibleClassChangeError, msg);
1347 void dvmThrowIncompatibleClassChangeErrorWithClassMessage(
1348 const char* descriptor)
1350 dvmThrowExceptionWithClassMessage(
1351 gDvm.exIncompatibleClassChangeError, descriptor);
1354 void dvmThrowInstantiationException(ClassObject* clazz, const char* extraDetail) {
1355 std::string className(dvmHumanReadableDescriptor(clazz->descriptor));
1356 dvmThrowExceptionFmt(gDvm.exInstantiationException,
1357 "can't instantiate class %s%s%s", className.c_str(),
1358 (extraDetail == NULL) ? "" : "; ",
1359 (extraDetail == NULL) ? "" : extraDetail);
1362 void dvmThrowInternalError(const char* msg) {
1363 dvmThrowException(gDvm.exInternalError, msg);
1366 void dvmThrowInterruptedException(const char* msg) {
1367 dvmThrowException(gDvm.exInterruptedException, msg);
1370 void dvmThrowLinkageError(const char* msg) {
1371 dvmThrowException(gDvm.exLinkageError, msg);
1374 void dvmThrowNegativeArraySizeException(s4 size) {
1375 dvmThrowExceptionFmt(gDvm.exNegativeArraySizeException, "%d", size);
1378 void dvmThrowNoClassDefFoundError(const char* descriptor) {
1379 dvmThrowExceptionWithClassMessage(gDvm.exNoClassDefFoundError,
1383 void dvmThrowChainedNoClassDefFoundError(const char* descriptor,
1385 dvmThrowChainedExceptionWithClassMessage(
1386 gDvm.exNoClassDefFoundError, descriptor, cause);
1389 void dvmThrowNoSuchFieldError(const char* msg) {
1390 dvmThrowException(gDvm.exNoSuchFieldError, msg);
1393 void dvmThrowNoSuchFieldException(const char* msg) {
1394 dvmThrowException(gDvm.exNoSuchFieldException, msg);
1397 void dvmThrowNoSuchMethodError(const char* msg) {
1398 dvmThrowException(gDvm.exNoSuchMethodError, msg);
1401 void dvmThrowNullPointerException(const char* msg) {
1402 dvmThrowException(gDvm.exNullPointerException, msg);
1405 void dvmThrowOutOfMemoryError(const char* msg) {
1406 dvmThrowException(gDvm.exOutOfMemoryError, msg);
1409 void dvmThrowRuntimeException(const char* msg) {
1410 dvmThrowException(gDvm.exRuntimeException, msg);
1413 void dvmThrowStaleDexCacheError(const char* msg) {
1414 dvmThrowException(gDvm.exStaleDexCacheError, msg);
1417 void dvmThrowStringIndexOutOfBoundsExceptionWithIndex(jsize stringLength,
1418 jsize requestIndex) {
1419 dvmThrowExceptionFmt(gDvm.exStringIndexOutOfBoundsException,
1420 "length=%d; index=%d", stringLength, requestIndex);
1423 void dvmThrowStringIndexOutOfBoundsExceptionWithRegion(jsize stringLength,
1424 jsize requestStart, jsize requestLength) {
1425 dvmThrowExceptionFmt(gDvm.exStringIndexOutOfBoundsException,
1426 "length=%d; regionStart=%d; regionLength=%d",
1427 stringLength, requestStart, requestLength);
1430 void dvmThrowTypeNotPresentException(const char* descriptor) {
1431 dvmThrowExceptionWithClassMessage(gDvm.exTypeNotPresentException,
1435 void dvmThrowUnsatisfiedLinkError(const char* msg) {
1436 dvmThrowException(gDvm.exUnsatisfiedLinkError, msg);
1439 void dvmThrowUnsupportedOperationException(const char* msg) {
1440 dvmThrowException(gDvm.exUnsupportedOperationException, msg);
1443 void dvmThrowVerifyError(const char* descriptor) {
1444 dvmThrowExceptionWithClassMessage(gDvm.exVerifyError, descriptor);
1447 void dvmThrowVirtualMachineError(const char* msg) {
1448 dvmThrowException(gDvm.exVirtualMachineError, msg);