OSDN Git Service

2005-03-17 Andrew Haley <aph@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 #ifdef INTERPRETER
124   if (func_addr == (_Unwind_Ptr) &_Jv_InterpMethod::run)
125     {
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;
130     }
131   else
132 #endif
133     {
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;
137     }
138
139   //printf ("unwind ip: %p\n", _Unwind_GetIP (context));
140
141   _Unwind_Reason_Code result = _URC_NO_REASON;
142   if (state->trace_function != NULL)
143     result = (state->trace_function) (state);
144   state->pos++;
145   return result;
146 }
147
148 // Return a raw stack trace from the current point of execution. The raw 
149 // trace will include all functions that have unwind info.
150 _Jv_StackTrace *
151 _Jv_StackTrace::GetStackTrace(void)
152 {
153   int trace_size = 100;
154   _Jv_StackFrame frames[trace_size];
155   _Jv_UnwindState state (trace_size);
156   state.frames = (_Jv_StackFrame *) &frames;
157
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 */
165   
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);  
172   return trace;
173 }
174
175 void
176 _Jv_StackTrace::getLineNumberForFrame(_Jv_StackFrame *frame, NameFinder *finder, 
177                  jstring *sourceFileName, jint *lineNum)
178 {
179 #ifdef INTERPRETER
180   if (frame->type == frame_interpreter)
181     {
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);
187       return;
188     }
189 #endif
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;
193   Dl_info info;
194   jstring binaryName = NULL;
195
196   void *ip = frame->ip;
197   _Unwind_Ptr offset = 0;
198   
199   if (dladdr (ip, &info))
200     {
201       if (info.dli_fname)
202         binaryName = JvNewStringUTF (info.dli_fname);
203       else
204         return;
205
206       // addr2line expects relative addresses for shared libraries.
207       if (strcmp (info.dli_fname, _Jv_argv[0]) == 0)
208         offset = (_Unwind_Ptr) ip;
209       else
210         offset = (_Unwind_Ptr) ip - (_Unwind_Ptr) info.dli_fbase;
211
212       //printf ("linenum ip: %p\n", ip);
213       //printf ("%s: 0x%x\n", info.dli_fname, offset);
214       //offset -= sizeof(void *);
215       
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.
218       offset -= 1;
219
220       // printf ("%s: 0x%x\n", info.dli_fname, offset);
221       
222       finder->lookup (binaryName, (jlong) offset);
223       *sourceFileName = finder->getSourceFile();
224       *lineNum = finder->getLineNum();
225     }
226 #endif
227 }
228
229 // Look up class and method info for the given stack frame, setting 
230 // frame->klass and frame->meth if they are known.
231 void
232 _Jv_StackTrace::FillInFrameInfo (_Jv_StackFrame *frame)
233 {
234   jclass klass = NULL;
235   _Jv_Method *meth = NULL;
236   
237   if (frame->type == frame_native)
238     {
239       klass = _Jv_StackTrace::ClassForFrame (frame);
240
241       if (klass != NULL)
242         // Find method in class
243         for (int j = 0; j < klass->method_count; j++)
244           {
245             if (klass->methods[j].ncode == frame->start_ip)
246               {
247                 meth = &klass->methods[j];
248                 break;
249               }
250           }
251     }
252 #ifdef INTERPRETER
253   else if (frame->type == frame_interpreter)
254     {
255       _Jv_InterpMethod *interp_meth = frame->interp.meth;
256       klass = interp_meth->defining_class;
257       meth = interp_meth->self;
258     }
259 #endif
260   else
261     JvFail ("Unknown frame type");
262   
263   frame->klass = klass;
264   frame->meth = meth;
265 }
266
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)))
271 {
272   ArrayList *list = new ArrayList ();
273
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");
278
279   for (int i = 0; i < trace->length; i++)
280     {
281       jstring sourceFileName = NULL;
282       jint lineNum = -1;
283       _Jv_StackFrame *frame = &trace->frames[i];
284       
285       jstring className = NULL;
286       jstring methodName = hex->concat (Long::toHexString ((jlong) frame->ip));
287
288       StackTraceElement *element = new StackTraceElement (sourceFileName, 
289         lineNum, className, methodName, 0);    
290       list->add (element);
291     }
292
293 #else /* SJLJ_EXCEPTIONS */
294
295   //JvSynchronized (ncodeMap);
296   UpdateNCodeMap ();
297
298   NameFinder *finder = new NameFinder();
299   int start_idx = 0;
300   int end_idx = trace->length - 1;
301
302   // First pass: strip superfluous frames from beginning and end of the trace.  
303   for (int i = 0; i < trace->length; i++)
304     {
305       _Jv_StackFrame *frame = &trace->frames[i];
306       FillInFrameInfo (frame);
307
308       if (!frame->klass || !frame->meth)
309         // Not a Java frame.
310         continue;
311
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)
317         start_idx = i + 1;
318
319       if (frame->klass == &Throwable::class$
320           && strcmp (frame->meth->name->chars(), "fillInStackTrace") == 0)
321         start_idx = i + 1;
322
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)
326         end_idx = i - 1;
327     }
328   
329   // Second pass: Look up line-number info for remaining frames.
330   for (int i = start_idx; i <= end_idx; i++)
331     {
332       _Jv_StackFrame *frame = &trace->frames[i];
333       
334       if (frame->klass == NULL)
335         // Not a Java frame.
336         continue;
337       
338       jstring className = frame->klass->getName ();
339       jstring methodName = NULL;
340       if (frame->meth)
341         methodName = JvNewStringUTF (frame->meth->name->chars());
342       
343       jstring sourceFileName = NULL;
344       jint lineNum = -1;
345       
346       getLineNumberForFrame(frame, finder, &sourceFileName, &lineNum);
347       
348       StackTraceElement *element = new StackTraceElement (sourceFileName, lineNum,
349         className, methodName, 0);
350       list->add (element);
351     }
352   
353   finder->close();
354 #endif /* SJLJ_EXCEPTIONS */
355
356   JArray<Object *> *array = JvNewObjectArray (list->size (), 
357     &StackTraceElement::class$, NULL);
358
359   return (JArray<StackTraceElement *>*) list->toArray (array);
360 }
361
362 struct CallingClassTraceData
363 {
364   jclass checkClass;    
365   jclass foundClass;
366   _Jv_Method *foundMeth;
367   bool seen_checkClass;
368 };
369
370 _Unwind_Reason_Code
371 _Jv_StackTrace::calling_class_trace_fn (_Jv_UnwindState *state)
372 {
373   CallingClassTraceData *trace_data = (CallingClassTraceData *)
374     state->trace_data;
375   _Jv_StackFrame *frame = &state->frames[state->pos];
376   FillInFrameInfo (frame);
377
378   if (trace_data->seen_checkClass
379       && frame->klass
380       && frame->klass != trace_data->checkClass)
381     {
382       trace_data->foundClass = frame->klass;
383       trace_data->foundMeth = frame->meth;
384       return _URC_NORMAL_STOP;
385     }
386   
387   if (frame->klass == trace_data->checkClass)
388     trace_data->seen_checkClass = true;
389     
390   return _URC_NO_REASON;
391 }
392
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.
401 jclass
402 _Jv_StackTrace::GetCallingClass (jclass checkClass)
403 {
404   jclass result = NULL;
405   GetCallerInfo (checkClass, &result, NULL);
406   return result;
407 }
408
409 void
410 _Jv_StackTrace::GetCallerInfo (jclass checkClass, jclass *caller_class,
411   _Jv_Method **caller_meth)
412 {
413 #ifndef SJLJ_EXCEPTIONS
414   int trace_size = 20;
415   _Jv_StackFrame frames[trace_size];
416   _Jv_UnwindState state (trace_size);
417   state.frames = (_Jv_StackFrame *) &frames;
418
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;
424
425   state.trace_function = calling_class_trace_fn;
426   state.trace_data = (void *) &trace_data;
427
428   //JvSynchronized (ncodeMap);
429   UpdateNCodeMap ();
430
431   _Unwind_Backtrace (UnwindTraceFn, &state);
432   
433   if (caller_class)
434     *caller_class = trace_data.foundClass;
435   if (caller_meth)
436     *caller_meth = trace_data.foundMeth;
437 #else
438   return;
439 #endif
440 }
441
442 // Return a java array containing the Java classes on the stack above CHECKCLASS.
443 JArray<jclass> *
444 _Jv_StackTrace::GetClassContext (jclass checkClass)
445 {
446   JArray<jclass> *result = NULL;
447
448   int trace_size = 100;
449   _Jv_StackFrame frames[trace_size];
450   _Jv_UnwindState state (trace_size);
451   state.frames = (_Jv_StackFrame *) &frames;
452
453   //JvSynchronized (ncodeMap);
454   UpdateNCodeMap ();
455
456   _Unwind_Backtrace (UnwindTraceFn, &state);
457
458   // Count the number of Java frames on the stack.
459   int jframe_count = 0;
460   bool seen_checkClass = false;
461   int start_pos = -1;
462   for (int i = 0; i < state.pos; i++)
463     {
464       _Jv_StackFrame *frame = &state.frames[i];
465       FillInFrameInfo (frame);
466       
467       if (seen_checkClass)
468         {
469           if (frame->klass)
470             {
471               jframe_count++;
472               if (start_pos == -1)
473                 start_pos = i;
474             }
475         }
476       else
477         seen_checkClass = frame->klass == checkClass;
478     }
479   result = (JArray<jclass> *) _Jv_NewObjectArray (jframe_count, &Class::class$, NULL);
480   int pos = 0;
481   
482   for (int i = start_pos; i < state.pos; i++)
483     {
484       _Jv_StackFrame *frame = &state.frames[i];
485       if (frame->klass)
486         elements(result)[pos++] = frame->klass;
487     }
488   return result;
489 }
490
491 _Unwind_Reason_Code
492 _Jv_StackTrace::non_system_trace_fn (_Jv_UnwindState *state)
493 {
494   _Jv_StackFrame *frame = &state->frames[state->pos];
495   FillInFrameInfo (frame);
496   
497   ClassLoader *classLoader = NULL;
498
499   if (frame->klass)
500     {
501       classLoader = frame->klass->getClassLoaderInternal();
502 #ifdef INTERPRETER
503       if (classLoader != NULL && classLoader != ClassLoader::systemClassLoader)
504         {
505           state->trace_data = (void *) classLoader;
506           return _URC_NORMAL_STOP;
507         }
508 #endif
509     }
510
511   return _URC_NO_REASON;
512 }
513
514 ClassLoader *
515 _Jv_StackTrace::GetFirstNonSystemClassLoader ()
516 {
517   int trace_size = 32;
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;
523
524   //JvSynchronized (ncodeMap);
525   UpdateNCodeMap ();
526   
527   _Unwind_Backtrace (UnwindTraceFn, &state);
528
529   if (state.trace_data)
530     return (ClassLoader *) state.trace_data;
531   
532   return NULL;
533 }