OSDN Git Service

* java/io/natFilePosix.cc (getCanonicalPath): Rewritten.
[pf3gnuchains/gcc-fork.git] / libjava / stacktrace.cc
1 // stacktrace.cc - Functions for unwinding & inspecting the call stack.
2
3 /* Copyright (C) 2005, 2006  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     if (!_Jv_IsInterpretedClass (klass))
59       {
60         //printf ("got %s\n", klass->name->data);
61         for (int i = 0; i < klass->method_count; i++)
62           {
63             _Jv_Method *method = &klass->methods[i];
64             void *ncode = method->ncode;
65             // Add non-abstract methods to ncodeMap.
66             if (ncode)
67               {
68                 ncode = UNWRAP_FUNCTION_DESCRIPTOR (ncode);
69                 ncodeMap->put ((java::lang::Object *) ncode, klass);
70               }
71           }
72       }
73 }
74
75 // Given a native frame, return the class which this code belongs 
76 // to. Returns NULL if this IP is not associated with a native Java class.
77 // If NCODE is supplied, it will be set with the ip for the entry point of the 
78 // enclosing method.
79 jclass
80 _Jv_StackTrace::ClassForFrame (_Jv_StackFrame *frame)
81 {
82   JvAssert (frame->type == frame_native);
83   jclass klass = NULL;
84   // use _Unwind_FindEnclosingFunction to find start of method
85   //void *entryPoint = _Unwind_FindEnclosingFunction (ip);
86
87   // look it up in ncodeMap
88   if (frame->start_ip)
89     klass = (jclass) ncodeMap->get ((jobject) frame->start_ip);
90
91   return klass;
92 }
93
94 _Unwind_Reason_Code
95 _Jv_StackTrace::UnwindTraceFn (struct _Unwind_Context *context, void *state_ptr)
96 {
97   _Jv_UnwindState *state = (_Jv_UnwindState *) state_ptr;
98   jint pos = state->pos;
99
100   // Check if the trace buffer needs to be extended.
101   if (pos == state->length)
102     {
103       int newLength = state->length * 2;
104       void *newFrames = _Jv_AllocBytes (newLength * sizeof(_Jv_StackFrame));
105       memcpy (newFrames, state->frames, state->length * sizeof(_Jv_StackFrame));      
106       state->frames = (_Jv_StackFrame *) newFrames;
107       state->length = newLength;
108     }
109
110   void *func_addr = (void *) _Unwind_GetRegionStart (context);
111
112   // If we see the interpreter's main function, "pop" an entry off the 
113   // interpreter stack and use that instead, so that the trace goes through 
114   // the java code and not the interpreter itself. This assumes a 1:1 
115   // correspondance between call frames in the interpreted stack and occurances
116   // of _Jv_InterpMethod::run() on the native stack.
117 #ifdef INTERPRETER
118   void *interp_run = (void *) &_Jv_InterpMethod::run;
119   if (func_addr == UNWRAP_FUNCTION_DESCRIPTOR (interp_run))
120     {
121       state->frames[pos].type = frame_interpreter;
122       state->frames[pos].interp.meth = state->interp_frame->self;
123       state->frames[pos].interp.pc = state->interp_frame->pc;
124       state->interp_frame = state->interp_frame->next;
125     }
126   else
127 #endif
128     {
129       state->frames[pos].type = frame_native;
130       state->frames[pos].ip = (void *) _Unwind_GetIP (context);
131       state->frames[pos].start_ip = func_addr;
132     }
133
134   //printf ("unwind ip: %p\n", _Unwind_GetIP (context));
135
136   _Unwind_Reason_Code result = _URC_NO_REASON;
137   if (state->trace_function != NULL)
138     result = (state->trace_function) (state);
139   state->pos++;
140   return result;
141 }
142
143 // Return a raw stack trace from the current point of execution. The raw 
144 // trace will include all functions that have unwind info.
145 _Jv_StackTrace *
146 _Jv_StackTrace::GetStackTrace(void)
147 {
148   int trace_size = 100;
149   _Jv_StackFrame frames[trace_size];
150   _Jv_UnwindState state (trace_size);
151   state.frames = (_Jv_StackFrame *) &frames;
152
153 #ifdef SJLJ_EXCEPTIONS
154   // The Unwind interface doesn't work with the SJLJ exception model.
155   // Fall back to a platform-specific unwinder.
156   fallback_backtrace (&state);
157 #else /* SJLJ_EXCEPTIONS */  
158   _Unwind_Backtrace (UnwindTraceFn, &state);
159 #endif /* SJLJ_EXCEPTIONS */
160   
161   // Copy the trace and return it.
162   int traceSize = sizeof (_Jv_StackTrace) + 
163     (sizeof (_Jv_StackFrame) * state.pos);
164   _Jv_StackTrace *trace = (_Jv_StackTrace *) _Jv_AllocBytes (traceSize);
165   trace->length = state.pos;
166   memcpy (trace->frames, state.frames, sizeof (_Jv_StackFrame) * state.pos);  
167   return trace;
168 }
169
170 void
171 _Jv_StackTrace::getLineNumberForFrame(_Jv_StackFrame *frame, NameFinder *finder, 
172                                       jstring *sourceFileName, jint *lineNum,
173                                       jstring *methodName)
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       if (*methodName == NULL && info.dli_sname)
203         *methodName = JvNewStringUTF (info.dli_sname);
204
205       // addr2line expects relative addresses for shared libraries.
206       if (strcmp (info.dli_fname, argv0) == 0)
207         offset = (_Unwind_Ptr) ip;
208       else
209         offset = (_Unwind_Ptr) ip - (_Unwind_Ptr) info.dli_fbase;
210
211       //printf ("linenum ip: %p\n", ip);
212       //printf ("%s: 0x%x\n", info.dli_fname, offset);
213       //offset -= sizeof(void *);
214       
215       // The unwinder gives us the return address. In order to get the right
216       // line number for the stack trace, roll it back a little.
217       offset -= 1;
218
219       // printf ("%s: 0x%x\n", info.dli_fname, offset);
220       
221       finder->lookup (binaryName, (jlong) offset);
222       *sourceFileName = finder->getSourceFile();
223       *lineNum = finder->getLineNum();
224     }
225 #endif
226 }
227
228 // Look up class and method info for the given stack frame, setting 
229 // frame->klass and frame->meth if they are known.
230 void
231 _Jv_StackTrace::FillInFrameInfo (_Jv_StackFrame *frame)
232 {
233   jclass klass = NULL;
234   _Jv_Method *meth = NULL;
235   
236   if (frame->type == frame_native)
237     {
238       klass = _Jv_StackTrace::ClassForFrame (frame);
239
240       if (klass != NULL)
241         // Find method in class
242         for (int j = 0; j < klass->method_count; j++)
243           {
244             void *wncode = UNWRAP_FUNCTION_DESCRIPTOR (klass->methods[j].ncode);
245             if (wncode == 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   const jboolean remove_unknown 
330     = gnu::gcj::runtime::NameFinder::removeUnknown();
331
332   // Second pass: Look up line-number info for remaining frames.
333   for (int i = start_idx; i <= end_idx; i++)
334     {
335       _Jv_StackFrame *frame = &trace->frames[i];
336       
337       if (frame->klass == NULL && remove_unknown)
338         // Not a Java frame.
339         continue;
340
341       jstring className = NULL;
342       if (frame->klass != NULL)
343         className = frame->klass->getName ();
344
345       jstring methodName = NULL;
346       if (frame->meth)
347         methodName = JvNewStringUTF (frame->meth->name->chars());
348       
349       jstring sourceFileName = NULL;
350       jint lineNum = -1;
351       
352       getLineNumberForFrame(frame, finder, &sourceFileName, &lineNum, 
353                             &methodName);
354       
355       StackTraceElement *element = new StackTraceElement (sourceFileName, lineNum,
356         className, methodName, 0);
357       list->add (element);
358     }
359   
360   finder->close();
361 #endif /* SJLJ_EXCEPTIONS */
362
363   JArray<Object *> *array = JvNewObjectArray (list->size (), 
364     &StackTraceElement::class$, NULL);
365
366   return (JArray<StackTraceElement *>*) list->toArray (array);
367 }
368
369 struct CallingClassTraceData
370 {
371   jclass checkClass;    
372   jclass foundClass;
373   _Jv_Method *foundMeth;
374   bool seen_checkClass;
375 };
376
377 _Unwind_Reason_Code
378 _Jv_StackTrace::calling_class_trace_fn (_Jv_UnwindState *state)
379 {
380   CallingClassTraceData *trace_data = (CallingClassTraceData *)
381     state->trace_data;
382   _Jv_StackFrame *frame = &state->frames[state->pos];
383   FillInFrameInfo (frame);
384
385   if (trace_data->seen_checkClass
386       && frame->klass
387       && frame->klass != trace_data->checkClass)
388     {
389       trace_data->foundClass = frame->klass;
390       trace_data->foundMeth = frame->meth;
391       return _URC_NORMAL_STOP;
392     }
393   
394   if (frame->klass == trace_data->checkClass)
395     trace_data->seen_checkClass = true;
396     
397   return _URC_NO_REASON;
398 }
399
400 // Find the class immediately above the given class on the call stack. Any 
401 // intermediate non-Java 
402 // frames are ignored. If the calling class could not be determined (eg because 
403 // the unwinder is not supported on this platform), NULL is returned.
404 // This function is used to implement calling-classloader checks and reflection
405 // accessibility checks.
406 // CHECKCLASS is typically the class calling GetCallingClass. The first class
407 // above CHECKCLASS on the call stack will be returned.
408 jclass
409 _Jv_StackTrace::GetCallingClass (jclass checkClass)
410 {
411   jclass result = NULL;
412   GetCallerInfo (checkClass, &result, NULL);
413   return result;
414 }
415
416 void
417 _Jv_StackTrace::GetCallerInfo (jclass checkClass, jclass *caller_class,
418   _Jv_Method **caller_meth)
419 {
420 #ifndef SJLJ_EXCEPTIONS
421   int trace_size = 20;
422   _Jv_StackFrame frames[trace_size];
423   _Jv_UnwindState state (trace_size);
424   state.frames = (_Jv_StackFrame *) &frames;
425
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;
431
432   state.trace_function = calling_class_trace_fn;
433   state.trace_data = (void *) &trace_data;
434
435   //JvSynchronized (ncodeMap);
436   UpdateNCodeMap ();
437
438   _Unwind_Backtrace (UnwindTraceFn, &state);
439   
440   if (caller_class)
441     *caller_class = trace_data.foundClass;
442   if (caller_meth)
443     *caller_meth = trace_data.foundMeth;
444 #else
445   return;
446 #endif
447 }
448
449 // Return a java array containing the Java classes on the stack above CHECKCLASS.
450 JArray<jclass> *
451 _Jv_StackTrace::GetClassContext (jclass checkClass)
452 {
453   JArray<jclass> *result = NULL;
454
455   int trace_size = 100;
456   _Jv_StackFrame frames[trace_size];
457   _Jv_UnwindState state (trace_size);
458   state.frames = (_Jv_StackFrame *) &frames;
459
460   //JvSynchronized (ncodeMap);
461   UpdateNCodeMap ();
462
463   _Unwind_Backtrace (UnwindTraceFn, &state);
464
465   // Count the number of Java frames on the stack.
466   int jframe_count = 0;
467   bool seen_checkClass = false;
468   int start_pos = -1;
469   for (int i = 0; i < state.pos; i++)
470     {
471       _Jv_StackFrame *frame = &state.frames[i];
472       FillInFrameInfo (frame);
473       
474       if (seen_checkClass)
475         {
476           if (frame->klass)
477             {
478               jframe_count++;
479               if (start_pos == -1)
480                 start_pos = i;
481             }
482         }
483       else
484         seen_checkClass = frame->klass == checkClass;
485     }
486   result = (JArray<jclass> *) _Jv_NewObjectArray (jframe_count, &Class::class$, NULL);
487   int pos = 0;
488   
489   for (int i = start_pos; i < state.pos; i++)
490     {
491       _Jv_StackFrame *frame = &state.frames[i];
492       if (frame->klass)
493         elements(result)[pos++] = frame->klass;
494     }
495   return result;
496 }
497
498 _Unwind_Reason_Code
499 _Jv_StackTrace::non_system_trace_fn (_Jv_UnwindState *state)
500 {
501   _Jv_StackFrame *frame = &state->frames[state->pos];
502   FillInFrameInfo (frame);
503   
504   ClassLoader *classLoader = NULL;
505
506   if (frame->klass)
507     {
508       classLoader = frame->klass->getClassLoaderInternal();
509 #ifdef INTERPRETER
510       if (classLoader != NULL)
511         {
512           state->trace_data = (void *) classLoader;
513           return _URC_NORMAL_STOP;
514         }
515 #endif
516     }
517
518   return _URC_NO_REASON;
519 }
520
521 ClassLoader *
522 _Jv_StackTrace::GetFirstNonSystemClassLoader ()
523 {
524   int trace_size = 32;
525   _Jv_StackFrame frames[trace_size];
526   _Jv_UnwindState state (trace_size);
527   state.frames = (_Jv_StackFrame *) &frames;
528   state.trace_function = non_system_trace_fn;
529   state.trace_data = NULL;
530
531   //JvSynchronized (ncodeMap);
532   UpdateNCodeMap ();
533   
534   _Unwind_Backtrace (UnwindTraceFn, &state);
535
536   if (state.trace_data)
537     return (ClassLoader *) state.trace_data;
538   
539   return NULL;
540 }