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