blob: 7b0a83542a7c5821c7ec345375083924e67013ce [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 * Exception handling.
18 */
19#include "Dalvik.h"
20#include "libdex/DexCatch.h"
21
22#include <stdlib.h>
23
24/*
25Notes on Exception Handling
26
27We have one fairly sticky issue to deal with: creating the exception stack
28trace. The trouble is that we need the current value of the program
29counter for the method now being executed, but that's only held in a local
30variable or hardware register in the main interpreter loop.
31
32The exception mechanism requires that the current stack trace be associated
33with a Throwable at the time the Throwable is constructed. The construction
34may or may not be associated with a throw. We have three situations to
35consider:
36
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.
43
44We need to have the current value for the PC, which means that for
45situation (3) the interpreter loop must copy it to an externally-accessible
46location before handling any opcode that could cause the VM to throw
47an exception. We can't store it globally, because the various threads
48would trample each other. We can't store it in the Thread structure,
49because it'll get overwritten as soon as the Throwable constructor starts
50executing. It needs to go on the stack, but our stack frames hold the
51caller's *saved* PC, not the current PC.
52
53Situation #1 doesn't require special handling. Situation #2 could be dealt
54with by passing the PC into the exception creation function. The trick
55is to solve situation #3 in a way that adds minimal overhead to common
56operations. Making it more costly to throw an exception is acceptable.
57
58There are a few ways to deal with this:
59
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.
71
72Solution (a) is the simplest, but breaks Dalvik's goal of mingling native
73and interpreted stacks.
74
75Solution (b) retains the simplicity of (a) without rearranging the stack,
76but now in some cases we're storing the PC twice, which feels wrong.
77
78Solution (c) usually works, because we push the saved PC onto the stack
79before the Throwable construction can overwrite the copy in Thread. One
80way 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)
84This is a risk for anything that could cause <clinit> to execute, e.g.
85executing a static method or accessing a static field. Attemping to access
86a field that doesn't exist in a class that does exist might cause this.
87It may be possible to simply bracket the dvmCallMethod*() functions to
88save/restore it.
89
90Solution (d) incurs additional overhead, but may have other benefits (e.g.
91it's easy to find the stack frames that should be removed before storage
92in the Throwable).
93
94Current plan is option (b), because it's simple, fast, and doesn't change
95the way the stack works.
96*/
97
98/* fwd */
99static bool initException(Object* exception, const char* msg, Object* cause,
100 Thread* self);
101
102
103/*
104 * Cache pointers to some of the exception classes we use locally.
Andy McFadden686e1e22009-05-26 16:56:30 -0700105 *
106 * Note this is NOT called during dexopt optimization. Some of the fields
107 * are initialized by the verifier (dvmVerifyCodeFlow).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800108 */
109bool dvmExceptionStartup(void)
110{
111 gDvm.classJavaLangThrowable =
112 dvmFindSystemClassNoInit("Ljava/lang/Throwable;");
113 gDvm.classJavaLangRuntimeException =
114 dvmFindSystemClassNoInit("Ljava/lang/RuntimeException;");
Andy McFadden4fbba1f2010-02-03 07:21:14 -0800115 gDvm.classJavaLangStackOverflowError =
116 dvmFindSystemClassNoInit("Ljava/lang/StackOverflowError;");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800117 gDvm.classJavaLangError =
118 dvmFindSystemClassNoInit("Ljava/lang/Error;");
119 gDvm.classJavaLangStackTraceElement =
120 dvmFindSystemClassNoInit("Ljava/lang/StackTraceElement;");
121 gDvm.classJavaLangStackTraceElementArray =
122 dvmFindArrayClass("[Ljava/lang/StackTraceElement;", NULL);
123 if (gDvm.classJavaLangThrowable == NULL ||
124 gDvm.classJavaLangStackTraceElement == NULL ||
125 gDvm.classJavaLangStackTraceElementArray == NULL)
126 {
127 LOGE("Could not find one or more essential exception classes\n");
128 return false;
129 }
130
131 /*
132 * Find the constructor. Note that, unlike other saved method lookups,
133 * we're using a Method* instead of a vtable offset. This is because
134 * constructors don't have vtable offsets. (Also, since we're creating
135 * the object in question, it's impossible for anyone to sub-class it.)
136 */
137 Method* meth;
138 meth = dvmFindDirectMethodByDescriptor(gDvm.classJavaLangStackTraceElement,
139 "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V");
140 if (meth == NULL) {
141 LOGE("Unable to find constructor for StackTraceElement\n");
142 return false;
143 }
144 gDvm.methJavaLangStackTraceElement_init = meth;
145
146 /* grab an offset for the stackData field */
147 gDvm.offJavaLangThrowable_stackState =
148 dvmFindFieldOffset(gDvm.classJavaLangThrowable,
149 "stackState", "Ljava/lang/Object;");
150 if (gDvm.offJavaLangThrowable_stackState < 0) {
151 LOGE("Unable to find Throwable.stackState\n");
152 return false;
153 }
154
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800155 /* and one for the cause field, just 'cause */
156 gDvm.offJavaLangThrowable_cause =
157 dvmFindFieldOffset(gDvm.classJavaLangThrowable,
158 "cause", "Ljava/lang/Throwable;");
159 if (gDvm.offJavaLangThrowable_cause < 0) {
160 LOGE("Unable to find Throwable.cause\n");
161 return false;
162 }
163
164 return true;
165}
166
167/*
168 * Clean up.
169 */
170void dvmExceptionShutdown(void)
171{
172 // nothing to do
173}
174
175
176/*
Andy McFadden01718122010-01-22 16:36:30 -0800177 * Format the message into a small buffer and pass it along.
178 */
179void dvmThrowExceptionFmtV(const char* exceptionDescriptor, const char* fmt,
180 va_list args)
181{
182 char msgBuf[512];
183
184 vsnprintf(msgBuf, sizeof(msgBuf), fmt, args);
185 dvmThrowChainedException(exceptionDescriptor, msgBuf, NULL);
186}
187
188/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800189 * Create a Throwable and throw an exception in the current thread (where
190 * "throwing" just means "set the thread's exception pointer").
191 *
192 * "msg" and/or "cause" may be NULL.
193 *
194 * If we have a bad exception hierarchy -- something in Throwable.<init>
195 * is missing -- then every attempt to throw an exception will result
196 * in another exception. Exceptions are generally allowed to "chain"
197 * to other exceptions, so it's hard to auto-detect this problem. It can
198 * only happen if the system classes are broken, so it's probably not
199 * worth spending cycles to detect it.
200 *
201 * We do have one case to worry about: if the classpath is completely
202 * wrong, we'll go into a death spin during startup because we can't find
203 * the initial class and then we can't find NoClassDefFoundError. We have
204 * to handle this case.
205 *
206 * [Do we want to cache pointers to common exception classes?]
207 */
208void dvmThrowChainedException(const char* exceptionDescriptor, const char* msg,
209 Object* cause)
210{
211 ClassObject* excepClass;
212
213 LOGV("THROW '%s' msg='%s' cause=%s\n",
214 exceptionDescriptor, msg,
215 (cause != NULL) ? cause->clazz->descriptor : "(none)");
216
217 if (gDvm.initializing) {
218 if (++gDvm.initExceptionCount >= 2) {
219 LOGE("Too many exceptions during init (failed on '%s' '%s')\n",
220 exceptionDescriptor, msg);
221 dvmAbort();
222 }
223 }
224
225 excepClass = dvmFindSystemClass(exceptionDescriptor);
226 if (excepClass == NULL) {
227 /*
228 * We couldn't find the exception class. The attempt to find a
229 * nonexistent class should have raised an exception. If no
230 * exception is currently raised, then we're pretty clearly unable
231 * to throw ANY sort of exception, and we need to pack it in.
232 *
233 * If we were able to throw the "class load failed" exception,
234 * stick with that. Ideally we'd stuff the original exception
235 * into the "cause" field, but since we can't find it we can't
236 * do that. The exception class name should be in the "message"
237 * field.
238 */
239 if (!dvmCheckException(dvmThreadSelf())) {
240 LOGE("FATAL: unable to throw exception (failed on '%s' '%s')\n",
241 exceptionDescriptor, msg);
242 dvmAbort();
243 }
244 return;
245 }
246
247 dvmThrowChainedExceptionByClass(excepClass, msg, cause);
248}
249
250/*
251 * Start/continue throwing process now that we have a class reference.
252 */
253void dvmThrowChainedExceptionByClass(ClassObject* excepClass, const char* msg,
254 Object* cause)
255{
256 Thread* self = dvmThreadSelf();
257 Object* exception;
258
259 /* make sure the exception is initialized */
260 if (!dvmIsClassInitialized(excepClass) && !dvmInitClass(excepClass)) {
261 LOGE("ERROR: unable to initialize exception class '%s'\n",
262 excepClass->descriptor);
263 if (strcmp(excepClass->descriptor, "Ljava/lang/InternalError;") == 0)
264 dvmAbort();
265 dvmThrowChainedException("Ljava/lang/InternalError;",
266 "failed to init original exception class", cause);
267 return;
268 }
269
270 exception = dvmAllocObject(excepClass, ALLOC_DEFAULT);
271 if (exception == NULL) {
272 /*
273 * We're in a lot of trouble. We might be in the process of
274 * throwing an out-of-memory exception, in which case the
275 * pre-allocated object will have been thrown when our object alloc
276 * failed. So long as there's an exception raised, return and
277 * allow the system to try to recover. If not, something is broken
278 * and we need to bail out.
279 */
280 if (dvmCheckException(self))
281 goto bail;
282 LOGE("FATAL: unable to allocate exception '%s' '%s'\n",
283 excepClass->descriptor, msg != NULL ? msg : "(no msg)");
284 dvmAbort();
285 }
286
287 /*
288 * Init the exception.
289 */
290 if (gDvm.optimizing) {
291 /* need the exception object, but can't invoke interpreted code */
292 LOGV("Skipping init of exception %s '%s'\n",
293 excepClass->descriptor, msg);
294 } else {
295 assert(excepClass == exception->clazz);
296 if (!initException(exception, msg, cause, self)) {
297 /*
298 * Whoops. If we can't initialize the exception, we can't use
299 * it. If there's an exception already set, the constructor
300 * probably threw an OutOfMemoryError.
301 */
302 if (!dvmCheckException(self)) {
303 /*
304 * We're required to throw something, so we just
305 * throw the pre-constructed internal error.
306 */
307 self->exception = gDvm.internalErrorObj;
308 }
309 goto bail;
310 }
311 }
312
313 self->exception = exception;
314
315bail:
316 dvmReleaseTrackedAlloc(exception, self);
317}
318
319/*
320 * Throw the named exception using the dotted form of the class
321 * descriptor as the exception message, and with the specified cause.
322 */
323void dvmThrowChainedExceptionWithClassMessage(const char* exceptionDescriptor,
324 const char* messageDescriptor, Object* cause)
325{
326 char* message = dvmDescriptorToDot(messageDescriptor);
327
328 dvmThrowChainedException(exceptionDescriptor, message, cause);
329 free(message);
330}
331
332/*
333 * Like dvmThrowExceptionWithMessageFromDescriptor, but take a
334 * class object instead of a name.
335 */
336void dvmThrowExceptionByClassWithClassMessage(ClassObject* exceptionClass,
337 const char* messageDescriptor)
338{
339 char* message = dvmDescriptorToName(messageDescriptor);
340
341 dvmThrowExceptionByClass(exceptionClass, message);
342 free(message);
343}
344
345/*
Dan Bornstein4a888b02009-12-07 15:46:23 -0800346 * Find and return an exception constructor method that can take the
347 * indicated parameters, or return NULL if no such constructor exists.
348 */
349static Method* findExceptionInitMethod(ClassObject* excepClass,
350 bool hasMessage, bool hasCause)
351{
352 if (hasMessage) {
353 Method* result;
354
355 if (hasCause) {
356 result = dvmFindDirectMethodByDescriptor(
357 excepClass, "<init>",
358 "(Ljava/lang/String;Ljava/lang/Throwable;)V");
359 } else {
360 result = dvmFindDirectMethodByDescriptor(
361 excepClass, "<init>", "(Ljava/lang/String;)V");
362 }
363
364 if (result != NULL) {
365 return result;
366 }
367
368 if (hasCause) {
369 return dvmFindDirectMethodByDescriptor(
370 excepClass, "<init>",
371 "(Ljava/lang/Object;Ljava/lang/Throwable;)V");
372 } else {
373 return dvmFindDirectMethodByDescriptor(
374 excepClass, "<init>", "(Ljava/lang/Object;)V");
375 }
376 } else if (hasCause) {
377 return dvmFindDirectMethodByDescriptor(
378 excepClass, "<init>", "(Ljava/lang/Throwable;)V");
379 } else {
380 return dvmFindDirectMethodByDescriptor(excepClass, "<init>", "()V");
381 }
382}
383
384/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800385 * Initialize an exception with an appropriate constructor.
386 *
387 * "exception" is the exception object to initialize.
388 * Either or both of "msg" and "cause" may be null.
389 * "self" is dvmThreadSelf(), passed in so we don't have to look it up again.
390 *
391 * If the process of initializing the exception causes another
392 * exception (e.g., OutOfMemoryError) to be thrown, return an error
393 * and leave self->exception intact.
394 */
395static bool initException(Object* exception, const char* msg, Object* cause,
396 Thread* self)
397{
398 enum {
399 kInitUnknown,
400 kInitNoarg,
401 kInitMsg,
402 kInitMsgThrow,
403 kInitThrow
404 } initKind = kInitUnknown;
405 Method* initMethod = NULL;
406 ClassObject* excepClass = exception->clazz;
407 StringObject* msgStr = NULL;
408 bool result = false;
409 bool needInitCause = false;
410
411 assert(self != NULL);
412 assert(self->exception == NULL);
413
414 /* if we have a message, create a String */
415 if (msg == NULL)
416 msgStr = NULL;
417 else {
Barry Hayes81f3ebe2010-06-15 16:17:37 -0700418 msgStr = dvmCreateStringFromCstr(msg);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800419 if (msgStr == NULL) {
420 LOGW("Could not allocate message string \"%s\" while "
421 "throwing internal exception (%s)\n",
422 msg, excepClass->descriptor);
423 goto bail;
424 }
425 }
426
Andy McFadden686e1e22009-05-26 16:56:30 -0700427 if (cause != NULL) {
428 if (!dvmInstanceof(cause->clazz, gDvm.classJavaLangThrowable)) {
429 LOGE("Tried to init exception with cause '%s'\n",
430 cause->clazz->descriptor);
431 dvmAbort();
432 }
433 }
434
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800435 /*
436 * The Throwable class has four public constructors:
437 * (1) Throwable()
438 * (2) Throwable(String message)
439 * (3) Throwable(String message, Throwable cause) (added in 1.4)
440 * (4) Throwable(Throwable cause) (added in 1.4)
441 *
442 * The first two are part of the original design, and most exception
443 * classes should support them. The third prototype was used by
444 * individual exceptions. e.g. ClassNotFoundException added it in 1.2.
445 * The general "cause" mechanism was added in 1.4. Some classes,
446 * such as IllegalArgumentException, initially supported the first
447 * two, but added the second two in a later release.
448 *
449 * Exceptions may be picky about how their "cause" field is initialized.
450 * If you call ClassNotFoundException(String), it may choose to
451 * initialize its "cause" field to null. Doing so prevents future
452 * calls to Throwable.initCause().
453 *
454 * So, if "cause" is not NULL, we need to look for a constructor that
455 * takes a throwable. If we can't find one, we fall back on calling
456 * #1/#2 and making a separate call to initCause(). Passing a null ref
457 * for "message" into Throwable(String, Throwable) is allowed, but we
458 * prefer to use the Throwable-only version because it has different
459 * behavior.
460 *
461 * java.lang.TypeNotPresentException is a strange case -- it has #3 but
462 * not #2. (Some might argue that the constructor is actually not #3,
463 * because it doesn't take the message string as an argument, but it
464 * has the same effect and we can work with it here.)
Dan Bornstein4a888b02009-12-07 15:46:23 -0800465 *
466 * java.lang.AssertionError is also a strange case -- it has a
467 * constructor that takes an Object, but not one that takes a String.
468 * There may be other cases like this, as well, so we generally look
469 * for an Object-taking constructor if we can't find one that takes
470 * a String.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800471 */
472 if (cause == NULL) {
473 if (msgStr == NULL) {
Dan Bornstein4a888b02009-12-07 15:46:23 -0800474 initMethod = findExceptionInitMethod(excepClass, false, false);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800475 initKind = kInitNoarg;
476 } else {
Dan Bornstein4a888b02009-12-07 15:46:23 -0800477 initMethod = findExceptionInitMethod(excepClass, true, false);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800478 if (initMethod != NULL) {
479 initKind = kInitMsg;
480 } else {
481 /* no #2, try #3 */
Dan Bornstein4a888b02009-12-07 15:46:23 -0800482 initMethod = findExceptionInitMethod(excepClass, true, true);
483 if (initMethod != NULL) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800484 initKind = kInitMsgThrow;
Dan Bornstein4a888b02009-12-07 15:46:23 -0800485 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800486 }
487 }
488 } else {
489 if (msgStr == NULL) {
Dan Bornstein4a888b02009-12-07 15:46:23 -0800490 initMethod = findExceptionInitMethod(excepClass, false, true);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800491 if (initMethod != NULL) {
492 initKind = kInitThrow;
493 } else {
Dan Bornstein4a888b02009-12-07 15:46:23 -0800494 initMethod = findExceptionInitMethod(excepClass, false, false);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800495 initKind = kInitNoarg;
496 needInitCause = true;
497 }
498 } else {
Dan Bornstein4a888b02009-12-07 15:46:23 -0800499 initMethod = findExceptionInitMethod(excepClass, true, true);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800500 if (initMethod != NULL) {
501 initKind = kInitMsgThrow;
502 } else {
Dan Bornstein4a888b02009-12-07 15:46:23 -0800503 initMethod = findExceptionInitMethod(excepClass, true, false);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800504 initKind = kInitMsg;
505 needInitCause = true;
506 }
507 }
508 }
509
510 if (initMethod == NULL) {
511 /*
512 * We can't find the desired constructor. This can happen if a
513 * subclass of java/lang/Throwable doesn't define an expected
514 * constructor, e.g. it doesn't provide one that takes a string
515 * when a message has been provided.
516 */
517 LOGW("WARNING: exception class '%s' missing constructor "
518 "(msg='%s' kind=%d)\n",
519 excepClass->descriptor, msg, initKind);
520 assert(strcmp(excepClass->descriptor,
521 "Ljava/lang/RuntimeException;") != 0);
Carl Shapirode750892010-06-08 16:37:12 -0700522 dvmThrowChainedException("Ljava/lang/RuntimeException;",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800523 "re-throw on exception class missing constructor", NULL);
524 goto bail;
525 }
526
527 /*
528 * Call the constructor with the appropriate arguments.
529 */
530 JValue unused;
531 switch (initKind) {
532 case kInitNoarg:
533 LOGVV("+++ exc noarg (ic=%d)\n", needInitCause);
534 dvmCallMethod(self, initMethod, exception, &unused);
535 break;
536 case kInitMsg:
537 LOGVV("+++ exc msg (ic=%d)\n", needInitCause);
538 dvmCallMethod(self, initMethod, exception, &unused, msgStr);
539 break;
540 case kInitThrow:
541 LOGVV("+++ exc throw");
542 assert(!needInitCause);
543 dvmCallMethod(self, initMethod, exception, &unused, cause);
544 break;
545 case kInitMsgThrow:
546 LOGVV("+++ exc msg+throw");
547 assert(!needInitCause);
548 dvmCallMethod(self, initMethod, exception, &unused, msgStr, cause);
549 break;
550 default:
551 assert(false);
552 goto bail;
553 }
554
555 /*
556 * It's possible the constructor has thrown an exception. If so, we
557 * return an error and let our caller deal with it.
558 */
559 if (self->exception != NULL) {
560 LOGW("Exception thrown (%s) while throwing internal exception (%s)\n",
561 self->exception->clazz->descriptor, exception->clazz->descriptor);
562 goto bail;
563 }
564
565 /*
566 * If this exception was caused by another exception, and we weren't
567 * able to find a cause-setting constructor, set the "cause" field
568 * with an explicit call.
569 */
570 if (needInitCause) {
571 Method* initCause;
572 initCause = dvmFindVirtualMethodHierByDescriptor(excepClass, "initCause",
573 "(Ljava/lang/Throwable;)Ljava/lang/Throwable;");
574 if (initCause != NULL) {
575 dvmCallMethod(self, initCause, exception, &unused, cause);
576 if (self->exception != NULL) {
577 /* initCause() threw an exception; return an error and
578 * let the caller deal with it.
579 */
580 LOGW("Exception thrown (%s) during initCause() "
581 "of internal exception (%s)\n",
582 self->exception->clazz->descriptor,
583 exception->clazz->descriptor);
584 goto bail;
585 }
586 } else {
587 LOGW("WARNING: couldn't find initCause in '%s'\n",
588 excepClass->descriptor);
589 }
590 }
591
592
593 result = true;
594
595bail:
596 dvmReleaseTrackedAlloc((Object*) msgStr, self); // NULL is ok
597 return result;
598}
599
600
601/*
602 * Clear the pending exception and the "initExceptionCount" counter. This
603 * is used by the optimization and verification code, which has to run with
604 * "initializing" set to avoid going into a death-spin if the "class not
605 * found" exception can't be found.
606 *
607 * This can also be called when the VM is in a "normal" state, e.g. when
608 * verifying classes that couldn't be verified at optimization time. The
609 * reset of initExceptionCount should be harmless in that case.
610 */
611void dvmClearOptException(Thread* self)
612{
613 self->exception = NULL;
614 gDvm.initExceptionCount = 0;
615}
616
617/*
618 * Returns "true" if this is a "checked" exception, i.e. it's a subclass
619 * of Throwable (assumed) but not a subclass of RuntimeException or Error.
620 */
621bool dvmIsCheckedException(const Object* exception)
622{
623 if (dvmInstanceof(exception->clazz, gDvm.classJavaLangError) ||
624 dvmInstanceof(exception->clazz, gDvm.classJavaLangRuntimeException))
625 {
626 return false;
627 } else {
628 return true;
629 }
630}
631
632/*
633 * Wrap the now-pending exception in a different exception. This is useful
634 * for reflection stuff that wants to hand a checked exception back from a
635 * method that doesn't declare it.
636 *
637 * If something fails, an (unchecked) exception related to that failure
638 * will be pending instead.
639 */
640void dvmWrapException(const char* newExcepStr)
641{
642 Thread* self = dvmThreadSelf();
643 Object* origExcep;
644 ClassObject* iteClass;
645
646 origExcep = dvmGetException(self);
647 dvmAddTrackedAlloc(origExcep, self); // don't let the GC free it
648
649 dvmClearException(self); // clear before class lookup
650 iteClass = dvmFindSystemClass(newExcepStr);
651 if (iteClass != NULL) {
652 Object* iteExcep;
653 Method* initMethod;
654
655 iteExcep = dvmAllocObject(iteClass, ALLOC_DEFAULT);
656 if (iteExcep != NULL) {
657 initMethod = dvmFindDirectMethodByDescriptor(iteClass, "<init>",
658 "(Ljava/lang/Throwable;)V");
659 if (initMethod != NULL) {
660 JValue unused;
661 dvmCallMethod(self, initMethod, iteExcep, &unused,
662 origExcep);
663
664 /* if <init> succeeded, replace the old exception */
665 if (!dvmCheckException(self))
666 dvmSetException(self, iteExcep);
667 }
668 dvmReleaseTrackedAlloc(iteExcep, NULL);
669
670 /* if initMethod doesn't exist, or failed... */
671 if (!dvmCheckException(self))
672 dvmSetException(self, origExcep);
673 } else {
674 /* leave OutOfMemoryError pending */
675 }
676 } else {
677 /* leave ClassNotFoundException pending */
678 }
679
680 assert(dvmCheckException(self));
681 dvmReleaseTrackedAlloc(origExcep, self);
682}
683
684/*
Andy McFadden686e1e22009-05-26 16:56:30 -0700685 * Get the "cause" field from an exception.
686 *
687 * The Throwable class initializes the "cause" field to "this" to
688 * differentiate between being initialized to null and never being
689 * initialized. We check for that here and convert it to NULL.
690 */
691Object* dvmGetExceptionCause(const Object* exception)
692{
693 if (!dvmInstanceof(exception->clazz, gDvm.classJavaLangThrowable)) {
694 LOGE("Tried to get cause from object of type '%s'\n",
695 exception->clazz->descriptor);
696 dvmAbort();
697 }
698 Object* cause =
699 dvmGetFieldObject(exception, gDvm.offJavaLangThrowable_cause);
700 if (cause == exception)
701 return NULL;
702 else
703 return cause;
704}
705
706/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800707 * Print the stack trace of the current exception on stderr. This is called
708 * from the JNI ExceptionDescribe call.
709 *
710 * For consistency we just invoke the Throwable printStackTrace method,
711 * which might be overridden in the exception object.
712 *
713 * Exceptions thrown during the course of printing the stack trace are
714 * ignored.
715 */
716void dvmPrintExceptionStackTrace(void)
717{
718 Thread* self = dvmThreadSelf();
719 Object* exception;
720 Method* printMethod;
721
722 exception = self->exception;
723 if (exception == NULL)
724 return;
725
Andy McFadden50cab512010-10-07 15:11:43 -0700726 dvmAddTrackedAlloc(exception, self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800727 self->exception = NULL;
728 printMethod = dvmFindVirtualMethodHierByDescriptor(exception->clazz,
729 "printStackTrace", "()V");
730 if (printMethod != NULL) {
731 JValue unused;
732 dvmCallMethod(self, printMethod, exception, &unused);
733 } else {
734 LOGW("WARNING: could not find printStackTrace in %s\n",
735 exception->clazz->descriptor);
736 }
737
738 if (self->exception != NULL) {
Elliott Hughes22680ee2010-07-20 17:23:06 -0700739 LOGW("NOTE: exception thrown while printing stack trace: %s\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800740 self->exception->clazz->descriptor);
741 }
742
743 self->exception = exception;
Andy McFadden50cab512010-10-07 15:11:43 -0700744 dvmReleaseTrackedAlloc(exception, self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800745}
746
747/*
748 * Search the method's list of exceptions for a match.
749 *
750 * Returns the offset of the catch block on success, or -1 on failure.
751 */
752static int findCatchInMethod(Thread* self, const Method* method, int relPc,
753 ClassObject* excepClass)
754{
755 /*
756 * Need to clear the exception before entry. Otherwise, dvmResolveClass
757 * might think somebody threw an exception while it was loading a class.
758 */
759 assert(!dvmCheckException(self));
760 assert(!dvmIsNativeMethod(method));
761
762 LOGVV("findCatchInMethod %s.%s excep=%s depth=%d\n",
763 method->clazz->descriptor, method->name, excepClass->descriptor,
764 dvmComputeExactFrameDepth(self->curFrame));
765
766 DvmDex* pDvmDex = method->clazz->pDvmDex;
767 const DexCode* pCode = dvmGetMethodCode(method);
768 DexCatchIterator iterator;
769
770 if (dexFindCatchHandler(&iterator, pCode, relPc)) {
771 for (;;) {
772 DexCatchHandler* handler = dexCatchIteratorNext(&iterator);
773
774 if (handler == NULL) {
775 break;
776 }
Carl Shapirode750892010-06-08 16:37:12 -0700777
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800778 if (handler->typeIdx == kDexNoIndex) {
779 /* catch-all */
780 LOGV("Match on catch-all block at 0x%02x in %s.%s for %s\n",
781 relPc, method->clazz->descriptor,
782 method->name, excepClass->descriptor);
783 return handler->address;
784 }
785
786 ClassObject* throwable =
787 dvmDexGetResolvedClass(pDvmDex, handler->typeIdx);
788 if (throwable == NULL) {
789 /*
790 * TODO: this behaves badly if we run off the stack
791 * while trying to throw an exception. The problem is
792 * that, if we're in a class loaded by a class loader,
793 * the call to dvmResolveClass has to ask the class
794 * loader for help resolving any previously-unresolved
795 * classes. If this particular class loader hasn't
796 * resolved StackOverflowError, it will call into
797 * interpreted code, and blow up.
798 *
799 * We currently replace the previous exception with
800 * the StackOverflowError, which means they won't be
801 * catching it *unless* they explicitly catch
802 * StackOverflowError, in which case we'll be unable
803 * to resolve the class referred to by the "catch"
804 * block.
805 *
806 * We end up getting a huge pile of warnings if we do
807 * a simple synthetic test, because this method gets
808 * called on every stack frame up the tree, and it
809 * fails every time.
810 *
811 * This eventually bails out, effectively becoming an
812 * uncatchable exception, so other than the flurry of
813 * warnings it's not really a problem. Still, we could
814 * probably handle this better.
815 */
816 throwable = dvmResolveClass(method->clazz, handler->typeIdx,
817 true);
818 if (throwable == NULL) {
819 /*
820 * We couldn't find the exception they wanted in
821 * our class files (or, perhaps, the stack blew up
822 * while we were querying a class loader). Cough
823 * up a warning, then move on to the next entry.
824 * Keep the exception status clear.
825 */
826 LOGW("Could not resolve class ref'ed in exception "
827 "catch list (class index %d, exception %s)\n",
828 handler->typeIdx,
829 (self->exception != NULL) ?
830 self->exception->clazz->descriptor : "(none)");
831 dvmClearException(self);
832 continue;
833 }
834 }
835
836 //LOGD("ADDR MATCH, check %s instanceof %s\n",
837 // excepClass->descriptor, pEntry->excepClass->descriptor);
838
839 if (dvmInstanceof(excepClass, throwable)) {
840 LOGV("Match on catch block at 0x%02x in %s.%s for %s\n",
841 relPc, method->clazz->descriptor,
842 method->name, excepClass->descriptor);
843 return handler->address;
844 }
845 }
846 }
847
848 LOGV("No matching catch block at 0x%02x in %s for %s\n",
849 relPc, method->name, excepClass->descriptor);
850 return -1;
851}
852
853/*
854 * Find a matching "catch" block. "pc" is the relative PC within the
855 * current method, indicating the offset from the start in 16-bit units.
856 *
857 * Returns the offset to the catch block, or -1 if we run up against a
858 * break frame without finding anything.
859 *
860 * The class resolution stuff we have to do while evaluating the "catch"
861 * blocks could cause an exception. The caller should clear the exception
862 * before calling here and restore it after.
863 *
864 * Sets *newFrame to the frame pointer of the frame with the catch block.
865 * If "scanOnly" is false, self->curFrame is also set to this value.
866 */
867int dvmFindCatchBlock(Thread* self, int relPc, Object* exception,
868 bool scanOnly, void** newFrame)
869{
870 void* fp = self->curFrame;
871 int catchAddr = -1;
872
873 assert(!dvmCheckException(self));
874
875 while (true) {
876 StackSaveArea* saveArea = SAVEAREA_FROM_FP(fp);
877 catchAddr = findCatchInMethod(self, saveArea->method, relPc,
878 exception->clazz);
879 if (catchAddr >= 0)
880 break;
881
882 /*
883 * Normally we'd check for ACC_SYNCHRONIZED methods and unlock
884 * them as we unroll. Dalvik uses what amount to generated
885 * "finally" blocks to take care of this for us.
886 */
887
888 /* output method profiling info */
889 if (!scanOnly) {
890 TRACE_METHOD_UNROLL(self, saveArea->method);
891 }
892
893 /*
894 * Move up one frame. If the next thing up is a break frame,
895 * break out now so we're left unrolled to the last method frame.
896 * We need to point there so we can roll up the JNI local refs
897 * if this was a native method.
898 */
899 assert(saveArea->prevFrame != NULL);
900 if (dvmIsBreakFrame(saveArea->prevFrame)) {
901 if (!scanOnly)
902 break; // bail with catchAddr == -1
903
904 /*
905 * We're scanning for the debugger. It needs to know if this
906 * exception is going to be caught or not, and we need to figure
907 * out if it will be caught *ever* not just between the current
908 * position and the next break frame. We can't tell what native
909 * code is going to do, so we assume it never catches exceptions.
910 *
911 * Start by finding an interpreted code frame.
912 */
913 fp = saveArea->prevFrame; // this is the break frame
914 saveArea = SAVEAREA_FROM_FP(fp);
915 fp = saveArea->prevFrame; // this may be a good one
916 while (fp != NULL) {
917 if (!dvmIsBreakFrame(fp)) {
918 saveArea = SAVEAREA_FROM_FP(fp);
919 if (!dvmIsNativeMethod(saveArea->method))
920 break;
921 }
922
923 fp = SAVEAREA_FROM_FP(fp)->prevFrame;
924 }
925 if (fp == NULL)
926 break; // bail with catchAddr == -1
927
928 /*
929 * Now fp points to the "good" frame. When the interp code
930 * invoked the native code, it saved a copy of its current PC
931 * into xtra.currentPc. Pull it out of there.
932 */
933 relPc =
934 saveArea->xtra.currentPc - SAVEAREA_FROM_FP(fp)->method->insns;
935 } else {
936 fp = saveArea->prevFrame;
937
938 /* savedPc in was-current frame goes with method in now-current */
939 relPc = saveArea->savedPc - SAVEAREA_FROM_FP(fp)->method->insns;
940 }
941 }
942
943 if (!scanOnly)
944 self->curFrame = fp;
945
946 /*
947 * The class resolution in findCatchInMethod() could cause an exception.
948 * Clear it to be safe.
949 */
950 self->exception = NULL;
951
952 *newFrame = fp;
953 return catchAddr;
954}
955
956/*
957 * We have to carry the exception's stack trace around, but in many cases
958 * it will never be examined. It makes sense to keep it in a compact,
959 * VM-specific object, rather than an array of Objects with strings.
960 *
961 * Pass in the thread whose stack we're interested in. If "thread" is
962 * not self, the thread must be suspended. This implies that the thread
963 * list lock is held, which means we can't allocate objects or we risk
964 * jamming the GC. So, we allow this function to return different formats.
965 * (This shouldn't be called directly -- see the inline functions in the
966 * header file.)
967 *
968 * If "wantObject" is true, this returns a newly-allocated Object, which is
969 * presently an array of integers, but could become something else in the
970 * future. If "wantObject" is false, return plain malloc data.
971 *
972 * NOTE: if we support class unloading, we will need to scan the class
973 * object references out of these arrays.
974 */
975void* dvmFillInStackTraceInternal(Thread* thread, bool wantObject, int* pCount)
976{
977 ArrayObject* stackData = NULL;
978 int* simpleData = NULL;
979 void* fp;
980 void* startFp;
981 int stackDepth;
982 int* intPtr;
983
984 if (pCount != NULL)
985 *pCount = 0;
986 fp = thread->curFrame;
987
988 assert(thread == dvmThreadSelf() || dvmIsSuspended(thread));
989
990 /*
991 * We're looking at a stack frame for code running below a Throwable
992 * constructor. We want to remove the Throwable methods and the
993 * superclass initializations so the user doesn't see them when they
994 * read the stack dump.
995 *
996 * TODO: this just scrapes off the top layers of Throwable. Might not do
997 * the right thing if we create an exception object or cause a VM
998 * exception while in a Throwable method.
999 */
1000 while (fp != NULL) {
1001 const StackSaveArea* saveArea = SAVEAREA_FROM_FP(fp);
1002 const Method* method = saveArea->method;
1003
1004 if (dvmIsBreakFrame(fp))
1005 break;
1006 if (!dvmInstanceof(method->clazz, gDvm.classJavaLangThrowable))
1007 break;
1008 //LOGD("EXCEP: ignoring %s.%s\n",
1009 // method->clazz->descriptor, method->name);
1010 fp = saveArea->prevFrame;
1011 }
1012 startFp = fp;
1013
1014 /*
1015 * Compute the stack depth.
1016 */
1017 stackDepth = 0;
1018 while (fp != NULL) {
1019 const StackSaveArea* saveArea = SAVEAREA_FROM_FP(fp);
1020
1021 if (!dvmIsBreakFrame(fp))
1022 stackDepth++;
1023
1024 assert(fp != saveArea->prevFrame);
1025 fp = saveArea->prevFrame;
1026 }
1027 //LOGD("EXCEP: stack depth is %d\n", stackDepth);
1028
1029 if (!stackDepth)
1030 goto bail;
1031
1032 /*
1033 * We need to store a pointer to the Method and the program counter.
1034 * We have 4-byte pointers, so we use '[I'.
1035 */
1036 if (wantObject) {
1037 assert(sizeof(Method*) == 4);
1038 stackData = dvmAllocPrimitiveArray('I', stackDepth*2, ALLOC_DEFAULT);
1039 if (stackData == NULL) {
1040 assert(dvmCheckException(dvmThreadSelf()));
1041 goto bail;
1042 }
1043 intPtr = (int*) stackData->contents;
1044 } else {
1045 /* array of ints; first entry is stack depth */
1046 assert(sizeof(Method*) == sizeof(int));
1047 simpleData = (int*) malloc(sizeof(int) * stackDepth*2);
1048 if (simpleData == NULL)
1049 goto bail;
1050
1051 assert(pCount != NULL);
1052 intPtr = simpleData;
1053 }
1054 if (pCount != NULL)
1055 *pCount = stackDepth;
1056
1057 fp = startFp;
1058 while (fp != NULL) {
1059 const StackSaveArea* saveArea = SAVEAREA_FROM_FP(fp);
1060 const Method* method = saveArea->method;
1061
1062 if (!dvmIsBreakFrame(fp)) {
1063 //LOGD("EXCEP keeping %s.%s\n", method->clazz->descriptor,
1064 // method->name);
1065
1066 *intPtr++ = (int) method;
1067 if (dvmIsNativeMethod(method)) {
1068 *intPtr++ = 0; /* no saved PC for native methods */
1069 } else {
1070 assert(saveArea->xtra.currentPc >= method->insns &&
Carl Shapirode750892010-06-08 16:37:12 -07001071 saveArea->xtra.currentPc <
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001072 method->insns + dvmGetMethodInsnsSize(method));
1073 *intPtr++ = (int) (saveArea->xtra.currentPc - method->insns);
1074 }
1075
1076 stackDepth--; // for verification
1077 }
1078
1079 assert(fp != saveArea->prevFrame);
1080 fp = saveArea->prevFrame;
1081 }
1082 assert(stackDepth == 0);
1083
1084bail:
1085 if (wantObject) {
1086 dvmReleaseTrackedAlloc((Object*) stackData, dvmThreadSelf());
1087 return stackData;
1088 } else {
1089 return simpleData;
1090 }
1091}
1092
1093
1094/*
1095 * Given an Object previously created by dvmFillInStackTrace(), use the
1096 * contents of the saved stack trace to generate an array of
1097 * java/lang/StackTraceElement objects.
1098 *
1099 * The returned array is not added to the "local refs" list.
1100 */
1101ArrayObject* dvmGetStackTrace(const Object* ostackData)
1102{
1103 const ArrayObject* stackData = (const ArrayObject*) ostackData;
1104 const int* intVals;
Carl Shapiroe3c01da2010-05-20 22:54:18 -07001105 int stackSize;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001106
1107 stackSize = stackData->length / 2;
1108 intVals = (const int*) stackData->contents;
1109 return dvmGetStackTraceRaw(intVals, stackSize);
1110}
1111
1112/*
1113 * Generate an array of StackTraceElement objects from the raw integer
1114 * data encoded by dvmFillInStackTrace().
1115 *
1116 * "intVals" points to the first {method,pc} pair.
1117 *
1118 * The returned array is not added to the "local refs" list.
1119 */
1120ArrayObject* dvmGetStackTraceRaw(const int* intVals, int stackDepth)
1121{
1122 ArrayObject* steArray = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001123 int i;
1124
1125 /* init this if we haven't yet */
1126 if (!dvmIsClassInitialized(gDvm.classJavaLangStackTraceElement))
1127 dvmInitClass(gDvm.classJavaLangStackTraceElement);
1128
1129 /* allocate a StackTraceElement array */
1130 steArray = dvmAllocArray(gDvm.classJavaLangStackTraceElementArray,
1131 stackDepth, kObjectArrayRefWidth, ALLOC_DEFAULT);
1132 if (steArray == NULL)
1133 goto bail;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001134
1135 /*
1136 * Allocate and initialize a StackTraceElement for each stack frame.
1137 * We use the standard constructor to configure the object.
1138 */
1139 for (i = 0; i < stackDepth; i++) {
1140 Object* ste;
1141 Method* meth;
1142 StringObject* className;
1143 StringObject* methodName;
1144 StringObject* fileName;
1145 int lineNumber, pc;
1146 const char* sourceFile;
1147 char* dotName;
1148
1149 ste = dvmAllocObject(gDvm.classJavaLangStackTraceElement,ALLOC_DEFAULT);
1150 if (ste == NULL)
1151 goto bail;
1152
1153 meth = (Method*) *intVals++;
1154 pc = *intVals++;
1155
1156 if (pc == -1) // broken top frame?
1157 lineNumber = 0;
1158 else
1159 lineNumber = dvmLineNumFromPC(meth, pc);
1160
1161 dotName = dvmDescriptorToDot(meth->clazz->descriptor);
Barry Hayes81f3ebe2010-06-15 16:17:37 -07001162 className = dvmCreateStringFromCstr(dotName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001163 free(dotName);
1164
Barry Hayes81f3ebe2010-06-15 16:17:37 -07001165 methodName = dvmCreateStringFromCstr(meth->name);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001166 sourceFile = dvmGetMethodSourceFile(meth);
1167 if (sourceFile != NULL)
Barry Hayes81f3ebe2010-06-15 16:17:37 -07001168 fileName = dvmCreateStringFromCstr(sourceFile);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001169 else
1170 fileName = NULL;
1171
1172 /*
1173 * Invoke:
1174 * public StackTraceElement(String declaringClass, String methodName,
1175 * String fileName, int lineNumber)
1176 * (where lineNumber==-2 means "native")
1177 */
1178 JValue unused;
1179 dvmCallMethod(dvmThreadSelf(), gDvm.methJavaLangStackTraceElement_init,
1180 ste, &unused, className, methodName, fileName, lineNumber);
1181
1182 dvmReleaseTrackedAlloc(ste, NULL);
1183 dvmReleaseTrackedAlloc((Object*) className, NULL);
1184 dvmReleaseTrackedAlloc((Object*) methodName, NULL);
1185 dvmReleaseTrackedAlloc((Object*) fileName, NULL);
1186
1187 if (dvmCheckException(dvmThreadSelf()))
1188 goto bail;
1189
Barry Hayes364f9d92010-06-11 16:12:47 -07001190 dvmSetObjectArrayElement(steArray, i, ste);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001191 }
1192
1193bail:
1194 dvmReleaseTrackedAlloc((Object*) steArray, NULL);
1195 return steArray;
1196}
1197
1198/*
1199 * Dump the contents of a raw stack trace to the log.
1200 */
1201void dvmLogRawStackTrace(const int* intVals, int stackDepth)
1202{
1203 int i;
1204
1205 /*
1206 * Run through the array of stack frame data.
1207 */
1208 for (i = 0; i < stackDepth; i++) {
1209 Method* meth;
1210 int lineNumber, pc;
1211 const char* sourceFile;
1212 char* dotName;
1213
1214 meth = (Method*) *intVals++;
1215 pc = *intVals++;
1216
1217 if (pc == -1) // broken top frame?
1218 lineNumber = 0;
1219 else
1220 lineNumber = dvmLineNumFromPC(meth, pc);
1221
1222 // probably don't need to do this, but it looks nicer
1223 dotName = dvmDescriptorToDot(meth->clazz->descriptor);
1224
1225 if (dvmIsNativeMethod(meth)) {
1226 LOGI("\tat %s.%s(Native Method)\n", dotName, meth->name);
1227 } else {
1228 LOGI("\tat %s.%s(%s:%d)\n",
1229 dotName, meth->name, dvmGetMethodSourceFile(meth),
1230 dvmLineNumFromPC(meth, pc));
1231 }
1232
1233 free(dotName);
1234
1235 sourceFile = dvmGetMethodSourceFile(meth);
1236 }
1237}
1238
1239/*
Andy McFadden8552f442010-09-16 15:32:43 -07001240 * Get the message string. We'd like to just grab the field out of
1241 * Throwable, but the getMessage() function can be overridden by the
1242 * sub-class.
1243 *
1244 * Returns the message string object, or NULL if it wasn't set or
1245 * we encountered a failure trying to retrieve it. The string will
1246 * be added to the tracked references table.
1247 */
1248static StringObject* getExceptionMessage(Object* exception)
1249{
1250 Thread* self = dvmThreadSelf();
1251 Method* getMessageMethod;
1252 StringObject* messageStr = NULL;
1253
1254 assert(exception == self->exception);
Andy McFadden50cab512010-10-07 15:11:43 -07001255 dvmAddTrackedAlloc(exception, self);
Andy McFadden8552f442010-09-16 15:32:43 -07001256 self->exception = NULL;
1257
1258 getMessageMethod = dvmFindVirtualMethodHierByDescriptor(exception->clazz,
1259 "getMessage", "()Ljava/lang/String;");
1260 if (getMessageMethod != NULL) {
1261 /* could be in NATIVE mode from CheckJNI, so switch state */
1262 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_RUNNING);
1263 JValue result;
1264
1265 dvmCallMethod(self, getMessageMethod, exception, &result);
1266 messageStr = (StringObject*) result.l;
Andy McFaddenbd74b4b2010-09-22 12:37:49 -07001267 if (messageStr != NULL)
1268 dvmAddTrackedAlloc((Object*) messageStr, self);
Andy McFadden8552f442010-09-16 15:32:43 -07001269
1270 dvmChangeStatus(self, oldStatus);
1271 } else {
1272 LOGW("WARNING: could not find getMessage in %s\n",
1273 exception->clazz->descriptor);
1274 }
1275
1276 if (self->exception != NULL) {
1277 LOGW("NOTE: exception thrown while retrieving exception message: %s\n",
1278 self->exception->clazz->descriptor);
1279 }
1280
1281 self->exception = exception;
Andy McFadden50cab512010-10-07 15:11:43 -07001282 dvmReleaseTrackedAlloc(exception, self);
Andy McFadden8552f442010-09-16 15:32:43 -07001283 return messageStr;
1284}
1285
1286/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001287 * Print the direct stack trace of the given exception to the log.
1288 */
1289static void logStackTraceOf(Object* exception)
1290{
1291 const ArrayObject* stackData;
1292 StringObject* messageStr;
1293 int stackSize;
1294 const int* intVals;
Andy McFaddende952db2010-09-16 13:33:32 -07001295 char* className;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001296
Andy McFaddende952db2010-09-16 13:33:32 -07001297 className = dvmDescriptorToDot(exception->clazz->descriptor);
Andy McFadden8552f442010-09-16 15:32:43 -07001298 messageStr = getExceptionMessage(exception);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001299 if (messageStr != NULL) {
1300 char* cp = dvmCreateCstrFromString(messageStr);
Andy McFadden8552f442010-09-16 15:32:43 -07001301 dvmReleaseTrackedAlloc((Object*) messageStr, dvmThreadSelf());
1302 messageStr = NULL;
1303
Andy McFaddende952db2010-09-16 13:33:32 -07001304 LOGI("%s: %s\n", className, cp);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001305 free(cp);
1306 } else {
Andy McFaddende952db2010-09-16 13:33:32 -07001307 LOGI("%s:\n", className);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001308 }
Andy McFaddende952db2010-09-16 13:33:32 -07001309 free(className);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001310
Andy McFaddende952db2010-09-16 13:33:32 -07001311 /*
1312 * This relies on the stackState field, which contains the "raw"
1313 * form of the stack. The Throwable class may clear this field
1314 * after it generates the "cooked" form, in which case we'll have
1315 * nothing to show.
1316 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001317 stackData = (const ArrayObject*) dvmGetFieldObject(exception,
1318 gDvm.offJavaLangThrowable_stackState);
1319 if (stackData == NULL) {
Andy McFaddende952db2010-09-16 13:33:32 -07001320 LOGI(" (raw stack trace not found)\n");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001321 return;
1322 }
1323
1324 stackSize = stackData->length / 2;
1325 intVals = (const int*) stackData->contents;
1326
1327 dvmLogRawStackTrace(intVals, stackSize);
1328}
1329
1330/*
1331 * Print the stack trace of the current thread's exception, as well as
1332 * the stack traces of any chained exceptions, to the log. We extract
1333 * the stored stack trace and process it internally instead of calling
1334 * interpreted code.
1335 */
1336void dvmLogExceptionStackTrace(void)
1337{
1338 Object* exception = dvmThreadSelf()->exception;
1339 Object* cause;
1340
1341 if (exception == NULL) {
1342 LOGW("tried to log a null exception?\n");
1343 return;
1344 }
1345
1346 for (;;) {
1347 logStackTraceOf(exception);
Andy McFadden686e1e22009-05-26 16:56:30 -07001348 cause = dvmGetExceptionCause(exception);
1349 if (cause == NULL) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001350 break;
1351 }
1352 LOGI("Caused by:\n");
1353 exception = cause;
1354 }
1355}
Elliott Hughes00160242010-10-20 17:14:57 -07001356
1357void dvmThrowAIOOBE(int index, int length)
1358{
1359 dvmThrowExceptionFmt("Ljava/lang/ArrayIndexOutOfBoundsException;",
1360 "index=%d length=%d", index, length);
1361}