2006-07-08 Matthias Klose <doko@debian.org>
[official-gcc.git] / libjava / stacktrace.cc
blob2ace9abc232e7212a5c4c6be51eaa8b48ec13a98
1 // stacktrace.cc - Functions for unwinding & inspecting the call stack.
3 /* Copyright (C) 2005, 2006 Free Software Foundation
5 This file is part of libgcj.
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
9 details. */
11 #include <config.h>
12 #include <platform.h>
14 #include <jvm.h>
15 #include <gcj/cni.h>
16 #include <java-interp.h>
17 #include <java-stack.h>
19 #include <stdio.h>
21 #include <java/lang/Class.h>
22 #include <java/lang/Long.h>
23 #include <java/util/ArrayList.h>
24 #include <java/util/IdentityHashMap.h>
25 #include <gnu/java/lang/MainThread.h>
26 #include <gnu/gcj/runtime/NameFinder.h>
27 #include <gnu/gcj/runtime/StringBuffer.h>
29 #include <sysdep/backtrace.h>
30 #include <sysdep/descriptor.h>
32 using namespace java::lang;
33 using namespace java::lang::reflect;
34 using namespace java::util;
35 using namespace gnu::gcj::runtime;
37 // Maps ncode values to their containing native class.
38 // NOTE: Currently this Map contradicts class GC for native classes. This map
39 // (and the "new class stack") will need to use WeakReferences in order to
40 // enable native class GC.
41 static java::util::IdentityHashMap *ncodeMap;
43 // Check the "class stack" for any classes initialized since we were last
44 // called, and add them to ncodeMap.
45 void
46 _Jv_StackTrace::UpdateNCodeMap ()
48 // The Map should be large enough so that a typical Java app doesn't cause
49 // it to rehash, without using too much memory. ~5000 entries should be
50 // enough.
51 if (ncodeMap == NULL)
52 ncodeMap = new java::util::IdentityHashMap (5087);
54 jclass klass;
55 while ((klass = _Jv_PopClass ()))
56 if (!_Jv_IsInterpretedClass (klass))
58 //printf ("got %s\n", klass->name->data);
59 for (int i = 0; i < klass->method_count; i++)
61 _Jv_Method *method = &klass->methods[i];
62 void *ncode = method->ncode;
63 // Add non-abstract methods to ncodeMap.
64 if (ncode)
66 ncode = UNWRAP_FUNCTION_DESCRIPTOR (ncode);
67 ncodeMap->put ((java::lang::Object *) ncode, klass);
73 // Given a native frame, return the class which this code belongs
74 // to. Returns NULL if this IP is not associated with a native Java class.
75 // If NCODE is supplied, it will be set with the ip for the entry point of the
76 // enclosing method.
77 jclass
78 _Jv_StackTrace::ClassForFrame (_Jv_StackFrame *frame)
80 JvAssert (frame->type == frame_native);
81 jclass klass = NULL;
83 // look it up in ncodeMap
84 if (frame->start_ip)
85 klass = (jclass) ncodeMap->get ((jobject) frame->start_ip);
87 return klass;
90 _Unwind_Reason_Code
91 _Jv_StackTrace::UnwindTraceFn (struct _Unwind_Context *context, void *state_ptr)
93 _Jv_UnwindState *state = (_Jv_UnwindState *) state_ptr;
94 jint pos = state->pos;
96 // Check if the trace buffer needs to be extended.
97 if (pos == state->length)
99 int newLength = state->length * 2;
100 void *newFrames = _Jv_AllocBytes (newLength * sizeof(_Jv_StackFrame));
101 memcpy (newFrames, state->frames, state->length * sizeof(_Jv_StackFrame));
102 state->frames = (_Jv_StackFrame *) newFrames;
103 state->length = newLength;
106 void *func_addr = (void *) _Unwind_GetRegionStart (context);
108 // If we see the interpreter's main function, "pop" an entry off the
109 // interpreter stack and use that instead, so that the trace goes through
110 // the java code and not the interpreter itself. This assumes a 1:1
111 // correspondance between call frames in the interpreted stack and occurances
112 // of _Jv_InterpMethod::run() on the native stack.
113 #ifdef INTERPRETER
114 void *interp_run = (void *) &_Jv_InterpMethod::run;
115 if (func_addr == UNWRAP_FUNCTION_DESCRIPTOR (interp_run))
117 state->frames[pos].type = frame_interpreter;
118 state->frames[pos].interp.meth = state->interp_frame->self;
119 state->frames[pos].interp.pc = state->interp_frame->pc;
120 state->interp_frame = state->interp_frame->next;
122 else
123 #endif
125 _Unwind_Ptr ip;
126 int ip_before_insn = 0;
127 ip = _Unwind_GetIPInfo (context, &ip_before_insn);
129 // If the unwinder gave us a 'return' address, roll it back a little
130 // to ensure we get the correct line number for the call itself.
131 if (! ip_before_insn)
132 --ip;
134 state->frames[pos].type = frame_native;
135 state->frames[pos].ip = (void *) ip;
136 state->frames[pos].start_ip = func_addr;
139 _Unwind_Reason_Code result = _URC_NO_REASON;
140 if (state->trace_function != NULL)
141 result = (state->trace_function) (state);
142 state->pos++;
143 return result;
146 // Return a raw stack trace from the current point of execution. The raw
147 // trace will include all functions that have unwind info.
148 _Jv_StackTrace *
149 _Jv_StackTrace::GetStackTrace(void)
151 int trace_size = 100;
152 _Jv_StackFrame frames[trace_size];
153 _Jv_UnwindState state (trace_size);
154 state.frames = (_Jv_StackFrame *) &frames;
156 #ifdef SJLJ_EXCEPTIONS
157 // The Unwind interface doesn't work with the SJLJ exception model.
158 // Fall back to a platform-specific unwinder.
159 fallback_backtrace (&state);
160 #else /* SJLJ_EXCEPTIONS */
161 _Unwind_Backtrace (UnwindTraceFn, &state);
162 #endif /* SJLJ_EXCEPTIONS */
164 // Copy the trace and return it.
165 int traceSize = sizeof (_Jv_StackTrace) +
166 (sizeof (_Jv_StackFrame) * state.pos);
167 _Jv_StackTrace *trace = (_Jv_StackTrace *) _Jv_AllocBytes (traceSize);
168 trace->length = state.pos;
169 memcpy (trace->frames, state.frames, sizeof (_Jv_StackFrame) * state.pos);
170 return trace;
173 void
174 _Jv_StackTrace::getLineNumberForFrame(_Jv_StackFrame *frame, NameFinder *finder,
175 jstring *sourceFileName, jint *lineNum,
176 jstring *methodName)
178 #ifdef INTERPRETER
179 if (frame->type == frame_interpreter)
181 _Jv_InterpMethod *interp_meth = frame->interp.meth;
182 _Jv_InterpClass *interp_class =
183 (_Jv_InterpClass *) interp_meth->defining_class->aux_info;
184 *sourceFileName = interp_class->source_file_name;
185 *lineNum = interp_meth->get_source_line(frame->interp.pc);
186 return;
188 #endif
190 // Use _Jv_platform_dladdr() to determine in which binary the address IP
191 // resides.
192 _Jv_AddrInfo info;
193 jstring binaryName = NULL;
194 const char *argv0 = _Jv_GetSafeArg(0);
196 void *ip = frame->ip;
197 _Unwind_Ptr offset = 0;
199 if (_Jv_platform_dladdr (ip, &info))
201 if (info.file_name)
202 binaryName = JvNewStringUTF (info.file_name);
203 else
204 return;
206 if (*methodName == NULL && info.sym_name)
207 *methodName = JvNewStringUTF (info.sym_name);
209 // addr2line expects relative addresses for shared libraries.
210 if (strcmp (info.file_name, argv0) == 0)
211 offset = (_Unwind_Ptr) ip;
212 else
213 offset = (_Unwind_Ptr) ip - (_Unwind_Ptr) info.base;
215 finder->lookup (binaryName, (jlong) offset);
216 *sourceFileName = finder->getSourceFile();
217 *lineNum = finder->getLineNum();
218 if (*lineNum == -1 && NameFinder::showRaw())
220 gnu::gcj::runtime::StringBuffer *t =
221 new gnu::gcj::runtime::StringBuffer(binaryName);
222 t->append ((jchar)' ');
223 t->append ((jchar)'[');
224 // + 1 to compensate for the - 1 adjustment above;
225 t->append (Long::toHexString (offset + 1));
226 t->append ((jchar)']');
227 *sourceFileName = t->toString();
232 // Look up class and method info for the given stack frame, setting
233 // frame->klass and frame->meth if they are known.
234 void
235 _Jv_StackTrace::FillInFrameInfo (_Jv_StackFrame *frame)
237 jclass klass = NULL;
238 _Jv_Method *meth = NULL;
240 if (frame->type == frame_native)
242 klass = _Jv_StackTrace::ClassForFrame (frame);
244 if (klass != NULL)
245 // Find method in class
246 for (int j = 0; j < klass->method_count; j++)
248 void *wncode = UNWRAP_FUNCTION_DESCRIPTOR (klass->methods[j].ncode);
249 if (wncode == frame->start_ip)
251 meth = &klass->methods[j];
252 break;
256 #ifdef INTERPRETER
257 else if (frame->type == frame_interpreter)
259 _Jv_InterpMethod *interp_meth = frame->interp.meth;
260 klass = interp_meth->defining_class;
261 meth = interp_meth->self;
263 #endif
264 else
265 JvFail ("Unknown frame type");
267 frame->klass = klass;
268 frame->meth = meth;
271 // Convert raw stack frames to a Java array of StackTraceElement objects.
272 JArray< ::java::lang::StackTraceElement *>*
273 _Jv_StackTrace::GetStackTraceElements (_Jv_StackTrace *trace,
274 Throwable *throwable __attribute__((unused)))
276 ArrayList *list = new ArrayList ();
278 #if defined (SJLJ_EXCEPTIONS) && ! defined (WIN32)
279 // We can't use the nCodeMap without unwinder support. Instead,
280 // fake the method name by giving the IP in hex - better than nothing.
281 jstring hex = JvNewStringUTF ("0x");
283 for (int i = 0; i < trace->length; i++)
285 jstring sourceFileName = NULL;
286 jint lineNum = -1;
287 _Jv_StackFrame *frame = &trace->frames[i];
289 jstring className = NULL;
290 jstring methodName = hex->concat (Long::toHexString ((jlong) frame->ip));
292 StackTraceElement *element = new StackTraceElement (sourceFileName,
293 lineNum, className, methodName, 0);
294 list->add (element);
297 #else /* SJLJ_EXCEPTIONS && !WIN32 */
299 //JvSynchronized (ncodeMap);
300 UpdateNCodeMap ();
302 NameFinder *finder = new NameFinder();
303 int start_idx = 0;
304 int end_idx = trace->length - 1;
306 // First pass: strip superfluous frames from beginning and end of the trace.
307 for (int i = 0; i < trace->length; i++)
309 _Jv_StackFrame *frame = &trace->frames[i];
310 FillInFrameInfo (frame);
312 if (!frame->klass || !frame->meth)
313 // Not a Java frame.
314 continue;
316 // Throw away the top of the stack till we see:
317 // - the constructor(s) of this Throwable, or
318 // - the Throwable.fillInStackTrace call.
319 if (frame->klass == throwable->getClass()
320 && strcmp (frame->meth->name->chars(), "<init>") == 0)
321 start_idx = i + 1;
323 if (frame->klass == &Throwable::class$
324 && strcmp (frame->meth->name->chars(), "fillInStackTrace") == 0)
325 start_idx = i + 1;
327 // End the trace at the application's main() method if we see call_main.
328 if (frame->klass == &gnu::java::lang::MainThread::class$
329 && strcmp (frame->meth->name->chars(), "call_main") == 0)
330 end_idx = i - 1;
333 const jboolean remove_unknown
334 = gnu::gcj::runtime::NameFinder::removeUnknown();
336 // Second pass: Look up line-number info for remaining frames.
337 for (int i = start_idx; i <= end_idx; i++)
339 _Jv_StackFrame *frame = &trace->frames[i];
341 if (frame->klass == NULL && remove_unknown)
342 // Not a Java frame.
343 continue;
345 jstring className = NULL;
346 if (frame->klass != NULL)
347 className = frame->klass->getName ();
349 jstring methodName = NULL;
350 if (frame->meth)
351 methodName = JvNewStringUTF (frame->meth->name->chars());
353 jstring sourceFileName = NULL;
354 jint lineNum = -1;
356 getLineNumberForFrame(frame, finder, &sourceFileName, &lineNum,
357 &methodName);
359 StackTraceElement *element = new StackTraceElement (sourceFileName, lineNum,
360 className, methodName, 0);
361 list->add (element);
364 finder->close();
365 #endif /* SJLJ_EXCEPTIONS && !WIN32 */
367 JArray<Object *> *array = JvNewObjectArray (list->size (),
368 &StackTraceElement::class$, NULL);
370 return (JArray<StackTraceElement *>*) list->toArray (array);
373 struct CallingClassTraceData
375 jclass checkClass;
376 jclass foundClass;
377 _Jv_Method *foundMeth;
378 bool seen_checkClass;
381 _Unwind_Reason_Code
382 _Jv_StackTrace::calling_class_trace_fn (_Jv_UnwindState *state)
384 CallingClassTraceData *trace_data = (CallingClassTraceData *)
385 state->trace_data;
386 _Jv_StackFrame *frame = &state->frames[state->pos];
387 FillInFrameInfo (frame);
389 if (trace_data->seen_checkClass
390 && frame->klass
391 && frame->klass != trace_data->checkClass)
393 trace_data->foundClass = frame->klass;
394 trace_data->foundMeth = frame->meth;
395 return _URC_NORMAL_STOP;
398 if (frame->klass == trace_data->checkClass)
399 trace_data->seen_checkClass = true;
401 return _URC_NO_REASON;
404 // Find the class immediately above the given class on the call stack. Any
405 // intermediate non-Java
406 // frames are ignored. If the calling class could not be determined (eg because
407 // the unwinder is not supported on this platform), NULL is returned.
408 // This function is used to implement calling-classloader checks and reflection
409 // accessibility checks.
410 // CHECKCLASS is typically the class calling GetCallingClass. The first class
411 // above CHECKCLASS on the call stack will be returned.
412 jclass
413 _Jv_StackTrace::GetCallingClass (jclass checkClass)
415 jclass result = NULL;
416 GetCallerInfo (checkClass, &result, NULL);
417 return result;
420 void
421 _Jv_StackTrace::GetCallerInfo (jclass checkClass, jclass *caller_class,
422 _Jv_Method **caller_meth)
424 #ifndef SJLJ_EXCEPTIONS
425 int trace_size = 20;
426 _Jv_StackFrame frames[trace_size];
427 _Jv_UnwindState state (trace_size);
428 state.frames = (_Jv_StackFrame *) &frames;
430 CallingClassTraceData trace_data;
431 trace_data.checkClass = checkClass;
432 trace_data.seen_checkClass = false;
433 trace_data.foundClass = NULL;
434 trace_data.foundMeth = NULL;
436 state.trace_function = calling_class_trace_fn;
437 state.trace_data = (void *) &trace_data;
439 //JvSynchronized (ncodeMap);
440 UpdateNCodeMap ();
442 _Unwind_Backtrace (UnwindTraceFn, &state);
444 if (caller_class)
445 *caller_class = trace_data.foundClass;
446 if (caller_meth)
447 *caller_meth = trace_data.foundMeth;
448 #else
449 return;
450 #endif
453 // Return a java array containing the Java classes on the stack above CHECKCLASS.
454 JArray<jclass> *
455 _Jv_StackTrace::GetClassContext (jclass checkClass)
457 JArray<jclass> *result = NULL;
459 int trace_size = 100;
460 _Jv_StackFrame frames[trace_size];
461 _Jv_UnwindState state (trace_size);
462 state.frames = (_Jv_StackFrame *) &frames;
464 //JvSynchronized (ncodeMap);
465 UpdateNCodeMap ();
467 #ifdef SJLJ_EXCEPTIONS
468 // The Unwind interface doesn't work with the SJLJ exception model.
469 // Fall back to a platform-specific unwinder.
470 fallback_backtrace (&state);
471 #else /* SJLJ_EXCEPTIONS */
472 _Unwind_Backtrace (UnwindTraceFn, &state);
473 #endif /* SJLJ_EXCEPTIONS */
475 // Count the number of Java frames on the stack.
476 int jframe_count = 0;
477 bool seen_checkClass = false;
478 int start_pos = -1;
479 for (int i = 0; i < state.pos; i++)
481 _Jv_StackFrame *frame = &state.frames[i];
482 FillInFrameInfo (frame);
484 if (seen_checkClass)
486 if (frame->klass)
488 jframe_count++;
489 if (start_pos == -1)
490 start_pos = i;
493 else
494 seen_checkClass = frame->klass == checkClass;
496 result = (JArray<jclass> *) _Jv_NewObjectArray (jframe_count, &Class::class$, NULL);
497 int pos = 0;
499 for (int i = start_pos; i < state.pos; i++)
501 _Jv_StackFrame *frame = &state.frames[i];
502 if (frame->klass)
503 elements(result)[pos++] = frame->klass;
505 return result;
508 _Unwind_Reason_Code
509 _Jv_StackTrace::non_system_trace_fn (_Jv_UnwindState *state)
511 _Jv_StackFrame *frame = &state->frames[state->pos];
512 FillInFrameInfo (frame);
514 ClassLoader *classLoader = NULL;
516 if (frame->klass)
518 classLoader = frame->klass->getClassLoaderInternal();
519 #ifdef INTERPRETER
520 if (classLoader != NULL)
522 state->trace_data = (void *) classLoader;
523 return _URC_NORMAL_STOP;
525 #endif
528 return _URC_NO_REASON;
531 ClassLoader *
532 _Jv_StackTrace::GetFirstNonSystemClassLoader ()
534 int trace_size = 32;
535 _Jv_StackFrame frames[trace_size];
536 _Jv_UnwindState state (trace_size);
537 state.frames = (_Jv_StackFrame *) &frames;
538 state.trace_function = non_system_trace_fn;
539 state.trace_data = NULL;
541 //JvSynchronized (ncodeMap);
542 UpdateNCodeMap ();
544 #ifdef SJLJ_EXCEPTIONS
545 // The Unwind interface doesn't work with the SJLJ exception model.
546 // Fall back to a platform-specific unwinder.
547 fallback_backtrace (&state);
548 #else /* SJLJ_EXCEPTIONS */
549 _Unwind_Backtrace (UnwindTraceFn, &state);
550 #endif /* SJLJ_EXCEPTIONS */
552 if (state.trace_data)
553 return (ClassLoader *) state.trace_data;
555 return NULL;