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
16 #include <java-interp.h>
17 #include <java-stack.h>
21 #include <java/lang/Class.h>
22 #include <java/lang/Long.h>
23 #include <java/security/AccessController.h>
24 #include <java/util/ArrayList.h>
25 #include <java/util/IdentityHashMap.h>
26 #include <gnu/java/lang/MainThread.h>
27 #include <gnu/gcj/runtime/NameFinder.h>
28 #include <gnu/gcj/runtime/StringBuffer.h>
30 #include <sysdep/backtrace.h>
31 #include <sysdep/descriptor.h>
33 using namespace java::lang
;
34 using namespace java::lang::reflect
;
35 using namespace java::util
;
36 using namespace gnu::gcj::runtime
;
38 // Maps ncode values to their containing native class.
39 // NOTE: Currently this Map contradicts class GC for native classes. This map
40 // (and the "new class stack") will need to use WeakReferences in order to
41 // enable native class GC.
42 static java::util::IdentityHashMap
*ncodeMap
;
44 // Check the "class stack" for any classes initialized since we were last
45 // called, and add them to ncodeMap.
47 _Jv_StackTrace::UpdateNCodeMap ()
49 // The Map should be large enough so that a typical Java app doesn't cause
50 // it to rehash, without using too much memory. ~5000 entries should be
53 ncodeMap
= new java::util::IdentityHashMap (5087);
56 while ((klass
= _Jv_PopClass ()))
57 if (!_Jv_IsInterpretedClass (klass
))
59 //printf ("got %s\n", klass->name->data);
60 for (int i
= 0; i
< klass
->method_count
; i
++)
62 _Jv_Method
*method
= &klass
->methods
[i
];
63 void *ncode
= method
->ncode
;
64 // Add non-abstract methods to ncodeMap.
67 ncode
= UNWRAP_FUNCTION_DESCRIPTOR (ncode
);
68 ncodeMap
->put ((java::lang::Object
*) ncode
, klass
);
74 // Given a native frame, return the class which this code belongs
75 // to. Returns NULL if this IP is not associated with a native Java class.
76 // If NCODE is supplied, it will be set with the ip for the entry point of the
79 _Jv_StackTrace::ClassForFrame (_Jv_StackFrame
*frame
)
81 JvAssert (frame
->type
== frame_native
);
84 // look it up in ncodeMap
86 klass
= (jclass
) ncodeMap
->get ((jobject
) frame
->start_ip
);
92 _Jv_StackTrace::UnwindTraceFn (struct _Unwind_Context
*context
, void *state_ptr
)
94 _Jv_UnwindState
*state
= (_Jv_UnwindState
*) state_ptr
;
95 jint pos
= state
->pos
;
97 // Check if the trace buffer needs to be extended.
98 if (pos
== state
->length
)
100 int newLength
= state
->length
* 2;
101 void *newFrames
= _Jv_AllocBytes (newLength
* sizeof(_Jv_StackFrame
));
102 memcpy (newFrames
, state
->frames
, state
->length
* sizeof(_Jv_StackFrame
));
103 state
->frames
= (_Jv_StackFrame
*) newFrames
;
104 state
->length
= newLength
;
107 void *func_addr
= (void *) _Unwind_GetRegionStart (context
);
109 // If we see the interpreter's main function, "pop" an entry off the
110 // interpreter stack and use that instead, so that the trace goes through
111 // the java code and not the interpreter itself. This assumes a 1:1
112 // correspondance between call frames in the interpreted stack and occurances
113 // of _Jv_InterpMethod::run() on the native stack.
115 void *interp_run
= (void *) &_Jv_InterpMethod::run
;
116 if (func_addr
== UNWRAP_FUNCTION_DESCRIPTOR (interp_run
))
118 state
->frames
[pos
].type
= frame_interpreter
;
119 state
->frames
[pos
].interp
.meth
= state
->interp_frame
->self
;
120 state
->frames
[pos
].interp
.pc
= state
->interp_frame
->pc
;
121 state
->interp_frame
= state
->interp_frame
->next
;
127 int ip_before_insn
= 0;
128 ip
= _Unwind_GetIPInfo (context
, &ip_before_insn
);
130 // If the unwinder gave us a 'return' address, roll it back a little
131 // to ensure we get the correct line number for the call itself.
132 if (! ip_before_insn
)
135 state
->frames
[pos
].type
= frame_native
;
136 state
->frames
[pos
].ip
= (void *) ip
;
137 state
->frames
[pos
].start_ip
= func_addr
;
140 _Unwind_Reason_Code result
= _URC_NO_REASON
;
141 if (state
->trace_function
!= NULL
)
142 result
= (state
->trace_function
) (state
);
147 // Return a raw stack trace from the current point of execution. The raw
148 // trace will include all functions that have unwind info.
150 _Jv_StackTrace::GetStackTrace(void)
152 int trace_size
= 100;
153 _Jv_StackFrame frames
[trace_size
];
154 _Jv_UnwindState
state (trace_size
);
155 state
.frames
= (_Jv_StackFrame
*) &frames
;
157 _Unwind_Backtrace (UnwindTraceFn
, &state
);
159 // Copy the trace and return it.
160 int traceSize
= sizeof (_Jv_StackTrace
) +
161 (sizeof (_Jv_StackFrame
) * state
.pos
);
162 _Jv_StackTrace
*trace
= (_Jv_StackTrace
*) _Jv_AllocBytes (traceSize
);
163 trace
->length
= state
.pos
;
164 memcpy (trace
->frames
, state
.frames
, sizeof (_Jv_StackFrame
) * state
.pos
);
169 _Jv_StackTrace::getLineNumberForFrame(_Jv_StackFrame
*frame
, NameFinder
*finder
,
170 jstring
*sourceFileName
, jint
*lineNum
,
174 if (frame
->type
== frame_interpreter
)
176 _Jv_InterpMethod
*interp_meth
= frame
->interp
.meth
;
177 _Jv_InterpClass
*interp_class
=
178 (_Jv_InterpClass
*) interp_meth
->defining_class
->aux_info
;
179 *sourceFileName
= interp_class
->source_file_name
;
180 // The interpreter advances the PC before executing an instruction,
181 // so roll-back 1 byte to ensure the line number is accurate.
182 *lineNum
= interp_meth
->get_source_line(frame
->interp
.pc
- 1);
187 // Use _Jv_platform_dladdr() to determine in which binary the address IP
190 jstring binaryName
= NULL
;
191 const char *argv0
= _Jv_GetSafeArg(0);
193 void *ip
= frame
->ip
;
194 _Unwind_Ptr offset
= 0;
196 if (_Jv_platform_dladdr (ip
, &info
))
199 binaryName
= JvNewStringUTF (info
.file_name
);
203 if (*methodName
== NULL
&& info
.sym_name
)
204 *methodName
= JvNewStringUTF (info
.sym_name
);
206 // addr2line expects relative addresses for shared libraries.
207 if (strcmp (info
.file_name
, argv0
) == 0)
208 offset
= (_Unwind_Ptr
) ip
;
210 offset
= (_Unwind_Ptr
) ip
- (_Unwind_Ptr
) info
.base
;
212 finder
->lookup (binaryName
, (jlong
) offset
);
213 *sourceFileName
= finder
->getSourceFile();
214 *lineNum
= finder
->getLineNum();
215 if (*lineNum
== -1 && NameFinder::showRaw())
217 gnu::gcj::runtime::StringBuffer
*t
=
218 new gnu::gcj::runtime::StringBuffer(binaryName
);
219 t
->append ((jchar
)' ');
220 t
->append ((jchar
)'[');
221 // + 1 to compensate for the - 1 adjustment above;
222 t
->append (Long::toHexString (offset
+ 1));
223 t
->append ((jchar
)']');
224 *sourceFileName
= t
->toString();
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 void *wncode
= UNWRAP_FUNCTION_DESCRIPTOR (klass
->methods
[j
].ncode
);
246 if (wncode
== frame
->start_ip
)
248 meth
= &klass
->methods
[j
];
254 else if (frame
->type
== frame_interpreter
)
256 _Jv_InterpMethod
*interp_meth
= frame
->interp
.meth
;
257 klass
= interp_meth
->defining_class
;
258 meth
= interp_meth
->self
;
262 JvFail ("Unknown frame type");
264 frame
->klass
= klass
;
268 // Convert raw stack frames to a Java array of StackTraceElement objects.
269 JArray
< ::java::lang::StackTraceElement
*>*
270 _Jv_StackTrace::GetStackTraceElements (_Jv_StackTrace
*trace
,
271 Throwable
*throwable
__attribute__((unused
)))
273 ArrayList
*list
= new ArrayList ();
275 #if defined (SJLJ_EXCEPTIONS) && ! defined (WIN32)
276 // We can't use the nCodeMap without unwinder support. Instead,
277 // fake the method name by giving the IP in hex - better than nothing.
278 jstring hex
= JvNewStringUTF ("0x");
280 for (int i
= 0; i
< trace
->length
; i
++)
282 jstring sourceFileName
= NULL
;
284 _Jv_StackFrame
*frame
= &trace
->frames
[i
];
286 jstring className
= NULL
;
287 jstring methodName
= hex
->concat (Long::toHexString ((jlong
) frame
->ip
));
289 StackTraceElement
*element
= new StackTraceElement (sourceFileName
,
290 lineNum
, className
, methodName
, 0);
294 #else /* SJLJ_EXCEPTIONS && !WIN32 */
296 //JvSynchronized (ncodeMap);
299 NameFinder
*finder
= new NameFinder();
301 int end_idx
= trace
->length
- 1;
303 // First pass: strip superfluous frames from beginning and end of the trace.
304 for (int i
= 0; i
< trace
->length
; i
++)
306 _Jv_StackFrame
*frame
= &trace
->frames
[i
];
307 FillInFrameInfo (frame
);
309 if (!frame
->klass
|| !frame
->meth
)
313 // Throw away the top of the stack till we see:
314 // - the constructor(s) of this Throwable, or
315 // - the Throwable.fillInStackTrace call.
316 if (frame
->klass
== throwable
->getClass()
317 && strcmp (frame
->meth
->name
->chars(), "<init>") == 0)
320 if (frame
->klass
== &Throwable::class$
321 && strcmp (frame
->meth
->name
->chars(), "fillInStackTrace") == 0)
324 // End the trace at the application's main() method if we see call_main.
325 if (frame
->klass
== &gnu::java::lang::MainThread::class$
326 && strcmp (frame
->meth
->name
->chars(), "call_main") == 0)
330 const jboolean remove_unknown
331 = gnu::gcj::runtime::NameFinder::removeUnknown();
333 // Second pass: Look up line-number info for remaining frames.
334 for (int i
= start_idx
; i
<= end_idx
; i
++)
336 _Jv_StackFrame
*frame
= &trace
->frames
[i
];
338 if (frame
->klass
== NULL
&& remove_unknown
)
342 jstring className
= NULL
;
343 if (frame
->klass
!= NULL
)
344 className
= frame
->klass
->getName ();
346 jstring methodName
= NULL
;
348 methodName
= JvNewStringUTF (frame
->meth
->name
->chars());
350 jstring sourceFileName
= NULL
;
353 getLineNumberForFrame(frame
, finder
, &sourceFileName
, &lineNum
,
356 StackTraceElement
*element
= new StackTraceElement (sourceFileName
, lineNum
,
357 className
, methodName
, 0);
362 #endif /* SJLJ_EXCEPTIONS && !WIN32 */
364 JArray
<Object
*> *array
= JvNewObjectArray (list
->size (),
365 &StackTraceElement::class$
, NULL
);
367 return (JArray
<StackTraceElement
*>*) list
->toArray (array
);
370 struct CallingClassTraceData
374 _Jv_Method
*foundMeth
;
375 bool seen_checkClass
;
379 _Jv_StackTrace::calling_class_trace_fn (_Jv_UnwindState
*state
)
381 CallingClassTraceData
*trace_data
= (CallingClassTraceData
*)
383 _Jv_StackFrame
*frame
= &state
->frames
[state
->pos
];
384 FillInFrameInfo (frame
);
386 if (trace_data
->seen_checkClass
388 && frame
->klass
!= trace_data
->checkClass
)
390 trace_data
->foundClass
= frame
->klass
;
391 trace_data
->foundMeth
= frame
->meth
;
392 return _URC_NORMAL_STOP
;
395 if (frame
->klass
== trace_data
->checkClass
)
396 trace_data
->seen_checkClass
= true;
398 return _URC_NO_REASON
;
401 // Find the class immediately above the given class on the call stack. Any
402 // intermediate non-Java
403 // frames are ignored. If the calling class could not be determined (eg because
404 // the unwinder is not supported on this platform), NULL is returned.
405 // This function is used to implement calling-classloader checks and reflection
406 // accessibility checks.
407 // CHECKCLASS is typically the class calling GetCallingClass. The first class
408 // above CHECKCLASS on the call stack will be returned.
410 _Jv_StackTrace::GetCallingClass (jclass checkClass
)
412 jclass result
= NULL
;
413 GetCallerInfo (checkClass
, &result
, NULL
);
418 _Jv_StackTrace::GetCallerInfo (jclass checkClass
, jclass
*caller_class
,
419 _Jv_Method
**caller_meth
)
422 _Jv_StackFrame frames
[trace_size
];
423 _Jv_UnwindState
state (trace_size
);
424 state
.frames
= (_Jv_StackFrame
*) &frames
;
426 CallingClassTraceData trace_data
;
427 trace_data
.checkClass
= checkClass
;
428 trace_data
.seen_checkClass
= false;
429 trace_data
.foundClass
= NULL
;
430 trace_data
.foundMeth
= NULL
;
432 state
.trace_function
= calling_class_trace_fn
;
433 state
.trace_data
= (void *) &trace_data
;
435 //JvSynchronized (ncodeMap);
438 _Unwind_Backtrace (UnwindTraceFn
, &state
);
441 *caller_class
= trace_data
.foundClass
;
443 *caller_meth
= trace_data
.foundMeth
;
446 // Return a java array containing the Java classes on the stack above CHECKCLASS.
448 _Jv_StackTrace::GetClassContext (jclass checkClass
)
450 JArray
<jclass
> *result
= NULL
;
452 int trace_size
= 100;
453 _Jv_StackFrame frames
[trace_size
];
454 _Jv_UnwindState
state (trace_size
);
455 state
.frames
= (_Jv_StackFrame
*) &frames
;
457 //JvSynchronized (ncodeMap);
460 _Unwind_Backtrace (UnwindTraceFn
, &state
);
462 // Count the number of Java frames on the stack.
463 int jframe_count
= 0;
464 bool seen_checkClass
= false;
466 for (int i
= 0; i
< state
.pos
; i
++)
468 _Jv_StackFrame
*frame
= &state
.frames
[i
];
469 FillInFrameInfo (frame
);
481 seen_checkClass
= frame
->klass
== checkClass
;
483 result
= (JArray
<jclass
> *) _Jv_NewObjectArray (jframe_count
, &Class::class$
, NULL
);
486 for (int i
= start_pos
; i
< state
.pos
; i
++)
488 _Jv_StackFrame
*frame
= &state
.frames
[i
];
490 elements(result
)[pos
++] = frame
->klass
;
496 _Jv_StackTrace::non_system_trace_fn (_Jv_UnwindState
*state
)
498 _Jv_StackFrame
*frame
= &state
->frames
[state
->pos
];
499 FillInFrameInfo (frame
);
501 ClassLoader
*classLoader
= NULL
;
505 classLoader
= frame
->klass
->getClassLoaderInternal();
507 if (classLoader
!= NULL
)
509 state
->trace_data
= (void *) classLoader
;
510 return _URC_NORMAL_STOP
;
515 return _URC_NO_REASON
;
519 _Jv_StackTrace::GetFirstNonSystemClassLoader ()
522 _Jv_StackFrame frames
[trace_size
];
523 _Jv_UnwindState
state (trace_size
);
524 state
.frames
= (_Jv_StackFrame
*) &frames
;
525 state
.trace_function
= non_system_trace_fn
;
526 state
.trace_data
= NULL
;
528 //JvSynchronized (ncodeMap);
531 _Unwind_Backtrace (UnwindTraceFn
, &state
);
533 if (state
.trace_data
)
534 return (ClassLoader
*) state
.trace_data
;
540 _Jv_StackTrace::accesscontrol_trace_fn (_Jv_UnwindState
*state
)
542 _Jv_StackFrame
*frame
= &state
->frames
[state
->pos
];
543 FillInFrameInfo (frame
);
545 if (!(frame
->klass
&& frame
->meth
))
546 return _URC_NO_REASON
;
548 bool *stopping
= (bool *) state
->trace_data
;
550 return _URC_NORMAL_STOP
;
552 if (frame
->klass
== &::java::security::AccessController::class$
553 && strcmp (frame
->meth
->name
->chars(), "doPrivileged") == 0)
556 return _URC_NO_REASON
;
559 JArray
<jobjectArray
> *
560 _Jv_StackTrace::GetAccessControlStack (void)
562 int trace_size
= 100;
563 _Jv_StackFrame frames
[trace_size
];
564 _Jv_UnwindState
state (trace_size
);
565 state
.frames
= (_Jv_StackFrame
*) &frames
;
566 state
.trace_function
= accesscontrol_trace_fn
;
567 bool stopping
= false;
568 state
.trace_data
= (void *) &stopping
;
571 _Unwind_Backtrace (UnwindTraceFn
, &state
);
575 for (int i
= 0; i
< state
.pos
; i
++)
577 _Jv_StackFrame
*frame
= &state
.frames
[i
];
579 if (frame
->klass
&& frame
->meth
)
583 jclass array_class
= _Jv_GetArrayClass (&::java::lang::Object::class$
, NULL
);
584 JArray
<jobjectArray
> *result
=
585 (JArray
<jobjectArray
> *) _Jv_NewObjectArray (2, array_class
, NULL
);
586 JArray
<jclass
> *classes
= (JArray
<jclass
> *)
587 _Jv_NewObjectArray (length
, &::java::lang::Class::class$
, NULL
);
588 JArray
<jstring
> *methods
= (JArray
<jstring
> *)
589 _Jv_NewObjectArray (length
, &::java::lang::String::class$
, NULL
);
590 jclass
*c
= elements (classes
);
591 jstring
*m
= elements (methods
);
593 for (int i
= 0, j
= 0; i
< state
.pos
; i
++)
595 _Jv_StackFrame
*frame
= &state
.frames
[i
];
596 if (!frame
->klass
|| !frame
->meth
)
599 m
[j
] = JvNewStringUTF (frame
->meth
->name
->chars());
603 jobjectArray
*elems
= elements (result
);
604 elems
[0] = (jobjectArray
) classes
;
605 elems
[1] = (jobjectArray
) methods
;