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,
104 * Cache pointers to some of the exception classes we use locally.
106 * Note this is NOT called during dexopt optimization. Some of the fields
107 * are initialized by the verifier (dvmVerifyCodeFlow).
109 bool dvmExceptionStartup(void)
111 gDvm.classJavaLangThrowable =
112 dvmFindSystemClassNoInit("Ljava/lang/Throwable;");
113 gDvm.classJavaLangRuntimeException =
114 dvmFindSystemClassNoInit("Ljava/lang/RuntimeException;");
115 gDvm.classJavaLangError =
116 dvmFindSystemClassNoInit("Ljava/lang/Error;");
117 gDvm.classJavaLangStackTraceElement =
118 dvmFindSystemClassNoInit("Ljava/lang/StackTraceElement;");
119 gDvm.classJavaLangStackTraceElementArray =
120 dvmFindArrayClass("[Ljava/lang/StackTraceElement;", NULL);
121 if (gDvm.classJavaLangThrowable == NULL ||
122 gDvm.classJavaLangStackTraceElement == NULL ||
123 gDvm.classJavaLangStackTraceElementArray == NULL)
125 LOGE("Could not find one or more essential exception classes\n");
130 * Find the constructor. Note that, unlike other saved method lookups,
131 * we're using a Method* instead of a vtable offset. This is because
132 * constructors don't have vtable offsets. (Also, since we're creating
133 * the object in question, it's impossible for anyone to sub-class it.)
136 meth = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangStackTraceElement,
137 "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V");
139 LOGE("Unable to find constructor for StackTraceElement\n");
142 gDvm.methJavaLangStackTraceElement_init = meth;
144 /* grab an offset for the stackData field */
145 gDvm.offJavaLangThrowable_stackState =
146 dvmFindFieldOffset(gDvm.classJavaLangThrowable,
147 "stackState", "Ljava/lang/Object;");
148 if (gDvm.offJavaLangThrowable_stackState < 0) {
149 LOGE("Unable to find Throwable.stackState\n");
153 /* and one for the message field, in case we want to show it */
154 gDvm.offJavaLangThrowable_message =
155 dvmFindFieldOffset(gDvm.classJavaLangThrowable,
156 "detailMessage", "Ljava/lang/String;");
157 if (gDvm.offJavaLangThrowable_message < 0) {
158 LOGE("Unable to find Throwable.detailMessage\n");
162 /* and one for the cause field, just 'cause */
163 gDvm.offJavaLangThrowable_cause =
164 dvmFindFieldOffset(gDvm.classJavaLangThrowable,
165 "cause", "Ljava/lang/Throwable;");
166 if (gDvm.offJavaLangThrowable_cause < 0) {
167 LOGE("Unable to find Throwable.cause\n");
177 void dvmExceptionShutdown(void)
184 * Create a Throwable and throw an exception in the current thread (where
185 * "throwing" just means "set the thread's exception pointer").
187 * "msg" and/or "cause" may be NULL.
189 * If we have a bad exception hierarchy -- something in Throwable.<init>
190 * is missing -- then every attempt to throw an exception will result
191 * in another exception. Exceptions are generally allowed to "chain"
192 * to other exceptions, so it's hard to auto-detect this problem. It can
193 * only happen if the system classes are broken, so it's probably not
194 * worth spending cycles to detect it.
196 * We do have one case to worry about: if the classpath is completely
197 * wrong, we'll go into a death spin during startup because we can't find
198 * the initial class and then we can't find NoClassDefFoundError. We have
199 * to handle this case.
201 * [Do we want to cache pointers to common exception classes?]
203 void dvmThrowChainedException(const char* exceptionDescriptor, const char* msg,
206 ClassObject* excepClass;
208 LOGV("THROW '%s' msg='%s' cause=%s\n",
209 exceptionDescriptor, msg,
210 (cause != NULL) ? cause->clazz->descriptor : "(none)");
212 if (gDvm.initializing) {
213 if (++gDvm.initExceptionCount >= 2) {
214 LOGE("Too many exceptions during init (failed on '%s' '%s')\n",
215 exceptionDescriptor, msg);
220 excepClass = dvmFindSystemClass(exceptionDescriptor);
221 if (excepClass == NULL) {
223 * We couldn't find the exception class. The attempt to find a
224 * nonexistent class should have raised an exception. If no
225 * exception is currently raised, then we're pretty clearly unable
226 * to throw ANY sort of exception, and we need to pack it in.
228 * If we were able to throw the "class load failed" exception,
229 * stick with that. Ideally we'd stuff the original exception
230 * into the "cause" field, but since we can't find it we can't
231 * do that. The exception class name should be in the "message"
234 if (!dvmCheckException(dvmThreadSelf())) {
235 LOGE("FATAL: unable to throw exception (failed on '%s' '%s')\n",
236 exceptionDescriptor, msg);
242 dvmThrowChainedExceptionByClass(excepClass, msg, cause);
246 * Start/continue throwing process now that we have a class reference.
248 void dvmThrowChainedExceptionByClass(ClassObject* excepClass, const char* msg,
251 Thread* self = dvmThreadSelf();
254 /* make sure the exception is initialized */
255 if (!dvmIsClassInitialized(excepClass) && !dvmInitClass(excepClass)) {
256 LOGE("ERROR: unable to initialize exception class '%s'\n",
257 excepClass->descriptor);
258 if (strcmp(excepClass->descriptor, "Ljava/lang/InternalError;") == 0)
260 dvmThrowChainedException("Ljava/lang/InternalError;",
261 "failed to init original exception class", cause);
265 exception = dvmAllocObject(excepClass, ALLOC_DEFAULT);
266 if (exception == NULL) {
268 * We're in a lot of trouble. We might be in the process of
269 * throwing an out-of-memory exception, in which case the
270 * pre-allocated object will have been thrown when our object alloc
271 * failed. So long as there's an exception raised, return and
272 * allow the system to try to recover. If not, something is broken
273 * and we need to bail out.
275 if (dvmCheckException(self))
277 LOGE("FATAL: unable to allocate exception '%s' '%s'\n",
278 excepClass->descriptor, msg != NULL ? msg : "(no msg)");
283 * Init the exception.
285 if (gDvm.optimizing) {
286 /* need the exception object, but can't invoke interpreted code */
287 LOGV("Skipping init of exception %s '%s'\n",
288 excepClass->descriptor, msg);
290 assert(excepClass == exception->clazz);
291 if (!initException(exception, msg, cause, self)) {
293 * Whoops. If we can't initialize the exception, we can't use
294 * it. If there's an exception already set, the constructor
295 * probably threw an OutOfMemoryError.
297 if (!dvmCheckException(self)) {
299 * We're required to throw something, so we just
300 * throw the pre-constructed internal error.
302 self->exception = gDvm.internalErrorObj;
308 self->exception = exception;
311 dvmReleaseTrackedAlloc(exception, self);
315 * Throw the named exception using the dotted form of the class
316 * descriptor as the exception message, and with the specified cause.
318 void dvmThrowChainedExceptionWithClassMessage(const char* exceptionDescriptor,
319 const char* messageDescriptor, Object* cause)
321 char* message = dvmDescriptorToDot(messageDescriptor);
323 dvmThrowChainedException(exceptionDescriptor, message, cause);
328 * Like dvmThrowExceptionWithMessageFromDescriptor, but take a
329 * class object instead of a name.
331 void dvmThrowExceptionByClassWithClassMessage(ClassObject* exceptionClass,
332 const char* messageDescriptor)
334 char* message = dvmDescriptorToName(messageDescriptor);
336 dvmThrowExceptionByClass(exceptionClass, message);
341 * Initialize an exception with an appropriate constructor.
343 * "exception" is the exception object to initialize.
344 * Either or both of "msg" and "cause" may be null.
345 * "self" is dvmThreadSelf(), passed in so we don't have to look it up again.
347 * If the process of initializing the exception causes another
348 * exception (e.g., OutOfMemoryError) to be thrown, return an error
349 * and leave self->exception intact.
351 static bool initException(Object* exception, const char* msg, Object* cause,
360 } initKind = kInitUnknown;
361 Method* initMethod = NULL;
362 ClassObject* excepClass = exception->clazz;
363 StringObject* msgStr = NULL;
365 bool needInitCause = false;
367 assert(self != NULL);
368 assert(self->exception == NULL);
370 /* if we have a message, create a String */
374 msgStr = dvmCreateStringFromCstr(msg, ALLOC_DEFAULT);
375 if (msgStr == NULL) {
376 LOGW("Could not allocate message string \"%s\" while "
377 "throwing internal exception (%s)\n",
378 msg, excepClass->descriptor);
384 if (!dvmInstanceof(cause->clazz, gDvm.classJavaLangThrowable)) {
385 LOGE("Tried to init exception with cause '%s'\n",
386 cause->clazz->descriptor);
392 * The Throwable class has four public constructors:
394 * (2) Throwable(String message)
395 * (3) Throwable(String message, Throwable cause) (added in 1.4)
396 * (4) Throwable(Throwable cause) (added in 1.4)
398 * The first two are part of the original design, and most exception
399 * classes should support them. The third prototype was used by
400 * individual exceptions. e.g. ClassNotFoundException added it in 1.2.
401 * The general "cause" mechanism was added in 1.4. Some classes,
402 * such as IllegalArgumentException, initially supported the first
403 * two, but added the second two in a later release.
405 * Exceptions may be picky about how their "cause" field is initialized.
406 * If you call ClassNotFoundException(String), it may choose to
407 * initialize its "cause" field to null. Doing so prevents future
408 * calls to Throwable.initCause().
410 * So, if "cause" is not NULL, we need to look for a constructor that
411 * takes a throwable. If we can't find one, we fall back on calling
412 * #1/#2 and making a separate call to initCause(). Passing a null ref
413 * for "message" into Throwable(String, Throwable) is allowed, but we
414 * prefer to use the Throwable-only version because it has different
417 * java.lang.TypeNotPresentException is a strange case -- it has #3 but
418 * not #2. (Some might argue that the constructor is actually not #3,
419 * because it doesn't take the message string as an argument, but it
420 * has the same effect and we can work with it here.)
423 if (msgStr == NULL) {
424 initMethod = dvmFindDirectMethodByDescriptor(excepClass, "<init>", "()V");
425 initKind = kInitNoarg;
427 initMethod = dvmFindDirectMethodByDescriptor(excepClass, "<init>",
428 "(Ljava/lang/String;)V");
429 if (initMethod != NULL) {
433 initMethod = dvmFindDirectMethodByDescriptor(excepClass, "<init>",
434 "(Ljava/lang/String;Ljava/lang/Throwable;)V");
435 if (initMethod != NULL)
436 initKind = kInitMsgThrow;
440 if (msgStr == NULL) {
441 initMethod = dvmFindDirectMethodByDescriptor(excepClass, "<init>",
442 "(Ljava/lang/Throwable;)V");
443 if (initMethod != NULL) {
444 initKind = kInitThrow;
446 initMethod = dvmFindDirectMethodByDescriptor(excepClass, "<init>", "()V");
447 initKind = kInitNoarg;
448 needInitCause = true;
451 initMethod = dvmFindDirectMethodByDescriptor(excepClass, "<init>",
452 "(Ljava/lang/String;Ljava/lang/Throwable;)V");
453 if (initMethod != NULL) {
454 initKind = kInitMsgThrow;
456 initMethod = dvmFindDirectMethodByDescriptor(excepClass, "<init>",
457 "(Ljava/lang/String;)V");
459 needInitCause = true;
464 if (initMethod == NULL) {
466 * We can't find the desired constructor. This can happen if a
467 * subclass of java/lang/Throwable doesn't define an expected
468 * constructor, e.g. it doesn't provide one that takes a string
469 * when a message has been provided.
471 LOGW("WARNING: exception class '%s' missing constructor "
472 "(msg='%s' kind=%d)\n",
473 excepClass->descriptor, msg, initKind);
474 assert(strcmp(excepClass->descriptor,
475 "Ljava/lang/RuntimeException;") != 0);
476 dvmThrowChainedException("Ljava/lang/RuntimeException;",
477 "re-throw on exception class missing constructor", NULL);
482 * Call the constructor with the appropriate arguments.
487 LOGVV("+++ exc noarg (ic=%d)\n", needInitCause);
488 dvmCallMethod(self, initMethod, exception, &unused);
491 LOGVV("+++ exc msg (ic=%d)\n", needInitCause);
492 dvmCallMethod(self, initMethod, exception, &unused, msgStr);
495 LOGVV("+++ exc throw");
496 assert(!needInitCause);
497 dvmCallMethod(self, initMethod, exception, &unused, cause);
500 LOGVV("+++ exc msg+throw");
501 assert(!needInitCause);
502 dvmCallMethod(self, initMethod, exception, &unused, msgStr, cause);
510 * It's possible the constructor has thrown an exception. If so, we
511 * return an error and let our caller deal with it.
513 if (self->exception != NULL) {
514 LOGW("Exception thrown (%s) while throwing internal exception (%s)\n",
515 self->exception->clazz->descriptor, exception->clazz->descriptor);
520 * If this exception was caused by another exception, and we weren't
521 * able to find a cause-setting constructor, set the "cause" field
522 * with an explicit call.
526 initCause = dvmFindVirtualMethodHierByDescriptor(excepClass, "initCause",
527 "(Ljava/lang/Throwable;)Ljava/lang/Throwable;");
528 if (initCause != NULL) {
529 dvmCallMethod(self, initCause, exception, &unused, cause);
530 if (self->exception != NULL) {
531 /* initCause() threw an exception; return an error and
532 * let the caller deal with it.
534 LOGW("Exception thrown (%s) during initCause() "
535 "of internal exception (%s)\n",
536 self->exception->clazz->descriptor,
537 exception->clazz->descriptor);
541 LOGW("WARNING: couldn't find initCause in '%s'\n",
542 excepClass->descriptor);
550 dvmReleaseTrackedAlloc((Object*) msgStr, self); // NULL is ok
556 * Clear the pending exception and the "initExceptionCount" counter. This
557 * is used by the optimization and verification code, which has to run with
558 * "initializing" set to avoid going into a death-spin if the "class not
559 * found" exception can't be found.
561 * This can also be called when the VM is in a "normal" state, e.g. when
562 * verifying classes that couldn't be verified at optimization time. The
563 * reset of initExceptionCount should be harmless in that case.
565 void dvmClearOptException(Thread* self)
567 self->exception = NULL;
568 gDvm.initExceptionCount = 0;
572 * Returns "true" if this is a "checked" exception, i.e. it's a subclass
573 * of Throwable (assumed) but not a subclass of RuntimeException or Error.
575 bool dvmIsCheckedException(const Object* exception)
577 if (dvmInstanceof(exception->clazz, gDvm.classJavaLangError) ||
578 dvmInstanceof(exception->clazz, gDvm.classJavaLangRuntimeException))
587 * Wrap the now-pending exception in a different exception. This is useful
588 * for reflection stuff that wants to hand a checked exception back from a
589 * method that doesn't declare it.
591 * If something fails, an (unchecked) exception related to that failure
592 * will be pending instead.
594 void dvmWrapException(const char* newExcepStr)
596 Thread* self = dvmThreadSelf();
598 ClassObject* iteClass;
600 origExcep = dvmGetException(self);
601 dvmAddTrackedAlloc(origExcep, self); // don't let the GC free it
603 dvmClearException(self); // clear before class lookup
604 iteClass = dvmFindSystemClass(newExcepStr);
605 if (iteClass != NULL) {
609 iteExcep = dvmAllocObject(iteClass, ALLOC_DEFAULT);
610 if (iteExcep != NULL) {
611 initMethod = dvmFindDirectMethodByDescriptor(iteClass, "<init>",
612 "(Ljava/lang/Throwable;)V");
613 if (initMethod != NULL) {
615 dvmCallMethod(self, initMethod, iteExcep, &unused,
618 /* if <init> succeeded, replace the old exception */
619 if (!dvmCheckException(self))
620 dvmSetException(self, iteExcep);
622 dvmReleaseTrackedAlloc(iteExcep, NULL);
624 /* if initMethod doesn't exist, or failed... */
625 if (!dvmCheckException(self))
626 dvmSetException(self, origExcep);
628 /* leave OutOfMemoryError pending */
631 /* leave ClassNotFoundException pending */
634 assert(dvmCheckException(self));
635 dvmReleaseTrackedAlloc(origExcep, self);
639 * Get the "cause" field from an exception.
641 * The Throwable class initializes the "cause" field to "this" to
642 * differentiate between being initialized to null and never being
643 * initialized. We check for that here and convert it to NULL.
645 Object* dvmGetExceptionCause(const Object* exception)
647 if (!dvmInstanceof(exception->clazz, gDvm.classJavaLangThrowable)) {
648 LOGE("Tried to get cause from object of type '%s'\n",
649 exception->clazz->descriptor);
653 dvmGetFieldObject(exception, gDvm.offJavaLangThrowable_cause);
654 if (cause == exception)
661 * Print the stack trace of the current exception on stderr. This is called
662 * from the JNI ExceptionDescribe call.
664 * For consistency we just invoke the Throwable printStackTrace method,
665 * which might be overridden in the exception object.
667 * Exceptions thrown during the course of printing the stack trace are
670 void dvmPrintExceptionStackTrace(void)
672 Thread* self = dvmThreadSelf();
676 exception = self->exception;
677 if (exception == NULL)
680 self->exception = NULL;
681 printMethod = dvmFindVirtualMethodHierByDescriptor(exception->clazz,
682 "printStackTrace", "()V");
683 if (printMethod != NULL) {
685 dvmCallMethod(self, printMethod, exception, &unused);
687 LOGW("WARNING: could not find printStackTrace in %s\n",
688 exception->clazz->descriptor);
691 if (self->exception != NULL) {
692 LOGI("NOTE: exception thrown while printing stack trace: %s\n",
693 self->exception->clazz->descriptor);
696 self->exception = exception;
700 * Search the method's list of exceptions for a match.
702 * Returns the offset of the catch block on success, or -1 on failure.
704 static int findCatchInMethod(Thread* self, const Method* method, int relPc,
705 ClassObject* excepClass)
708 * Need to clear the exception before entry. Otherwise, dvmResolveClass
709 * might think somebody threw an exception while it was loading a class.
711 assert(!dvmCheckException(self));
712 assert(!dvmIsNativeMethod(method));
714 LOGVV("findCatchInMethod %s.%s excep=%s depth=%d\n",
715 method->clazz->descriptor, method->name, excepClass->descriptor,
716 dvmComputeExactFrameDepth(self->curFrame));
718 DvmDex* pDvmDex = method->clazz->pDvmDex;
719 const DexCode* pCode = dvmGetMethodCode(method);
720 DexCatchIterator iterator;
722 if (dexFindCatchHandler(&iterator, pCode, relPc)) {
724 DexCatchHandler* handler = dexCatchIteratorNext(&iterator);
726 if (handler == NULL) {
730 if (handler->typeIdx == kDexNoIndex) {
732 LOGV("Match on catch-all block at 0x%02x in %s.%s for %s\n",
733 relPc, method->clazz->descriptor,
734 method->name, excepClass->descriptor);
735 return handler->address;
738 ClassObject* throwable =
739 dvmDexGetResolvedClass(pDvmDex, handler->typeIdx);
740 if (throwable == NULL) {
742 * TODO: this behaves badly if we run off the stack
743 * while trying to throw an exception. The problem is
744 * that, if we're in a class loaded by a class loader,
745 * the call to dvmResolveClass has to ask the class
746 * loader for help resolving any previously-unresolved
747 * classes. If this particular class loader hasn't
748 * resolved StackOverflowError, it will call into
749 * interpreted code, and blow up.
751 * We currently replace the previous exception with
752 * the StackOverflowError, which means they won't be
753 * catching it *unless* they explicitly catch
754 * StackOverflowError, in which case we'll be unable
755 * to resolve the class referred to by the "catch"
758 * We end up getting a huge pile of warnings if we do
759 * a simple synthetic test, because this method gets
760 * called on every stack frame up the tree, and it
763 * This eventually bails out, effectively becoming an
764 * uncatchable exception, so other than the flurry of
765 * warnings it's not really a problem. Still, we could
766 * probably handle this better.
768 throwable = dvmResolveClass(method->clazz, handler->typeIdx,
770 if (throwable == NULL) {
772 * We couldn't find the exception they wanted in
773 * our class files (or, perhaps, the stack blew up
774 * while we were querying a class loader). Cough
775 * up a warning, then move on to the next entry.
776 * Keep the exception status clear.
778 LOGW("Could not resolve class ref'ed in exception "
779 "catch list (class index %d, exception %s)\n",
781 (self->exception != NULL) ?
782 self->exception->clazz->descriptor : "(none)");
783 dvmClearException(self);
788 //LOGD("ADDR MATCH, check %s instanceof %s\n",
789 // excepClass->descriptor, pEntry->excepClass->descriptor);
791 if (dvmInstanceof(excepClass, throwable)) {
792 LOGV("Match on catch block at 0x%02x in %s.%s for %s\n",
793 relPc, method->clazz->descriptor,
794 method->name, excepClass->descriptor);
795 return handler->address;
800 LOGV("No matching catch block at 0x%02x in %s for %s\n",
801 relPc, method->name, excepClass->descriptor);
806 * Find a matching "catch" block. "pc" is the relative PC within the
807 * current method, indicating the offset from the start in 16-bit units.
809 * Returns the offset to the catch block, or -1 if we run up against a
810 * break frame without finding anything.
812 * The class resolution stuff we have to do while evaluating the "catch"
813 * blocks could cause an exception. The caller should clear the exception
814 * before calling here and restore it after.
816 * Sets *newFrame to the frame pointer of the frame with the catch block.
817 * If "scanOnly" is false, self->curFrame is also set to this value.
819 int dvmFindCatchBlock(Thread* self, int relPc, Object* exception,
820 bool scanOnly, void** newFrame)
822 void* fp = self->curFrame;
825 assert(!dvmCheckException(self));
828 StackSaveArea* saveArea = SAVEAREA_FROM_FP(fp);
829 catchAddr = findCatchInMethod(self, saveArea->method, relPc,
835 * Normally we'd check for ACC_SYNCHRONIZED methods and unlock
836 * them as we unroll. Dalvik uses what amount to generated
837 * "finally" blocks to take care of this for us.
840 /* output method profiling info */
842 TRACE_METHOD_UNROLL(self, saveArea->method);
846 * Move up one frame. If the next thing up is a break frame,
847 * break out now so we're left unrolled to the last method frame.
848 * We need to point there so we can roll up the JNI local refs
849 * if this was a native method.
851 assert(saveArea->prevFrame != NULL);
852 if (dvmIsBreakFrame(saveArea->prevFrame)) {
854 break; // bail with catchAddr == -1
857 * We're scanning for the debugger. It needs to know if this
858 * exception is going to be caught or not, and we need to figure
859 * out if it will be caught *ever* not just between the current
860 * position and the next break frame. We can't tell what native
861 * code is going to do, so we assume it never catches exceptions.
863 * Start by finding an interpreted code frame.
865 fp = saveArea->prevFrame; // this is the break frame
866 saveArea = SAVEAREA_FROM_FP(fp);
867 fp = saveArea->prevFrame; // this may be a good one
869 if (!dvmIsBreakFrame(fp)) {
870 saveArea = SAVEAREA_FROM_FP(fp);
871 if (!dvmIsNativeMethod(saveArea->method))
875 fp = SAVEAREA_FROM_FP(fp)->prevFrame;
878 break; // bail with catchAddr == -1
881 * Now fp points to the "good" frame. When the interp code
882 * invoked the native code, it saved a copy of its current PC
883 * into xtra.currentPc. Pull it out of there.
886 saveArea->xtra.currentPc - SAVEAREA_FROM_FP(fp)->method->insns;
888 fp = saveArea->prevFrame;
890 /* savedPc in was-current frame goes with method in now-current */
891 relPc = saveArea->savedPc - SAVEAREA_FROM_FP(fp)->method->insns;
899 * The class resolution in findCatchInMethod() could cause an exception.
900 * Clear it to be safe.
902 self->exception = NULL;
909 * We have to carry the exception's stack trace around, but in many cases
910 * it will never be examined. It makes sense to keep it in a compact,
911 * VM-specific object, rather than an array of Objects with strings.
913 * Pass in the thread whose stack we're interested in. If "thread" is
914 * not self, the thread must be suspended. This implies that the thread
915 * list lock is held, which means we can't allocate objects or we risk
916 * jamming the GC. So, we allow this function to return different formats.
917 * (This shouldn't be called directly -- see the inline functions in the
920 * If "wantObject" is true, this returns a newly-allocated Object, which is
921 * presently an array of integers, but could become something else in the
922 * future. If "wantObject" is false, return plain malloc data.
924 * NOTE: if we support class unloading, we will need to scan the class
925 * object references out of these arrays.
927 void* dvmFillInStackTraceInternal(Thread* thread, bool wantObject, int* pCount)
929 ArrayObject* stackData = NULL;
930 int* simpleData = NULL;
938 fp = thread->curFrame;
940 assert(thread == dvmThreadSelf() || dvmIsSuspended(thread));
943 * We're looking at a stack frame for code running below a Throwable
944 * constructor. We want to remove the Throwable methods and the
945 * superclass initializations so the user doesn't see them when they
946 * read the stack dump.
948 * TODO: this just scrapes off the top layers of Throwable. Might not do
949 * the right thing if we create an exception object or cause a VM
950 * exception while in a Throwable method.
953 const StackSaveArea* saveArea = SAVEAREA_FROM_FP(fp);
954 const Method* method = saveArea->method;
956 if (dvmIsBreakFrame(fp))
958 if (!dvmInstanceof(method->clazz, gDvm.classJavaLangThrowable))
960 //LOGD("EXCEP: ignoring %s.%s\n",
961 // method->clazz->descriptor, method->name);
962 fp = saveArea->prevFrame;
967 * Compute the stack depth.
971 const StackSaveArea* saveArea = SAVEAREA_FROM_FP(fp);
973 if (!dvmIsBreakFrame(fp))
976 assert(fp != saveArea->prevFrame);
977 fp = saveArea->prevFrame;
979 //LOGD("EXCEP: stack depth is %d\n", stackDepth);
985 * We need to store a pointer to the Method and the program counter.
986 * We have 4-byte pointers, so we use '[I'.
989 assert(sizeof(Method*) == 4);
990 stackData = dvmAllocPrimitiveArray('I', stackDepth*2, ALLOC_DEFAULT);
991 if (stackData == NULL) {
992 assert(dvmCheckException(dvmThreadSelf()));
995 intPtr = (int*) stackData->contents;
997 /* array of ints; first entry is stack depth */
998 assert(sizeof(Method*) == sizeof(int));
999 simpleData = (int*) malloc(sizeof(int) * stackDepth*2);
1000 if (simpleData == NULL)
1003 assert(pCount != NULL);
1004 intPtr = simpleData;
1007 *pCount = stackDepth;
1010 while (fp != NULL) {
1011 const StackSaveArea* saveArea = SAVEAREA_FROM_FP(fp);
1012 const Method* method = saveArea->method;
1014 if (!dvmIsBreakFrame(fp)) {
1015 //LOGD("EXCEP keeping %s.%s\n", method->clazz->descriptor,
1018 *intPtr++ = (int) method;
1019 if (dvmIsNativeMethod(method)) {
1020 *intPtr++ = 0; /* no saved PC for native methods */
1022 assert(saveArea->xtra.currentPc >= method->insns &&
1023 saveArea->xtra.currentPc <
1024 method->insns + dvmGetMethodInsnsSize(method));
1025 *intPtr++ = (int) (saveArea->xtra.currentPc - method->insns);
1028 stackDepth--; // for verification
1031 assert(fp != saveArea->prevFrame);
1032 fp = saveArea->prevFrame;
1034 assert(stackDepth == 0);
1038 dvmReleaseTrackedAlloc((Object*) stackData, dvmThreadSelf());
1047 * Given an Object previously created by dvmFillInStackTrace(), use the
1048 * contents of the saved stack trace to generate an array of
1049 * java/lang/StackTraceElement objects.
1051 * The returned array is not added to the "local refs" list.
1053 ArrayObject* dvmGetStackTrace(const Object* ostackData)
1055 const ArrayObject* stackData = (const ArrayObject*) ostackData;
1059 stackSize = stackData->length / 2;
1060 intVals = (const int*) stackData->contents;
1061 return dvmGetStackTraceRaw(intVals, stackSize);
1065 * Generate an array of StackTraceElement objects from the raw integer
1066 * data encoded by dvmFillInStackTrace().
1068 * "intVals" points to the first {method,pc} pair.
1070 * The returned array is not added to the "local refs" list.
1072 ArrayObject* dvmGetStackTraceRaw(const int* intVals, int stackDepth)
1074 ArrayObject* steArray = NULL;
1078 /* init this if we haven't yet */
1079 if (!dvmIsClassInitialized(gDvm.classJavaLangStackTraceElement))
1080 dvmInitClass(gDvm.classJavaLangStackTraceElement);
1082 /* allocate a StackTraceElement array */
1083 steArray = dvmAllocArray(gDvm.classJavaLangStackTraceElementArray,
1084 stackDepth, kObjectArrayRefWidth, ALLOC_DEFAULT);
1085 if (steArray == NULL)
1087 stePtr = (Object**) steArray->contents;
1090 * Allocate and initialize a StackTraceElement for each stack frame.
1091 * We use the standard constructor to configure the object.
1093 for (i = 0; i < stackDepth; i++) {
1096 StringObject* className;
1097 StringObject* methodName;
1098 StringObject* fileName;
1100 const char* sourceFile;
1103 ste = dvmAllocObject(gDvm.classJavaLangStackTraceElement,ALLOC_DEFAULT);
1107 meth = (Method*) *intVals++;
1110 if (pc == -1) // broken top frame?
1113 lineNumber = dvmLineNumFromPC(meth, pc);
1115 dotName = dvmDescriptorToDot(meth->clazz->descriptor);
1116 className = dvmCreateStringFromCstr(dotName, ALLOC_DEFAULT);
1119 methodName = dvmCreateStringFromCstr(meth->name, ALLOC_DEFAULT);
1120 sourceFile = dvmGetMethodSourceFile(meth);
1121 if (sourceFile != NULL)
1122 fileName = dvmCreateStringFromCstr(sourceFile, ALLOC_DEFAULT);
1128 * public StackTraceElement(String declaringClass, String methodName,
1129 * String fileName, int lineNumber)
1130 * (where lineNumber==-2 means "native")
1133 dvmCallMethod(dvmThreadSelf(), gDvm.methJavaLangStackTraceElement_init,
1134 ste, &unused, className, methodName, fileName, lineNumber);
1136 dvmReleaseTrackedAlloc(ste, NULL);
1137 dvmReleaseTrackedAlloc((Object*) className, NULL);
1138 dvmReleaseTrackedAlloc((Object*) methodName, NULL);
1139 dvmReleaseTrackedAlloc((Object*) fileName, NULL);
1141 if (dvmCheckException(dvmThreadSelf()))
1148 dvmReleaseTrackedAlloc((Object*) steArray, NULL);
1153 * Dump the contents of a raw stack trace to the log.
1155 void dvmLogRawStackTrace(const int* intVals, int stackDepth)
1160 * Run through the array of stack frame data.
1162 for (i = 0; i < stackDepth; i++) {
1165 const char* sourceFile;
1168 meth = (Method*) *intVals++;
1171 if (pc == -1) // broken top frame?
1174 lineNumber = dvmLineNumFromPC(meth, pc);
1176 // probably don't need to do this, but it looks nicer
1177 dotName = dvmDescriptorToDot(meth->clazz->descriptor);
1179 if (dvmIsNativeMethod(meth)) {
1180 LOGI("\tat %s.%s(Native Method)\n", dotName, meth->name);
1182 LOGI("\tat %s.%s(%s:%d)\n",
1183 dotName, meth->name, dvmGetMethodSourceFile(meth),
1184 dvmLineNumFromPC(meth, pc));
1189 sourceFile = dvmGetMethodSourceFile(meth);
1194 * Print the direct stack trace of the given exception to the log.
1196 static void logStackTraceOf(Object* exception)
1198 const ArrayObject* stackData;
1199 StringObject* messageStr;
1203 messageStr = (StringObject*) dvmGetFieldObject(exception,
1204 gDvm.offJavaLangThrowable_message);
1205 if (messageStr != NULL) {
1206 char* cp = dvmCreateCstrFromString(messageStr);
1207 LOGI("%s: %s\n", exception->clazz->descriptor, cp);
1210 LOGI("%s:\n", exception->clazz->descriptor);
1213 stackData = (const ArrayObject*) dvmGetFieldObject(exception,
1214 gDvm.offJavaLangThrowable_stackState);
1215 if (stackData == NULL) {
1216 LOGI(" (no stack trace data found)\n");
1220 stackSize = stackData->length / 2;
1221 intVals = (const int*) stackData->contents;
1223 dvmLogRawStackTrace(intVals, stackSize);
1227 * Print the stack trace of the current thread's exception, as well as
1228 * the stack traces of any chained exceptions, to the log. We extract
1229 * the stored stack trace and process it internally instead of calling
1232 void dvmLogExceptionStackTrace(void)
1234 Object* exception = dvmThreadSelf()->exception;
1237 if (exception == NULL) {
1238 LOGW("tried to log a null exception?\n");
1243 logStackTraceOf(exception);
1244 cause = dvmGetExceptionCause(exception);
1245 if (cause == NULL) {
1248 LOGI("Caused by:\n");