OSDN Git Service

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