OSDN Git Service

2005-03-10 Bryce McKinlay <mckinlay@redhat.com>
[pf3gnuchains/gcc-fork.git] / libjava / stacktrace.cc
1 // stacktrace.cc - Functions for unwinding & inspecting the call stack.
2
3 /* Copyright (C) 2005  Free Software Foundation
4
5    This file is part of libgcj.
6
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License.  Please consult the file "LIBGCJ_LICENSE" for
9 details.  */
10
11 #include <config.h>
12
13 #include <jvm.h>
14 #include <gcj/cni.h>
15 #include <java-interp.h>
16 #include <java-stack.h>
17
18 #ifdef HAVE_DLFCN_H
19 #include <dlfcn.h>
20 #endif
21
22 #include <stdio.h>
23
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
31 #include <sysdep/backtrace.h>
32
33 using namespace java::lang;
34 using namespace java::lang::reflect;
35 using namespace java::util;
36 using namespace gnu::gcj::runtime;
37
38 struct _Jv_FindCallingClassState: _Jv_UnwindState
39 {
40   jclass result;
41 };
42
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;
48
49 // Check the "class stack" for any classes initialized since we were last 
50 // called, and add them to ncodeMap.
51 void 
52 _Jv_StackTrace::UpdateNCodeMap ()
53 {
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 
56   // enough.
57   if (ncodeMap == NULL)
58     ncodeMap = new java::util::IdentityHashMap (5087);
59   
60   jclass klass;
61   while ((klass = _Jv_PopClass ()))
62     {
63       //printf ("got %s\n", klass->name->data);
64 #ifdef INTERPRETER
65       JvAssert (! _Jv_IsInterpretedClass (klass));
66 #endif
67       for (int i=0; i < klass->method_count; i++)
68         {
69           _Jv_Method *method = &klass->methods[i];
70           // Add non-abstract methods to ncodeMap.
71           if (method->ncode)
72             {
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);
76             }
77         }
78     }
79 }
80
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 
84 // enclosing method.
85 jclass
86 _Jv_StackTrace::ClassForFrame (_Jv_StackFrame *frame)
87 {
88   JvAssert (frame->type == frame_native);
89   jclass klass = NULL;
90   // use _Unwind_FindEnclosingFunction to find start of method
91   //void *entryPoint = _Unwind_FindEnclosingFunction (ip);
92
93   // look it up in ncodeMap
94   if (frame->start_ip)
95     klass = (jclass) ncodeMap->get ((jobject) frame->start_ip);
96
97   return klass;
98 }
99
100 _Unwind_Reason_Code
101 _Jv_StackTrace::UnwindTraceFn (struct _Unwind_Context *context, void *state_ptr)
102 {
103   _Jv_UnwindState *state = (_Jv_UnwindState *) state_ptr;
104   jint pos = state->pos;
105
106   // Check if the trace buffer needs to be extended.
107   if (pos == state->length)
108     {
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;
114     }
115   
116   _Unwind_Ptr func_addr = _Unwind_GetRegionStart (context);
117   
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)
124     {
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;
129     }
130   else
131     {
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;
135     }
136
137   //printf ("unwind ip: %p\n", _Unwind_GetIP (context));
138
139   _Unwind_Reason_Code result = _URC_NO_REASON;
140   if (state->trace_function != NULL)
141     result = (state->trace_function) (state);
142   state->pos++;
143   return result;
144 }
145
146 // Return a raw stack trace from the current point of execution. The raw 
147 // trace will include all functions that have unwind info.
148 _Jv_StackTrace *
149 _Jv_StackTrace::GetStackTrace(void)
150 {
151   int trace_size = 100;
152   _Jv_StackFrame frames[trace_size];
153   _Jv_UnwindState state (trace_size);
154   state.frames = (_Jv_StackFrame *) &frames;
155
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 */
163   
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);  
170   return trace;
171 }
172
173 void
174 _Jv_StackTrace::getLineNumberForFrame(_Jv_StackFrame *frame, NameFinder *finder, 
175                  jstring *sourceFileName, jint *lineNum)
176 {
177   if (frame->type == frame_interpreter)
178     {
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);
184       return;
185     }
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;
189   Dl_info info;
190   jstring binaryName = NULL;
191
192   void *ip = frame->ip;
193   _Unwind_Ptr offset = 0;
194   
195   if (dladdr (ip, &info))
196     {
197       if (info.dli_fname)
198         binaryName = JvNewStringUTF (info.dli_fname);
199       else
200         return;
201
202       // addr2line expects relative addresses for shared libraries.
203       if (strcmp (info.dli_fname, _Jv_argv[0]) == 0)
204         offset = (_Unwind_Ptr) ip;
205       else
206         offset = (_Unwind_Ptr) ip - (_Unwind_Ptr) info.dli_fbase;
207
208       //printf ("linenum ip: %p\n", ip);
209       //printf ("%s: 0x%x\n", info.dli_fname, offset);
210       //offset -= sizeof(void *);
211       
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.
214       offset -= 1;
215
216       // printf ("%s: 0x%x\n", info.dli_fname, offset);
217       
218       finder->lookup (binaryName, (jlong) offset);
219       *sourceFileName = finder->getSourceFile();
220       *lineNum = finder->getLineNum();
221     }
222 #endif
223 }
224
225 // Look up class and method info for the given stack frame, setting 
226 // frame->klass and frame->meth if they are known.
227 void
228 _Jv_StackTrace::FillInFrameInfo (_Jv_StackFrame *frame)
229 {
230   jclass klass = NULL;
231   _Jv_Method *meth = NULL;
232   
233   if (frame->type == frame_native)
234     {
235       klass = _Jv_StackTrace::ClassForFrame (frame);
236
237       if (klass != NULL)
238         // Find method in class
239         for (int j = 0; j < klass->method_count; j++)
240           {
241             if (klass->methods[j].ncode == frame->start_ip)
242               {
243                 meth = &klass->methods[j];
244                 break;
245               }
246           }
247     }
248   else if (frame->type == frame_interpreter)
249     {
250       _Jv_InterpMethod *interp_meth = frame->interp.meth;
251       klass = interp_meth->defining_class;
252       meth = interp_meth->self;
253     }
254   else
255     JvFail ("Unknown frame type");
256   
257   frame->klass = klass;
258   frame->meth = meth;
259 }
260
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)))
265 {
266   ArrayList *list = new ArrayList ();
267
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");
272
273   for (int i = 0; i < trace->length; i++)
274     {
275       jstring sourceFileName = NULL;
276       jint lineNum = -1;
277       _Jv_StackFrame *frame = &trace->frames[i];
278       
279       jstring className = NULL;
280       jstring methodName = hex->concat (Long::toHexString ((jlong) frame->ip));
281
282       StackTraceElement *element = new StackTraceElement (sourceFileName, 
283         lineNum, className, methodName, 0);    
284       list->add (element);
285     }
286
287 #else /* SJLJ_EXCEPTIONS */
288
289   //JvSynchronized (ncodeMap);
290   UpdateNCodeMap ();
291
292   NameFinder *finder = new NameFinder();
293   int start_idx = 0;
294   int end_idx = trace->length - 1;
295
296   // First pass: strip superfluous frames from beginning and end of the trace.  
297   for (int i = 0; i < trace->length; i++)
298     {
299       _Jv_StackFrame *frame = &trace->frames[i];
300       FillInFrameInfo (frame);
301
302       if (!frame->klass || !frame->meth)
303         // Not a Java frame.
304         continue;
305
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)
311         start_idx = i + 1;
312
313       if (frame->klass == &Throwable::class$
314           && strcmp (frame->meth->name->chars(), "fillInStackTrace") == 0)
315         start_idx = i + 1;
316
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)
320         end_idx = i - 1;
321     }
322   
323   // Second pass: Look up line-number info for remaining frames.
324   for (int i = start_idx; i <= end_idx; i++)
325     {
326       _Jv_StackFrame *frame = &trace->frames[i];
327       
328       if (frame->klass == NULL)
329         // Not a Java frame.
330         continue;
331       
332       jstring className = frame->klass->getName ();
333       jstring methodName = NULL;
334       if (frame->meth)
335         methodName = JvNewStringUTF (frame->meth->name->chars());
336       
337       jstring sourceFileName = NULL;
338       jint lineNum = -1;
339       
340       getLineNumberForFrame(frame, finder, &sourceFileName, &lineNum);
341       
342       StackTraceElement *element = new StackTraceElement (sourceFileName, lineNum,
343         className, methodName, 0);
344       list->add (element);
345     }
346   
347   finder->close();
348 #endif /* SJLJ_EXCEPTIONS */
349
350   JArray<Object *> *array = JvNewObjectArray (list->size (), 
351     &StackTraceElement::class$, NULL);
352
353   return (JArray<StackTraceElement *>*) list->toArray (array);
354 }
355
356 struct CallingClassTraceData
357 {
358   jclass checkClass;    
359   jclass foundClass;
360   _Jv_Method *foundMeth;
361   bool seen_checkClass;
362 };
363
364 _Unwind_Reason_Code
365 _Jv_StackTrace::calling_class_trace_fn (_Jv_UnwindState *state)
366 {
367   CallingClassTraceData *trace_data = (CallingClassTraceData *)
368     state->trace_data;
369   _Jv_StackFrame *frame = &state->frames[state->pos];
370   FillInFrameInfo (frame);
371
372   if (trace_data->seen_checkClass
373       && frame->klass
374       && frame->klass != trace_data->checkClass)
375     {
376       trace_data->foundClass = frame->klass;
377       trace_data->foundMeth = frame->meth;
378       return _URC_NORMAL_STOP;
379     }
380   
381   if (frame->klass == trace_data->checkClass)
382     trace_data->seen_checkClass = true;
383     
384   return _URC_NO_REASON;
385 }
386
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.
395 jclass
396 _Jv_StackTrace::GetCallingClass (jclass checkClass)
397 {
398   jclass result = NULL;
399   GetCallerInfo (checkClass, &result, NULL);
400   return result;
401 }
402
403 void
404 _Jv_StackTrace::GetCallerInfo (jclass checkClass, jclass *caller_class,
405   _Jv_Method **caller_meth)
406 {
407 #ifndef SJLJ_EXCEPTIONS
408   int trace_size = 20;
409   _Jv_StackFrame frames[trace_size];
410   _Jv_UnwindState state (trace_size);
411   state.frames = (_Jv_StackFrame *) &frames;
412
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;
418
419   state.trace_function = calling_class_trace_fn;
420   state.trace_data = (void *) &trace_data;
421
422   //JvSynchronized (ncodeMap);
423   UpdateNCodeMap ();
424
425   _Unwind_Backtrace (UnwindTraceFn, &state);
426   
427   if (caller_class)
428     *caller_class = trace_data.foundClass;
429   if (caller_meth)
430     *caller_meth = trace_data.foundMeth;
431 #else
432   return NULL;
433 #endif
434 }
435
436 // Return a java array containing the Java classes on the stack above CHECKCLASS.
437 JArray<jclass> *
438 _Jv_StackTrace::GetClassContext (jclass checkClass)
439 {
440   JArray<jclass> *result = NULL;
441
442   int trace_size = 100;
443   _Jv_StackFrame frames[trace_size];
444   _Jv_UnwindState state (trace_size);
445   state.frames = (_Jv_StackFrame *) &frames;
446
447   //JvSynchronized (ncodeMap);
448   UpdateNCodeMap ();
449
450   _Unwind_Backtrace (UnwindTraceFn, &state);
451
452   // Count the number of Java frames on the stack.
453   int jframe_count = 0;
454   bool seen_checkClass = false;
455   int start_pos = -1;
456   for (int i = 0; i < state.pos; i++)
457     {
458       _Jv_StackFrame *frame = &state.frames[i];
459       FillInFrameInfo (frame);
460       
461       if (seen_checkClass
462           && frame->klass
463           && frame->klass != checkClass)
464         {
465           jframe_count++;
466           if (start_pos == -1)
467             start_pos = i;
468         }
469
470       if (!seen_checkClass
471           && frame->klass
472           && frame->klass == checkClass)
473         seen_checkClass = true;
474     }
475   result = (JArray<jclass> *) _Jv_NewObjectArray (jframe_count, &Class::class$, NULL);
476   int pos = 0;
477   
478   for (int i = start_pos; i < state.pos; i++)
479     {
480       _Jv_StackFrame *frame = &state.frames[i];
481       if (frame->klass)
482         elements(result)[pos++] = frame->klass;
483     }
484   return result;
485 }
486
487 _Unwind_Reason_Code
488 _Jv_StackTrace::non_system_trace_fn (_Jv_UnwindState *state)
489 {
490   _Jv_StackFrame *frame = &state->frames[state->pos];
491   FillInFrameInfo (frame);
492   
493   ClassLoader *classLoader = NULL;
494
495   if (frame->klass)
496     {
497       classLoader = frame->klass->getClassLoaderInternal();
498       if (classLoader != NULL && classLoader != ClassLoader::systemClassLoader)
499         {
500           state->trace_data = (void *) classLoader;
501           return _URC_NORMAL_STOP;
502         }
503     }
504
505   return _URC_NO_REASON;
506 }
507
508 ClassLoader *
509 _Jv_StackTrace::GetFirstNonSystemClassLoader ()
510 {
511   int trace_size = 32;
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;
517
518   //JvSynchronized (ncodeMap);
519   UpdateNCodeMap ();
520   
521   _Unwind_Backtrace (UnwindTraceFn, &state);
522
523   if (state.trace_data)
524     return (ClassLoader *) state.trace_data;
525   
526   return NULL;
527 }