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
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>
30 #include <gnu/gcj/runtime/StringBuffer.h>
32 #include <sysdep/backtrace.h>
33 #include <sysdep/descriptor.h>
35 using namespace java::lang
;
36 using namespace java::lang::reflect
;
37 using namespace java::util
;
38 using namespace gnu::gcj::runtime
;
40 // Maps ncode values to their containing native class.
41 // NOTE: Currently this Map contradicts class GC for native classes. This map
42 // (and the "new class stack") will need to use WeakReferences in order to
43 // enable native class GC.
44 static java::util::IdentityHashMap
*ncodeMap
;
46 // Check the "class stack" for any classes initialized since we were last
47 // called, and add them to ncodeMap.
49 _Jv_StackTrace::UpdateNCodeMap ()
51 // The Map should be large enough so that a typical Java app doesn't cause
52 // it to rehash, without using too much memory. ~5000 entries should be
55 ncodeMap
= new java::util::IdentityHashMap (5087);
58 while ((klass
= _Jv_PopClass ()))
59 if (!_Jv_IsInterpretedClass (klass
))
61 //printf ("got %s\n", klass->name->data);
62 for (int i
= 0; i
< klass
->method_count
; i
++)
64 _Jv_Method
*method
= &klass
->methods
[i
];
65 void *ncode
= method
->ncode
;
66 // Add non-abstract methods to ncodeMap.
69 ncode
= UNWRAP_FUNCTION_DESCRIPTOR (ncode
);
70 ncodeMap
->put ((java::lang::Object
*) ncode
, klass
);
76 // Given a native frame, return the class which this code belongs
77 // to. Returns NULL if this IP is not associated with a native Java class.
78 // If NCODE is supplied, it will be set with the ip for the entry point of the
81 _Jv_StackTrace::ClassForFrame (_Jv_StackFrame
*frame
)
83 JvAssert (frame
->type
== frame_native
);
85 // use _Unwind_FindEnclosingFunction to find start of method
86 //void *entryPoint = _Unwind_FindEnclosingFunction (ip);
88 // look it up in ncodeMap
90 klass
= (jclass
) ncodeMap
->get ((jobject
) frame
->start_ip
);
96 _Jv_StackTrace::UnwindTraceFn (struct _Unwind_Context
*context
, void *state_ptr
)
98 _Jv_UnwindState
*state
= (_Jv_UnwindState
*) state_ptr
;
99 jint pos
= state
->pos
;
101 // Check if the trace buffer needs to be extended.
102 if (pos
== state
->length
)
104 int newLength
= state
->length
* 2;
105 void *newFrames
= _Jv_AllocBytes (newLength
* sizeof(_Jv_StackFrame
));
106 memcpy (newFrames
, state
->frames
, state
->length
* sizeof(_Jv_StackFrame
));
107 state
->frames
= (_Jv_StackFrame
*) newFrames
;
108 state
->length
= newLength
;
111 void *func_addr
= (void *) _Unwind_GetRegionStart (context
);
113 // If we see the interpreter's main function, "pop" an entry off the
114 // interpreter stack and use that instead, so that the trace goes through
115 // the java code and not the interpreter itself. This assumes a 1:1
116 // correspondance between call frames in the interpreted stack and occurances
117 // of _Jv_InterpMethod::run() on the native stack.
119 void *interp_run
= (void *) &_Jv_InterpMethod::run
;
120 if (func_addr
== UNWRAP_FUNCTION_DESCRIPTOR (interp_run
))
122 state
->frames
[pos
].type
= frame_interpreter
;
123 state
->frames
[pos
].interp
.meth
= state
->interp_frame
->self
;
124 state
->frames
[pos
].interp
.pc
= state
->interp_frame
->pc
;
125 state
->interp_frame
= state
->interp_frame
->next
;
130 state
->frames
[pos
].type
= frame_native
;
131 state
->frames
[pos
].ip
= (void *) _Unwind_GetIP (context
);
132 state
->frames
[pos
].start_ip
= func_addr
;
135 //printf ("unwind ip: %p\n", _Unwind_GetIP (context));
137 _Unwind_Reason_Code result
= _URC_NO_REASON
;
138 if (state
->trace_function
!= NULL
)
139 result
= (state
->trace_function
) (state
);
144 // Return a raw stack trace from the current point of execution. The raw
145 // trace will include all functions that have unwind info.
147 _Jv_StackTrace::GetStackTrace(void)
149 int trace_size
= 100;
150 _Jv_StackFrame frames
[trace_size
];
151 _Jv_UnwindState
state (trace_size
);
152 state
.frames
= (_Jv_StackFrame
*) &frames
;
154 #ifdef SJLJ_EXCEPTIONS
155 // The Unwind interface doesn't work with the SJLJ exception model.
156 // Fall back to a platform-specific unwinder.
157 fallback_backtrace (&state
);
158 #else /* SJLJ_EXCEPTIONS */
159 _Unwind_Backtrace (UnwindTraceFn
, &state
);
160 #endif /* SJLJ_EXCEPTIONS */
162 // Copy the trace and return it.
163 int traceSize
= sizeof (_Jv_StackTrace
) +
164 (sizeof (_Jv_StackFrame
) * state
.pos
);
165 _Jv_StackTrace
*trace
= (_Jv_StackTrace
*) _Jv_AllocBytes (traceSize
);
166 trace
->length
= state
.pos
;
167 memcpy (trace
->frames
, state
.frames
, sizeof (_Jv_StackFrame
) * state
.pos
);
172 _Jv_StackTrace::getLineNumberForFrame(_Jv_StackFrame
*frame
, NameFinder
*finder
,
173 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
);
187 // Use dladdr() to determine in which binary the address IP resides.
188 #if defined (HAVE_DLFCN_H) && defined (HAVE_DLADDR)
190 jstring binaryName
= NULL
;
191 const char *argv0
= _Jv_GetSafeArg(0);
193 void *ip
= frame
->ip
;
194 _Unwind_Ptr offset
= 0;
196 if (dladdr (ip
, &info
))
199 binaryName
= JvNewStringUTF (info
.dli_fname
);
203 if (*methodName
== NULL
&& info
.dli_sname
)
204 *methodName
= JvNewStringUTF (info
.dli_sname
);
206 // addr2line expects relative addresses for shared libraries.
207 if (strcmp (info
.dli_fname
, argv0
) == 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();
225 if (*lineNum
== -1 && NameFinder::showRaw())
227 gnu::gcj::runtime::StringBuffer
*t
=
228 new gnu::gcj::runtime::StringBuffer(binaryName
);
229 t
->append ((jchar
)' ');
230 t
->append ((jchar
)'[');
231 // + 1 to compensate for the - 1 adjustment above;
232 t
->append (Long::toHexString (offset
+ 1));
233 t
->append ((jchar
)']');
234 *sourceFileName
= t
->toString();
240 // Look up class and method info for the given stack frame, setting
241 // frame->klass and frame->meth if they are known.
243 _Jv_StackTrace::FillInFrameInfo (_Jv_StackFrame
*frame
)
246 _Jv_Method
*meth
= NULL
;
248 if (frame
->type
== frame_native
)
250 klass
= _Jv_StackTrace::ClassForFrame (frame
);
253 // Find method in class
254 for (int j
= 0; j
< klass
->method_count
; j
++)
256 void *wncode
= UNWRAP_FUNCTION_DESCRIPTOR (klass
->methods
[j
].ncode
);
257 if (wncode
== frame
->start_ip
)
259 meth
= &klass
->methods
[j
];
265 else if (frame
->type
== frame_interpreter
)
267 _Jv_InterpMethod
*interp_meth
= frame
->interp
.meth
;
268 klass
= interp_meth
->defining_class
;
269 meth
= interp_meth
->self
;
273 JvFail ("Unknown frame type");
275 frame
->klass
= klass
;
279 // Convert raw stack frames to a Java array of StackTraceElement objects.
280 JArray
< ::java::lang::StackTraceElement
*>*
281 _Jv_StackTrace::GetStackTraceElements (_Jv_StackTrace
*trace
,
282 Throwable
*throwable
__attribute__((unused
)))
284 ArrayList
*list
= new ArrayList ();
286 #ifdef SJLJ_EXCEPTIONS
287 // We can't use the nCodeMap without unwinder support. Instead,
288 // fake the method name by giving the IP in hex - better than nothing.
289 jstring hex
= JvNewStringUTF ("0x");
291 for (int i
= 0; i
< trace
->length
; i
++)
293 jstring sourceFileName
= NULL
;
295 _Jv_StackFrame
*frame
= &trace
->frames
[i
];
297 jstring className
= NULL
;
298 jstring methodName
= hex
->concat (Long::toHexString ((jlong
) frame
->ip
));
300 StackTraceElement
*element
= new StackTraceElement (sourceFileName
,
301 lineNum
, className
, methodName
, 0);
305 #else /* SJLJ_EXCEPTIONS */
307 //JvSynchronized (ncodeMap);
310 NameFinder
*finder
= new NameFinder();
312 int end_idx
= trace
->length
- 1;
314 // First pass: strip superfluous frames from beginning and end of the trace.
315 for (int i
= 0; i
< trace
->length
; i
++)
317 _Jv_StackFrame
*frame
= &trace
->frames
[i
];
318 FillInFrameInfo (frame
);
320 if (!frame
->klass
|| !frame
->meth
)
324 // Throw away the top of the stack till we see:
325 // - the constructor(s) of this Throwable, or
326 // - the Throwable.fillInStackTrace call.
327 if (frame
->klass
== throwable
->getClass()
328 && strcmp (frame
->meth
->name
->chars(), "<init>") == 0)
331 if (frame
->klass
== &Throwable::class$
332 && strcmp (frame
->meth
->name
->chars(), "fillInStackTrace") == 0)
335 // End the trace at the application's main() method if we see call_main.
336 if (frame
->klass
== &gnu::java::lang::MainThread::class$
337 && strcmp (frame
->meth
->name
->chars(), "call_main") == 0)
341 const jboolean remove_unknown
342 = gnu::gcj::runtime::NameFinder::removeUnknown();
344 // Second pass: Look up line-number info for remaining frames.
345 for (int i
= start_idx
; i
<= end_idx
; i
++)
347 _Jv_StackFrame
*frame
= &trace
->frames
[i
];
349 if (frame
->klass
== NULL
&& remove_unknown
)
353 jstring className
= NULL
;
354 if (frame
->klass
!= NULL
)
355 className
= frame
->klass
->getName ();
357 jstring methodName
= NULL
;
359 methodName
= JvNewStringUTF (frame
->meth
->name
->chars());
361 jstring sourceFileName
= NULL
;
364 getLineNumberForFrame(frame
, finder
, &sourceFileName
, &lineNum
,
367 StackTraceElement
*element
= new StackTraceElement (sourceFileName
, lineNum
,
368 className
, methodName
, 0);
373 #endif /* SJLJ_EXCEPTIONS */
375 JArray
<Object
*> *array
= JvNewObjectArray (list
->size (),
376 &StackTraceElement::class$
, NULL
);
378 return (JArray
<StackTraceElement
*>*) list
->toArray (array
);
381 struct CallingClassTraceData
385 _Jv_Method
*foundMeth
;
386 bool seen_checkClass
;
390 _Jv_StackTrace::calling_class_trace_fn (_Jv_UnwindState
*state
)
392 CallingClassTraceData
*trace_data
= (CallingClassTraceData
*)
394 _Jv_StackFrame
*frame
= &state
->frames
[state
->pos
];
395 FillInFrameInfo (frame
);
397 if (trace_data
->seen_checkClass
399 && frame
->klass
!= trace_data
->checkClass
)
401 trace_data
->foundClass
= frame
->klass
;
402 trace_data
->foundMeth
= frame
->meth
;
403 return _URC_NORMAL_STOP
;
406 if (frame
->klass
== trace_data
->checkClass
)
407 trace_data
->seen_checkClass
= true;
409 return _URC_NO_REASON
;
412 // Find the class immediately above the given class on the call stack. Any
413 // intermediate non-Java
414 // frames are ignored. If the calling class could not be determined (eg because
415 // the unwinder is not supported on this platform), NULL is returned.
416 // This function is used to implement calling-classloader checks and reflection
417 // accessibility checks.
418 // CHECKCLASS is typically the class calling GetCallingClass. The first class
419 // above CHECKCLASS on the call stack will be returned.
421 _Jv_StackTrace::GetCallingClass (jclass checkClass
)
423 jclass result
= NULL
;
424 GetCallerInfo (checkClass
, &result
, NULL
);
429 _Jv_StackTrace::GetCallerInfo (jclass checkClass
, jclass
*caller_class
,
430 _Jv_Method
**caller_meth
)
432 #ifndef SJLJ_EXCEPTIONS
434 _Jv_StackFrame frames
[trace_size
];
435 _Jv_UnwindState
state (trace_size
);
436 state
.frames
= (_Jv_StackFrame
*) &frames
;
438 CallingClassTraceData trace_data
;
439 trace_data
.checkClass
= checkClass
;
440 trace_data
.seen_checkClass
= false;
441 trace_data
.foundClass
= NULL
;
442 trace_data
.foundMeth
= NULL
;
444 state
.trace_function
= calling_class_trace_fn
;
445 state
.trace_data
= (void *) &trace_data
;
447 //JvSynchronized (ncodeMap);
450 _Unwind_Backtrace (UnwindTraceFn
, &state
);
453 *caller_class
= trace_data
.foundClass
;
455 *caller_meth
= trace_data
.foundMeth
;
461 // Return a java array containing the Java classes on the stack above CHECKCLASS.
463 _Jv_StackTrace::GetClassContext (jclass checkClass
)
465 JArray
<jclass
> *result
= NULL
;
467 int trace_size
= 100;
468 _Jv_StackFrame frames
[trace_size
];
469 _Jv_UnwindState
state (trace_size
);
470 state
.frames
= (_Jv_StackFrame
*) &frames
;
472 //JvSynchronized (ncodeMap);
475 _Unwind_Backtrace (UnwindTraceFn
, &state
);
477 // Count the number of Java frames on the stack.
478 int jframe_count
= 0;
479 bool seen_checkClass
= false;
481 for (int i
= 0; i
< state
.pos
; i
++)
483 _Jv_StackFrame
*frame
= &state
.frames
[i
];
484 FillInFrameInfo (frame
);
496 seen_checkClass
= frame
->klass
== checkClass
;
498 result
= (JArray
<jclass
> *) _Jv_NewObjectArray (jframe_count
, &Class::class$
, NULL
);
501 for (int i
= start_pos
; i
< state
.pos
; i
++)
503 _Jv_StackFrame
*frame
= &state
.frames
[i
];
505 elements(result
)[pos
++] = frame
->klass
;
511 _Jv_StackTrace::non_system_trace_fn (_Jv_UnwindState
*state
)
513 _Jv_StackFrame
*frame
= &state
->frames
[state
->pos
];
514 FillInFrameInfo (frame
);
516 ClassLoader
*classLoader
= NULL
;
520 classLoader
= frame
->klass
->getClassLoaderInternal();
522 if (classLoader
!= NULL
)
524 state
->trace_data
= (void *) classLoader
;
525 return _URC_NORMAL_STOP
;
530 return _URC_NO_REASON
;
534 _Jv_StackTrace::GetFirstNonSystemClassLoader ()
537 _Jv_StackFrame frames
[trace_size
];
538 _Jv_UnwindState
state (trace_size
);
539 state
.frames
= (_Jv_StackFrame
*) &frames
;
540 state
.trace_function
= non_system_trace_fn
;
541 state
.trace_data
= NULL
;
543 //JvSynchronized (ncodeMap);
546 _Unwind_Backtrace (UnwindTraceFn
, &state
);
548 if (state
.trace_data
)
549 return (ClassLoader
*) state
.trace_data
;