OSDN Git Service

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