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-2019, 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 and Cygwin.  */
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 ada__exceptions__raise_from_signal_handler
68 extern void Raise_From_Signal_Handler (struct Exception_Data *, const char *)
69   ATTRIBUTE_NORETURN;
70 
71 
72 #if defined (_WIN32) || (defined (__CYGWIN__) && defined (__SEH__))
73 
74 /* Prototypes.  */
75 extern void _global_unwind2 (void *);
76 
77 EXCEPTION_DISPOSITION __gnat_SEH_error_handler
78 (struct _EXCEPTION_RECORD*, void*, struct _CONTEXT*, void*) ATTRIBUTE_NORETURN;
79 
80 struct Exception_Data *
81 __gnat_map_SEH (EXCEPTION_RECORD* ExceptionRecord, const char **msg);
82 
83 /* Convert an SEH exception to an Ada one.  Return the exception ID and set
84    MSG to the corresponding message.  */
85 
86 struct Exception_Data *
__gnat_map_SEH(EXCEPTION_RECORD * ExceptionRecord,const char ** msg)87 __gnat_map_SEH (EXCEPTION_RECORD* ExceptionRecord, const char **msg)
88 {
89   switch (ExceptionRecord->ExceptionCode)
90     {
91     case EXCEPTION_ACCESS_VIOLATION:
92       /* If the failing address isn't maximally aligned or if the page before
93 	 the faulting page is not accessible, this is a program error.  */
94       if ((ExceptionRecord->ExceptionInformation[1] & 3) != 0
95 	  || IsBadCodePtr
96 	     ((FARPROC)(ExceptionRecord->ExceptionInformation[1] + 4096)))
97 	{
98 	  *msg = "EXCEPTION_ACCESS_VIOLATION";
99 	  return &program_error;
100 	}
101       else
102 	{
103 	  /* Otherwise this is a stack overflow.  */
104 	  *msg = "stack overflow or erroneous memory access";
105 	  return &storage_error;
106 	}
107 
108     case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
109       *msg = "EXCEPTION_ARRAY_BOUNDS_EXCEEDED";
110       return &constraint_error;
111 
112     case EXCEPTION_DATATYPE_MISALIGNMENT:
113       *msg = "EXCEPTION_DATATYPE_MISALIGNMENT";
114       return &constraint_error;
115 
116     case EXCEPTION_FLT_DENORMAL_OPERAND:
117       *msg = "EXCEPTION_FLT_DENORMAL_OPERAND";
118       return &constraint_error;
119 
120     case EXCEPTION_FLT_DIVIDE_BY_ZERO:
121       *msg = "EXCEPTION_FLT_DENORMAL_OPERAND";
122       return &constraint_error;
123 
124     case EXCEPTION_FLT_INVALID_OPERATION:
125       *msg = "EXCEPTION_FLT_INVALID_OPERATION";
126       return &constraint_error;
127 
128     case EXCEPTION_FLT_OVERFLOW:
129       *msg = "EXCEPTION_FLT_OVERFLOW";
130       return &constraint_error;
131 
132     case EXCEPTION_FLT_STACK_CHECK:
133       *msg = "EXCEPTION_FLT_STACK_CHECK";
134       return &program_error;
135 
136     case EXCEPTION_FLT_UNDERFLOW:
137       *msg = "EXCEPTION_FLT_UNDERFLOW";
138       return &constraint_error;
139 
140     case EXCEPTION_INT_DIVIDE_BY_ZERO:
141       *msg = "EXCEPTION_INT_DIVIDE_BY_ZERO";
142       return &constraint_error;
143 
144     case EXCEPTION_INT_OVERFLOW:
145       *msg = "EXCEPTION_INT_OVERFLOW";
146       return &constraint_error;
147 
148     case EXCEPTION_INVALID_DISPOSITION:
149       *msg = "EXCEPTION_INVALID_DISPOSITION";
150       return &program_error;
151 
152     case EXCEPTION_NONCONTINUABLE_EXCEPTION:
153       *msg = "EXCEPTION_NONCONTINUABLE_EXCEPTION";
154       return &program_error;
155 
156     case EXCEPTION_PRIV_INSTRUCTION:
157       *msg = "EXCEPTION_PRIV_INSTRUCTION";
158       return &program_error;
159 
160     case EXCEPTION_SINGLE_STEP:
161       *msg = "EXCEPTION_SINGLE_STEP";
162       return &program_error;
163 
164     case EXCEPTION_STACK_OVERFLOW:
165       *msg = "EXCEPTION_STACK_OVERFLOW";
166       return &storage_error;
167 
168     default:
169       *msg = NULL;
170       return NULL;
171     }
172 }
173 
174 #if !(defined (_WIN64) && defined (__SEH__))
175 
176 /* The "fake" exception handler to be associated with the .text section.  */
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; it's equivalent to RtlUnwind (EstablisherFrame, NULL, NULL, 0);
198      Note that this routine is documented as internal to Windows and should
199      not be used.  */
200   _global_unwind2 (EstablisherFrame);
201 #endif
202 
203   Raise_From_Signal_Handler (exception, msg);
204 }
205 
206 #endif /* !(defined (_WIN64) && defined (__SEH__)) */
207 
208 #if defined (_WIN64)
209 
210 /*  On x86-64/Windows the EH mechanism is no more based on a chained list of
211     handlers addresses on the stack.  Instead unwinding information is used
212     to retrieve the exception handler (similar to DWARF2 unwinding).  So in
213     order to register an exception handler, we need to put in the binary
214     some unwinding information.  This information can be present statically
215     in the image file inside the .pdata section or registered through the
216     RtlAddFunctionTable API.  In the case where the GCC toolchain does not
217     generate the .pdata information for each function, we don't really need
218     to handle SEH exceptions except for signal handling, so we register a
219     "fake" unwinding data that associates a SEH exception handler with the
220     complete .text section.  As we never return from the handler, the system
221     does not try to do the final unwinding using the .pdata information and
222     the unwinding is handled by the runtime using the GNAT or GCC mechanism.
223 
224     Solutions based on SetUnhandledExceptionFilter have been discarded as this
225     function is mostly disabled on latest Windows versions.
226 
227     Using AddVectoredExceptionHandler should also be discarded as it overrides
228     all SEH exception handlers that might be present in the program itself and
229     the loaded DLL; for example it results in unexpected behavior in the Win32
230     subsystem.  */
231 
232 #ifndef __SEH__
233 
234   /* Do not use this trick when GCC generates the .pdata information, since it
235      is not necessary and will conflict with the per-function data.  */
236 asm
237 (
238  " .section .rdata, \"dr\"\n"
239  " .align 4\n"
240  "unwind_info:\n"
241  " .byte 9\n" /* UNW_FLAG_EHANDLER | UNW_VERSION */
242  " .byte 0\n" /* Prologue size.  */
243  " .byte 0\n" /* Count of unwind code.  */
244  " .byte 0\n" /* Frame register and offset.  */
245  " .rva __gnat_SEH_error_handler\n"
246  "\n"
247  " .section .pdata, \"dr\"\n"
248  " .align 4\n"
249  " .long 0\n" /* ImageBase */
250  " .rva etext\n"
251  " .rva unwind_info\n"
252  "\n"
253  " .text\n"
254 );
255 
256 #endif /* __SEH__ */
257 
258 /* Nothing to do, the handler is either not used or statically installed by
259    the asm statement just above.  */
__gnat_install_SEH_handler(void * eh ATTRIBUTE_UNUSED)260 void __gnat_install_SEH_handler (void *eh ATTRIBUTE_UNUSED)
261 {
262 }
263 
264 #else /* defined (_WIN64) */
265 
266 /*  Install the Win32 SEH exception handler.  Note that the caller must have
267     allocated 8 bytes on the stack and pass the pointer to this stack space.
268     This is needed as the SEH exception handler must be on the stack of the
269     thread.
270 
271        int buf[2];
272 
273        __gnat_install_SEH_handler ((void*)buf);
274 
275        main();
276 
277    This call must be done before calling the main procedure or the thread
278    entry.  The stack space must exist during the entire main run.  */
279 
280 void
__gnat_install_SEH_handler(void * ER)281 __gnat_install_SEH_handler (void *ER)
282 {
283   int *ptr;
284 
285   /* Put current handler in PTR.  */
286   asm ("mov %%fs:(0),%0" : "=r" (ptr));
287 
288   ((int *)ER)[0] = (int)ptr;                       /* previous handler */
289   ((int *)ER)[1] = (int)__gnat_SEH_error_handler;  /* new handler */
290 
291   /* ER is the new handler, set fs:(0) to this value.  */
292   asm volatile ("mov %0,%%fs:(0)": : "r" (ER));
293 }
294 
295 #endif
296 
297 #else /* defined (_WIN32) */
298 
299 /* For all non-Windows targets we provide a dummy SEH install handler.  */
__gnat_install_SEH_handler(void * eh ATTRIBUTE_UNUSED)300 void __gnat_install_SEH_handler (void *eh ATTRIBUTE_UNUSED)
301 {
302 }
303 
304 #endif
305 
306 #ifdef __cplusplus
307 }
308 #endif
309