OSDN Git Service

2011-07-12 Andrew Haley <aph@redhat.com>
[pf3gnuchains/gcc-fork.git] / libjava / exception.cc
1 // Functions for Exception Support for Java.
2
3 /* Copyright (C) 1998, 1999, 2001, 2002, 2006, 2010  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 <stddef.h>
14 #include <stdlib.h>
15
16 #include <java/lang/Class.h>
17 #include <java/lang/NullPointerException.h>
18 #include <gnu/gcj/RawData.h> 
19 #include <gcj/cni.h>
20 #include <jvm.h>
21
22 // unwind-pe.h uses std::abort(), but sometimes we compile libjava
23 // without libstdc++-v3. The following hack forces it to use
24 // stdlib.h's abort().
25 namespace std
26 {
27   static __attribute__ ((__noreturn__)) void
28   abort ()
29   {
30     ::abort ();
31   }
32 }
33 #include "unwind.h"
34
35 struct alignment_test_struct
36 {
37   char space;
38   char end[0] __attribute__((aligned));
39 };
40
41 struct java_exception_header
42 {
43   /* Cache handler details between Phase 1 and Phase 2.  */
44   _Unwind_Ptr landingPad;
45   int handlerSwitchValue;
46
47   /* The object being thrown.  Compiled code expects this to be immediately
48      before the generic exception header.  Which is complicated by the fact
49      that _Unwind_Exception is ((aligned)).  */
50
51   char pad[sizeof(jthrowable) < sizeof(alignment_test_struct)
52            ? sizeof(alignment_test_struct) - sizeof(jthrowable) : 0]
53     __attribute__((aligned));
54
55   jthrowable value;
56
57   /* The generic exception header.  */
58   _Unwind_Exception unwindHeader;
59 };
60
61 #ifdef __ARM_EABI_UNWINDER__
62 // This is the exception class we report -- "GNUCJAVA".
63
64 const _Unwind_Exception_Class __gcj_exception_class
65   = {'G', 'N', 'U', 'C', 'J', 'A', 'V', 'A'};
66
67 static inline java_exception_header *
68 get_exception_header_from_ue (_Unwind_Exception *exc)
69 {
70   return reinterpret_cast<java_exception_header *>(exc + 1) - 1;
71 }
72
73 extern "C" void __cxa_begin_cleanup (_Unwind_Exception*);
74
75 #else // !__ARM_EABI_UNWINDER__
76 // This is the exception class we report -- "GNUCJAVA".
77 const _Unwind_Exception_Class __gcj_exception_class
78 = ((((((((_Unwind_Exception_Class) 'G' 
79          << 8 | (_Unwind_Exception_Class) 'N')
80         << 8 | (_Unwind_Exception_Class) 'U')
81        << 8 | (_Unwind_Exception_Class) 'C')
82       << 8 | (_Unwind_Exception_Class) 'J')
83      << 8 | (_Unwind_Exception_Class) 'A')
84     << 8 | (_Unwind_Exception_Class) 'V')
85    << 8 | (_Unwind_Exception_Class) 'A');
86
87
88 static inline java_exception_header *
89 get_exception_header_from_ue (_Unwind_Exception *exc)
90 {
91   return reinterpret_cast<java_exception_header *>(exc + 1) - 1;
92 }
93 #endif // !__ARM_EABI_UNWINDER__
94
95 /* Perform a throw, Java style. Throw will unwind through this call,
96    so there better not be any handlers or exception thrown here. */
97
98 extern "C" void
99 _Jv_Throw (jthrowable value)
100 {
101   java_exception_header *xh
102     = static_cast<java_exception_header *>(_Jv_AllocRawObj (sizeof (*xh)));
103
104   if (value == NULL)
105     value = new java::lang::NullPointerException ();
106   xh->value = value;
107
108   memcpy (&xh->unwindHeader.exception_class, &__gcj_exception_class,
109           sizeof xh->unwindHeader.exception_class);
110   xh->unwindHeader.exception_cleanup = NULL;
111
112   /* We're happy with setjmp/longjmp exceptions or region-based
113      exception handlers: entry points are provided here for both.  */
114 #ifdef SJLJ_EXCEPTIONS
115   _Unwind_SjLj_RaiseException (&xh->unwindHeader);
116 #else
117   _Unwind_RaiseException (&xh->unwindHeader);
118 #endif
119
120   /* If code == _URC_END_OF_STACK, then we reached top of stack without
121      finding a handler for the exception.  Since each thread is run in
122      a try/catch, this oughtn't happen.  If code is something else, we
123      encountered some sort of heinous lossage from which we could not
124      recover.  As is the way of such things, almost certainly we will have
125      crashed before now, rather than actually being able to diagnose the
126      problem.  */
127   abort();
128 }
129
130 \f
131 #include "unwind-pe.h"
132 \f
133 struct lsda_header_info
134 {
135   _Unwind_Ptr Start;
136   _Unwind_Ptr LPStart;
137   const unsigned char *TType;
138   const unsigned char *action_table;
139   unsigned char ttype_encoding;
140   unsigned char call_site_encoding;
141 };
142
143 static const unsigned char *
144 parse_lsda_header (_Unwind_Context *context, const unsigned char *p,
145                    lsda_header_info *info)
146 {
147   _uleb128_t tmp;
148   unsigned char lpstart_encoding;
149
150   info->Start = (context ? _Unwind_GetRegionStart (context) : 0);
151
152   // Find @LPStart, the base to which landing pad offsets are relative.
153   lpstart_encoding = *p++;
154   if (lpstart_encoding != DW_EH_PE_omit)
155     p = read_encoded_value (context, lpstart_encoding, p, &info->LPStart);
156   else
157     info->LPStart = info->Start;
158
159   // Find @TType, the base of the handler and exception spec type data.
160   info->ttype_encoding = *p++;
161   if (info->ttype_encoding != DW_EH_PE_omit)
162     {
163       p = read_uleb128 (p, &tmp);
164       info->TType = p + tmp;
165     }
166   else
167     info->TType = 0;
168
169   // The encoding and length of the call-site table; the action table
170   // immediately follows.
171   info->call_site_encoding = *p++;
172   p = read_uleb128 (p, &tmp);
173   info->action_table = p + tmp;
174
175   return p;
176 }
177
178 #ifdef __ARM_EABI_UNWINDER__
179
180 static void **
181 get_ttype_entry(_Unwind_Context *, lsda_header_info* info, _uleb128_t i)
182 {
183   _Unwind_Ptr ptr;
184
185   ptr = (_Unwind_Ptr) (info->TType - (i * 4));
186   ptr = _Unwind_decode_target2(ptr);
187   
188   return reinterpret_cast<void **>(ptr);
189 }
190
191 #else
192
193 static void **
194 get_ttype_entry (_Unwind_Context *context, lsda_header_info *info, long i)
195 {
196   _Unwind_Ptr ptr;
197
198   i *= size_of_encoded_value (info->ttype_encoding);
199   read_encoded_value (context, info->ttype_encoding, info->TType - i, &ptr);
200
201   return reinterpret_cast<void **>(ptr);
202 }
203
204 #endif
205
206 // Using a different personality function name causes link failures
207 // when trying to mix code using different exception handling models.
208 #ifdef SJLJ_EXCEPTIONS
209 #define PERSONALITY_FUNCTION    __gcj_personality_sj0
210 #define __builtin_eh_return_data_regno(x) x
211 #else
212 #define PERSONALITY_FUNCTION    __gcj_personality_v0
213 #endif
214
215 #ifdef __ARM_EABI_UNWINDER__
216
217 #define CONTINUE_UNWINDING \
218   do                                                            \
219     {                                                           \
220       if (__gnu_unwind_frame(ue_header, context) != _URC_OK)    \
221         return _URC_FAILURE;                                    \
222       return _URC_CONTINUE_UNWIND;                              \
223     }                                                           \
224   while (0)
225
226 extern "C" _Unwind_Reason_Code
227 PERSONALITY_FUNCTION (_Unwind_State state,
228                       struct _Unwind_Exception* ue_header,
229                       struct _Unwind_Context* context)
230 #else
231
232 #define CONTINUE_UNWINDING return _URC_CONTINUE_UNWIND
233
234 extern "C" _Unwind_Reason_Code
235 PERSONALITY_FUNCTION (int version,
236                       _Unwind_Action actions,
237                       _Unwind_Exception_Class exception_class,
238                       struct _Unwind_Exception *ue_header,
239                       struct _Unwind_Context *context)
240
241 #endif
242 {
243   java_exception_header *xh = get_exception_header_from_ue (ue_header);
244
245   lsda_header_info info;
246   const unsigned char *language_specific_data;
247   const unsigned char *action_record;
248   const unsigned char *p;
249   _Unwind_Ptr landing_pad, ip;
250   int handler_switch_value;
251   bool saw_cleanup;
252   bool saw_handler;
253   bool foreign_exception;
254   int ip_before_insn = 0;
255
256 #ifdef __ARM_EABI_UNWINDER__
257   _Unwind_Action actions;
258
259   switch (state & _US_ACTION_MASK)
260     {
261     case _US_VIRTUAL_UNWIND_FRAME:
262       actions = _UA_SEARCH_PHASE;
263       break;
264
265     case _US_UNWIND_FRAME_STARTING:
266       actions = _UA_CLEANUP_PHASE;
267       if (!(state & _US_FORCE_UNWIND)
268           && ue_header->barrier_cache.sp == _Unwind_GetGR(context, 13))
269         actions |= _UA_HANDLER_FRAME;
270       break;
271
272     case _US_UNWIND_FRAME_RESUME:
273       CONTINUE_UNWINDING;
274       break;
275
276     default:
277       std::abort();
278     }
279   actions |= state & _US_FORCE_UNWIND;
280
281   // We don't know which runtime we're working with, so can't check this.
282   // However the ABI routines hide this from us, and we don't actually need
283   // to know.
284   foreign_exception = false;
285
286   // The dwarf unwinder assumes the context structure holds things like the
287   // function and LSDA pointers.  The ARM implementation caches these in
288   // the exception header (UCB).  To avoid rewriting everything we make the
289   // virtual IP register point at the UCB.
290   ip = (_Unwind_Ptr) ue_header;
291   _Unwind_SetGR(context, 12, ip);
292
293 #else
294   // Interface version check.
295   if (version != 1)
296     return _URC_FATAL_PHASE1_ERROR;
297   foreign_exception = exception_class != __gcj_exception_class;
298 #endif
299
300   // Shortcut for phase 2 found handler for domestic exception.
301   if (actions == (_UA_CLEANUP_PHASE | _UA_HANDLER_FRAME)
302       && !foreign_exception)
303     {
304       handler_switch_value = xh->handlerSwitchValue;
305       landing_pad = xh->landingPad;
306       goto install_context;
307     }
308
309   // FIXME: In Phase 1, record _Unwind_GetIPInfo in xh->obj as a part of
310   // the stack trace for this exception.  This will only collect Java
311   // frames, but perhaps that is acceptable.
312   // FIXME2: _Unwind_GetIPInfo is nonsensical for SJLJ, being a call-site
313   // index instead of a PC value.  We could perhaps arrange for
314   // _Unwind_GetRegionStart to return context->fc->jbuf[1], which
315   // is the address of the handler label for __builtin_longjmp, but
316   // there is no solution for DONT_USE_BUILTIN_SETJMP.
317
318   language_specific_data = (const unsigned char *)
319     _Unwind_GetLanguageSpecificData (context);
320
321   // If no LSDA, then there are no handlers or cleanups.
322   if (! language_specific_data)
323     CONTINUE_UNWINDING;
324
325   // Parse the LSDA header.
326   p = parse_lsda_header (context, language_specific_data, &info);
327 #ifdef HAVE_GETIPINFO
328   ip = _Unwind_GetIPInfo (context, &ip_before_insn);
329 #else
330   ip = _Unwind_GetIP (context);
331 #endif
332   if (! ip_before_insn)
333     --ip;
334   landing_pad = 0;
335   action_record = 0;
336   handler_switch_value = 0;
337
338 #ifdef SJLJ_EXCEPTIONS
339   // The given "IP" is an index into the call-site table, with two
340   // exceptions -- -1 means no-action, and 0 means terminate.  But
341   // since we're using uleb128 values, we've not got random access
342   // to the array.
343   if ((int) ip <= 0)
344     return _URC_CONTINUE_UNWIND;
345   else
346     {
347       _uleb128_t cs_lp, cs_action;
348       do
349         {
350           p = read_uleb128 (p, &cs_lp);
351           p = read_uleb128 (p, &cs_action);
352         }
353       while (--ip);
354
355       // Can never have null landing pad for sjlj -- that would have
356       // been indicated by a -1 call site index.
357       landing_pad = cs_lp + 1;
358       if (cs_action)
359         action_record = info.action_table + cs_action - 1;
360       goto found_something;
361     }
362 #else
363   // Search the call-site table for the action associated with this IP.
364   while (p < info.action_table)
365     {
366       _Unwind_Ptr cs_start, cs_len, cs_lp;
367       _uleb128_t cs_action;
368
369       // Note that all call-site encodings are "absolute" displacements.
370       p = read_encoded_value (0, info.call_site_encoding, p, &cs_start);
371       p = read_encoded_value (0, info.call_site_encoding, p, &cs_len);
372       p = read_encoded_value (0, info.call_site_encoding, p, &cs_lp);
373       p = read_uleb128 (p, &cs_action);
374
375       // The table is sorted, so if we've passed the ip, stop.
376       if (ip < info.Start + cs_start)
377         p = info.action_table;
378       else if (ip < info.Start + cs_start + cs_len)
379         {
380           if (cs_lp)
381             landing_pad = info.LPStart + cs_lp;
382           if (cs_action)
383             action_record = info.action_table + cs_action - 1;
384           goto found_something;
385         }
386     }
387 #endif // SJLJ_EXCEPTIONS
388
389   // If ip is not present in the table, C++ would call terminate.
390   // ??? It is perhaps better to tweek the LSDA so that no-action
391   // is mapped to no-entry for Java.
392   CONTINUE_UNWINDING;
393
394  found_something:
395   saw_cleanup = false;
396   saw_handler = false;
397
398   if (landing_pad == 0)
399     {
400       // If ip is present, and has a null landing pad, there are
401       // no cleanups or handlers to be run.
402     }
403   else if (action_record == 0)
404     {
405       // If ip is present, has a non-null landing pad, and a null
406       // action table offset, then there are only cleanups present.
407       // Cleanups use a zero switch value, as set above.
408       saw_cleanup = true;
409     }
410   else
411     {
412       // Otherwise we have a catch handler.
413       _sleb128_t ar_filter, ar_disp;
414
415       while (1)
416         {
417           p = action_record;
418           p = read_sleb128 (p, &ar_filter);
419           read_sleb128 (p, &ar_disp);
420
421           if (ar_filter == 0)
422             {
423               // Zero filter values are cleanups.
424               saw_cleanup = true;
425             }
426
427           // During forced unwinding, we only run cleanups.  With a
428           // foreign exception class, we have no class info to match.
429           else if ((actions & _UA_FORCE_UNWIND)
430                    || foreign_exception)
431             ;
432
433           else if (ar_filter > 0)
434             {
435               // Positive filter values are handlers.
436
437               void **catch_word = get_ttype_entry (context, &info, ar_filter);
438               jclass catch_type = (jclass)*catch_word;
439
440               // FIXME: This line is a kludge to work around exception
441               // handlers written in C++, which don't yet use indirect
442               // dispatch.
443               if (catch_type == *(void **)&java::lang::Class::class$)
444                 catch_type = (jclass)catch_word;
445
446               if (_Jv_IsInstanceOf (xh->value, catch_type))
447                 {
448                   handler_switch_value = ar_filter;
449                   saw_handler = true;
450                   break;
451                 }
452             }
453           else
454             {
455               // Negative filter values are exception specifications,
456               // which Java does not use.
457               // ??? Perhaps better to make them an index into a table
458               // of null-terminated strings instead of playing games
459               // with Utf8Const+1 as above.
460               abort ();
461             }
462
463           if (ar_disp == 0)
464             break;
465           action_record = p + ar_disp;
466         }
467     }
468
469   if (! saw_handler && ! saw_cleanup)
470         CONTINUE_UNWINDING;
471
472   if (actions & _UA_SEARCH_PHASE)
473     {
474       if (! saw_handler)
475         CONTINUE_UNWINDING;
476
477       // For domestic exceptions, we cache data from phase 1 for phase 2.
478       if (! foreign_exception)
479         {
480           xh->handlerSwitchValue = handler_switch_value;
481           xh->landingPad = landing_pad;
482         }
483       return _URC_HANDLER_FOUND;
484     }
485
486  install_context:
487   _Unwind_SetGR (context, __builtin_eh_return_data_regno (0),
488                  (_Unwind_Ptr) &xh->unwindHeader);
489   _Unwind_SetGR (context, __builtin_eh_return_data_regno (1),
490                  handler_switch_value);
491   _Unwind_SetIP (context, landing_pad);
492 #ifdef __ARM_EABI_UNWINDER__
493   if (saw_cleanup)
494     __cxa_begin_cleanup(ue_header);
495 #endif
496   return _URC_INSTALL_CONTEXT;
497 }