1 /****************************************************************************
2  *                                                                          *
3  *                         GNAT COMPILER COMPONENTS                         *
4  *                                                                          *
5  *                              S E H - I N I T                             *
6  *                                                                          *
7  *                          C Implementation File                           *
8  *                                                                          *
9  *           Copyright (C) 2005-2014, Free Software Foundation, Inc.        *
10  *                                                                          *
11  * GNAT is free software;  you can  redistribute it  and/or modify it under *
12  * terms of the  GNU General Public License as published  by the Free Soft- *
13  * ware  Foundation;  either version 3,  or (at your option) any later ver- *
14  * sion.  GNAT is distributed in the hope that it will be useful, but WITH- *
15  * OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY *
16  * or FITNESS FOR A PARTICULAR PURPOSE.                                     *
17  *                                                                          *
18  * As a special exception under Section 7 of GPL version 3, you are granted *
19  * additional permissions described in the GCC Runtime Library Exception,   *
20  * version 3.1, as published by the Free Software Foundation.               *
21  *                                                                          *
22  * You should have received a copy of the GNU General Public License and    *
23  * a copy of the GCC Runtime Library Exception along with this program;     *
24  * see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see    *
25  * <http://www.gnu.org/licenses/>.                                          *
26  *                                                                          *
27  * GNAT was originally developed  by the GNAT team at  New York University. *
28  * Extensive contributions were provided by Ada Core Technologies Inc.      *
29  *                                                                          *
30  ****************************************************************************/
31 
32 /*  This unit contains support for SEH (Structured Exception Handling).
33     Right now the only implementation is for Win32.  */
34 
35 #if defined (_WIN32) || (defined (__CYGWIN__) && defined (__SEH__))
36 /* Include system headers, before system.h poisons malloc.  */
37 #include <windows.h>
38 #include <excpt.h>
39 #endif
40 
41 #ifdef IN_RTS
42 #include "tconfig.h"
43 #include "tsystem.h"
44 
45 /* We don't have libiberty, so use malloc.  */
46 #define xmalloc(S) malloc (S)
47 
48 #else
49 #include "config.h"
50 #include "system.h"
51 #endif
52 
53 #include "raise.h"
54 
55 #ifdef __cplusplus
56 extern "C" {
57 #endif
58 
59 /* Addresses of exception data blocks for predefined exceptions. */
60 extern struct Exception_Data constraint_error;
61 extern struct Exception_Data numeric_error;
62 extern struct Exception_Data program_error;
63 extern struct Exception_Data storage_error;
64 extern struct Exception_Data tasking_error;
65 extern struct Exception_Data _abort_signal;
66 
67 #define Raise_From_Signal_Handler \
68                       ada__exceptions__raise_from_signal_handler
69 extern void Raise_From_Signal_Handler (struct Exception_Data *, const char *)
70   ATTRIBUTE_NORETURN;
71 
72 
73 #if defined (_WIN32) || (defined (__CYGWIN__) && defined (__SEH__))
74 
75 /* Prototypes.  */
76 extern void _global_unwind2 (void *);
77 
78 EXCEPTION_DISPOSITION __gnat_SEH_error_handler
79 (struct _EXCEPTION_RECORD*, void*, struct _CONTEXT*, void*) ATTRIBUTE_NORETURN;
80 
81 struct Exception_Data *
82 __gnat_map_SEH (EXCEPTION_RECORD* ExceptionRecord, const char **msg);
83 
84 /* Convert an SEH exception to an Ada one.  Return the exception ID
85    and set MSG with the corresponding message.  */
86 
87 struct Exception_Data *
__gnat_map_SEH(EXCEPTION_RECORD * ExceptionRecord,const char ** msg)88 __gnat_map_SEH (EXCEPTION_RECORD* ExceptionRecord, const char **msg)
89 {
90   switch (ExceptionRecord->ExceptionCode)
91     {
92     case EXCEPTION_ACCESS_VIOLATION:
93       /* If the failing address isn't maximally-aligned or if the page
94 	 before the faulting page is not accessible, this is a program error.
95       */
96       if ((ExceptionRecord->ExceptionInformation[1] & 3) != 0
97 	  || IsBadCodePtr
98 	  ((FARPROC)(ExceptionRecord->ExceptionInformation[1] + 4096)))
99 	{
100 	  *msg = "EXCEPTION_ACCESS_VIOLATION";
101 	  return &program_error;
102 	}
103       else
104 	{
105 	  /* otherwise it is a stack overflow  */
106 	  *msg = "stack overflow or erroneous memory access";
107 	  return &storage_error;
108 	}
109 
110     case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
111       *msg = "EXCEPTION_ARRAY_BOUNDS_EXCEEDED";
112       return &constraint_error;
113 
114     case EXCEPTION_DATATYPE_MISALIGNMENT:
115       *msg = "EXCEPTION_DATATYPE_MISALIGNMENT";
116       return &constraint_error;
117 
118     case EXCEPTION_FLT_DENORMAL_OPERAND:
119       *msg = "EXCEPTION_FLT_DENORMAL_OPERAND";
120       return &constraint_error;
121 
122     case EXCEPTION_FLT_DIVIDE_BY_ZERO:
123       *msg = "EXCEPTION_FLT_DENORMAL_OPERAND";
124       return &constraint_error;
125 
126     case EXCEPTION_FLT_INVALID_OPERATION:
127       *msg = "EXCEPTION_FLT_INVALID_OPERATION";
128       return &constraint_error;
129 
130     case EXCEPTION_FLT_OVERFLOW:
131       *msg = "EXCEPTION_FLT_OVERFLOW";
132       return &constraint_error;
133 
134     case EXCEPTION_FLT_STACK_CHECK:
135       *msg = "EXCEPTION_FLT_STACK_CHECK";
136       return &program_error;
137 
138     case EXCEPTION_FLT_UNDERFLOW:
139       *msg = "EXCEPTION_FLT_UNDERFLOW";
140       return &constraint_error;
141 
142     case EXCEPTION_INT_DIVIDE_BY_ZERO:
143       *msg = "EXCEPTION_INT_DIVIDE_BY_ZERO";
144       return &constraint_error;
145 
146     case EXCEPTION_INT_OVERFLOW:
147       *msg = "EXCEPTION_INT_OVERFLOW";
148       return &constraint_error;
149 
150     case EXCEPTION_INVALID_DISPOSITION:
151       *msg = "EXCEPTION_INVALID_DISPOSITION";
152       return &program_error;
153 
154     case EXCEPTION_NONCONTINUABLE_EXCEPTION:
155       *msg = "EXCEPTION_NONCONTINUABLE_EXCEPTION";
156       return &program_error;
157 
158     case EXCEPTION_PRIV_INSTRUCTION:
159       *msg = "EXCEPTION_PRIV_INSTRUCTION";
160       return &program_error;
161 
162     case EXCEPTION_SINGLE_STEP:
163       *msg = "EXCEPTION_SINGLE_STEP";
164       return &program_error;
165 
166     case EXCEPTION_STACK_OVERFLOW:
167       *msg = "EXCEPTION_STACK_OVERFLOW";
168       return &storage_error;
169 
170     default:
171       *msg = NULL;
172       return NULL;
173     }
174 }
175 
176 #if !(defined (_WIN64) && defined (__SEH__))
177 
178 EXCEPTION_DISPOSITION
__gnat_SEH_error_handler(struct _EXCEPTION_RECORD * ExceptionRecord,void * EstablisherFrame ATTRIBUTE_UNUSED,struct _CONTEXT * ContextRecord ATTRIBUTE_UNUSED,void * DispatcherContext ATTRIBUTE_UNUSED)179 __gnat_SEH_error_handler (struct _EXCEPTION_RECORD* ExceptionRecord,
180 			  void *EstablisherFrame ATTRIBUTE_UNUSED,
181 			  struct _CONTEXT* ContextRecord ATTRIBUTE_UNUSED,
182 			  void *DispatcherContext ATTRIBUTE_UNUSED)
183 {
184   struct Exception_Data *exception;
185   const char *msg;
186 
187   exception = __gnat_map_SEH (ExceptionRecord, &msg);
188 
189   if (exception == NULL)
190     {
191       exception = &program_error;
192       msg = "unhandled signal";
193     }
194 
195 #if ! defined (_WIN64)
196   /* This call is important as it avoids locking the second time we catch a
197      signal. Note that this routine is documented as internal to Windows and
198      should not be used.  */
199 
200   _global_unwind2 (EstablisherFrame);
201   /* Call equivalent to RtlUnwind (EstablisherFrame, NULL, NULL, 0); */
202 #endif
203 
204   Raise_From_Signal_Handler (exception, msg);
205 }
206 #endif /* !(defined (_WIN64) && defined (__SEH__)) */
207 
208 #if defined (_WIN64)
209 /*  On x86_64 windows exception mechanism is no more based on a chained list
210     of handlers addresses on the stack. Instead unwinding information is used
211     to retrieve the exception handler (similar to ZCX GCC mechanism). So in
212     order to register an exception handler we need to put in the final
213     executable some unwinding information. This information might be present
214     statically in the image file inside the .pdata section or registered
215     through RtlAddFunctionTable API. Currently the GCC toolchain does not
216     generate the .pdata information for each function. As we don't need to
217     handle SEH exceptions except for signal handling we are registering a
218     "fake" unwinding data that associate a SEH exception handler to the
219     complete .text section. As we never return from the handler, the system
220     does not try to do the final unwinding using the pdata information. The
221     unwinding is handled by the runtime using either the GNAT SJLJ mechanism
222     or the ZCX GCC mechanism.
223 
224     Solutions based on SetUnhandledExceptionFilter have been discarded as this
225     function is mostly disabled on last Windows versions.
226     Using AddVectoredExceptionHandler should also be discarded as it overrides
227     all SEH exception handlers that might be present in the program itself and
228     the loaded DLL (for example it results in unexpected behaviors in the
229     Win32 subsystem.  */
230 
231 #ifndef __SEH__
232   /* Don't use this trick when SEH are emitted by gcc, as it will conflict with
233      them.  */
234 asm
235 (
236  " .section .rdata, \"dr\"\n"
237  " .align 4\n"
238  "unwind_info:\n"
239  " .byte 9\n" /* UNW_FLAG_EHANDLER | UNW_VERSION */
240  " .byte 0\n" /* Prologue size.  */
241  " .byte 0\n" /* Count of unwind code.  */
242  " .byte 0\n" /* Frame register and offset.  */
243  " .rva __gnat_SEH_error_handler\n"
244  "\n"
245  " .section .pdata, \"dr\"\n"
246  " .align 4\n"
247  " .long 0\n" /* ImageBase */
248  " .rva etext\n"
249  " .rva unwind_info\n"
250  "\n"
251  " .text\n"
252 );
253 #endif /* __SEH__ */
254 
__gnat_install_SEH_handler(void * eh ATTRIBUTE_UNUSED)255 void __gnat_install_SEH_handler (void *eh ATTRIBUTE_UNUSED)
256 {
257   /* Nothing to do, the handler is statically installed by the asm statement
258      just above.  */
259 }
260 
261 #else /* defined (_WIN64) */
262 /*  Install the Win32 SEH exception handler. Note that the caller must have
263     allocated 8 bytes on the stack and pass the pointer to this stack
264     space. This is needed as the SEH exception handler must be on the stack of
265     the thread.
266 
267        int buf[2];
268 
269        __gnat_install_SEH_handler ((void*)buf);
270 
271        main();
272 
273    This call must be done before calling the main procedure or the thread
274    entry. The stack space must exists during all the main run.  */
275 
276 void
__gnat_install_SEH_handler(void * ER)277 __gnat_install_SEH_handler (void *ER)
278 {
279   int *ptr;
280 
281   /* put current handler in ptr */
282 
283   asm ("mov %%fs:(0),%0" : "=r" (ptr));
284 
285   ((int *)ER)[0] = (int)ptr;                       /* previous handler */
286   ((int *)ER)[1] = (int)__gnat_SEH_error_handler;  /* new handler */
287 
288   /* ER is the new handler, set fs:(0) with this value */
289 
290   asm volatile ("mov %0,%%fs:(0)": : "r" (ER));
291 }
292 #endif
293 
294 #else /* defined (_WIN32) */
295 /* For all non Windows targets we provide a dummy SEH install handler.  */
__gnat_install_SEH_handler(void * eh ATTRIBUTE_UNUSED)296 void __gnat_install_SEH_handler (void *eh ATTRIBUTE_UNUSED)
297 {
298 }
299 #endif
300 
301 #ifdef __cplusplus
302 }
303 #endif
304