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/Boolean.h>
22 #include <java/lang/Class.h>
23 #include <java/lang/Long.h>
24 #include <java/security/AccessController.h>
25 #include <java/util/ArrayList.h>
26 #include <java/util/IdentityHashMap.h>
27 #include <gnu/classpath/jdwp/Jdwp.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);
86 // look it up in ncodeMap
88 klass = (jclass) ncodeMap->get ((jobject) frame->start_ip);
94 _Jv_StackTrace::UnwindTraceFn (struct _Unwind_Context *context, void *state_ptr)
96 _Jv_UnwindState *state = (_Jv_UnwindState *) state_ptr;
97 jint pos = state->pos;
99 // Check if the trace buffer needs to be extended.
100 if (pos == state->length)
102 int newLength = state->length * 2;
103 void *newFrames = _Jv_AllocBytes (newLength * sizeof(_Jv_StackFrame));
104 memcpy (newFrames, state->frames, state->length * sizeof(_Jv_StackFrame));
105 state->frames = (_Jv_StackFrame *) newFrames;
106 state->length = newLength;
109 void *func_addr = (void *) _Unwind_GetRegionStart (context);
111 // If we see the interpreter's main function, "pop" an entry off the
112 // interpreter stack and use that instead, so that the trace goes through
113 // the java code and not the interpreter itself. This assumes a 1:1
114 // correspondance between call frames in the interpreted stack and occurances
115 // of _Jv_InterpMethod::run() on the native stack.
117 void *interp_run = NULL;
119 if (::gnu::classpath::jdwp::Jdwp::isDebugging)
120 interp_run = (void *) &_Jv_InterpMethod::run_debug;
122 interp_run = (void *) &_Jv_InterpMethod::run;
124 if (func_addr == UNWRAP_FUNCTION_DESCRIPTOR (interp_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;
135 int ip_before_insn = 0;
136 ip = _Unwind_GetIPInfo (context, &ip_before_insn);
138 // If the unwinder gave us a 'return' address, roll it back a little
139 // to ensure we get the correct line number for the call itself.
140 if (! ip_before_insn)
143 state->frames[pos].type = frame_native;
144 state->frames[pos].ip = (void *) ip;
145 state->frames[pos].start_ip = func_addr;
148 _Unwind_Reason_Code result = _URC_NO_REASON;
149 if (state->trace_function != NULL)
150 result = (state->trace_function) (state);
155 // Return a raw stack trace from the current point of execution. The raw
156 // trace will include all functions that have unwind info.
158 _Jv_StackTrace::GetStackTrace(void)
160 int trace_size = 100;
161 _Jv_StackFrame frames[trace_size];
162 _Jv_UnwindState state (trace_size);
163 state.frames = (_Jv_StackFrame *) &frames;
165 _Unwind_Backtrace (UnwindTraceFn, &state);
167 // Copy the trace and return it.
168 int traceSize = sizeof (_Jv_StackTrace) +
169 (sizeof (_Jv_StackFrame) * state.pos);
170 _Jv_StackTrace *trace = (_Jv_StackTrace *) _Jv_AllocBytes (traceSize);
171 trace->length = state.pos;
172 memcpy (trace->frames, state.frames, sizeof (_Jv_StackFrame) * state.pos);
177 _Jv_StackTrace::getLineNumberForFrame(_Jv_StackFrame *frame, NameFinder *finder,
178 jstring *sourceFileName, jint *lineNum,
182 if (frame->type == frame_interpreter)
184 _Jv_InterpMethod *interp_meth = frame->interp.meth;
185 _Jv_InterpClass *interp_class =
186 (_Jv_InterpClass *) interp_meth->defining_class->aux_info;
187 *sourceFileName = interp_class->source_file_name;
188 // The interpreter advances the PC before executing an instruction,
189 // so roll-back 1 byte to ensure the line number is accurate.
190 *lineNum = interp_meth->get_source_line(frame->interp.pc - 1);
195 // Use _Jv_platform_dladdr() to determine in which binary the address IP
198 jstring binaryName = NULL;
199 const char *argv0 = _Jv_GetSafeArg(0);
201 void *ip = frame->ip;
202 _Unwind_Ptr offset = 0;
204 if (_Jv_platform_dladdr (ip, &info))
207 binaryName = JvNewStringUTF (info.file_name);
211 if (*methodName == NULL && info.sym_name)
212 *methodName = JvNewStringUTF (info.sym_name);
214 // addr2line expects relative addresses for shared libraries.
215 if (strcmp (info.file_name, argv0) == 0)
216 offset = (_Unwind_Ptr) ip;
218 offset = (_Unwind_Ptr) ip - (_Unwind_Ptr) info.base;
220 finder->lookup (binaryName, (jlong) offset);
221 *sourceFileName = finder->getSourceFile();
222 *lineNum = finder->getLineNum();
223 if (*lineNum == -1 && NameFinder::showRaw())
225 gnu::gcj::runtime::StringBuffer *t =
226 new gnu::gcj::runtime::StringBuffer(binaryName);
227 t->append ((jchar)' ');
228 t->append ((jchar)'[');
229 // + 1 to compensate for the - 1 adjustment above;
230 t->append (Long::toHexString (offset + 1));
231 t->append ((jchar)']');
232 *sourceFileName = t->toString();
237 // Look up class and method info for the given stack frame, setting
238 // frame->klass and frame->meth if they are known.
240 _Jv_StackTrace::FillInFrameInfo (_Jv_StackFrame *frame)
243 _Jv_Method *meth = NULL;
245 if (frame->type == frame_native)
247 klass = _Jv_StackTrace::ClassForFrame (frame);
250 // Find method in class
251 for (int j = 0; j < klass->method_count; j++)
253 void *wncode = UNWRAP_FUNCTION_DESCRIPTOR (klass->methods[j].ncode);
254 if (wncode == frame->start_ip)
256 meth = &klass->methods[j];
262 else if (frame->type == frame_interpreter)
264 _Jv_InterpMethod *interp_meth = frame->interp.meth;
265 klass = interp_meth->defining_class;
266 meth = interp_meth->self;
270 JvFail ("Unknown frame type");
272 frame->klass = klass;
276 // Convert raw stack frames to a Java array of StackTraceElement objects.
277 JArray< ::java::lang::StackTraceElement *>*
278 _Jv_StackTrace::GetStackTraceElements (_Jv_StackTrace *trace,
279 Throwable *throwable __attribute__((unused)))
281 ArrayList *list = new ArrayList ();
283 #if defined (SJLJ_EXCEPTIONS) && ! defined (WIN32)
284 // We can't use the nCodeMap without unwinder support. Instead,
285 // fake the method name by giving the IP in hex - better than nothing.
286 jstring hex = JvNewStringUTF ("0x");
288 for (int i = 0; i < trace->length; i++)
290 jstring sourceFileName = NULL;
292 _Jv_StackFrame *frame = &trace->frames[i];
294 jstring className = NULL;
295 jstring methodName = hex->concat (Long::toHexString ((jlong) frame->ip));
297 StackTraceElement *element = new StackTraceElement (sourceFileName,
298 lineNum, className, methodName, 0);
302 #else /* SJLJ_EXCEPTIONS && !WIN32 */
304 //JvSynchronized (ncodeMap);
307 NameFinder *finder = new NameFinder();
309 int end_idx = trace->length - 1;
311 // First pass: strip superfluous frames from beginning and end of the trace.
312 for (int i = 0; i < trace->length; i++)
314 _Jv_StackFrame *frame = &trace->frames[i];
315 FillInFrameInfo (frame);
317 if (!frame->klass || !frame->meth)
321 // Throw away the top of the stack till we see:
322 // - the constructor(s) of this Throwable, or
323 // - the Throwable.fillInStackTrace call.
324 if (frame->klass == throwable->getClass()
325 && strcmp (frame->meth->name->chars(), "<init>") == 0)
328 if (frame->klass == &Throwable::class$
329 && strcmp (frame->meth->name->chars(), "fillInStackTrace") == 0)
332 // End the trace at the application's main() method if we see call_main.
333 if (frame->klass == &gnu::java::lang::MainThread::class$
334 && strcmp (frame->meth->name->chars(), "call_main") == 0)
338 const jboolean remove_unknown
339 = gnu::gcj::runtime::NameFinder::removeUnknown();
341 // Second pass: Look up line-number info for remaining frames.
342 for (int i = start_idx; i <= end_idx; i++)
344 _Jv_StackFrame *frame = &trace->frames[i];
346 if (frame->klass == NULL && remove_unknown)
350 jstring className = NULL;
351 if (frame->klass != NULL)
352 className = frame->klass->getName ();
354 jstring methodName = NULL;
356 methodName = JvNewStringUTF (frame->meth->name->chars());
358 jstring sourceFileName = NULL;
361 getLineNumberForFrame(frame, finder, &sourceFileName, &lineNum,
364 StackTraceElement *element = new StackTraceElement (sourceFileName, lineNum,
365 className, methodName, 0);
370 #endif /* SJLJ_EXCEPTIONS && !WIN32 */
372 JArray<Object *> *array = JvNewObjectArray (list->size (),
373 &StackTraceElement::class$, NULL);
375 return (JArray<StackTraceElement *>*) list->toArray (array);
378 struct CallingClassTraceData
382 _Jv_Method *foundMeth;
383 bool seen_checkClass;
387 _Jv_StackTrace::calling_class_trace_fn (_Jv_UnwindState *state)
389 CallingClassTraceData *trace_data = (CallingClassTraceData *)
391 _Jv_StackFrame *frame = &state->frames[state->pos];
392 FillInFrameInfo (frame);
394 if (trace_data->seen_checkClass
396 && frame->klass != trace_data->checkClass)
398 trace_data->foundClass = frame->klass;
399 trace_data->foundMeth = frame->meth;
400 return _URC_NORMAL_STOP;
403 if (frame->klass == trace_data->checkClass)
404 trace_data->seen_checkClass = true;
406 return _URC_NO_REASON;
409 // Find the class immediately above the given class on the call stack. Any
410 // intermediate non-Java
411 // frames are ignored. If the calling class could not be determined (eg because
412 // the unwinder is not supported on this platform), NULL is returned.
413 // This function is used to implement calling-classloader checks and reflection
414 // accessibility checks.
415 // CHECKCLASS is typically the class calling GetCallingClass. The first class
416 // above CHECKCLASS on the call stack will be returned.
418 _Jv_StackTrace::GetCallingClass (jclass checkClass)
420 jclass result = NULL;
421 GetCallerInfo (checkClass, &result, NULL);
426 _Jv_StackTrace::GetCallerInfo (jclass checkClass, jclass *caller_class,
427 _Jv_Method **caller_meth)
430 _Jv_StackFrame frames[trace_size];
431 _Jv_UnwindState state (trace_size);
432 state.frames = (_Jv_StackFrame *) &frames;
434 CallingClassTraceData trace_data;
435 trace_data.checkClass = checkClass;
436 trace_data.seen_checkClass = false;
437 trace_data.foundClass = NULL;
438 trace_data.foundMeth = NULL;
440 state.trace_function = calling_class_trace_fn;
441 state.trace_data = (void *) &trace_data;
443 //JvSynchronized (ncodeMap);
446 _Unwind_Backtrace (UnwindTraceFn, &state);
449 *caller_class = trace_data.foundClass;
451 *caller_meth = trace_data.foundMeth;
454 // Return a java array containing the Java classes on the stack above CHECKCLASS.
456 _Jv_StackTrace::GetClassContext (jclass checkClass)
458 JArray<jclass> *result = NULL;
460 int trace_size = 100;
461 _Jv_StackFrame frames[trace_size];
462 _Jv_UnwindState state (trace_size);
463 state.frames = (_Jv_StackFrame *) &frames;
465 //JvSynchronized (ncodeMap);
468 _Unwind_Backtrace (UnwindTraceFn, &state);
470 // Count the number of Java frames on the stack.
471 int jframe_count = 0;
472 bool seen_checkClass = false;
474 for (int i = 0; i < state.pos; i++)
476 _Jv_StackFrame *frame = &state.frames[i];
477 FillInFrameInfo (frame);
489 seen_checkClass = frame->klass == checkClass;
491 result = (JArray<jclass> *) _Jv_NewObjectArray (jframe_count, &Class::class$, NULL);
494 for (int i = start_pos; i < state.pos; i++)
496 _Jv_StackFrame *frame = &state.frames[i];
498 elements(result)[pos++] = frame->klass;
504 _Jv_StackTrace::non_system_trace_fn (_Jv_UnwindState *state)
506 _Jv_StackFrame *frame = &state->frames[state->pos];
507 FillInFrameInfo (frame);
509 ClassLoader *classLoader = NULL;
513 classLoader = frame->klass->getClassLoaderInternal();
515 if (classLoader != NULL)
517 state->trace_data = (void *) classLoader;
518 return _URC_NORMAL_STOP;
523 return _URC_NO_REASON;
527 _Jv_StackTrace::GetFirstNonSystemClassLoader ()
530 _Jv_StackFrame frames[trace_size];
531 _Jv_UnwindState state (trace_size);
532 state.frames = (_Jv_StackFrame *) &frames;
533 state.trace_function = non_system_trace_fn;
534 state.trace_data = NULL;
536 //JvSynchronized (ncodeMap);
539 _Unwind_Backtrace (UnwindTraceFn, &state);
541 if (state.trace_data)
542 return (ClassLoader *) state.trace_data;
547 struct AccessControlTraceData
554 _Jv_StackTrace::accesscontrol_trace_fn (_Jv_UnwindState *state)
556 AccessControlTraceData *trace_data = (AccessControlTraceData *)
558 _Jv_StackFrame *frame = &state->frames[state->pos];
559 FillInFrameInfo (frame);
561 if (!(frame->klass && frame->meth))
562 return _URC_NO_REASON;
564 trace_data->length++;
566 // If the previous frame was a call to doPrivileged, then this is
567 // the last frame we look at.
568 if (trace_data->privileged)
569 return _URC_NORMAL_STOP;
571 if (frame->klass == &::java::security::AccessController::class$
572 && strcmp (frame->meth->name->chars(), "doPrivileged") == 0)
573 trace_data->privileged = true;
575 return _URC_NO_REASON;
579 _Jv_StackTrace::GetAccessControlStack (void)
581 int trace_size = 100;
582 _Jv_StackFrame frames[trace_size];
583 _Jv_UnwindState state (trace_size);
584 state.frames = (_Jv_StackFrame *) &frames;
586 AccessControlTraceData trace_data;
587 trace_data.length = 0;
588 trace_data.privileged = false;
590 state.trace_function = accesscontrol_trace_fn;
591 state.trace_data = (void *) &trace_data;
594 _Unwind_Backtrace (UnwindTraceFn, &state);
596 JArray<jclass> *classes = (JArray<jclass> *)
597 _Jv_NewObjectArray (trace_data.length, &::java::lang::Class::class$, NULL);
598 jclass *c = elements (classes);
600 for (int i = 0, j = 0; i < state.pos; i++)
602 _Jv_StackFrame *frame = &state.frames[i];
603 if (!frame->klass || !frame->meth)
609 jobjectArray result =
610 (jobjectArray) _Jv_NewObjectArray (2, &::java::lang::Object::class$,
612 jobject *r = elements (result);
613 r[0] = (jobject) classes;
614 r[1] = (jobject) new Boolean (trace_data.privileged);