1 // stacktrace.cc - Functions for unwinding & inspecting the call stack.
3 /* Copyright (C) 2005 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
15 #include <java-interp.h>
16 #include <java-stack.h>
24 #include <java/lang/Class.h>
25 #include <java/lang/Long.h>
26 #include <java/util/ArrayList.h>
27 #include <java/util/IdentityHashMap.h>
28 #include <gnu/java/lang/MainThread.h>
29 #include <gnu/gcj/runtime/NameFinder.h>
31 #include <sysdep/backtrace.h>
33 using namespace java::lang;
34 using namespace java::lang::reflect;
35 using namespace java::util;
36 using namespace gnu::gcj::runtime;
38 struct _Jv_FindCallingClassState: _Jv_UnwindState
43 // Maps ncode values to their containing native class.
44 // NOTE: Currently this Map contradicts class GC for native classes. This map
45 // (and the "new class stack") will need to use WeakReferences in order to
46 // enable native class GC.
47 static java::util::IdentityHashMap *ncodeMap;
49 // Check the "class stack" for any classes initialized since we were last
50 // called, and add them to ncodeMap.
52 _Jv_StackTrace::UpdateNCodeMap ()
54 // The Map should be large enough so that a typical Java app doesn't cause
55 // it to rehash, without using too much memory. ~5000 entries should be
58 ncodeMap = new java::util::IdentityHashMap (5087);
61 while ((klass = _Jv_PopClass ()))
63 //printf ("got %s\n", klass->name->data);
65 JvAssert (! _Jv_IsInterpretedClass (klass));
67 for (int i=0; i < klass->method_count; i++)
69 _Jv_Method *method = &klass->methods[i];
70 // Add non-abstract methods to ncodeMap.
73 //printf("map->put 0x%x / %s.%s\n", method->ncode, klass->name->data,
74 // method->name->data);
75 ncodeMap->put ((java::lang::Object *) method->ncode, klass);
81 // Given a native frame, return the class which this code belongs
82 // to. Returns NULL if this IP is not associated with a native Java class.
83 // If NCODE is supplied, it will be set with the ip for the entry point of the
86 _Jv_StackTrace::ClassForFrame (_Jv_StackFrame *frame)
88 JvAssert (frame->type == frame_native);
90 // use _Unwind_FindEnclosingFunction to find start of method
91 //void *entryPoint = _Unwind_FindEnclosingFunction (ip);
93 // look it up in ncodeMap
95 klass = (jclass) ncodeMap->get ((jobject) frame->start_ip);
101 _Jv_StackTrace::UnwindTraceFn (struct _Unwind_Context *context, void *state_ptr)
103 _Jv_UnwindState *state = (_Jv_UnwindState *) state_ptr;
104 jint pos = state->pos;
106 // Check if the trace buffer needs to be extended.
107 if (pos == state->length)
109 int newLength = state->length *= 2;
110 void *newFrames = _Jv_AllocBytes (newLength * sizeof(_Jv_StackFrame));
111 memcpy (newFrames, state->frames, state->length * sizeof(_Jv_StackFrame));
112 state->frames = (_Jv_StackFrame *) newFrames;
113 state->length = newLength;
116 _Unwind_Ptr func_addr = _Unwind_GetRegionStart (context);
118 // If we see the interpreter's main function, "pop" an entry off the
119 // interpreter stack and use that instead, so that the trace goes through
120 // the java code and not the interpreter itself. This assumes a 1:1
121 // correspondance between call frames in the interpreted stack and occurances
122 // of _Jv_InterpMethod::run() on the native stack.
123 if (func_addr == (_Unwind_Ptr) &_Jv_InterpMethod::run)
125 state->frames[pos].type = frame_interpreter;
126 state->frames[pos].interp.meth = state->interp_frame->self;
127 state->frames[pos].interp.pc = state->interp_frame->pc;
128 state->interp_frame = state->interp_frame->next;
132 state->frames[pos].type = frame_native;
133 state->frames[pos].ip = (void *) _Unwind_GetIP (context);
134 state->frames[pos].start_ip = (void *) func_addr;
137 //printf ("unwind ip: %p\n", _Unwind_GetIP (context));
139 _Unwind_Reason_Code result = _URC_NO_REASON;
140 if (state->trace_function != NULL)
141 result = (state->trace_function) (state);
146 // Return a raw stack trace from the current point of execution. The raw
147 // trace will include all functions that have unwind info.
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);
174 _Jv_StackTrace::getLineNumberForFrame(_Jv_StackFrame *frame, NameFinder *finder,
175 jstring *sourceFileName, jint *lineNum)
177 if (frame->type == frame_interpreter)
179 _Jv_InterpMethod *interp_meth = frame->interp.meth;
180 _Jv_InterpClass *interp_class =
181 (_Jv_InterpClass *) interp_meth->defining_class->aux_info;
182 *sourceFileName = interp_class->source_file_name;
183 *lineNum = interp_meth->get_source_line(frame->interp.pc);
186 // Use dladdr() to determine in which binary the address IP resides.
187 #if defined (HAVE_DLFCN_H) && defined (HAVE_DLADDR)
188 extern char **_Jv_argv;
190 jstring binaryName = NULL;
192 void *ip = frame->ip;
193 _Unwind_Ptr offset = 0;
195 if (dladdr (ip, &info))
198 binaryName = JvNewStringUTF (info.dli_fname);
202 // addr2line expects relative addresses for shared libraries.
203 if (strcmp (info.dli_fname, _Jv_argv[0]) == 0)
204 offset = (_Unwind_Ptr) ip;
206 offset = (_Unwind_Ptr) ip - (_Unwind_Ptr) info.dli_fbase;
208 //printf ("linenum ip: %p\n", ip);
209 //printf ("%s: 0x%x\n", info.dli_fname, offset);
210 //offset -= sizeof(void *);
212 // The unwinder gives us the return address. In order to get the right
213 // line number for the stack trace, roll it back a little.
216 // printf ("%s: 0x%x\n", info.dli_fname, offset);
218 finder->lookup (binaryName, (jlong) offset);
219 *sourceFileName = finder->getSourceFile();
220 *lineNum = finder->getLineNum();
225 // Look up class and method info for the given stack frame, setting
226 // frame->klass and frame->meth if they are known.
228 _Jv_StackTrace::FillInFrameInfo (_Jv_StackFrame *frame)
231 _Jv_Method *meth = NULL;
233 if (frame->type == frame_native)
235 klass = _Jv_StackTrace::ClassForFrame (frame);
238 // Find method in class
239 for (int j = 0; j < klass->method_count; j++)
241 if (klass->methods[j].ncode == frame->start_ip)
243 meth = &klass->methods[j];
248 else if (frame->type == frame_interpreter)
250 _Jv_InterpMethod *interp_meth = frame->interp.meth;
251 klass = interp_meth->defining_class;
252 meth = interp_meth->self;
255 JvFail ("Unknown frame type");
257 frame->klass = klass;
261 // Convert raw stack frames to a Java array of StackTraceElement objects.
262 JArray< ::java::lang::StackTraceElement *>*
263 _Jv_StackTrace::GetStackTraceElements (_Jv_StackTrace *trace,
264 Throwable *throwable __attribute__((unused)))
266 ArrayList *list = new ArrayList ();
268 #ifdef SJLJ_EXCEPTIONS
269 // We can't use the nCodeMap without unwinder support. Instead,
270 // fake the method name by giving the IP in hex - better than nothing.
271 jstring hex = JvNewStringUTF ("0x");
273 for (int i = 0; i < trace->length; i++)
275 jstring sourceFileName = NULL;
277 _Jv_StackFrame *frame = &trace->frames[i];
279 jstring className = NULL;
280 jstring methodName = hex->concat (Long::toHexString ((jlong) frame->ip));
282 StackTraceElement *element = new StackTraceElement (sourceFileName,
283 lineNum, className, methodName, 0);
287 #else /* SJLJ_EXCEPTIONS */
289 //JvSynchronized (ncodeMap);
292 NameFinder *finder = new NameFinder();
294 int end_idx = trace->length - 1;
296 // First pass: strip superfluous frames from beginning and end of the trace.
297 for (int i = 0; i < trace->length; i++)
299 _Jv_StackFrame *frame = &trace->frames[i];
300 FillInFrameInfo (frame);
302 if (!frame->klass || !frame->meth)
306 // Throw away the top of the stack till we see:
307 // - the constructor(s) of this Throwable, or
308 // - the Throwable.fillInStackTrace call.
309 if (frame->klass == throwable->getClass()
310 && strcmp (frame->meth->name->chars(), "<init>") == 0)
313 if (frame->klass == &Throwable::class$
314 && strcmp (frame->meth->name->chars(), "fillInStackTrace") == 0)
317 // End the trace at the application's main() method if we see call_main.
318 if (frame->klass == &gnu::java::lang::MainThread::class$
319 && strcmp (frame->meth->name->chars(), "call_main") == 0)
323 // Second pass: Look up line-number info for remaining frames.
324 for (int i = start_idx; i <= end_idx; i++)
326 _Jv_StackFrame *frame = &trace->frames[i];
328 if (frame->klass == NULL)
332 jstring className = frame->klass->getName ();
333 jstring methodName = NULL;
335 methodName = JvNewStringUTF (frame->meth->name->chars());
337 jstring sourceFileName = NULL;
340 getLineNumberForFrame(frame, finder, &sourceFileName, &lineNum);
342 StackTraceElement *element = new StackTraceElement (sourceFileName, lineNum,
343 className, methodName, 0);
348 #endif /* SJLJ_EXCEPTIONS */
350 JArray<Object *> *array = JvNewObjectArray (list->size (),
351 &StackTraceElement::class$, NULL);
353 return (JArray<StackTraceElement *>*) list->toArray (array);
356 struct CallingClassTraceData
360 _Jv_Method *foundMeth;
361 bool seen_checkClass;
365 _Jv_StackTrace::calling_class_trace_fn (_Jv_UnwindState *state)
367 CallingClassTraceData *trace_data = (CallingClassTraceData *)
369 _Jv_StackFrame *frame = &state->frames[state->pos];
370 FillInFrameInfo (frame);
372 if (trace_data->seen_checkClass
374 && frame->klass != trace_data->checkClass)
376 trace_data->foundClass = frame->klass;
377 trace_data->foundMeth = frame->meth;
378 return _URC_NORMAL_STOP;
381 if (frame->klass == trace_data->checkClass)
382 trace_data->seen_checkClass = true;
384 return _URC_NO_REASON;
387 // Find the class immediately above the given class on the call stack. Any
388 // intermediate non-Java
389 // frames are ignored. If the calling class could not be determined (eg because
390 // the unwinder is not supported on this platform), NULL is returned.
391 // This function is used to implement calling-classloader checks and reflection
392 // accessibility checks.
393 // CHECKCLASS is typically the class calling GetCallingClass. The first class
394 // above CHECKCLASS on the call stack will be returned.
396 _Jv_StackTrace::GetCallingClass (jclass checkClass)
398 jclass result = NULL;
399 GetCallerInfo (checkClass, &result, NULL);
404 _Jv_StackTrace::GetCallerInfo (jclass checkClass, jclass *caller_class,
405 _Jv_Method **caller_meth)
407 #ifndef SJLJ_EXCEPTIONS
409 _Jv_StackFrame frames[trace_size];
410 _Jv_UnwindState state (trace_size);
411 state.frames = (_Jv_StackFrame *) &frames;
413 CallingClassTraceData trace_data;
414 trace_data.checkClass = checkClass;
415 trace_data.seen_checkClass = false;
416 trace_data.foundClass = NULL;
417 trace_data.foundMeth = NULL;
419 state.trace_function = calling_class_trace_fn;
420 state.trace_data = (void *) &trace_data;
422 //JvSynchronized (ncodeMap);
425 _Unwind_Backtrace (UnwindTraceFn, &state);
428 *caller_class = trace_data.foundClass;
430 *caller_meth = trace_data.foundMeth;
436 // Return a java array containing the Java classes on the stack above CHECKCLASS.
438 _Jv_StackTrace::GetClassContext (jclass checkClass)
440 JArray<jclass> *result = NULL;
442 int trace_size = 100;
443 _Jv_StackFrame frames[trace_size];
444 _Jv_UnwindState state (trace_size);
445 state.frames = (_Jv_StackFrame *) &frames;
447 //JvSynchronized (ncodeMap);
450 _Unwind_Backtrace (UnwindTraceFn, &state);
452 // Count the number of Java frames on the stack.
453 int jframe_count = 0;
454 bool seen_checkClass = false;
456 for (int i = 0; i < state.pos; i++)
458 _Jv_StackFrame *frame = &state.frames[i];
459 FillInFrameInfo (frame);
463 && frame->klass != checkClass)
472 && frame->klass == checkClass)
473 seen_checkClass = true;
475 result = (JArray<jclass> *) _Jv_NewObjectArray (jframe_count, &Class::class$, NULL);
478 for (int i = start_pos; i < state.pos; i++)
480 _Jv_StackFrame *frame = &state.frames[i];
482 elements(result)[pos++] = frame->klass;
488 _Jv_StackTrace::non_system_trace_fn (_Jv_UnwindState *state)
490 _Jv_StackFrame *frame = &state->frames[state->pos];
491 FillInFrameInfo (frame);
493 ClassLoader *classLoader = NULL;
497 classLoader = frame->klass->getClassLoaderInternal();
498 if (classLoader != NULL && classLoader != ClassLoader::systemClassLoader)
500 state->trace_data = (void *) classLoader;
501 return _URC_NORMAL_STOP;
505 return _URC_NO_REASON;
509 _Jv_StackTrace::GetFirstNonSystemClassLoader ()
512 _Jv_StackFrame frames[trace_size];
513 _Jv_UnwindState state (trace_size);
514 state.frames = (_Jv_StackFrame *) &frames;
515 state.trace_function = non_system_trace_fn;
516 state.trace_data = NULL;
518 //JvSynchronized (ncodeMap);
521 _Unwind_Backtrace (UnwindTraceFn, &state);
523 if (state.trace_data)
524 return (ClassLoader *) state.trace_data;