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.
124 if (func_addr == (_Unwind_Ptr) &_Jv_InterpMethod::run)
126 state->frames[pos].type = frame_interpreter;
127 state->frames[pos].interp.meth = state->interp_frame->self;
128 state->frames[pos].interp.pc = state->interp_frame->pc;
129 state->interp_frame = state->interp_frame->next;
134 state->frames[pos].type = frame_native;
135 state->frames[pos].ip = (void *) _Unwind_GetIP (context);
136 state->frames[pos].start_ip = (void *) func_addr;
139 //printf ("unwind ip: %p\n", _Unwind_GetIP (context));
141 _Unwind_Reason_Code result = _URC_NO_REASON;
142 if (state->trace_function != NULL)
143 result = (state->trace_function) (state);
148 // Return a raw stack trace from the current point of execution. The raw
149 // trace will include all functions that have unwind info.
151 _Jv_StackTrace::GetStackTrace(void)
153 int trace_size = 100;
154 _Jv_StackFrame frames[trace_size];
155 _Jv_UnwindState state (trace_size);
156 state.frames = (_Jv_StackFrame *) &frames;
158 #ifdef SJLJ_EXCEPTIONS
159 // The Unwind interface doesn't work with the SJLJ exception model.
160 // Fall back to a platform-specific unwinder.
161 fallback_backtrace (&state);
162 #else /* SJLJ_EXCEPTIONS */
163 _Unwind_Backtrace (UnwindTraceFn, &state);
164 #endif /* SJLJ_EXCEPTIONS */
166 // Copy the trace and return it.
167 int traceSize = sizeof (_Jv_StackTrace) +
168 (sizeof (_Jv_StackFrame) * state.pos);
169 _Jv_StackTrace *trace = (_Jv_StackTrace *) _Jv_AllocBytes (traceSize);
170 trace->length = state.pos;
171 memcpy (trace->frames, state.frames, sizeof (_Jv_StackFrame) * state.pos);
176 _Jv_StackTrace::getLineNumberForFrame(_Jv_StackFrame *frame, NameFinder *finder,
177 jstring *sourceFileName, jint *lineNum)
180 if (frame->type == frame_interpreter)
182 _Jv_InterpMethod *interp_meth = frame->interp.meth;
183 _Jv_InterpClass *interp_class =
184 (_Jv_InterpClass *) interp_meth->defining_class->aux_info;
185 *sourceFileName = interp_class->source_file_name;
186 *lineNum = interp_meth->get_source_line(frame->interp.pc);
190 // Use dladdr() to determine in which binary the address IP resides.
191 #if defined (HAVE_DLFCN_H) && defined (HAVE_DLADDR)
192 extern char **_Jv_argv;
194 jstring binaryName = NULL;
196 void *ip = frame->ip;
197 _Unwind_Ptr offset = 0;
199 if (dladdr (ip, &info))
202 binaryName = JvNewStringUTF (info.dli_fname);
206 // addr2line expects relative addresses for shared libraries.
207 if (strcmp (info.dli_fname, _Jv_argv[0]) == 0)
208 offset = (_Unwind_Ptr) ip;
210 offset = (_Unwind_Ptr) ip - (_Unwind_Ptr) info.dli_fbase;
212 //printf ("linenum ip: %p\n", ip);
213 //printf ("%s: 0x%x\n", info.dli_fname, offset);
214 //offset -= sizeof(void *);
216 // The unwinder gives us the return address. In order to get the right
217 // line number for the stack trace, roll it back a little.
220 // printf ("%s: 0x%x\n", info.dli_fname, offset);
222 finder->lookup (binaryName, (jlong) offset);
223 *sourceFileName = finder->getSourceFile();
224 *lineNum = finder->getLineNum();
229 // Look up class and method info for the given stack frame, setting
230 // frame->klass and frame->meth if they are known.
232 _Jv_StackTrace::FillInFrameInfo (_Jv_StackFrame *frame)
235 _Jv_Method *meth = NULL;
237 if (frame->type == frame_native)
239 klass = _Jv_StackTrace::ClassForFrame (frame);
242 // Find method in class
243 for (int j = 0; j < klass->method_count; j++)
245 if (klass->methods[j].ncode == frame->start_ip)
247 meth = &klass->methods[j];
253 else if (frame->type == frame_interpreter)
255 _Jv_InterpMethod *interp_meth = frame->interp.meth;
256 klass = interp_meth->defining_class;
257 meth = interp_meth->self;
261 JvFail ("Unknown frame type");
263 frame->klass = klass;
267 // Convert raw stack frames to a Java array of StackTraceElement objects.
268 JArray< ::java::lang::StackTraceElement *>*
269 _Jv_StackTrace::GetStackTraceElements (_Jv_StackTrace *trace,
270 Throwable *throwable __attribute__((unused)))
272 ArrayList *list = new ArrayList ();
274 #ifdef SJLJ_EXCEPTIONS
275 // We can't use the nCodeMap without unwinder support. Instead,
276 // fake the method name by giving the IP in hex - better than nothing.
277 jstring hex = JvNewStringUTF ("0x");
279 for (int i = 0; i < trace->length; i++)
281 jstring sourceFileName = NULL;
283 _Jv_StackFrame *frame = &trace->frames[i];
285 jstring className = NULL;
286 jstring methodName = hex->concat (Long::toHexString ((jlong) frame->ip));
288 StackTraceElement *element = new StackTraceElement (sourceFileName,
289 lineNum, className, methodName, 0);
293 #else /* SJLJ_EXCEPTIONS */
295 //JvSynchronized (ncodeMap);
298 NameFinder *finder = new NameFinder();
300 int end_idx = trace->length - 1;
302 // First pass: strip superfluous frames from beginning and end of the trace.
303 for (int i = 0; i < trace->length; i++)
305 _Jv_StackFrame *frame = &trace->frames[i];
306 FillInFrameInfo (frame);
308 if (!frame->klass || !frame->meth)
312 // Throw away the top of the stack till we see:
313 // - the constructor(s) of this Throwable, or
314 // - the Throwable.fillInStackTrace call.
315 if (frame->klass == throwable->getClass()
316 && strcmp (frame->meth->name->chars(), "<init>") == 0)
319 if (frame->klass == &Throwable::class$
320 && strcmp (frame->meth->name->chars(), "fillInStackTrace") == 0)
323 // End the trace at the application's main() method if we see call_main.
324 if (frame->klass == &gnu::java::lang::MainThread::class$
325 && strcmp (frame->meth->name->chars(), "call_main") == 0)
329 // Second pass: Look up line-number info for remaining frames.
330 for (int i = start_idx; i <= end_idx; i++)
332 _Jv_StackFrame *frame = &trace->frames[i];
334 if (frame->klass == NULL)
338 jstring className = frame->klass->getName ();
339 jstring methodName = NULL;
341 methodName = JvNewStringUTF (frame->meth->name->chars());
343 jstring sourceFileName = NULL;
346 getLineNumberForFrame(frame, finder, &sourceFileName, &lineNum);
348 StackTraceElement *element = new StackTraceElement (sourceFileName, lineNum,
349 className, methodName, 0);
354 #endif /* SJLJ_EXCEPTIONS */
356 JArray<Object *> *array = JvNewObjectArray (list->size (),
357 &StackTraceElement::class$, NULL);
359 return (JArray<StackTraceElement *>*) list->toArray (array);
362 struct CallingClassTraceData
366 _Jv_Method *foundMeth;
367 bool seen_checkClass;
371 _Jv_StackTrace::calling_class_trace_fn (_Jv_UnwindState *state)
373 CallingClassTraceData *trace_data = (CallingClassTraceData *)
375 _Jv_StackFrame *frame = &state->frames[state->pos];
376 FillInFrameInfo (frame);
378 if (trace_data->seen_checkClass
380 && frame->klass != trace_data->checkClass)
382 trace_data->foundClass = frame->klass;
383 trace_data->foundMeth = frame->meth;
384 return _URC_NORMAL_STOP;
387 if (frame->klass == trace_data->checkClass)
388 trace_data->seen_checkClass = true;
390 return _URC_NO_REASON;
393 // Find the class immediately above the given class on the call stack. Any
394 // intermediate non-Java
395 // frames are ignored. If the calling class could not be determined (eg because
396 // the unwinder is not supported on this platform), NULL is returned.
397 // This function is used to implement calling-classloader checks and reflection
398 // accessibility checks.
399 // CHECKCLASS is typically the class calling GetCallingClass. The first class
400 // above CHECKCLASS on the call stack will be returned.
402 _Jv_StackTrace::GetCallingClass (jclass checkClass)
404 jclass result = NULL;
405 GetCallerInfo (checkClass, &result, NULL);
410 _Jv_StackTrace::GetCallerInfo (jclass checkClass, jclass *caller_class,
411 _Jv_Method **caller_meth)
413 #ifndef SJLJ_EXCEPTIONS
415 _Jv_StackFrame frames[trace_size];
416 _Jv_UnwindState state (trace_size);
417 state.frames = (_Jv_StackFrame *) &frames;
419 CallingClassTraceData trace_data;
420 trace_data.checkClass = checkClass;
421 trace_data.seen_checkClass = false;
422 trace_data.foundClass = NULL;
423 trace_data.foundMeth = NULL;
425 state.trace_function = calling_class_trace_fn;
426 state.trace_data = (void *) &trace_data;
428 //JvSynchronized (ncodeMap);
431 _Unwind_Backtrace (UnwindTraceFn, &state);
434 *caller_class = trace_data.foundClass;
436 *caller_meth = trace_data.foundMeth;
442 // Return a java array containing the Java classes on the stack above CHECKCLASS.
444 _Jv_StackTrace::GetClassContext (jclass checkClass)
446 JArray<jclass> *result = NULL;
448 int trace_size = 100;
449 _Jv_StackFrame frames[trace_size];
450 _Jv_UnwindState state (trace_size);
451 state.frames = (_Jv_StackFrame *) &frames;
453 //JvSynchronized (ncodeMap);
456 _Unwind_Backtrace (UnwindTraceFn, &state);
458 // Count the number of Java frames on the stack.
459 int jframe_count = 0;
460 bool seen_checkClass = false;
462 for (int i = 0; i < state.pos; i++)
464 _Jv_StackFrame *frame = &state.frames[i];
465 FillInFrameInfo (frame);
477 seen_checkClass = frame->klass == checkClass;
479 result = (JArray<jclass> *) _Jv_NewObjectArray (jframe_count, &Class::class$, NULL);
482 for (int i = start_pos; i < state.pos; i++)
484 _Jv_StackFrame *frame = &state.frames[i];
486 elements(result)[pos++] = frame->klass;
492 _Jv_StackTrace::non_system_trace_fn (_Jv_UnwindState *state)
494 _Jv_StackFrame *frame = &state->frames[state->pos];
495 FillInFrameInfo (frame);
497 ClassLoader *classLoader = NULL;
501 classLoader = frame->klass->getClassLoaderInternal();
503 if (classLoader != NULL && classLoader != ClassLoader::systemClassLoader)
505 state->trace_data = (void *) classLoader;
506 return _URC_NORMAL_STOP;
511 return _URC_NO_REASON;
515 _Jv_StackTrace::GetFirstNonSystemClassLoader ()
518 _Jv_StackFrame frames[trace_size];
519 _Jv_UnwindState state (trace_size);
520 state.frames = (_Jv_StackFrame *) &frames;
521 state.trace_function = non_system_trace_fn;
522 state.trace_data = NULL;
524 //JvSynchronized (ncodeMap);
527 _Unwind_Backtrace (UnwindTraceFn, &state);
529 if (state.trace_data)
530 return (ClassLoader *) state.trace_data;