OSDN Git Service

* doc/invoke.texi (Invoking G++): Clarify prose for g++.
[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 #include <platform.h>
13
14 #include <jvm.h>
15 #include <gcj/cni.h>
16 #include <java-interp.h>
17 #include <java-stack.h>
18
19 #include <stdio.h>
20
21 #include <java/lang/Class.h>
22 #include <java/lang/Long.h>
23 #include <java/util/ArrayList.h>
24 #include <java/util/IdentityHashMap.h>
25 #include <gnu/java/lang/MainThread.h>
26 #include <gnu/gcj/runtime/NameFinder.h>
27 #include <gnu/gcj/runtime/StringBuffer.h>
28
29 #include <sysdep/backtrace.h>
30 #include <sysdep/descriptor.h>
31
32 using namespace java::lang;
33 using namespace java::lang::reflect;
34 using namespace java::util;
35 using namespace gnu::gcj::runtime;
36
37 // Maps ncode values to their containing native class.
38 // NOTE: Currently this Map contradicts class GC for native classes. This map
39 // (and the "new class stack") will need to use WeakReferences in order to 
40 // enable native class GC.
41 static java::util::IdentityHashMap *ncodeMap;
42
43 // Check the "class stack" for any classes initialized since we were last 
44 // called, and add them to ncodeMap.
45 void 
46 _Jv_StackTrace::UpdateNCodeMap ()
47 {
48   // The Map should be large enough so that a typical Java app doesn't cause 
49   // it to rehash, without using too much memory. ~5000 entries should be 
50   // enough.
51   if (ncodeMap == NULL)
52     ncodeMap = new java::util::IdentityHashMap (5087);
53   
54   jclass klass;
55   while ((klass = _Jv_PopClass ()))
56     if (!_Jv_IsInterpretedClass (klass))
57       {
58         //printf ("got %s\n", klass->name->data);
59         for (int i = 0; i < klass->method_count; i++)
60           {
61             _Jv_Method *method = &klass->methods[i];
62             void *ncode = method->ncode;
63             // Add non-abstract methods to ncodeMap.
64             if (ncode)
65               {
66                 ncode = UNWRAP_FUNCTION_DESCRIPTOR (ncode);
67                 ncodeMap->put ((java::lang::Object *) ncode, klass);
68               }
69           }
70       }
71 }
72
73 // Given a native frame, return the class which this code belongs 
74 // to. Returns NULL if this IP is not associated with a native Java class.
75 // If NCODE is supplied, it will be set with the ip for the entry point of the 
76 // enclosing method.
77 jclass
78 _Jv_StackTrace::ClassForFrame (_Jv_StackFrame *frame)
79 {
80   JvAssert (frame->type == frame_native);
81   jclass klass = NULL;
82   // use _Unwind_FindEnclosingFunction to find start of method
83   //void *entryPoint = _Unwind_FindEnclosingFunction (ip);
84
85   // look it up in ncodeMap
86   if (frame->start_ip)
87     klass = (jclass) ncodeMap->get ((jobject) frame->start_ip);
88
89   return klass;
90 }
91
92 _Unwind_Reason_Code
93 _Jv_StackTrace::UnwindTraceFn (struct _Unwind_Context *context, void *state_ptr)
94 {
95   _Jv_UnwindState *state = (_Jv_UnwindState *) state_ptr;
96   jint pos = state->pos;
97
98   // Check if the trace buffer needs to be extended.
99   if (pos == state->length)
100     {
101       int newLength = state->length * 2;
102       void *newFrames = _Jv_AllocBytes (newLength * sizeof(_Jv_StackFrame));
103       memcpy (newFrames, state->frames, state->length * sizeof(_Jv_StackFrame));      
104       state->frames = (_Jv_StackFrame *) newFrames;
105       state->length = newLength;
106     }
107
108   void *func_addr = (void *) _Unwind_GetRegionStart (context);
109
110   // If we see the interpreter's main function, "pop" an entry off the 
111   // interpreter stack and use that instead, so that the trace goes through 
112   // the java code and not the interpreter itself. This assumes a 1:1 
113   // correspondance between call frames in the interpreted stack and occurances
114   // of _Jv_InterpMethod::run() on the native stack.
115 #ifdef INTERPRETER
116   void *interp_run = (void *) &_Jv_InterpMethod::run;
117   if (func_addr == UNWRAP_FUNCTION_DESCRIPTOR (interp_run))
118     {
119       state->frames[pos].type = frame_interpreter;
120       state->frames[pos].interp.meth = state->interp_frame->self;
121       state->frames[pos].interp.pc = state->interp_frame->pc;
122       state->interp_frame = state->interp_frame->next;
123     }
124   else
125 #endif
126     {
127       state->frames[pos].type = frame_native;
128       state->frames[pos].ip = (void *) _Unwind_GetIP (context);
129       state->frames[pos].start_ip = func_addr;
130     }
131
132   //printf ("unwind ip: %p\n", _Unwind_GetIP (context));
133
134   _Unwind_Reason_Code result = _URC_NO_REASON;
135   if (state->trace_function != NULL)
136     result = (state->trace_function) (state);
137   state->pos++;
138   return result;
139 }
140
141 // Return a raw stack trace from the current point of execution. The raw 
142 // trace will include all functions that have unwind info.
143 _Jv_StackTrace *
144 _Jv_StackTrace::GetStackTrace(void)
145 {
146   int trace_size = 100;
147   _Jv_StackFrame frames[trace_size];
148   _Jv_UnwindState state (trace_size);
149   state.frames = (_Jv_StackFrame *) &frames;
150
151 #ifdef SJLJ_EXCEPTIONS
152   // The Unwind interface doesn't work with the SJLJ exception model.
153   // Fall back to a platform-specific unwinder.
154   fallback_backtrace (&state);
155 #else /* SJLJ_EXCEPTIONS */  
156   _Unwind_Backtrace (UnwindTraceFn, &state);
157 #endif /* SJLJ_EXCEPTIONS */
158   
159   // Copy the trace and return it.
160   int traceSize = sizeof (_Jv_StackTrace) + 
161     (sizeof (_Jv_StackFrame) * state.pos);
162   _Jv_StackTrace *trace = (_Jv_StackTrace *) _Jv_AllocBytes (traceSize);
163   trace->length = state.pos;
164   memcpy (trace->frames, state.frames, sizeof (_Jv_StackFrame) * state.pos);  
165   return trace;
166 }
167
168 void
169 _Jv_StackTrace::getLineNumberForFrame(_Jv_StackFrame *frame, NameFinder *finder, 
170                                       jstring *sourceFileName, jint *lineNum,
171                                       jstring *methodName)
172 {
173 #ifdef INTERPRETER
174   if (frame->type == frame_interpreter)
175     {
176       _Jv_InterpMethod *interp_meth = frame->interp.meth;
177       _Jv_InterpClass *interp_class = 
178          (_Jv_InterpClass *) interp_meth->defining_class->aux_info;
179       *sourceFileName = interp_class->source_file_name;
180       *lineNum = interp_meth->get_source_line(frame->interp.pc);
181       return;
182     }
183 #endif
184
185   // Use _Jv_platform_dladdr() to determine in which binary the address IP
186   // resides.
187   _Jv_AddrInfo info;
188   jstring binaryName = NULL;
189   const char *argv0 = _Jv_GetSafeArg(0);
190
191   void *ip = frame->ip;
192   _Unwind_Ptr offset = 0;
193
194   if (_Jv_platform_dladdr (ip, &info))
195     {
196       if (info.file_name)
197         binaryName = JvNewStringUTF (info.file_name);
198       else
199         return;
200
201       if (*methodName == NULL && info.sym_name)
202         *methodName = JvNewStringUTF (info.sym_name);
203
204       // addr2line expects relative addresses for shared libraries.
205       if (strcmp (info.file_name, argv0) == 0)
206         offset = (_Unwind_Ptr) ip;
207       else
208         offset = (_Unwind_Ptr) ip - (_Unwind_Ptr) info.base;
209
210       // The unwinder gives us the return address. In order to get the right
211       // line number for the stack trace, roll it back a little.
212       offset -= 1;
213
214       finder->lookup (binaryName, (jlong) offset);
215       *sourceFileName = finder->getSourceFile();
216       *lineNum = finder->getLineNum();
217       if (*lineNum == -1 && NameFinder::showRaw())
218         {
219           gnu::gcj::runtime::StringBuffer *t =
220             new gnu::gcj::runtime::StringBuffer(binaryName);
221           t->append ((jchar)' ');
222           t->append ((jchar)'[');
223           // + 1 to compensate for the - 1 adjustment above;
224           t->append (Long::toHexString (offset + 1));
225           t->append ((jchar)']');
226           *sourceFileName = t->toString();
227         }
228     }
229 }
230
231 // Look up class and method info for the given stack frame, setting 
232 // frame->klass and frame->meth if they are known.
233 void
234 _Jv_StackTrace::FillInFrameInfo (_Jv_StackFrame *frame)
235 {
236   jclass klass = NULL;
237   _Jv_Method *meth = NULL;
238   
239   if (frame->type == frame_native)
240     {
241       klass = _Jv_StackTrace::ClassForFrame (frame);
242
243       if (klass != NULL)
244         // Find method in class
245         for (int j = 0; j < klass->method_count; j++)
246           {
247             void *wncode = UNWRAP_FUNCTION_DESCRIPTOR (klass->methods[j].ncode);
248             if (wncode == frame->start_ip)
249               {
250                 meth = &klass->methods[j];
251                 break;
252               }
253           }
254     }
255 #ifdef INTERPRETER
256   else if (frame->type == frame_interpreter)
257     {
258       _Jv_InterpMethod *interp_meth = frame->interp.meth;
259       klass = interp_meth->defining_class;
260       meth = interp_meth->self;
261     }
262 #endif
263   else
264     JvFail ("Unknown frame type");
265   
266   frame->klass = klass;
267   frame->meth = meth;
268 }
269
270 // Convert raw stack frames to a Java array of StackTraceElement objects.
271 JArray< ::java::lang::StackTraceElement *>*
272 _Jv_StackTrace::GetStackTraceElements (_Jv_StackTrace *trace, 
273   Throwable *throwable __attribute__((unused)))
274 {
275   ArrayList *list = new ArrayList ();
276
277 #if defined (SJLJ_EXCEPTIONS) && ! defined (WIN32)
278   // We can't use the nCodeMap without unwinder support. Instead,
279   // fake the method name by giving the IP in hex - better than nothing.  
280   jstring hex = JvNewStringUTF ("0x");
281
282   for (int i = 0; i < trace->length; i++)
283     {
284       jstring sourceFileName = NULL;
285       jint lineNum = -1;
286       _Jv_StackFrame *frame = &trace->frames[i];
287       
288       jstring className = NULL;
289       jstring methodName = hex->concat (Long::toHexString ((jlong) frame->ip));
290
291       StackTraceElement *element = new StackTraceElement (sourceFileName, 
292         lineNum, className, methodName, 0);    
293       list->add (element);
294     }
295
296 #else /* SJLJ_EXCEPTIONS && !WIN32 */
297
298   //JvSynchronized (ncodeMap);
299   UpdateNCodeMap ();
300
301   NameFinder *finder = new NameFinder();
302   int start_idx = 0;
303   int end_idx = trace->length - 1;
304
305   // First pass: strip superfluous frames from beginning and end of the trace.  
306   for (int i = 0; i < trace->length; i++)
307     {
308       _Jv_StackFrame *frame = &trace->frames[i];
309       FillInFrameInfo (frame);
310
311       if (!frame->klass || !frame->meth)
312         // Not a Java frame.
313         continue;
314
315       // Throw away the top of the stack till we see:
316       //  - the constructor(s) of this Throwable, or
317       //  - the Throwable.fillInStackTrace call.
318       if (frame->klass == throwable->getClass()
319           && strcmp (frame->meth->name->chars(), "<init>") == 0)
320         start_idx = i + 1;
321
322       if (frame->klass == &Throwable::class$
323           && strcmp (frame->meth->name->chars(), "fillInStackTrace") == 0)
324         start_idx = i + 1;
325
326       // End the trace at the application's main() method if we see call_main.
327       if (frame->klass == &gnu::java::lang::MainThread::class$
328           && strcmp (frame->meth->name->chars(), "call_main") == 0)
329         end_idx = i - 1;
330     }
331   
332   const jboolean remove_unknown 
333     = gnu::gcj::runtime::NameFinder::removeUnknown();
334
335   // Second pass: Look up line-number info for remaining frames.
336   for (int i = start_idx; i <= end_idx; i++)
337     {
338       _Jv_StackFrame *frame = &trace->frames[i];
339       
340       if (frame->klass == NULL && remove_unknown)
341         // Not a Java frame.
342         continue;
343
344       jstring className = NULL;
345       if (frame->klass != NULL)
346         className = frame->klass->getName ();
347
348       jstring methodName = NULL;
349       if (frame->meth)
350         methodName = JvNewStringUTF (frame->meth->name->chars());
351       
352       jstring sourceFileName = NULL;
353       jint lineNum = -1;
354       
355       getLineNumberForFrame(frame, finder, &sourceFileName, &lineNum, 
356                             &methodName);
357       
358       StackTraceElement *element = new StackTraceElement (sourceFileName, lineNum,
359         className, methodName, 0);
360       list->add (element);
361     }
362   
363   finder->close();
364 #endif /* SJLJ_EXCEPTIONS && !WIN32 */
365
366   JArray<Object *> *array = JvNewObjectArray (list->size (), 
367     &StackTraceElement::class$, NULL);
368
369   return (JArray<StackTraceElement *>*) list->toArray (array);
370 }
371
372 struct CallingClassTraceData
373 {
374   jclass checkClass;    
375   jclass foundClass;
376   _Jv_Method *foundMeth;
377   bool seen_checkClass;
378 };
379
380 _Unwind_Reason_Code
381 _Jv_StackTrace::calling_class_trace_fn (_Jv_UnwindState *state)
382 {
383   CallingClassTraceData *trace_data = (CallingClassTraceData *)
384     state->trace_data;
385   _Jv_StackFrame *frame = &state->frames[state->pos];
386   FillInFrameInfo (frame);
387
388   if (trace_data->seen_checkClass
389       && frame->klass
390       && frame->klass != trace_data->checkClass)
391     {
392       trace_data->foundClass = frame->klass;
393       trace_data->foundMeth = frame->meth;
394       return _URC_NORMAL_STOP;
395     }
396   
397   if (frame->klass == trace_data->checkClass)
398     trace_data->seen_checkClass = true;
399     
400   return _URC_NO_REASON;
401 }
402
403 // Find the class immediately above the given class on the call stack. Any 
404 // intermediate non-Java 
405 // frames are ignored. If the calling class could not be determined (eg because 
406 // the unwinder is not supported on this platform), NULL is returned.
407 // This function is used to implement calling-classloader checks and reflection
408 // accessibility checks.
409 // CHECKCLASS is typically the class calling GetCallingClass. The first class
410 // above CHECKCLASS on the call stack will be returned.
411 jclass
412 _Jv_StackTrace::GetCallingClass (jclass checkClass)
413 {
414   jclass result = NULL;
415   GetCallerInfo (checkClass, &result, NULL);
416   return result;
417 }
418
419 void
420 _Jv_StackTrace::GetCallerInfo (jclass checkClass, jclass *caller_class,
421   _Jv_Method **caller_meth)
422 {
423 #ifndef SJLJ_EXCEPTIONS
424   int trace_size = 20;
425   _Jv_StackFrame frames[trace_size];
426   _Jv_UnwindState state (trace_size);
427   state.frames = (_Jv_StackFrame *) &frames;
428
429   CallingClassTraceData trace_data;
430   trace_data.checkClass = checkClass;
431   trace_data.seen_checkClass = false;
432   trace_data.foundClass = NULL;
433   trace_data.foundMeth = NULL;
434
435   state.trace_function = calling_class_trace_fn;
436   state.trace_data = (void *) &trace_data;
437
438   //JvSynchronized (ncodeMap);
439   UpdateNCodeMap ();
440
441   _Unwind_Backtrace (UnwindTraceFn, &state);
442   
443   if (caller_class)
444     *caller_class = trace_data.foundClass;
445   if (caller_meth)
446     *caller_meth = trace_data.foundMeth;
447 #else
448   return;
449 #endif
450 }
451
452 // Return a java array containing the Java classes on the stack above CHECKCLASS.
453 JArray<jclass> *
454 _Jv_StackTrace::GetClassContext (jclass checkClass)
455 {
456   JArray<jclass> *result = NULL;
457
458   int trace_size = 100;
459   _Jv_StackFrame frames[trace_size];
460   _Jv_UnwindState state (trace_size);
461   state.frames = (_Jv_StackFrame *) &frames;
462
463   //JvSynchronized (ncodeMap);
464   UpdateNCodeMap ();
465
466 #ifdef SJLJ_EXCEPTIONS
467   // The Unwind interface doesn't work with the SJLJ exception model.
468   // Fall back to a platform-specific unwinder.
469   fallback_backtrace (&state);
470 #else /* SJLJ_EXCEPTIONS */  
471   _Unwind_Backtrace (UnwindTraceFn, &state);
472 #endif /* SJLJ_EXCEPTIONS */  
473
474   // Count the number of Java frames on the stack.
475   int jframe_count = 0;
476   bool seen_checkClass = false;
477   int start_pos = -1;
478   for (int i = 0; i < state.pos; i++)
479     {
480       _Jv_StackFrame *frame = &state.frames[i];
481       FillInFrameInfo (frame);
482       
483       if (seen_checkClass)
484         {
485           if (frame->klass)
486             {
487               jframe_count++;
488               if (start_pos == -1)
489                 start_pos = i;
490             }
491         }
492       else
493         seen_checkClass = frame->klass == checkClass;
494     }
495   result = (JArray<jclass> *) _Jv_NewObjectArray (jframe_count, &Class::class$, NULL);
496   int pos = 0;
497   
498   for (int i = start_pos; i < state.pos; i++)
499     {
500       _Jv_StackFrame *frame = &state.frames[i];
501       if (frame->klass)
502         elements(result)[pos++] = frame->klass;
503     }
504   return result;
505 }
506
507 _Unwind_Reason_Code
508 _Jv_StackTrace::non_system_trace_fn (_Jv_UnwindState *state)
509 {
510   _Jv_StackFrame *frame = &state->frames[state->pos];
511   FillInFrameInfo (frame);
512   
513   ClassLoader *classLoader = NULL;
514
515   if (frame->klass)
516     {
517       classLoader = frame->klass->getClassLoaderInternal();
518 #ifdef INTERPRETER
519       if (classLoader != NULL)
520         {
521           state->trace_data = (void *) classLoader;
522           return _URC_NORMAL_STOP;
523         }
524 #endif
525     }
526
527   return _URC_NO_REASON;
528 }
529
530 ClassLoader *
531 _Jv_StackTrace::GetFirstNonSystemClassLoader ()
532 {
533   int trace_size = 32;
534   _Jv_StackFrame frames[trace_size];
535   _Jv_UnwindState state (trace_size);
536   state.frames = (_Jv_StackFrame *) &frames;
537   state.trace_function = non_system_trace_fn;
538   state.trace_data = NULL;
539
540   //JvSynchronized (ncodeMap);
541   UpdateNCodeMap ();
542   
543 #ifdef SJLJ_EXCEPTIONS
544   // The Unwind interface doesn't work with the SJLJ exception model.
545   // Fall back to a platform-specific unwinder.
546   fallback_backtrace (&state);
547 #else /* SJLJ_EXCEPTIONS */  
548   _Unwind_Backtrace (UnwindTraceFn, &state);
549 #endif /* SJLJ_EXCEPTIONS */  
550
551   if (state.trace_data)
552     return (ClassLoader *) state.trace_data;
553   
554   return NULL;
555 }