OSDN Git Service

* libtool-version: Updated.
[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 #include <sysdep/descriptor.h>
33
34 using namespace java::lang;
35 using namespace java::lang::reflect;
36 using namespace java::util;
37 using namespace gnu::gcj::runtime;
38
39 // Maps ncode values to their containing native class.
40 // NOTE: Currently this Map contradicts class GC for native classes. This map
41 // (and the "new class stack") will need to use WeakReferences in order to 
42 // enable native class GC.
43 static java::util::IdentityHashMap *ncodeMap;
44
45 // Check the "class stack" for any classes initialized since we were last 
46 // called, and add them to ncodeMap.
47 void 
48 _Jv_StackTrace::UpdateNCodeMap ()
49 {
50   // The Map should be large enough so that a typical Java app doesn't cause 
51   // it to rehash, without using too much memory. ~5000 entries should be 
52   // enough.
53   if (ncodeMap == NULL)
54     ncodeMap = new java::util::IdentityHashMap (5087);
55   
56   jclass klass;
57   while ((klass = _Jv_PopClass ()))
58     {
59       //printf ("got %s\n", klass->name->data);
60 #ifdef INTERPRETER
61       JvAssert (! _Jv_IsInterpretedClass (klass));
62 #endif
63       for (int i=0; i < klass->method_count; i++)
64         {
65           _Jv_Method *method = &klass->methods[i];
66           void *ncode = method->ncode;
67           // Add non-abstract methods to ncodeMap.
68           if (ncode)
69             {
70               ncode = UNWRAP_FUNCTION_DESCRIPTOR (ncode);
71               ncodeMap->put ((java::lang::Object *)ncode, klass);
72             }
73         }
74     }
75 }
76
77 // Given a native frame, return the class which this code belongs 
78 // to. Returns NULL if this IP is not associated with a native Java class.
79 // If NCODE is supplied, it will be set with the ip for the entry point of the 
80 // enclosing method.
81 jclass
82 _Jv_StackTrace::ClassForFrame (_Jv_StackFrame *frame)
83 {
84   JvAssert (frame->type == frame_native);
85   jclass klass = NULL;
86   // use _Unwind_FindEnclosingFunction to find start of method
87   //void *entryPoint = _Unwind_FindEnclosingFunction (ip);
88
89   // look it up in ncodeMap
90   if (frame->start_ip)
91     klass = (jclass) ncodeMap->get ((jobject) frame->start_ip);
92
93   return klass;
94 }
95
96 _Unwind_Reason_Code
97 _Jv_StackTrace::UnwindTraceFn (struct _Unwind_Context *context, void *state_ptr)
98 {
99   _Jv_UnwindState *state = (_Jv_UnwindState *) state_ptr;
100   jint pos = state->pos;
101
102   // Check if the trace buffer needs to be extended.
103   if (pos == state->length)
104     {
105       int newLength = state->length *= 2;
106       void *newFrames = _Jv_AllocBytes (newLength * sizeof(_Jv_StackFrame));
107       memcpy (newFrames, state->frames, state->length * sizeof(_Jv_StackFrame));      
108       state->frames = (_Jv_StackFrame *) newFrames;
109       state->length = newLength;
110     }
111   
112   _Unwind_Ptr func_addr = _Unwind_GetRegionStart (context);
113   
114   // If we see the interpreter's main function, "pop" an entry off the 
115   // interpreter stack and use that instead, so that the trace goes through 
116   // the java code and not the interpreter itself. This assumes a 1:1 
117   // correspondance between call frames in the interpreted stack and occurances
118   // of _Jv_InterpMethod::run() on the native stack.
119 #ifdef INTERPRETER
120   if (func_addr == (_Unwind_Ptr) &_Jv_InterpMethod::run)
121     {
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;
126     }
127   else
128 #endif
129     {
130       state->frames[pos].type = frame_native;
131       state->frames[pos].ip = (void *) _Unwind_GetIP (context);
132       state->frames[pos].start_ip = (void *) func_addr;
133     }
134
135   //printf ("unwind ip: %p\n", _Unwind_GetIP (context));
136
137   _Unwind_Reason_Code result = _URC_NO_REASON;
138   if (state->trace_function != NULL)
139     result = (state->trace_function) (state);
140   state->pos++;
141   return result;
142 }
143
144 // Return a raw stack trace from the current point of execution. The raw 
145 // trace will include all functions that have unwind info.
146 _Jv_StackTrace *
147 _Jv_StackTrace::GetStackTrace(void)
148 {
149   int trace_size = 100;
150   _Jv_StackFrame frames[trace_size];
151   _Jv_UnwindState state (trace_size);
152   state.frames = (_Jv_StackFrame *) &frames;
153
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 */
161   
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);  
168   return trace;
169 }
170
171 void
172 _Jv_StackTrace::getLineNumberForFrame(_Jv_StackFrame *frame, NameFinder *finder, 
173                  jstring *sourceFileName, jint *lineNum)
174 {
175 #ifdef INTERPRETER
176   if (frame->type == frame_interpreter)
177     {
178       _Jv_InterpMethod *interp_meth = frame->interp.meth;
179       _Jv_InterpClass *interp_class = 
180          (_Jv_InterpClass *) interp_meth->defining_class->aux_info;
181       *sourceFileName = interp_class->source_file_name;
182       *lineNum = interp_meth->get_source_line(frame->interp.pc);
183       return;
184     }
185 #endif
186   // Use dladdr() to determine in which binary the address IP resides.
187 #if defined (HAVE_DLFCN_H) && defined (HAVE_DLADDR)
188   Dl_info info;
189   jstring binaryName = NULL;
190   const char *argv0 = _Jv_GetSafeArg(0);
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, argv0) == 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 #ifdef INTERPRETER
249   else if (frame->type == frame_interpreter)
250     {
251       _Jv_InterpMethod *interp_meth = frame->interp.meth;
252       klass = interp_meth->defining_class;
253       meth = interp_meth->self;
254     }
255 #endif
256   else
257     JvFail ("Unknown frame type");
258   
259   frame->klass = klass;
260   frame->meth = meth;
261 }
262
263 // Convert raw stack frames to a Java array of StackTraceElement objects.
264 JArray< ::java::lang::StackTraceElement *>*
265 _Jv_StackTrace::GetStackTraceElements (_Jv_StackTrace *trace, 
266   Throwable *throwable __attribute__((unused)))
267 {
268   ArrayList *list = new ArrayList ();
269
270 #ifdef SJLJ_EXCEPTIONS
271   // We can't use the nCodeMap without unwinder support. Instead,
272   // fake the method name by giving the IP in hex - better than nothing.  
273   jstring hex = JvNewStringUTF ("0x");
274
275   for (int i = 0; i < trace->length; i++)
276     {
277       jstring sourceFileName = NULL;
278       jint lineNum = -1;
279       _Jv_StackFrame *frame = &trace->frames[i];
280       
281       jstring className = NULL;
282       jstring methodName = hex->concat (Long::toHexString ((jlong) frame->ip));
283
284       StackTraceElement *element = new StackTraceElement (sourceFileName, 
285         lineNum, className, methodName, 0);    
286       list->add (element);
287     }
288
289 #else /* SJLJ_EXCEPTIONS */
290
291   //JvSynchronized (ncodeMap);
292   UpdateNCodeMap ();
293
294   NameFinder *finder = new NameFinder();
295   int start_idx = 0;
296   int end_idx = trace->length - 1;
297
298   // First pass: strip superfluous frames from beginning and end of the trace.  
299   for (int i = 0; i < trace->length; i++)
300     {
301       _Jv_StackFrame *frame = &trace->frames[i];
302       FillInFrameInfo (frame);
303
304       if (!frame->klass || !frame->meth)
305         // Not a Java frame.
306         continue;
307
308       // Throw away the top of the stack till we see:
309       //  - the constructor(s) of this Throwable, or
310       //  - the Throwable.fillInStackTrace call.
311       if (frame->klass == throwable->getClass()
312           && strcmp (frame->meth->name->chars(), "<init>") == 0)
313         start_idx = i + 1;
314
315       if (frame->klass == &Throwable::class$
316           && strcmp (frame->meth->name->chars(), "fillInStackTrace") == 0)
317         start_idx = i + 1;
318
319       // End the trace at the application's main() method if we see call_main.
320       if (frame->klass == &gnu::java::lang::MainThread::class$
321           && strcmp (frame->meth->name->chars(), "call_main") == 0)
322         end_idx = i - 1;
323     }
324   
325   // Second pass: Look up line-number info for remaining frames.
326   for (int i = start_idx; i <= end_idx; i++)
327     {
328       _Jv_StackFrame *frame = &trace->frames[i];
329       
330       if (frame->klass == NULL)
331         // Not a Java frame.
332         continue;
333       
334       jstring className = frame->klass->getName ();
335       jstring methodName = NULL;
336       if (frame->meth)
337         methodName = JvNewStringUTF (frame->meth->name->chars());
338       
339       jstring sourceFileName = NULL;
340       jint lineNum = -1;
341       
342       getLineNumberForFrame(frame, finder, &sourceFileName, &lineNum);
343       
344       StackTraceElement *element = new StackTraceElement (sourceFileName, lineNum,
345         className, methodName, 0);
346       list->add (element);
347     }
348   
349   finder->close();
350 #endif /* SJLJ_EXCEPTIONS */
351
352   JArray<Object *> *array = JvNewObjectArray (list->size (), 
353     &StackTraceElement::class$, NULL);
354
355   return (JArray<StackTraceElement *>*) list->toArray (array);
356 }
357
358 struct CallingClassTraceData
359 {
360   jclass checkClass;    
361   jclass foundClass;
362   _Jv_Method *foundMeth;
363   bool seen_checkClass;
364 };
365
366 _Unwind_Reason_Code
367 _Jv_StackTrace::calling_class_trace_fn (_Jv_UnwindState *state)
368 {
369   CallingClassTraceData *trace_data = (CallingClassTraceData *)
370     state->trace_data;
371   _Jv_StackFrame *frame = &state->frames[state->pos];
372   FillInFrameInfo (frame);
373
374   if (trace_data->seen_checkClass
375       && frame->klass
376       && frame->klass != trace_data->checkClass)
377     {
378       trace_data->foundClass = frame->klass;
379       trace_data->foundMeth = frame->meth;
380       return _URC_NORMAL_STOP;
381     }
382   
383   if (frame->klass == trace_data->checkClass)
384     trace_data->seen_checkClass = true;
385     
386   return _URC_NO_REASON;
387 }
388
389 // Find the class immediately above the given class on the call stack. Any 
390 // intermediate non-Java 
391 // frames are ignored. If the calling class could not be determined (eg because 
392 // the unwinder is not supported on this platform), NULL is returned.
393 // This function is used to implement calling-classloader checks and reflection
394 // accessibility checks.
395 // CHECKCLASS is typically the class calling GetCallingClass. The first class
396 // above CHECKCLASS on the call stack will be returned.
397 jclass
398 _Jv_StackTrace::GetCallingClass (jclass checkClass)
399 {
400   jclass result = NULL;
401   GetCallerInfo (checkClass, &result, NULL);
402   return result;
403 }
404
405 void
406 _Jv_StackTrace::GetCallerInfo (jclass checkClass, jclass *caller_class,
407   _Jv_Method **caller_meth)
408 {
409 #ifndef SJLJ_EXCEPTIONS
410   int trace_size = 20;
411   _Jv_StackFrame frames[trace_size];
412   _Jv_UnwindState state (trace_size);
413   state.frames = (_Jv_StackFrame *) &frames;
414
415   CallingClassTraceData trace_data;
416   trace_data.checkClass = checkClass;
417   trace_data.seen_checkClass = false;
418   trace_data.foundClass = NULL;
419   trace_data.foundMeth = NULL;
420
421   state.trace_function = calling_class_trace_fn;
422   state.trace_data = (void *) &trace_data;
423
424   //JvSynchronized (ncodeMap);
425   UpdateNCodeMap ();
426
427   _Unwind_Backtrace (UnwindTraceFn, &state);
428   
429   if (caller_class)
430     *caller_class = trace_data.foundClass;
431   if (caller_meth)
432     *caller_meth = trace_data.foundMeth;
433 #else
434   return;
435 #endif
436 }
437
438 // Return a java array containing the Java classes on the stack above CHECKCLASS.
439 JArray<jclass> *
440 _Jv_StackTrace::GetClassContext (jclass checkClass)
441 {
442   JArray<jclass> *result = NULL;
443
444   int trace_size = 100;
445   _Jv_StackFrame frames[trace_size];
446   _Jv_UnwindState state (trace_size);
447   state.frames = (_Jv_StackFrame *) &frames;
448
449   //JvSynchronized (ncodeMap);
450   UpdateNCodeMap ();
451
452   _Unwind_Backtrace (UnwindTraceFn, &state);
453
454   // Count the number of Java frames on the stack.
455   int jframe_count = 0;
456   bool seen_checkClass = false;
457   int start_pos = -1;
458   for (int i = 0; i < state.pos; i++)
459     {
460       _Jv_StackFrame *frame = &state.frames[i];
461       FillInFrameInfo (frame);
462       
463       if (seen_checkClass)
464         {
465           if (frame->klass)
466             {
467               jframe_count++;
468               if (start_pos == -1)
469                 start_pos = i;
470             }
471         }
472       else
473         seen_checkClass = frame->klass == checkClass;
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 #ifdef INTERPRETER
499       if (classLoader != NULL)
500         {
501           state->trace_data = (void *) classLoader;
502           return _URC_NORMAL_STOP;
503         }
504 #endif
505     }
506
507   return _URC_NO_REASON;
508 }
509
510 ClassLoader *
511 _Jv_StackTrace::GetFirstNonSystemClassLoader ()
512 {
513   int trace_size = 32;
514   _Jv_StackFrame frames[trace_size];
515   _Jv_UnwindState state (trace_size);
516   state.frames = (_Jv_StackFrame *) &frames;
517   state.trace_function = non_system_trace_fn;
518   state.trace_data = NULL;
519
520   //JvSynchronized (ncodeMap);
521   UpdateNCodeMap ();
522   
523   _Unwind_Backtrace (UnwindTraceFn, &state);
524
525   if (state.trace_data)
526     return (ClassLoader *) state.trace_data;
527   
528   return NULL;
529 }