Debian Codegraph @

gcc/ada/init.c

raw
1 /****************************************************************************
2 * *
3 * GNAT COMPILER COMPONENTS *
4 * *
5 * I N I T *
6 * *
7 * C Implementation File *
8 * *
9 * Copyright (C) 1992-2025, 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 initialization circuits that are system dependent.
33 A major part of the functionality involves stack overflow checking.
34 The GCC backend generates probe instructions to test for stack overflow.
35 For details on the exact approach used to generate these probes, see the
36 "Using and Porting GCC" manual, in particular the "Stack Checking" section
37 and the subsection "Specifying How Stack Checking is Done". The handlers
38 installed by this file are used to catch the resulting signals that come
39 from these probes failing (i.e. touching protected pages). */
40
41 /* This file should be kept synchronized with s-init.ads, s-init.adb and the
42 s-init-*.adb variants. All these files implement the required functionality
43 for different targets. */
44
45 /* The following include is here to meet the published VxWorks requirement
46 that the __vxworks header appear before any other include. */
47 #ifdef __vxworks
48 #include "vxWorks.h"
49 #include "version.h" /* for _WRS_VXWORKS_MAJOR */
50 #endif
51
52 #ifdef __ANDROID__
53 #undef __linux__
54 #endif
55
56 #ifdef IN_RTS
57
58 #ifdef STANDALONE
59 #include "runtime.h"
60 #else
61 #include "tconfig.h"
62 #include "tsystem.h"
63 #endif
64
65 #include <sys/stat.h>
66
67 /* We don't have libiberty, so use malloc. */
68 #define xmalloc(S) malloc (S)
69 #else
70 #include "config.h"
71 #include "system.h"
72 #endif
73
74 #include "adaint.h"
75 #include "raise.h"
76
77 #ifdef __cplusplus
78 extern "C" {
79 #endif
80
81 extern void __gnat_raise_program_error (const void *, int);
82
83 /* Addresses of exception data blocks for predefined exceptions. Tasking_Error
84 is not used in this unit, and the abort signal is only used on IRIX.
85 ??? Revisit this part since IRIX is no longer supported. */
86 extern struct Exception_Data constraint_error;
87 extern struct Exception_Data numeric_error;
88 extern struct Exception_Data program_error;
89 extern struct Exception_Data storage_error;
90
91 /* Exception IDs for CHERI Ada exceptions (see Interfaces.CHERI.Exceptions) */
92 #ifdef __CHERI__
93 extern Exception_Id capability_bound_error_id;
94 extern Exception_Id capability_permission_error_id;
95 extern Exception_Id capability_sealed_error_id;
96 extern Exception_Id capability_tag_error_id;
97 #endif
98
99 /* For the Cert run time we use the regular raise exception routine because
100 __gnat_raise_from_signal_handler is not available. */
101 #ifdef CERT
102 #define Raise_From_Signal_Handler __gnat_raise_exception
103 #else
104 #define Raise_From_Signal_Handler __gnat_raise_from_signal_handler
105 #endif
106
107 extern void Raise_From_Signal_Handler (struct Exception_Data *, const void *)
108 ATTRIBUTE_NORETURN;
109
110 /* Global values computed by the binder. Note that these variables are
111 declared here, not in the binder file, to avoid having unresolved
112 references in the shared libgnat. */
113 int __gl_main_priority = -1;
114 int __gl_main_cpu = -1;
115 int __gl_time_slice_val = -1;
116 char __gl_wc_encoding = 'n';
117 char __gl_locking_policy = ' ';
118 char __gl_queuing_policy = ' ';
119 char __gl_task_dispatching_policy = ' ';
120 char *__gl_priority_specific_dispatching = 0;
121 int __gl_num_specific_dispatching = 0;
122 char *__gl_interrupt_states = 0;
123 int __gl_num_interrupt_states = 0;
124 int __gl_unreserve_all_interrupts = 0;
125 int __gl_exception_tracebacks = 0;
126 int __gl_exception_tracebacks_symbolic = 0;
127 int __gl_detect_blocking = 0;
128 int __gl_default_stack_size = -1;
129 int __gl_leap_seconds_support = 0;
130 int __gl_canonical_streams = 0;
131 char *__gl_bind_env_addr = NULL;
132 int __gl_xdr_stream = 0;
133 int __gl_interrupts_default_to_system = 0;
134
135 /* This value is not used anymore, but kept for bootstrapping purpose. */
136 int __gl_zero_cost_exceptions = 0;
137
138 /* Indication of whether synchronous signal handler has already been
139 installed by a previous call to adainit. */
140 int __gnat_handler_installed = 0;
141
142 #ifndef IN_RTS
143 int __gnat_inside_elab_final_code = 0;
144 /* ??? This variable is obsolete since 2001-08-29 but is kept to allow
145 bootstrap from old GNAT versions (< 3.15). */
146 #endif
147
148 /* HAVE_GNAT_INIT_FLOAT must be set on every targets where a __gnat_init_float
149 is defined. If this is not set then a void implementation will be defined
150 at the end of this unit. */
151 #undef HAVE_GNAT_INIT_FLOAT
152
153 /******************************/
154 /* __gnat_get_interrupt_state */
155 /******************************/
156
157 char __gnat_get_interrupt_state (int);
158
159 /* This routine is called from the runtime as needed to determine the state
160 of an interrupt, as set by an Interrupt_State pragma or an
161 Interrupts_System_By_Default pragma appearing anywhere in the current
162 partition. The input argument is the interrupt number, and the result
163 is one of the following:
164
165 'u' if Interrupt_State pragma set to User;
166 'r' if Interrupt_State pragma set to Runtime;
167 's' if Interrupt_State pragma set to System or
168 Interrupts_System_By_Default in effect; otherwise
169 'n' (there is no Interrupt_State pragma and no request for a default).
170
171 See pragma Interrupt_State documentation for a description
172 of the effect and meaning of states User, Runtime, and System. */
173
174 char
175 __gnat_get_interrupt_state (int intrup)
176 {
177 if (intrup >= __gl_num_interrupt_states)
178 return (__gl_interrupts_default_to_system ? 's' : 'n');
179 else
180 return __gl_interrupt_states [intrup];
181 }
182
183 /***********************************/
184 /* __gnat_get_specific_dispatching */
185 /***********************************/
186
187 char __gnat_get_specific_dispatching (int);
188
189 /* This routine is called from the runtime as needed to determine the
190 priority specific dispatching policy, as set by a
191 Priority_Specific_Dispatching pragma appearing anywhere in the current
192 partition. The input argument is the priority number, and the result
193 is the upper case first character of the policy name, e.g. 'F' for
194 FIFO_Within_Priorities. A space ' ' is returned if no
195 Priority_Specific_Dispatching pragma is used in the partition. */
196
197 char
198 __gnat_get_specific_dispatching (int priority)
199 {
200 if (__gl_num_specific_dispatching == 0)
201 return ' ';
202 else if (priority >= __gl_num_specific_dispatching)
203 return 'F';
204 else
205 return __gl_priority_specific_dispatching [priority];
206 }
207
208 #ifndef IN_RTS
209
210 /**********************/
211 /* __gnat_set_globals */
212 /**********************/
213
214 /* This routine is kept for bootstrapping purposes, since the binder generated
215 file now sets the __gl_* variables directly. */
216
217 void
218 __gnat_set_globals (void)
219 {
220 }
221
222 #endif
223
224 /***************/
225 /* AIX Section */
226 /***************/
227
228 #if defined (_AIX)
229
230 #include <signal.h>
231 #include <sys/time.h>
232
233 /* Some versions of AIX don't define SA_NODEFER. */
234
235 #ifndef SA_NODEFER
236 #define SA_NODEFER 0
237 #endif /* SA_NODEFER */
238
239 /* Versions of AIX before 4.3 don't have nanosleep but provide
240 nsleep instead. */
241
242 #ifndef _AIXVERSION_430
243
244 extern int nanosleep (struct timestruc_t *, struct timestruc_t *);
245
246 int
247 nanosleep (struct timestruc_t *Rqtp, struct timestruc_t *Rmtp)
248 {
249 return nsleep (Rqtp, Rmtp);
250 }
251
252 #endif /* _AIXVERSION_430 */
253
254 static void
255 __gnat_error_handler (int sig,
256 siginfo_t *si ATTRIBUTE_UNUSED,
257 void *ucontext ATTRIBUTE_UNUSED)
258 {
259 struct Exception_Data *exception;
260 const char *msg;
261
262 switch (sig)
263 {
264 case SIGSEGV:
265 /* ??? we need to detect the case of a *real* SIGSEGV. */
266 exception = &storage_error;
267 msg = "stack overflow or erroneous memory access";
268 break;
269
270 case SIGBUS:
271 exception = &constraint_error;
272 msg = "SIGBUS";
273 break;
274
275 case SIGFPE:
276 exception = &constraint_error;
277 msg = "SIGFPE";
278 break;
279
280 default:
281 exception = &program_error;
282 msg = "unhandled signal";
283 }
284
285 Raise_From_Signal_Handler (exception, msg);
286 }
287
288 void
289 __gnat_install_handler (void)
290 {
291 struct sigaction act;
292
293 /* Set up signal handler to map synchronous signals to appropriate
294 exceptions. Make sure that the handler isn't interrupted by another
295 signal that might cause a scheduling event! */
296
297 act.sa_flags = SA_NODEFER | SA_RESTART | SA_SIGINFO;
298 act.sa_sigaction = __gnat_error_handler;
299 sigemptyset (&act.sa_mask);
300
301 /* Do not install handlers if interrupt state is "System". */
302 if (__gnat_get_interrupt_state (SIGABRT) != 's')
303 sigaction (SIGABRT, &act, NULL);
304 if (__gnat_get_interrupt_state (SIGFPE) != 's')
305 sigaction (SIGFPE, &act, NULL);
306 if (__gnat_get_interrupt_state (SIGILL) != 's')
307 sigaction (SIGILL, &act, NULL);
308 if (__gnat_get_interrupt_state (SIGSEGV) != 's')
309 sigaction (SIGSEGV, &act, NULL);
310 if (__gnat_get_interrupt_state (SIGBUS) != 's')
311 sigaction (SIGBUS, &act, NULL);
312
313 __gnat_handler_installed = 1;
314 }
315
316 /*****************/
317 /* HP-UX section */
318 /*****************/
319
320 #elif defined (__hpux__)
321
322 #include <signal.h>
323 #include <sys/ucontext.h>
324
325 #if defined (IN_RTS) && defined (__ia64__)
326
327 #include <sys/uc_access.h>
328
329 #define HAVE_GNAT_ADJUST_CONTEXT_FOR_RAISE
330
331 void
332 __gnat_adjust_context_for_raise (int signo ATTRIBUTE_UNUSED, void *ucontext)
333 {
334 ucontext_t *uc = (ucontext_t *) ucontext;
335 uint64_t ip;
336
337 /* Adjust on itanium, as GetIPInfo is not supported. */
338 __uc_get_ip (uc, &ip);
339 __uc_set_ip (uc, ip + 1);
340 }
341 #endif /* IN_RTS && __ia64__ */
342
343 /* Tasking and Non-tasking signal handler. Map SIGnal to Ada exception
344 propagation after the required low level adjustments. */
345
346 static void
347 __gnat_error_handler (int sig, siginfo_t *si ATTRIBUTE_UNUSED, void *ucontext)
348 {
349 struct Exception_Data *exception;
350 const char *msg;
351
352 __gnat_adjust_context_for_raise (sig, ucontext);
353
354 switch (sig)
355 {
356 case SIGSEGV:
357 /* ??? we need to detect the case of a *real* SIGSEGV. */
358 exception = &storage_error;
359 msg = "stack overflow or erroneous memory access";
360 break;
361
362 case SIGBUS:
363 exception = &constraint_error;
364 msg = "SIGBUS";
365 break;
366
367 case SIGFPE:
368 exception = &constraint_error;
369 msg = "SIGFPE";
370 break;
371
372 default:
373 exception = &program_error;
374 msg = "unhandled signal";
375 }
376
377 Raise_From_Signal_Handler (exception, msg);
378 }
379
380 /* This must be in keeping with System.OS_Interface.Alternate_Stack_Size. */
381 #if defined (__hppa__)
382 char __gnat_alternate_stack[16 * 1024]; /* 2 * SIGSTKSZ */
383 #else
384 char __gnat_alternate_stack[128 * 1024]; /* MINSIGSTKSZ */
385 #endif
386
387 void
388 __gnat_install_handler (void)
389 {
390 struct sigaction act;
391
392 /* Set up signal handler to map synchronous signals to appropriate
393 exceptions. Make sure that the handler isn't interrupted by another
394 signal that might cause a scheduling event! Also setup an alternate
395 stack region for the handler execution so that stack overflows can be
396 handled properly, avoiding a SEGV generation from stack usage by the
397 handler itself. */
398
399 stack_t stack;
400 stack.ss_sp = __gnat_alternate_stack;
401 stack.ss_size = sizeof (__gnat_alternate_stack);
402 stack.ss_flags = 0;
403 sigaltstack (&stack, NULL);
404
405 act.sa_sigaction = __gnat_error_handler;
406 act.sa_flags = SA_NODEFER | SA_RESTART | SA_SIGINFO;
407 sigemptyset (&act.sa_mask);
408
409 /* Do not install handlers if interrupt state is "System". */
410 if (__gnat_get_interrupt_state (SIGABRT) != 's')
411 sigaction (SIGABRT, &act, NULL);
412 if (__gnat_get_interrupt_state (SIGFPE) != 's')
413 sigaction (SIGFPE, &act, NULL);
414 if (__gnat_get_interrupt_state (SIGILL) != 's')
415 sigaction (SIGILL, &act, NULL);
416 if (__gnat_get_interrupt_state (SIGBUS) != 's')
417 sigaction (SIGBUS, &act, NULL);
418 act.sa_flags |= SA_ONSTACK;
419 if (__gnat_get_interrupt_state (SIGSEGV) != 's')
420 sigaction (SIGSEGV, &act, NULL);
421
422 __gnat_handler_installed = 1;
423 }
424
425 /*********************/
426 /* GNU/Linux Section */
427 /*********************/
428
429 #elif defined (__linux__)
430
431 #include <signal.h>
432
433 #define __USE_GNU 1 /* required to get REG_EIP/RIP from glibc's ucontext.h */
434 #include <sys/ucontext.h>
435
436 /* GNU/Linux, which uses glibc, does not define NULL in included
437 header files. */
438
439 #if !defined (NULL)
440 #define NULL ((void *) 0)
441 #endif
442
443 #if defined (MaRTE)
444
445 /* MaRTE OS provides its own version of sigaction, sigfillset, and
446 sigemptyset (overriding these symbol names). We want to make sure that
447 the versions provided by the underlying C library are used here (these
448 versions are renamed by MaRTE to linux_sigaction, fake_linux_sigfillset,
449 and fake_linux_sigemptyset, respectively). The MaRTE library will not
450 always be present (it will not be linked if no tasking constructs are
451 used), so we use the weak symbol mechanism to point always to the symbols
452 defined within the C library. */
453
454 #pragma weak linux_sigaction
455 int linux_sigaction (int signum, const struct sigaction *act,
456 struct sigaction *oldact)
457 {
458 return sigaction (signum, act, oldact);
459 }
460 #define sigaction(signum, act, oldact) linux_sigaction (signum, act, oldact)
461
462 #pragma weak fake_linux_sigfillset
463 void fake_linux_sigfillset (sigset_t *set)
464 {
465 sigfillset (set);
466 }
467 #define sigfillset(set) fake_linux_sigfillset (set)
468
469 #pragma weak fake_linux_sigemptyset
470 void fake_linux_sigemptyset (sigset_t *set)
471 {
472 sigemptyset (set);
473 }
474 #define sigemptyset(set) fake_linux_sigemptyset (set)
475
476 #endif
477
478 #if defined (__i386__) || defined (__x86_64__) || defined (__ia64__) \
479 || defined (__ARMEL__)
480
481 #define HAVE_GNAT_ADJUST_CONTEXT_FOR_RAISE
482
483 void
484 __gnat_adjust_context_for_raise (int signo ATTRIBUTE_UNUSED, void *ucontext)
485 {
486 #ifndef STANDALONE
487 mcontext_t *mcontext = &((ucontext_t *) ucontext)->uc_mcontext;
488
489 /* On the i386 and x86-64 architectures, stack checking is performed by
490 means of probes with moving stack pointer, that is to say the probed
491 address is always the value of the stack pointer. Upon hitting the
492 guard page, the stack pointer therefore points to an inaccessible
493 address and an alternate signal stack is needed to run the handler.
494 But there is an additional twist: on these architectures, the EH
495 return code writes the address of the handler at the target CFA's
496 value on the stack before doing the jump. As a consequence, if
497 there is an active handler in the frame whose stack has overflowed,
498 the stack pointer must nevertheless point to an accessible address
499 by the time the EH return is executed.
500
501 We therefore adjust the saved value of the stack pointer by the size
502 of one page + a small dope of 4 words, in order to make sure that it
503 points to an accessible address in case it's used as the target CFA.
504 The stack checking code guarantees that this address is unused by the
505 time this happens. */
506
507 #if defined (__i386__)
508 unsigned long *pc = (unsigned long *)mcontext->gregs[REG_EIP];
509 /* The pattern is "orl $0x0,(%esp)" for a probe in 32-bit mode. */
510 if (signo == SIGSEGV && pc && *pc == 0x00240c83)
511 mcontext->gregs[REG_ESP] += 4096 + 4 * sizeof (unsigned long);
512 #elif defined (__x86_64__)
513 unsigned long long *pc = (unsigned long long *)mcontext->gregs[REG_RIP];
514 if (signo == SIGSEGV && pc
515 /* The pattern is "orq $0x0,(%rsp)" for a probe in 64-bit mode. */
516 && ((*pc & 0xffffffffffLL) == 0x00240c8348LL
517 /* The pattern may also be "orl $0x0,(%esp)" for a probe in
518 x32 mode. */
519 || (*pc & 0xffffffffLL) == 0x00240c83LL))
520 mcontext->gregs[REG_RSP] += 4096 + 4 * sizeof (unsigned long);
521 #elif defined (__ia64__)
522 /* ??? The IA-64 unwinder doesn't compensate for signals. */
523 mcontext->sc_ip++;
524 #elif defined (__ARMEL__)
525 /* ARM Bump has to be an even number because of odd/even architecture. */
526 mcontext->arm_pc+=2;
527 #ifdef __thumb2__
528 #define CPSR_THUMB_BIT 5
529 /* For thumb, the return address much have the low order bit set, otherwise
530 the unwinder will reset to "arm" mode upon return. As long as the
531 compilation unit containing the landing pad is compiled with the same
532 mode (arm vs thumb) as the signaling compilation unit, this works. */
533 if (mcontext->arm_cpsr & (1<<CPSR_THUMB_BIT))
534 mcontext->arm_pc+=1;
535 #endif
536 #endif
537 #endif
538 }
539
540 #endif
541
542 static void
543 __gnat_error_handler (int sig, siginfo_t *si ATTRIBUTE_UNUSED, void *ucontext)
544 {
545 struct Exception_Data *exception;
546 const char *msg;
547
548 /* Adjusting is required for every fault context, so adjust for this one
549 now, before we possibly trigger a recursive fault below. */
550 __gnat_adjust_context_for_raise (sig, ucontext);
551
552 switch (sig)
553 {
554 case SIGSEGV:
555 /* Here we would like a discrimination test to see whether the page
556 before the faulting address is accessible. Unfortunately, Linux
557 seems to have no way of giving us the faulting address.
558
559 In old versions of init.c, we had a test of the page before the
560 stack pointer:
561
562 ((volatile char *)
563 ((long) si->esp_at_signal & - getpagesize ()))[getpagesize ()];
564
565 but that's wrong since it tests the stack pointer location and the
566 stack probing code may not move it until all probes succeed.
567
568 For now we simply do not attempt any discrimination at all. Note
569 that this is quite acceptable, since a "real" SIGSEGV can only
570 occur as the result of an erroneous program. */
571 exception = &storage_error;
572 msg = "stack overflow or erroneous memory access";
573 break;
574
575 case SIGBUS:
576 exception = &storage_error;
577 msg = "SIGBUS: possible stack overflow";
578 break;
579
580 case SIGFPE:
581 exception = &constraint_error;
582 msg = "SIGFPE";
583 break;
584
585 default:
586 exception = &program_error;
587 msg = "unhandled signal";
588 }
589
590 Raise_From_Signal_Handler (exception, msg);
591 }
592
593 #ifndef __ia64__
594 #define HAVE_GNAT_ALTERNATE_STACK 1
595 /* This must be in keeping with System.OS_Interface.Alternate_Stack_Size. */
596 char __gnat_alternate_stack[32 * 1024];
597 #endif
598
599 #ifdef __XENO__
600 #include <sys/mman.h>
601 #include <native/task.h>
602
603 RT_TASK main_task;
604 #endif
605
606 void
607 __gnat_install_handler (void)
608 {
609 struct sigaction act;
610
611 #ifdef __XENO__
612 int prio;
613
614 if (__gl_main_priority == -1)
615 prio = 49;
616 else
617 prio = __gl_main_priority;
618
619 /* Avoid memory swapping for this program */
620
621 mlockall (MCL_CURRENT|MCL_FUTURE);
622
623 /* Turn the current Linux task into a native Xenomai task */
624
625 rt_task_shadow (&main_task, "environment_task", prio, T_FPU);
626 #endif
627
628 /* Set up signal handler to map synchronous signals to appropriate
629 exceptions. Make sure that the handler isn't interrupted by another
630 signal that might cause a scheduling event! Also setup an alternate
631 stack region for the handler execution so that stack overflows can be
632 handled properly, avoiding a SEGV generation from stack usage by the
633 handler itself. */
634
635 act.sa_sigaction = __gnat_error_handler;
636 act.sa_flags = SA_NODEFER | SA_RESTART | SA_SIGINFO;
637 sigemptyset (&act.sa_mask);
638
639 /* Do not install handlers if interrupt state is "System". */
640 if (__gnat_get_interrupt_state (SIGABRT) != 's')
641 sigaction (SIGABRT, &act, NULL);
642 if (__gnat_get_interrupt_state (SIGFPE) != 's')
643 sigaction (SIGFPE, &act, NULL);
644 if (__gnat_get_interrupt_state (SIGILL) != 's')
645 sigaction (SIGILL, &act, NULL);
646 if (__gnat_get_interrupt_state (SIGBUS) != 's')
647 sigaction (SIGBUS, &act, NULL);
648 if (__gnat_get_interrupt_state (SIGSEGV) != 's')
649 {
650 #ifdef HAVE_GNAT_ALTERNATE_STACK
651 /* Setup an alternate stack region for the handler execution so that
652 stack overflows can be handled properly, avoiding a SEGV generation
653 from stack usage by the handler itself. */
654 stack_t stack;
655
656 stack.ss_sp = __gnat_alternate_stack;
657 stack.ss_size = sizeof (__gnat_alternate_stack);
658 stack.ss_flags = 0;
659 sigaltstack (&stack, NULL);
660
661 act.sa_flags |= SA_ONSTACK;
662 #endif
663 sigaction (SIGSEGV, &act, NULL);
664 }
665
666 __gnat_handler_installed = 1;
667 }
668
669 /*******************/
670 /* LynxOS Section */
671 /*******************/
672
673 #elif defined (__Lynx__)
674
675 #include <signal.h>
676 #include <unistd.h>
677
678 /* SA_SIGINFO is not supported by default on LynxOS, so all we have
679 available here is the "sig" argument. On newer LynxOS versions it's
680 possible to support SA_SIGINFO by setting a kernel configuration macro.
681
682 To wit:
683
684 #define NONPOSIX_SA_HANDLER_PROTO (0)
685
686 This macro must be set to 1 in either sys/bsp.<bspname>/uparam.h
687 or in the associated uparam.h customization file sys/bsp.<bspname>/xparam.h
688 (uparam.h includes xparam.h for customization)
689
690 The NONPOSIX_SA_HANDLER_PROTO macro makes it possible to provide
691 signal-catching function with 'info' and 'context' input parameters
692 even if SA_SIGINFO flag is not set or it is set for a non-realtime signal.
693
694 It also allows signal-catching function to update thread context even
695 if SA_UPDATECTX flag is not set.
696
697 This would be useful, but relying on that would transmit the requirement
698 to users to configure that feature as well, which is undesirable. */
699
700 static void
701 __gnat_error_handler (int sig)
702 {
703 struct Exception_Data *exception;
704 const char *msg;
705
706 switch(sig)
707 {
708 case SIGFPE:
709 exception = &constraint_error;
710 msg = "SIGFPE";
711 break;
712 case SIGILL:
713 exception = &constraint_error;
714 msg = "SIGILL";
715 break;
716 case SIGSEGV:
717 exception = &storage_error;
718 msg = "stack overflow or erroneous memory access";
719 break;
720 case SIGBUS:
721 exception = &constraint_error;
722 msg = "SIGBUS";
723 break;
724 default:
725 exception = &program_error;
726 msg = "unhandled signal";
727 }
728
729 Raise_From_Signal_Handler (exception, msg);
730 }
731
732 void
733 __gnat_install_handler (void)
734 {
735 struct sigaction act;
736
737 act.sa_handler = __gnat_error_handler;
738 act.sa_flags = 0x0;
739 sigemptyset (&act.sa_mask);
740
741 /* Do not install handlers if interrupt state is "System". */
742 if (__gnat_get_interrupt_state (SIGFPE) != 's')
743 sigaction (SIGFPE, &act, NULL);
744 if (__gnat_get_interrupt_state (SIGILL) != 's')
745 sigaction (SIGILL, &act, NULL);
746 if (__gnat_get_interrupt_state (SIGSEGV) != 's')
747 sigaction (SIGSEGV, &act, NULL);
748 if (__gnat_get_interrupt_state (SIGBUS) != 's')
749 sigaction (SIGBUS, &act, NULL);
750
751 __gnat_handler_installed = 1;
752 }
753
754 /*******************/
755 /* Solaris Section */
756 /*******************/
757
758 #elif defined (__sun__) && !defined (__vxworks)
759
760 #include <signal.h>
761 #include <siginfo.h>
762 #include <sys/ucontext.h>
763 #include <sys/regset.h>
764
765 static void
766 __gnat_error_handler (int sig, siginfo_t *si, void *ucontext ATTRIBUTE_UNUSED)
767 {
768 struct Exception_Data *exception;
769 static int recurse = 0;
770 const char *msg;
771
772 switch (sig)
773 {
774 case SIGSEGV:
775 /* If the problem was permissions, this is a constraint error.
776 Likewise if the failing address isn't maximally aligned or if
777 we've recursed.
778
779 ??? Using a static variable here isn't task-safe, but it's
780 much too hard to do anything else and we're just determining
781 which exception to raise. */
782 if (si->si_code == SEGV_ACCERR
783 || (long) si->si_addr == 0
784 || (((long) si->si_addr) & 3) != 0
785 || recurse)
786 {
787 exception = &constraint_error;
788 msg = "SIGSEGV";
789 }
790 else
791 {
792 /* See if the page before the faulting page is accessible. Do that
793 by trying to access it. We'd like to simply try to access
794 4096 + the faulting address, but it's not guaranteed to be
795 the actual address, just to be on the same page. */
796 recurse++;
797 ((volatile char *)
798 ((long) si->si_addr & - getpagesize ()))[getpagesize ()];
799 exception = &storage_error;
800 msg = "stack overflow or erroneous memory access";
801 }
802 break;
803
804 case SIGBUS:
805 exception = &program_error;
806 msg = "SIGBUS";
807 break;
808
809 case SIGFPE:
810 exception = &constraint_error;
811 msg = "SIGFPE";
812 break;
813
814 default:
815 exception = &program_error;
816 msg = "unhandled signal";
817 }
818
819 recurse = 0;
820 Raise_From_Signal_Handler (exception, msg);
821 }
822
823 void
824 __gnat_install_handler (void)
825 {
826 struct sigaction act;
827
828 /* Set up signal handler to map synchronous signals to appropriate
829 exceptions. Make sure that the handler isn't interrupted by another
830 signal that might cause a scheduling event! */
831
832 act.sa_sigaction = __gnat_error_handler;
833 act.sa_flags = SA_NODEFER | SA_RESTART | SA_SIGINFO;
834 sigemptyset (&act.sa_mask);
835
836 /* Do not install handlers if interrupt state is "System". */
837 if (__gnat_get_interrupt_state (SIGABRT) != 's')
838 sigaction (SIGABRT, &act, NULL);
839 if (__gnat_get_interrupt_state (SIGFPE) != 's')
840 sigaction (SIGFPE, &act, NULL);
841 if (__gnat_get_interrupt_state (SIGSEGV) != 's')
842 sigaction (SIGSEGV, &act, NULL);
843 if (__gnat_get_interrupt_state (SIGBUS) != 's')
844 sigaction (SIGBUS, &act, NULL);
845
846 __gnat_handler_installed = 1;
847 }
848
849 /***************/
850 /* VMS Section */
851 /***************/
852
853 #elif defined (VMS)
854
855 /* Routine called from binder to override default feature values. */
856 void __gnat_set_features (void);
857 int __gnat_features_set = 0;
858 void (*__gnat_ctrl_c_handler) (void) = 0;
859
860 #ifdef __IA64
861 #define lib_get_curr_invo_context LIB$I64_GET_CURR_INVO_CONTEXT
862 #define lib_get_prev_invo_context LIB$I64_GET_PREV_INVO_CONTEXT
863 #define lib_get_invo_handle LIB$I64_GET_INVO_HANDLE
864 #else
865 #define lib_get_curr_invo_context LIB$GET_CURR_INVO_CONTEXT
866 #define lib_get_prev_invo_context LIB$GET_PREV_INVO_CONTEXT
867 #define lib_get_invo_handle LIB$GET_INVO_HANDLE
868 #endif
869
870 /* Masks for facility identification. */
871 #define FAC_MASK 0x0fff0000
872 #define DECADA_M_FACILITY 0x00310000
873
874 /* Define macro symbols for the VMS conditions that become Ada exceptions.
875 It would be better to just include <ssdef.h> */
876
877 #define SS$_CONTINUE 1
878 #define SS$_ACCVIO 12
879 #define SS$_HPARITH 1284
880 #define SS$_INTDIV 1156
881 #define SS$_STKOVF 1364
882 #define SS$_CONTROLC 1617
883 #define SS$_RESIGNAL 2328
884
885 #define MTH$_FLOOVEMAT 1475268 /* Some ACVC_21 CXA tests */
886
887 /* The following codes must be resignalled, and not handled here. */
888
889 /* These codes are in standard message libraries. */
890 extern int C$_SIGKILL;
891 extern int C$_SIGINT;
892 extern int SS$_DEBUG;
893 extern int LIB$_KEYNOTFOU;
894 extern int LIB$_ACTIMAGE;
895
896 /* These codes are non standard, which is to say the author is
897 not sure if they are defined in the standard message libraries
898 so keep them as macros for now. */
899 #define RDB$_STREAM_EOF 20480426
900 #define FDL$_UNPRIKW 11829410
901 #define CMA$_EXIT_THREAD 4227492
902
903 struct cond_sigargs
904 {
905 unsigned int sigarg;
906 unsigned int sigargval;
907 };
908
909 struct cond_subtests
910 {
911 unsigned int num;
912 const struct cond_sigargs sigargs[];
913 };
914
915 struct cond_except
916 {
917 unsigned int cond;
918 const struct Exception_Data *except;
919 unsigned int needs_adjust; /* 1 = adjust PC, 0 = no adjust */
920 const struct cond_subtests *subtests;
921 };
922
923 struct descriptor_s
924 {
925 unsigned short len, mbz;
926 __char_ptr32 adr;
927 };
928
929 /* Conditions that don't have an Ada exception counterpart must raise
930 Non_Ada_Error. Since this is defined in s-auxdec, it should only be
931 referenced by user programs, not the compiler or tools. Hence the
932 #ifdef IN_RTS. */
933
934 #ifdef IN_RTS
935
936 #define Status_Error ada__io_exceptions__status_error
937 extern struct Exception_Data Status_Error;
938
939 #define Mode_Error ada__io_exceptions__mode_error
940 extern struct Exception_Data Mode_Error;
941
942 #define Name_Error ada__io_exceptions__name_error
943 extern struct Exception_Data Name_Error;
944
945 #define Use_Error ada__io_exceptions__use_error
946 extern struct Exception_Data Use_Error;
947
948 #define Device_Error ada__io_exceptions__device_error
949 extern struct Exception_Data Device_Error;
950
951 #define End_Error ada__io_exceptions__end_error
952 extern struct Exception_Data End_Error;
953
954 #define Data_Error ada__io_exceptions__data_error
955 extern struct Exception_Data Data_Error;
956
957 #define Layout_Error ada__io_exceptions__layout_error
958 extern struct Exception_Data Layout_Error;
959
960 #define Non_Ada_Error system__aux_dec__non_ada_error
961 extern struct Exception_Data Non_Ada_Error;
962
963 #define Coded_Exception system__vms_exception_table__coded_exception
964 extern struct Exception_Data *Coded_Exception (void *);
965
966 #define Base_Code_In system__vms_exception_table__base_code_in
967 extern void *Base_Code_In (void *);
968
969 /* DEC Ada exceptions are not defined in a header file, so they
970 must be declared. */
971
972 #define ADA$_ALREADY_OPEN 0x0031a594
973 #define ADA$_CONSTRAINT_ERRO 0x00318324
974 #define ADA$_DATA_ERROR 0x003192c4
975 #define ADA$_DEVICE_ERROR 0x003195e4
976 #define ADA$_END_ERROR 0x00319904
977 #define ADA$_FAC_MODE_MISMAT 0x0031a8b3
978 #define ADA$_IOSYSFAILED 0x0031af04
979 #define ADA$_KEYSIZERR 0x0031aa3c
980 #define ADA$_KEY_MISMATCH 0x0031a8e3
981 #define ADA$_LAYOUT_ERROR 0x00319c24
982 #define ADA$_LINEXCMRS 0x0031a8f3
983 #define ADA$_MAXLINEXC 0x0031a8eb
984 #define ADA$_MODE_ERROR 0x00319f44
985 #define ADA$_MRN_MISMATCH 0x0031a8db
986 #define ADA$_MRS_MISMATCH 0x0031a8d3
987 #define ADA$_NAME_ERROR 0x0031a264
988 #define ADA$_NOT_OPEN 0x0031a58c
989 #define ADA$_ORG_MISMATCH 0x0031a8bb
990 #define ADA$_PROGRAM_ERROR 0x00318964
991 #define ADA$_RAT_MISMATCH 0x0031a8cb
992 #define ADA$_RFM_MISMATCH 0x0031a8c3
993 #define ADA$_STAOVF 0x00318cac
994 #define ADA$_STATUS_ERROR 0x0031a584
995 #define ADA$_STORAGE_ERROR 0x00318c84
996 #define ADA$_UNSUPPORTED 0x0031a8ab
997 #define ADA$_USE_ERROR 0x0031a8a4
998
999 /* DEC Ada specific conditions. */
1000 static const struct cond_except dec_ada_cond_except_table [] =
1001 {
1002 {ADA$_PROGRAM_ERROR, &program_error, 0, 0},
1003 {ADA$_USE_ERROR, &Use_Error, 0, 0},
1004 {ADA$_KEYSIZERR, &program_error, 0, 0},
1005 {ADA$_STAOVF, &storage_error, 0, 0},
1006 {ADA$_CONSTRAINT_ERRO, &constraint_error, 0, 0},
1007 {ADA$_IOSYSFAILED, &Device_Error, 0, 0},
1008 {ADA$_LAYOUT_ERROR, &Layout_Error, 0, 0},
1009 {ADA$_STORAGE_ERROR, &storage_error, 0, 0},
1010 {ADA$_DATA_ERROR, &Data_Error, 0, 0},
1011 {ADA$_DEVICE_ERROR, &Device_Error, 0, 0},
1012 {ADA$_END_ERROR, &End_Error, 0, 0},
1013 {ADA$_MODE_ERROR, &Mode_Error, 0, 0},
1014 {ADA$_NAME_ERROR, &Name_Error, 0, 0},
1015 {ADA$_STATUS_ERROR, &Status_Error, 0, 0},
1016 {ADA$_NOT_OPEN, &Use_Error, 0, 0},
1017 {ADA$_ALREADY_OPEN, &Use_Error, 0, 0},
1018 {ADA$_USE_ERROR, &Use_Error, 0, 0},
1019 {ADA$_UNSUPPORTED, &Use_Error, 0, 0},
1020 {ADA$_FAC_MODE_MISMAT, &Use_Error, 0, 0},
1021 {ADA$_ORG_MISMATCH, &Use_Error, 0, 0},
1022 {ADA$_RFM_MISMATCH, &Use_Error, 0, 0},
1023 {ADA$_RAT_MISMATCH, &Use_Error, 0, 0},
1024 {ADA$_MRS_MISMATCH, &Use_Error, 0, 0},
1025 {ADA$_MRN_MISMATCH, &Use_Error, 0, 0},
1026 {ADA$_KEY_MISMATCH, &Use_Error, 0, 0},
1027 {ADA$_MAXLINEXC, &constraint_error, 0, 0},
1028 {ADA$_LINEXCMRS, &constraint_error, 0, 0},
1029
1030 #if 0
1031 /* Already handled by a pragma Import_Exception
1032 in Aux_IO_Exceptions */
1033 {ADA$_LOCK_ERROR, &Lock_Error, 0, 0},
1034 {ADA$_EXISTENCE_ERROR, &Existence_Error, 0, 0},
1035 {ADA$_KEY_ERROR, &Key_Error, 0, 0},
1036 #endif
1037
1038 {0, 0, 0, 0}
1039 };
1040
1041 #endif /* IN_RTS */
1042
1043 /* Non-DEC Ada specific conditions that map to Ada exceptions. */
1044
1045 /* Subtest for ACCVIO Constraint_Error, kept for compatibility,
1046 in hindsight should have just made ACCVIO == Storage_Error. */
1047 #define ACCVIO_VIRTUAL_ADDR 3
1048 static const struct cond_subtests accvio_c_e =
1049 {1, /* number of subtests below */
1050 {
1051 { ACCVIO_VIRTUAL_ADDR, 0 }
1052 }
1053 };
1054
1055 /* Macro flag to adjust PC which gets off by one for some conditions,
1056 not sure if this is reliably true, PC could be off by more for
1057 HPARITH for example, unless a trapb is inserted. */
1058 #define NEEDS_ADJUST 1
1059
1060 static const struct cond_except system_cond_except_table [] =
1061 {
1062 {MTH$_FLOOVEMAT, &constraint_error, 0, 0},
1063 {SS$_INTDIV, &constraint_error, 0, 0},
1064 {SS$_HPARITH, &constraint_error, NEEDS_ADJUST, 0},
1065 {SS$_ACCVIO, &constraint_error, NEEDS_ADJUST, &accvio_c_e},
1066 {SS$_ACCVIO, &storage_error, NEEDS_ADJUST, 0},
1067 {SS$_STKOVF, &storage_error, NEEDS_ADJUST, 0},
1068 {0, 0, 0, 0}
1069 };
1070
1071 /* To deal with VMS conditions and their mapping to Ada exceptions,
1072 the __gnat_error_handler routine below is installed as an exception
1073 vector having precedence over DEC frame handlers. Some conditions
1074 still need to be handled by such handlers, however, in which case
1075 __gnat_error_handler needs to return SS$_RESIGNAL. Consider for
1076 instance the use of a third party library compiled with DECAda and
1077 performing its own exception handling internally.
1078
1079 To allow some user-level flexibility, which conditions should be
1080 resignaled is controlled by a predicate function, provided with the
1081 condition value and returning a boolean indication stating whether
1082 this condition should be resignaled or not.
1083
1084 That predicate function is called indirectly, via a function pointer,
1085 by __gnat_error_handler, and changing that pointer is allowed to the
1086 user code by way of the __gnat_set_resignal_predicate interface.
1087
1088 The user level function may then implement what it likes, including
1089 for instance the maintenance of a dynamic data structure if the set
1090 of to be resignalled conditions has to change over the program's
1091 lifetime.
1092
1093 ??? This is not a perfect solution to deal with the possible
1094 interactions between the GNAT and the DECAda exception handling
1095 models and better (more general) schemes are studied. This is so
1096 just provided as a convenient workaround in the meantime, and
1097 should be use with caution since the implementation has been kept
1098 very simple. */
1099
1100 typedef int resignal_predicate (int code);
1101
1102 static const int * const cond_resignal_table [] =
1103 {
1104 &C$_SIGKILL,
1105 (int *)CMA$_EXIT_THREAD,
1106 &SS$_DEBUG,
1107 &LIB$_KEYNOTFOU,
1108 &LIB$_ACTIMAGE,
1109 (int *) RDB$_STREAM_EOF,
1110 (int *) FDL$_UNPRIKW,
1111 0
1112 };
1113
1114 static const int facility_resignal_table [] =
1115 {
1116 0x1380000, /* RDB */
1117 0x2220000, /* SQL */
1118 0
1119 };
1120
1121 /* Default GNAT predicate for resignaling conditions. */
1122
1123 static int
1124 __gnat_default_resignal_p (int code)
1125 {
1126 int i, iexcept;
1127
1128 for (i = 0; facility_resignal_table [i]; i++)
1129 if ((code & FAC_MASK) == facility_resignal_table [i])
1130 return 1;
1131
1132 for (i = 0, iexcept = 0;
1133 cond_resignal_table [i]
1134 && !(iexcept = LIB$MATCH_COND (&code, &cond_resignal_table [i]));
1135 i++);
1136
1137 return iexcept;
1138 }
1139
1140 /* Static pointer to predicate that the __gnat_error_handler exception
1141 vector invokes to determine if it should resignal a condition. */
1142
1143 static resignal_predicate *__gnat_resignal_p = __gnat_default_resignal_p;
1144
1145 /* User interface to change the predicate pointer to PREDICATE. Reset to
1146 the default if PREDICATE is null. */
1147
1148 void
1149 __gnat_set_resignal_predicate (resignal_predicate *predicate)
1150 {
1151 if (predicate == NULL)
1152 __gnat_resignal_p = __gnat_default_resignal_p;
1153 else
1154 __gnat_resignal_p = predicate;
1155 }
1156
1157 /* Should match System.Parameters.Default_Exception_Msg_Max_Length. */
1158 #define Default_Exception_Msg_Max_Length 512
1159
1160 /* Action routine for SYS$PUTMSG. There may be multiple
1161 conditions, each with text to be appended to MESSAGE
1162 and separated by line termination. */
1163 static int
1164 copy_msg (struct descriptor_s *msgdesc, char *message)
1165 {
1166 int len = strlen (message);
1167 int copy_len;
1168
1169 /* Check for buffer overflow and skip. */
1170 if (len > 0 && len <= Default_Exception_Msg_Max_Length - 3)
1171 {
1172 strcat (message, "\r\n");
1173 len += 2;
1174 }
1175
1176 /* Check for buffer overflow and truncate if necessary. */
1177 copy_len = (len + msgdesc->len <= Default_Exception_Msg_Max_Length - 1 ?
1178 msgdesc->len :
1179 Default_Exception_Msg_Max_Length - 1 - len);
1180 strncpy (&message [len], msgdesc->adr, copy_len);
1181 message [len + copy_len] = 0;
1182
1183 return 0;
1184 }
1185
1186 /* Scan TABLE for a match for the condition contained in SIGARGS,
1187 and return the entry, or the empty entry if no match found. */
1188 static const struct cond_except *
1189 scan_conditions ( int *sigargs, const struct cond_except *table [])
1190 {
1191 int i;
1192 struct cond_except entry;
1193
1194 /* Scan the exception condition table for a match and fetch
1195 the associated GNAT exception pointer. */
1196 for (i = 0; (*table) [i].cond; i++)
1197 {
1198 unsigned int match = LIB$MATCH_COND (&sigargs [1], &(*table) [i].cond);
1199 const struct cond_subtests *subtests = (*table) [i].subtests;
1200
1201 if (match)
1202 {
1203 if (!subtests)
1204 {
1205 return &(*table) [i];
1206 }
1207 else
1208 {
1209 unsigned int ii;
1210 int num = (*subtests).num;
1211
1212 /* Perform subtests to differentiate exception. */
1213 for (ii = 0; ii < num; ii++)
1214 {
1215 unsigned int arg = (*subtests).sigargs [ii].sigarg;
1216 unsigned int argval = (*subtests).sigargs [ii].sigargval;
1217
1218 if (sigargs [arg] != argval)
1219 {
1220 num = 0;
1221 break;
1222 }
1223 }
1224
1225 /* All subtests passed. */
1226 if (num == (*subtests).num)
1227 return &(*table) [i];
1228 }
1229 }
1230 }
1231
1232 /* No match, return the null terminating entry. */
1233 return &(*table) [i];
1234 }
1235
1236 /* __gnat_handle_vms_condtition is both a frame based handler
1237 for the runtime, and an exception vector for the compiler. */
1238 long
1239 __gnat_handle_vms_condition (int *sigargs, void *mechargs)
1240 {
1241 struct Exception_Data *exception = 0;
1242 unsigned int needs_adjust = 0;
1243 void *base_code;
1244 struct descriptor_s gnat_facility = {4, 0, "GNAT"};
1245 char message [Default_Exception_Msg_Max_Length];
1246
1247 const char *msg = "";
1248
1249 /* Check for conditions to resignal which aren't effected by pragma
1250 Import_Exception. */
1251 if (__gnat_resignal_p (sigargs [1]))
1252 return SS$_RESIGNAL;
1253 #ifndef IN_RTS
1254 /* toplev.cc handles this for compiler. */
1255 if (sigargs [1] == SS$_HPARITH)
1256 return SS$_RESIGNAL;
1257 #endif
1258
1259 #ifdef IN_RTS
1260 /* See if it's an imported exception. Beware that registered exceptions
1261 are bound to their base code, with the severity bits masked off. */
1262 base_code = Base_Code_In ((void *) sigargs[1]);
1263 exception = Coded_Exception (base_code);
1264 #endif
1265
1266 if (exception == 0)
1267 #ifdef IN_RTS
1268 {
1269 int i;
1270 struct cond_except cond;
1271 const struct cond_except *cond_table;
1272 const struct cond_except *cond_tables [] = {dec_ada_cond_except_table,
1273 system_cond_except_table,
1274 0};
1275 unsigned int ctrlc = SS$_CONTROLC;
1276 unsigned int *sigint = &C$_SIGINT;
1277 int ctrlc_match = LIB$MATCH_COND (&sigargs [1], &ctrlc);
1278 int sigint_match = LIB$MATCH_COND (&sigargs [1], &sigint);
1279
1280 extern int SYS$DCLAST (void (*astadr)(), unsigned long long astprm,
1281 unsigned int acmode);
1282
1283 /* If SS$_CONTROLC has been imported as an exception, it will take
1284 priority over a Ctrl/C handler. See above. SIGINT has a
1285 different condition value due to it's DECCCRTL roots and it's
1286 the condition that gets raised for a "kill -INT". */
1287 if ((ctrlc_match || sigint_match) && __gnat_ctrl_c_handler)
1288 {
1289 SYS$DCLAST (__gnat_ctrl_c_handler, 0, 0);
1290 return SS$_CONTINUE;
1291 }
1292
1293 i = 0;
1294 while ((cond_table = cond_tables[i++]) && !exception)
1295 {
1296 cond = *scan_conditions (sigargs, &cond_table);
1297 exception = (struct Exception_Data *) cond.except;
1298 }
1299
1300 if (exception)
1301 needs_adjust = cond.needs_adjust;
1302 else
1303 /* User programs expect Non_Ada_Error to be raised if no match,
1304 reference DEC Ada test CXCONDHAN. */
1305 exception = &Non_Ada_Error;
1306 }
1307 #else
1308 {
1309 /* Pretty much everything is just a program error in the compiler */
1310 exception = &program_error;
1311 }
1312 #endif
1313
1314 message[0] = 0;
1315 /* Subtract PC & PSL fields as per ABI for SYS$PUTMSG. */
1316 sigargs[0] -= 2;
1317
1318 extern int SYS$PUTMSG (void *, int (*)(), void *, unsigned long long);
1319
1320 /* If it was a DEC Ada specific condtiion, make it GNAT otherwise
1321 keep the old facility. */
1322 if ((sigargs [1] & FAC_MASK) == DECADA_M_FACILITY)
1323 SYS$PUTMSG (sigargs, copy_msg, &gnat_facility,
1324 (unsigned long long ) message);
1325 else
1326 SYS$PUTMSG (sigargs, copy_msg, 0,
1327 (unsigned long long ) message);
1328
1329 /* Add back PC & PSL fields as per ABI for SYS$PUTMSG. */
1330 sigargs[0] += 2;
1331 msg = message;
1332
1333 if (needs_adjust)
1334 __gnat_adjust_context_for_raise (sigargs [1], (void *)mechargs);
1335
1336 Raise_From_Signal_Handler (exception, msg);
1337 }
1338
1339 #if defined (IN_RTS) && defined (__IA64)
1340 /* Called only from adasigio.b32. This is a band aid to avoid going
1341 through the VMS signal handling code which results in a 0x8000 per
1342 handled exception memory leak in P2 space (see VMS source listing
1343 sys/lis/exception.lis) due to the allocation of working space that
1344 is expected to be deallocated upon return from the condition handler,
1345 which doesn't return in GNAT compiled code. */
1346 void
1347 GNAT$STOP (int *sigargs)
1348 {
1349 /* Note that there are no mechargs. We rely on the fact that condtions
1350 raised from DEClib I/O do not require an "adjust". Also the count
1351 will be off by 2, since LIB$STOP didn't get a chance to add the
1352 PC and PSL fields, so we bump it so PUTMSG comes out right. */
1353 sigargs [0] += 2;
1354 __gnat_handle_vms_condition (sigargs, 0);
1355 }
1356 #endif
1357
1358 void
1359 __gnat_install_handler (void)
1360 {
1361 long prvhnd ATTRIBUTE_UNUSED;
1362
1363 #if !defined (IN_RTS)
1364 extern int SYS$SETEXV (unsigned int vector, int (*addres)(),
1365 unsigned int accmode, void *(*(prvhnd)));
1366 SYS$SETEXV (1, __gnat_handle_vms_condition, 3, &prvhnd);
1367 #endif
1368
1369 __gnat_handler_installed = 1;
1370 }
1371
1372 /* __gnat_adjust_context_for_raise for Alpha - see comments along with the
1373 default version later in this file. */
1374
1375 #if defined (IN_RTS) && defined (__alpha__)
1376
1377 #include <vms/chfctxdef.h>
1378 #include <vms/chfdef.h>
1379
1380 #define HAVE_GNAT_ADJUST_CONTEXT_FOR_RAISE
1381
1382 void
1383 __gnat_adjust_context_for_raise (int signo ATTRIBUTE_UNUSED, void *ucontext)
1384 {
1385 if (signo == SS$_HPARITH)
1386 {
1387 /* Sub one to the address of the instruction signaling the condition,
1388 located in the sigargs array. */
1389
1390 CHF$MECH_ARRAY * mechargs = (CHF$MECH_ARRAY *) ucontext;
1391 CHF$SIGNAL_ARRAY * sigargs
1392 = (CHF$SIGNAL_ARRAY *) mechargs->chf$q_mch_sig_addr;
1393
1394 int vcount = sigargs->chf$is_sig_args;
1395 int * pc_slot = & (&sigargs->chf$l_sig_name)[vcount-2];
1396
1397 (*pc_slot)--;
1398 }
1399 }
1400
1401 #endif
1402
1403 /* __gnat_adjust_context_for_raise for ia64. */
1404
1405 #if defined (IN_RTS) && defined (__IA64)
1406
1407 #include <vms/chfctxdef.h>
1408 #include <vms/chfdef.h>
1409
1410 #define HAVE_GNAT_ADJUST_CONTEXT_FOR_RAISE
1411
1412 typedef unsigned long long u64;
1413
1414 void
1415 __gnat_adjust_context_for_raise (int signo ATTRIBUTE_UNUSED, void *ucontext)
1416 {
1417 /* Add one to the address of the instruction signaling the condition,
1418 located in the 64bits sigargs array. */
1419
1420 CHF$MECH_ARRAY * mechargs = (CHF$MECH_ARRAY *) ucontext;
1421
1422 CHF64$SIGNAL_ARRAY *chfsig64
1423 = (CHF64$SIGNAL_ARRAY *) mechargs->chf$ph_mch_sig64_addr;
1424
1425 u64 * post_sigarray
1426 = (u64 *)chfsig64 + 1 + chfsig64->chf64$l_sig_args;
1427
1428 u64 * ih_pc_loc = post_sigarray - 2;
1429
1430 (*ih_pc_loc) ++;
1431 }
1432
1433 #endif
1434
1435 /* Easier interface for LIB$GET_LOGICAL: put the equivalence of NAME into BUF,
1436 always NUL terminated. In case of error or if the result is longer than
1437 LEN (length of BUF) an empty string is written info BUF. */
1438
1439 static void
1440 __gnat_vms_get_logical (const char *name, char *buf, int len)
1441 {
1442 struct descriptor_s name_desc, result_desc;
1443 int status;
1444 unsigned short rlen;
1445
1446 /* Build the descriptor for NAME. */
1447 name_desc.len = strlen (name);
1448 name_desc.mbz = 0;
1449 name_desc.adr = (char *)name;
1450
1451 /* Build the descriptor for the result. */
1452 result_desc.len = len;
1453 result_desc.mbz = 0;
1454 result_desc.adr = buf;
1455
1456 status = LIB$GET_LOGICAL (&name_desc, &result_desc, &rlen);
1457
1458 if ((status & 1) == 1 && rlen < len)
1459 buf[rlen] = 0;
1460 else
1461 buf[0] = 0;
1462 }
1463
1464 /* Size of a page on ia64 and alpha VMS. */
1465 #define VMS_PAGESIZE 8192
1466
1467 /* User mode. */
1468 #define PSL__C_USER 3
1469
1470 /* No access. */
1471 #define PRT__C_NA 0
1472
1473 /* Descending region. */
1474 #define VA__M_DESCEND 1
1475
1476 /* Get by virtual address. */
1477 #define VA___REGSUM_BY_VA 1
1478
1479 /* Memory region summary. */
1480 struct regsum
1481 {
1482 unsigned long long q_region_id;
1483 unsigned int l_flags;
1484 unsigned int l_region_protection;
1485 void *pq_start_va;
1486 unsigned long long q_region_size;
1487 void *pq_first_free_va;
1488 };
1489
1490 extern int SYS$GET_REGION_INFO (unsigned int, unsigned long long *,
1491 void *, void *, unsigned int,
1492 void *, unsigned int *);
1493 extern int SYS$EXPREG_64 (unsigned long long *, unsigned long long,
1494 unsigned int, unsigned int, void **,
1495 unsigned long long *);
1496 extern int SYS$SETPRT_64 (void *, unsigned long long, unsigned int,
1497 unsigned int, void **, unsigned long long *,
1498 unsigned int *);
1499
1500 /* Add a guard page in the memory region containing ADDR at ADDR +/- SIZE.
1501 (The sign depends on the kind of the memory region). */
1502
1503 static int
1504 __gnat_set_stack_guard_page (void *addr, unsigned long size)
1505 {
1506 int status;
1507 void *ret_va;
1508 unsigned long long ret_len;
1509 unsigned int ret_prot;
1510 void *start_va;
1511 unsigned long long length;
1512 unsigned int retlen;
1513 struct regsum buffer;
1514
1515 /* Get the region for ADDR. */
1516 status = SYS$GET_REGION_INFO
1517 (VA___REGSUM_BY_VA, NULL, addr, NULL, sizeof (buffer), &buffer, &retlen);
1518
1519 if ((status & 1) != 1)
1520 return -1;
1521
1522 /* Extend the region. */
1523 status = SYS$EXPREG_64 (&buffer.q_region_id,
1524 size, 0, 0, &start_va, &length);
1525
1526 if ((status & 1) != 1)
1527 return -1;
1528
1529 /* Create a guard page. */
1530 if (!(buffer.l_flags & VA__M_DESCEND))
1531 start_va = (void *)((unsigned long long)start_va + length - VMS_PAGESIZE);
1532
1533 status = SYS$SETPRT_64 (start_va, VMS_PAGESIZE, PSL__C_USER, PRT__C_NA,
1534 &ret_va, &ret_len, &ret_prot);
1535
1536 if ((status & 1) != 1)
1537 return -1;
1538 return 0;
1539 }
1540
1541 /* Read logicals to limit the stack(s) size. */
1542
1543 static void
1544 __gnat_set_stack_limit (void)
1545 {
1546 #ifdef __ia64__
1547 void *sp;
1548 unsigned long size;
1549 char value[16];
1550 char *e;
1551
1552 /* The main stack. */
1553 __gnat_vms_get_logical ("GNAT_STACK_SIZE", value, sizeof (value));
1554 size = strtoul (value, &e, 0);
1555 if (e > value && *e == 0)
1556 {
1557 asm ("mov %0=sp" : "=r" (sp));
1558 __gnat_set_stack_guard_page (sp, size * 1024);
1559 }
1560
1561 /* The register stack. */
1562 __gnat_vms_get_logical ("GNAT_RBS_SIZE", value, sizeof (value));
1563 size = strtoul (value, &e, 0);
1564 if (e > value && *e == 0)
1565 {
1566 asm ("mov %0=ar.bsp" : "=r" (sp));
1567 __gnat_set_stack_guard_page (sp, size * 1024);
1568 }
1569 #endif
1570 }
1571
1572 #ifdef IN_RTS
1573 extern int SYS$IEEE_SET_FP_CONTROL (void *, void *, void *);
1574 #define K_TRUE 1
1575 #define __int64 long long
1576 #define __NEW_STARLET
1577 #include <vms/ieeedef.h>
1578 #endif
1579
1580 /* Feature logical name and global variable address pair.
1581 If we ever add another feature logical to this list, the
1582 feature struct will need to be enhanced to take into account
1583 possible values for *gl_addr. */
1584 struct feature {
1585 const char *name;
1586 int *gl_addr;
1587 };
1588
1589 /* Default values for GNAT features set by environment or binder. */
1590 int __gl_heap_size = 64;
1591
1592 /* Default float format is 'I' meaning IEEE. If gnatbind detetcts that a
1593 VAX Float format is specified, it will set this global variable to 'V'.
1594 Subsequently __gnat_set_features will test the variable and if set for
1595 VAX Float will call a Starlet function to enable trapping for invalid
1596 operation, drivide by zero, and overflow. This will prevent the VMS runtime
1597 (specifically OTS$CHECK_FP_MODE) from complaining about inconsistent
1598 floating point settings in a mixed language program. Ideally the setting
1599 would be determined at link time based on settings in the object files,
1600 however the VMS linker seems to take the setting from the first object
1601 in the link, e.g. pcrt0.o which is float representation neutral. */
1602 char __gl_float_format = 'I';
1603
1604 /* Array feature logical names and global variable addresses. */
1605 static const struct feature features[] =
1606 {
1607 {"GNAT$NO_MALLOC_64", &__gl_heap_size},
1608 {0, 0}
1609 };
1610
1611 void
1612 __gnat_set_features (void)
1613 {
1614 int i;
1615 char buff[16];
1616 #ifdef IN_RTS
1617 IEEE clrmsk, setmsk, prvmsk;
1618
1619 clrmsk.ieee$q_flags = 0LL;
1620 setmsk.ieee$q_flags = 0LL;
1621 #endif
1622
1623 /* Loop through features array and test name for enable/disable. */
1624 for (i = 0; features[i].name; i++)
1625 {
1626 __gnat_vms_get_logical (features[i].name, buff, sizeof (buff));
1627
1628 if (strcmp (buff, "ENABLE") == 0
1629 || strcmp (buff, "TRUE") == 0
1630 || strcmp (buff, "1") == 0)
1631 *features[i].gl_addr = 32;
1632 else if (strcmp (buff, "DISABLE") == 0
1633 || strcmp (buff, "FALSE") == 0
1634 || strcmp (buff, "0") == 0)
1635 *features[i].gl_addr = 64;
1636 }
1637
1638 /* Features to artificially limit the stack size. */
1639 __gnat_set_stack_limit ();
1640
1641 #ifdef IN_RTS
1642 if (__gl_float_format == 'V')
1643 {
1644 setmsk.ieee$v_trap_enable_inv = K_TRUE;
1645 setmsk.ieee$v_trap_enable_dze = K_TRUE;
1646 setmsk.ieee$v_trap_enable_ovf = K_TRUE;
1647 SYS$IEEE_SET_FP_CONTROL (&clrmsk, &setmsk, &prvmsk);
1648 }
1649 #endif
1650
1651 __gnat_features_set = 1;
1652 }
1653
1654 /* Return true if the VMS version is 7.x. */
1655
1656 extern unsigned int LIB$GETSYI (int *, ...);
1657
1658 #define SYI$_VERSION 0x1000
1659
1660 int
1661 __gnat_is_vms_v7 (void)
1662 {
1663 struct descriptor_s desc;
1664 char version[8];
1665 int status;
1666 int code = SYI$_VERSION;
1667
1668 desc.len = sizeof (version);
1669 desc.mbz = 0;
1670 desc.adr = version;
1671
1672 status = LIB$GETSYI (&code, 0, &desc);
1673 if ((status & 1) == 1 && version[1] == '7' && version[2] == '.')
1674 return 1;
1675 else
1676 return 0;
1677 }
1678
1679 /*******************/
1680 /* FreeBSD Section */
1681 /*******************/
1682
1683 #elif defined (__FreeBSD__) || defined (__DragonFly__)
1684
1685 #include <signal.h>
1686 #include <sys/ucontext.h>
1687 #include <unistd.h>
1688
1689 static void
1690 #ifdef __CHERI__
1691 __gnat_error_handler (int sig,
1692 siginfo_t *si,
1693 void *ucontext ATTRIBUTE_UNUSED)
1694 #else
1695 __gnat_error_handler (int sig,
1696 siginfo_t *si ATTRIBUTE_UNUSED,
1697 void *ucontext ATTRIBUTE_UNUSED)
1698 #endif /* __CHERI__ */
1699 {
1700 struct Exception_Data *exception;
1701 const char *msg;
1702
1703 switch (sig)
1704 {
1705 case SIGFPE:
1706 exception = &constraint_error;
1707 msg = "SIGFPE";
1708 break;
1709
1710 case SIGILL:
1711 exception = &constraint_error;
1712 msg = "SIGILL";
1713 break;
1714
1715 case SIGSEGV:
1716 exception = &storage_error;
1717 msg = "stack overflow or erroneous memory access";
1718 break;
1719
1720 case SIGBUS:
1721 exception = &storage_error;
1722 msg = "SIGBUS: possible stack overflow";
1723 break;
1724
1725 #ifdef __CHERI__
1726 case SIGPROT:
1727 switch (si->si_code)
1728 {
1729 case PROT_CHERI_TAG:
1730 exception = capability_tag_error_id;
1731 msg = "Capability tag fault";
1732 break;
1733
1734 case PROT_CHERI_SEALED:
1735 exception = capability_sealed_error_id;
1736 msg = "Capability sealed fault";
1737 break;
1738
1739 case PROT_CHERI_UNALIGNED_BASE:
1740 exception = &storage_error;
1741 msg = "SIGPROT: unaligned base address";
1742 break;
1743
1744 case PROT_CHERI_BOUNDS:
1745 exception = capability_bound_error_id;
1746 msg = "Capability bounds fault";
1747 break;
1748
1749 case PROT_CHERI_IMPRECISE:
1750 exception = capability_bound_error_id;
1751 msg = "Imprecise capability bounds fault";
1752 break;
1753
1754 case PROT_CHERI_TYPE:
1755 exception = capability_permission_error_id;
1756 msg = "Capability type mismatch fault";
1757 break;
1758
1759 case PROT_CHERI_PERM:
1760 exception = capability_permission_error_id;
1761 msg = "Capability permission fault";
1762 break;
1763
1764 case PROT_CHERI_STORELOCAL:
1765 exception = capability_permission_error_id;
1766 msg = "Capability store-local fault";
1767 break;
1768
1769 case PROT_CHERI_CINVOKE:
1770 exception = capability_permission_error_id;
1771 msg = "CInvoke fault";
1772 break;
1773
1774 case PROT_CHERI_SYSREG:
1775 exception = capability_permission_error_id;
1776 msg = "Capability system register fault";
1777 break;
1778
1779 default:
1780 exception = &program_error;
1781 msg = "SIGPROT: unhandled signal code";
1782 }
1783 break;
1784 #endif /* __CHERI__ */
1785
1786 default:
1787 exception = &program_error;
1788 msg = "unhandled signal";
1789 }
1790
1791 Raise_From_Signal_Handler (exception, msg);
1792 }
1793
1794 void
1795 __gnat_install_handler (void)
1796 {
1797 struct sigaction act;
1798
1799 /* Set up signal handler to map synchronous signals to appropriate
1800 exceptions. Make sure that the handler isn't interrupted by another
1801 signal that might cause a scheduling event! */
1802
1803 act.sa_sigaction
1804 = (void (*)(int, struct __siginfo *, void*)) __gnat_error_handler;
1805 act.sa_flags = SA_NODEFER | SA_RESTART | SA_SIGINFO;
1806 (void) sigemptyset (&act.sa_mask);
1807
1808 (void) sigaction (SIGILL, &act, NULL);
1809 (void) sigaction (SIGFPE, &act, NULL);
1810 (void) sigaction (SIGSEGV, &act, NULL);
1811 (void) sigaction (SIGBUS, &act, NULL);
1812
1813 #ifdef __CHERI__
1814 (void) sigaction (SIGPROT, &act, NULL);
1815 #endif
1816
1817 __gnat_handler_installed = 1;
1818 }
1819
1820 /*************************************/
1821 /* VxWorks Section (including Vx653) */
1822 /*************************************/
1823
1824 #elif defined(__vxworks)
1825
1826 #include <signal.h>
1827 #include <taskLib.h>
1828 #if (defined (__i386__) || defined (__x86_64__)) && !defined (VTHREADS)
1829 #include <sysLib.h>
1830 #endif
1831
1832 #include "sigtramp.h"
1833
1834 #ifndef __RTP__
1835 #include <intLib.h>
1836 #include <iv.h>
1837 #endif
1838
1839 #if ((defined (ARMEL) && (_WRS_VXWORKS_MAJOR == 6))) && !defined(__RTP__)
1840 #define VXWORKS_FORCE_GUARD_PAGE 1
1841 #include <vmLib.h>
1842 extern size_t vxIntStackOverflowSize;
1843 #define INT_OVERFLOW_SIZE vxIntStackOverflowSize
1844 #endif
1845
1846 /* VxWorks 653 vThreads expects the field excCnt to be zeroed when a signal is.
1847 handled. The VxWorks version of longjmp does this; GCC's builtin_longjmp
1848 doesn't. A similar issue is present VxWorks 7.2 and affects ZCX as well
1849 as builtin_longjmp. This field only exists in Kernel mode, not RTP. */
1850 #if defined(VTHREADS) || (!defined(__RTP__) && (_WRS_VXWORKS_MAJOR >= 7))
1851 # ifdef VTHREADS
1852 # include "private/vThreadsP.h"
1853 # define EXCCNT vThreads.excCnt
1854 # else
1855 # include "private/taskLibP.h"
1856 # define EXCCNT excCnt
1857 # endif
1858 # define CLEAR_EXCEPTION_COUNT() \
1859 do \
1860 { \
1861 WIND_TCB *currentTask = (WIND_TCB *) taskIdSelf(); \
1862 currentTask->EXCCNT = 0; \
1863 } while (0)
1864 #else
1865 # define CLEAR_EXCEPTION_COUNT()
1866 #endif
1867
1868 #ifndef __RTP__
1869
1870 /* Directly vectored Interrupt routines are not supported when using RTPs. */
1871
1872 extern void * __gnat_inum_to_ivec (int);
1873
1874 /* This is needed by the GNAT run time to handle Vxworks interrupts. */
1875 void *
1876 __gnat_inum_to_ivec (int num)
1877 {
1878 return (void *) INUM_TO_IVEC (num);
1879 }
1880 #endif
1881
1882 #if !defined(__alpha_vxworks) && ((_WRS_VXWORKS_MAJOR != 6) && (_WRS_VXWORKS_MAJOR != 7)) && !defined(__RTP__)
1883
1884 /* getpid is used by s-parint.adb, but is not defined by VxWorks, except
1885 on Alpha VxWorks and VxWorks 6.x (including RTPs). */
1886
1887 extern long getpid (void);
1888
1889 long
1890 getpid (void)
1891 {
1892 return taskIdSelf ();
1893 }
1894 #endif
1895
1896 /* When stack checking is performed by probing a guard page on the stack,
1897 sometimes this guard page is not properly reset on VxWorks. We need to
1898 manually reset it in this case.
1899 This function returns TRUE in case the guard page was hit by the
1900 signal. */
1901 static int
1902 __gnat_reset_guard_page (int sig)
1903 {
1904 /* On ARM VxWorks 6.x and x86_64 VxWorks 7, the guard page is left un-armed
1905 by the kernel after being violated, so subsequent violations aren't
1906 detected.
1907 So we retrieve the address of the guard page from the TCB and compare it
1908 with the page that is violated and re-arm that page if there's a match. */
1909 #if defined (VXWORKS_FORCE_GUARD_PAGE)
1910
1911 /* Ignore signals that are not stack overflow signals */
1912 if (sig != SIGSEGV && sig != SIGBUS && sig != SIGILL) return FALSE;
1913
1914 /* If the target does not support guard pages, INT_OVERFLOW_SIZE will be 0 */
1915 if (INT_OVERFLOW_SIZE == 0) return FALSE;
1916
1917 TASK_ID tid = taskIdSelf ();
1918 WIND_TCB *pTcb = taskTcb (tid);
1919 VIRT_ADDR guardPage = (VIRT_ADDR) pTcb->pStackEnd - INT_OVERFLOW_SIZE;
1920 UINT stateMask = VM_STATE_MASK_VALID;
1921 UINT guardState = VM_STATE_VALID_NOT;
1922
1923 #if (_WRS_VXWORKS_MAJOR >= 7)
1924 stateMask |= MMU_ATTR_SPL_MSK;
1925 guardState |= MMU_ATTR_NO_BLOCK;
1926 #endif
1927
1928 UINT nState;
1929 vmStateGet (NULL, guardPage, &nState);
1930 if ((nState & VM_STATE_MASK_VALID) != VM_STATE_VALID_NOT)
1931 {
1932 /* If the guard page has a valid state, we need to reset to
1933 invalid state here */
1934 vmStateSet (NULL, guardPage, INT_OVERFLOW_SIZE, stateMask, guardState);
1935 return TRUE;
1936 }
1937 #endif /* VXWORKS_FORCE_GUARD_PAGE */
1938 return FALSE;
1939 }
1940
1941 /* Handle different SIGnal to exception mappings in different VxWorks
1942 versions. */
1943 void
1944 __gnat_map_signal (int sig,
1945 siginfo_t *si ATTRIBUTE_UNUSED,
1946 void *sc ATTRIBUTE_UNUSED)
1947 {
1948 struct Exception_Data *exception;
1949 const char *msg;
1950
1951 switch (sig)
1952 {
1953 case SIGFPE:
1954 exception = &constraint_error;
1955 msg = "SIGFPE";
1956 break;
1957 #ifdef VTHREADS
1958 #ifdef __VXWORKSMILS__
1959 case SIGILL:
1960 exception = &storage_error;
1961 msg = "SIGILL: possible stack overflow";
1962 break;
1963 case SIGSEGV:
1964 exception = &storage_error;
1965 msg = "SIGSEGV";
1966 break;
1967 case SIGBUS:
1968 exception = &program_error;
1969 msg = "SIGBUS";
1970 break;
1971 #else
1972 case SIGILL:
1973 exception = &constraint_error;
1974 msg = "Floating point exception or SIGILL";
1975 break;
1976 case SIGSEGV:
1977 exception = &storage_error;
1978 msg = "SIGSEGV";
1979 break;
1980 case SIGBUS:
1981 exception = &storage_error;
1982 msg = "SIGBUS: possible stack overflow";
1983 break;
1984 #endif
1985 #elif (_WRS_VXWORKS_MAJOR >= 6)
1986 case SIGILL:
1987 exception = &constraint_error;
1988 msg = "SIGILL";
1989 break;
1990 #ifdef __RTP__
1991 /* In RTP mode a SIGSEGV is most likely due to a stack overflow,
1992 since stack checking uses the probing mechanism. */
1993 case SIGSEGV:
1994 exception = &storage_error;
1995 msg = "SIGSEGV: possible stack overflow";
1996 break;
1997 case SIGBUS:
1998 exception = &program_error;
1999 msg = "SIGBUS";
2000 break;
2001 #else
2002 /* VxWorks 6 kernel mode with probing. SIGBUS for guard page hit */
2003 case SIGSEGV:
2004 exception = &storage_error;
2005 msg = "SIGSEGV";
2006 break;
2007 case SIGBUS:
2008 exception = &storage_error;
2009 msg = "SIGBUS: possible stack overflow";
2010 break;
2011 #endif
2012 #else
2013 /* VxWorks 5: a SIGILL is most likely due to a stack overflow,
2014 since stack checking uses the stack limit mechanism. */
2015 case SIGILL:
2016 exception = &storage_error;
2017 msg = "SIGILL: possible stack overflow";
2018 break;
2019 case SIGSEGV:
2020 exception = &storage_error;
2021 msg = "SIGSEGV";
2022 break;
2023 case SIGBUS:
2024 exception = &program_error;
2025 msg = "SIGBUS";
2026 break;
2027 #endif
2028 default:
2029 exception = &program_error;
2030 msg = "unhandled signal";
2031 }
2032
2033 if (__gnat_reset_guard_page (sig))
2034 {
2035 /* Set the exception message: we know for sure that we have a
2036 stack overflow here */
2037 exception = &storage_error;
2038
2039 switch (sig)
2040 {
2041 case SIGSEGV:
2042 msg = "SIGSEGV: stack overflow";
2043 break;
2044 case SIGBUS:
2045 msg = "SIGBUS: stack overflow";
2046 break;
2047 case SIGILL:
2048 msg = "SIGILL: stack overflow";
2049 break;
2050 }
2051 }
2052
2053 CLEAR_EXCEPTION_COUNT ();
2054 Raise_From_Signal_Handler (exception, msg);
2055 }
2056
2057 #if defined (ARMEL) && (_WRS_VXWORKS_MAJOR >= 7) && !defined (__aarch64__)
2058
2059 /* ARM-vx7 case with arm unwinding exceptions */
2060 #define HAVE_GNAT_ADJUST_CONTEXT_FOR_RAISE
2061
2062 #include <arch/../regs.h>
2063 #ifndef __RTP__
2064 #include <sigLib.h>
2065 #else
2066 #include <signal.h>
2067 #include <regs.h>
2068 #include <ucontext.h>
2069 #endif /* __RTP__ */
2070
2071 void
2072 __gnat_adjust_context_for_raise (int signo ATTRIBUTE_UNUSED,
2073 void *sc ATTRIBUTE_UNUSED)
2074 {
2075 /* In case of ARM exceptions, the registers context have the PC pointing
2076 to the instruction that raised the signal. However the unwinder expects
2077 the instruction to be in the range ]PC,PC+1]. */
2078 uintptr_t *pc_addr;
2079 #ifdef __RTP__
2080 mcontext_t *mcontext = &((ucontext_t *) sc)->uc_mcontext;
2081 pc_addr = (uintptr_t*)&mcontext->regs.pc;
2082 #else
2083 struct sigcontext * sctx = (struct sigcontext *) sc;
2084 pc_addr = (uintptr_t*)&sctx->sc_pregs->pc;
2085 #endif
2086 /* ARM Bump has to be an even number because of odd/even architecture. */
2087 *pc_addr += 2;
2088 }
2089 #endif /* ARMEL && _WRS_VXWORKS_MAJOR >= 7 */
2090
2091 /* Tasking and Non-tasking signal handler. Map SIGnal to Ada exception
2092 propagation after the required low level adjustments. */
2093
2094 static void
2095 __gnat_error_handler (int sig, siginfo_t *si, void *sc)
2096 {
2097 sigset_t mask;
2098
2099 /* VxWorks on e500v2 clears the SPE bit of the MSR when entering CPU
2100 exception state. To allow the handler and exception to work properly
2101 when they contain SPE instructions, we need to set it back before doing
2102 anything else.
2103 This mechanism is only need in kernel mode. */
2104 #if !(defined (__RTP__) || defined (VTHREADS)) && ((CPU == PPCE500V2) || (CPU == PPC85XX))
2105 unsigned msr;
2106 /* Read the MSR value */
2107 asm volatile ("mfmsr %0" : "=r" (msr));
2108 /* Force the SPE bit if not set. */
2109 if ((msr & 0x02000000) == 0)
2110 {
2111 msr |= 0x02000000;
2112 /* Store to MSR */
2113 asm volatile ("mtmsr %0" : : "r" (msr));
2114 }
2115 #endif
2116
2117 /* VxWorks will always mask out the signal during the signal handler and
2118 will reenable it on a longjmp. GNAT does not generate a longjmp to
2119 return from a signal handler so the signal will still be masked unless
2120 we unmask it. */
2121 sigprocmask (SIG_SETMASK, NULL, &mask);
2122 sigdelset (&mask, sig);
2123 sigprocmask (SIG_SETMASK, &mask, NULL);
2124
2125 #if defined (__ARMEL__) || defined (__PPC__) || defined (__i386__) || defined (__x86_64__) || defined (__aarch64__)
2126 /* On certain targets, kernel mode, we process signals through a Call Frame
2127 Info trampoline, voiding the need for myriads of fallback_frame_state
2128 variants in the ZCX runtime. We have no simple way to distinguish ZCX
2129 from SJLJ here, so we do this for SJLJ as well even though this is not
2130 necessary. This only incurs a few extra instructions and a tiny
2131 amount of extra stack usage. */
2132
2133 #ifdef HAVE_GNAT_ADJUST_CONTEXT_FOR_RAISE
2134 /* We need to sometimes to adjust the PC in case of signals so that it
2135 doesn't reference the exception that actually raised the signal but the
2136 instruction before it. */
2137 __gnat_adjust_context_for_raise (sig, sc);
2138 #endif
2139
2140 __gnat_sigtramp (sig, (void *)si, (void *)sc,
2141 (__sigtramphandler_t *)&__gnat_map_signal);
2142
2143 #else
2144 __gnat_map_signal (sig, si, sc);
2145 #endif
2146 }
2147
2148 #if defined(__leon__) && defined(_WRS_KERNEL)
2149 /* For LEON VxWorks we need to install a trap handler for stack overflow */
2150
2151 extern void excEnt (void);
2152 /* VxWorks exception handler entry */
2153
2154 struct trap_entry {
2155 unsigned long inst_first;
2156 unsigned long inst_second;
2157 unsigned long inst_third;
2158 unsigned long inst_fourth;
2159 };
2160 /* Four instructions representing entries in the trap table */
2161
2162 struct trap_entry *trap_0_entry;
2163 /* We will set the location of the entry for software trap 0 in the trap
2164 table. */
2165 #endif
2166
2167 void
2168 __gnat_install_handler (void)
2169 {
2170 struct sigaction act;
2171
2172 /* Setup signal handler to map synchronous signals to appropriate
2173 exceptions. Make sure that the handler isn't interrupted by another
2174 signal that might cause a scheduling event! */
2175
2176 act.sa_sigaction = __gnat_error_handler;
2177 act.sa_flags = SA_SIGINFO | SA_ONSTACK;
2178 sigemptyset (&act.sa_mask);
2179
2180 /* For VxWorks, install all signal handlers, since pragma Interrupt_State
2181 applies to vectored hardware interrupts, not signals. */
2182 sigaction (SIGFPE, &act, NULL);
2183 sigaction (SIGILL, &act, NULL);
2184 sigaction (SIGSEGV, &act, NULL);
2185 sigaction (SIGBUS, &act, NULL);
2186
2187 #if defined(__leon__) && defined(_WRS_KERNEL)
2188 /* Specific to the LEON VxWorks kernel run-time library */
2189
2190 /* For stack checking the compiler triggers a software trap 0 (ta 0) in
2191 case of overflow (we use the stack limit mechanism). We need to install
2192 the trap handler here for this software trap (the OS does not handle
2193 it) as if it were a data_access_exception (trap 9). We do the same as
2194 if we put in the trap table a VXSPARC_BAD_TRAP(9). Software trap 0 is
2195 located at vector 0x80, and each entry takes 4 words. */
2196
2197 trap_0_entry = (struct trap_entry *)(intVecBaseGet () + 0x80 * 4);
2198
2199 /* mov 0x9, %l7 */
2200
2201 trap_0_entry->inst_first = 0xae102000 + 9;
2202
2203 /* sethi %hi(excEnt), %l6 */
2204
2205 /* The 22 most significant bits of excEnt are obtained shifting 10 times
2206 to the right. */
2207
2208 trap_0_entry->inst_second = 0x2d000000 + ((unsigned long)excEnt >> 10);
2209
2210 /* jmp %l6+%lo(excEnt) */
2211
2212 /* The 10 least significant bits of excEnt are obtained by masking */
2213
2214 trap_0_entry->inst_third = 0x81c5a000 + ((unsigned long)excEnt & 0x3ff);
2215
2216 /* rd %psr, %l0 */
2217
2218 trap_0_entry->inst_fourth = 0xa1480000;
2219 #endif
2220
2221 #ifdef __HANDLE_VXSIM_SC
2222 /* By experiment, found that sysModel () returns the following string
2223 prefix for vxsim when running on Linux and Windows. */
2224 {
2225 char *model = sysModel ();
2226 if ((strncmp (model, "Linux", 5) == 0)
2227 || (strncmp (model, "Windows", 7) == 0)
2228 || (strncmp (model, "SIMLINUX", 8) == 0) /* vx7 */
2229 || (strncmp (model, "SIMNT", 5) == 0)) /* ditto */
2230 __gnat_set_is_vxsim (TRUE);
2231 }
2232 #endif
2233
2234 __gnat_handler_installed = 1;
2235 }
2236
2237 #define HAVE_GNAT_INIT_FLOAT
2238
2239 void
2240 __gnat_init_float (void)
2241 {
2242 /* Disable overflow/underflow exceptions on the PPC processor, needed
2243 to get correct Ada semantics. Note that for AE653 vThreads, the HW
2244 overflow settings are an OS configuration issue. The instructions
2245 below have no effect. */
2246 #if defined (_ARCH_PPC) && !defined (_SOFT_FLOAT) && (!defined (VTHREADS) || defined (__VXWORKSMILS__))
2247 #if defined (__SPE__)
2248 {
2249 /* For e500v2, do nothing and leave the responsibility to install the
2250 handler and enable the exceptions to the BSP. */
2251 }
2252 #else
2253 asm ("mtfsb0 25");
2254 asm ("mtfsb0 26");
2255 #endif
2256 #endif
2257
2258 #if (defined (__i386__) || defined (__x86_64__)) && !defined (VTHREADS)
2259 /* This is used to properly initialize the FPU on an x86 for each
2260 process thread. */
2261 asm ("finit");
2262 #endif
2263
2264 /* Similarly for SPARC64. Achieved by masking bits in the Trap Enable Mask
2265 field of the Floating-point Status Register (see the SPARC Architecture
2266 Manual Version 9, p 48). */
2267 #if defined (sparc64)
2268
2269 #define FSR_TEM_NVM (1 << 27) /* Invalid operand */
2270 #define FSR_TEM_OFM (1 << 26) /* Overflow */
2271 #define FSR_TEM_UFM (1 << 25) /* Underflow */
2272 #define FSR_TEM_DZM (1 << 24) /* Division by Zero */
2273 #define FSR_TEM_NXM (1 << 23) /* Inexact result */
2274 {
2275 unsigned int fsr;
2276
2277 __asm__("st %%fsr, %0" : "=m" (fsr));
2278 fsr &= ~(FSR_TEM_OFM | FSR_TEM_UFM);
2279 __asm__("ld %0, %%fsr" : : "m" (fsr));
2280 }
2281 #endif
2282 }
2283
2284 /* This subprogram is called by System.Task_Primitives.Operations.Enter_Task
2285 (if not null) when a new task is created. It is initialized by
2286 System.Stack_Checking.Operations.Initialize_Stack_Limit.
2287 The use of a hook avoids to drag stack checking subprograms if stack
2288 checking is not used. */
2289 void (*__gnat_set_stack_limit_hook)(void) = (void (*)(void))0;
2290
2291 /******************/
2292 /* NetBSD Section */
2293 /******************/
2294
2295 #elif defined(__NetBSD__)
2296
2297 #include <signal.h>
2298 #include <unistd.h>
2299
2300 static void
2301 __gnat_error_handler (int sig)
2302 {
2303 struct Exception_Data *exception;
2304 const char *msg;
2305
2306 switch(sig)
2307 {
2308 case SIGFPE:
2309 exception = &constraint_error;
2310 msg = "SIGFPE";
2311 break;
2312 case SIGILL:
2313 exception = &constraint_error;
2314 msg = "SIGILL";
2315 break;
2316 case SIGSEGV:
2317 exception = &storage_error;
2318 msg = "stack overflow or erroneous memory access";
2319 break;
2320 case SIGBUS:
2321 exception = &constraint_error;
2322 msg = "SIGBUS";
2323 break;
2324 default:
2325 exception = &program_error;
2326 msg = "unhandled signal";
2327 }
2328
2329 Raise_From_Signal_Handler (exception, msg);
2330 }
2331
2332 void
2333 __gnat_install_handler (void)
2334 {
2335 struct sigaction act;
2336
2337 act.sa_handler = __gnat_error_handler;
2338 act.sa_flags = SA_NODEFER | SA_RESTART;
2339 sigemptyset (&act.sa_mask);
2340
2341 /* Do not install handlers if interrupt state is "System". */
2342 if (__gnat_get_interrupt_state (SIGFPE) != 's')
2343 sigaction (SIGFPE, &act, NULL);
2344 if (__gnat_get_interrupt_state (SIGILL) != 's')
2345 sigaction (SIGILL, &act, NULL);
2346 if (__gnat_get_interrupt_state (SIGSEGV) != 's')
2347 sigaction (SIGSEGV, &act, NULL);
2348 if (__gnat_get_interrupt_state (SIGBUS) != 's')
2349 sigaction (SIGBUS, &act, NULL);
2350
2351 __gnat_handler_installed = 1;
2352 }
2353
2354 /*******************/
2355 /* OpenBSD Section */
2356 /*******************/
2357
2358 #elif defined(__OpenBSD__)
2359
2360 #include <signal.h>
2361 #include <unistd.h>
2362
2363 static void
2364 __gnat_error_handler (int sig)
2365 {
2366 struct Exception_Data *exception;
2367 const char *msg;
2368
2369 switch(sig)
2370 {
2371 case SIGFPE:
2372 exception = &constraint_error;
2373 msg = "SIGFPE";
2374 break;
2375 case SIGILL:
2376 exception = &constraint_error;
2377 msg = "SIGILL";
2378 break;
2379 case SIGSEGV:
2380 exception = &storage_error;
2381 msg = "stack overflow or erroneous memory access";
2382 break;
2383 case SIGBUS:
2384 exception = &constraint_error;
2385 msg = "SIGBUS";
2386 break;
2387 default:
2388 exception = &program_error;
2389 msg = "unhandled signal";
2390 }
2391
2392 Raise_From_Signal_Handler (exception, msg);
2393 }
2394
2395 void
2396 __gnat_install_handler (void)
2397 {
2398 struct sigaction act;
2399
2400 act.sa_handler = __gnat_error_handler;
2401 act.sa_flags = SA_NODEFER | SA_RESTART;
2402 sigemptyset (&act.sa_mask);
2403
2404 /* Do not install handlers if interrupt state is "System" */
2405 if (__gnat_get_interrupt_state (SIGFPE) != 's')
2406 sigaction (SIGFPE, &act, NULL);
2407 if (__gnat_get_interrupt_state (SIGILL) != 's')
2408 sigaction (SIGILL, &act, NULL);
2409 if (__gnat_get_interrupt_state (SIGSEGV) != 's')
2410 sigaction (SIGSEGV, &act, NULL);
2411 if (__gnat_get_interrupt_state (SIGBUS) != 's')
2412 sigaction (SIGBUS, &act, NULL);
2413
2414 __gnat_handler_installed = 1;
2415 }
2416
2417 /******************/
2418 /* Darwin Section */
2419 /******************/
2420
2421 #elif defined(__APPLE__)
2422
2423 #include <TargetConditionals.h>
2424 #include <signal.h>
2425 #include <stdlib.h>
2426 #include <sys/syscall.h>
2427 #include <sys/sysctl.h>
2428
2429 /* This must be in keeping with System.OS_Interface.Alternate_Stack_Size. */
2430 char __gnat_alternate_stack[32 * 1024]; /* 1 * MINSIGSTKSZ */
2431
2432 /* Defined in xnu unix_signal.c.
2433 Tell the kernel to re-use alt stack when delivering a signal. */
2434 #define UC_RESET_ALT_STACK 0x80000000
2435
2436 #if !(defined (__arm__) || defined (__arm64__) || TARGET_IPHONE_SIMULATOR)
2437 #include <mach/mach_vm.h>
2438 #include <mach/mach_init.h>
2439 #include <mach/vm_statistics.h>
2440 #endif
2441
2442 #ifdef __arm64__
2443 #include <sys/ucontext.h>
2444 #include "sigtramp.h"
2445 #endif
2446
2447 /* Return true if ADDR is within a stack guard area. */
2448 static int
2449 __gnat_is_stack_guard (mach_vm_address_t addr)
2450 {
2451 #if !(defined (__arm__) || defined (__arm64__) || TARGET_IPHONE_SIMULATOR)
2452 kern_return_t kret;
2453 vm_region_submap_info_data_64_t info;
2454 mach_vm_address_t start;
2455 mach_vm_size_t size;
2456 natural_t depth;
2457 mach_msg_type_number_t count;
2458
2459 count = VM_REGION_SUBMAP_INFO_COUNT_64;
2460 start = addr;
2461 size = -1;
2462 depth = 9999;
2463 kret = mach_vm_region_recurse (mach_task_self (), &start, &size, &depth,
2464 (vm_region_recurse_info_t) &info, &count);
2465 if (kret == KERN_SUCCESS
2466 && addr >= start && addr < (start + size)
2467 && info.protection == VM_PROT_NONE
2468 && info.user_tag == VM_MEMORY_STACK)
2469 return 1;
2470 return 0;
2471 #else
2472 /* Pagezero for arm. */
2473 return addr >= 4096;
2474 #endif
2475 }
2476
2477 #define HAVE_GNAT_ADJUST_CONTEXT_FOR_RAISE
2478
2479 #if defined (__x86_64__)
2480 static int
2481 __darwin_major_version (void)
2482 {
2483 static int cache = -1;
2484 if (cache < 0)
2485 {
2486 int mib[2] = {CTL_KERN, KERN_OSRELEASE};
2487 size_t len;
2488
2489 /* Find out how big the buffer needs to be (and set cache to 0
2490 on failure). */
2491 if (sysctl (mib, 2, NULL, &len, NULL, 0) == 0)
2492 {
2493 char release[len];
2494 sysctl (mib, 2, release, &len, NULL, 0);
2495 /* Darwin releases are of the form L.M.N where L is the major
2496 version, so strtol will return L. */
2497 cache = (int) strtol (release, NULL, 10);
2498 }
2499 else
2500 {
2501 cache = 0;
2502 }
2503 }
2504 return cache;
2505 }
2506 #endif
2507
2508 void
2509 __gnat_adjust_context_for_raise (int signo ATTRIBUTE_UNUSED,
2510 void *ucontext ATTRIBUTE_UNUSED)
2511 {
2512 #if defined (__x86_64__)
2513 if (__darwin_major_version () < 12)
2514 {
2515 /* Work around radar #10302855, where the unwinders (libunwind or
2516 libgcc_s depending on the system revision) and the DWARF unwind
2517 data for sigtramp have different ideas about register numbering,
2518 causing rbx and rdx to be transposed. */
2519 ucontext_t *uc = (ucontext_t *)ucontext;
2520 unsigned long t = uc->uc_mcontext->__ss.__rbx;
2521
2522 uc->uc_mcontext->__ss.__rbx = uc->uc_mcontext->__ss.__rdx;
2523 uc->uc_mcontext->__ss.__rdx = t;
2524 }
2525 #elif defined(__arm64__)
2526 /* Even though the CFI is marked as a signal frame, we need this. */
2527 ucontext_t *uc = (ucontext_t *)ucontext;
2528 uc->uc_mcontext->__ss.__pc++;
2529 #endif
2530 }
2531
2532 static void
2533 __gnat_map_signal (int sig, siginfo_t *si, void *mcontext ATTRIBUTE_UNUSED)
2534 {
2535 struct Exception_Data *exception;
2536 const char *msg;
2537
2538 switch (sig)
2539 {
2540 case SIGSEGV:
2541 case SIGBUS:
2542 if (__gnat_is_stack_guard ((unsigned long)si->si_addr))
2543 {
2544 #ifdef __arm64__
2545 /* ??? This is a kludge to make stack checking work. The problem is
2546 that the trampoline doesn't restore LR and, consequently, doesn't
2547 make it possible to unwind past an interrupted frame which hasn"t
2548 saved LR on the stack yet. Therefore, for probes in the prologue
2549 (32-bit probes as opposed to standard 64-bit probes), we make the
2550 unwinder skip the not-yet-established frame altogether. */
2551 mcontext_t mc = (mcontext_t)mcontext;
2552 if (!(*(unsigned int *)(mc->__ss.__pc-1) & ((unsigned int)1 << 30)))
2553 mc->__ss.__pc = mc->__ss.__lr;
2554 #endif
2555 exception = &storage_error;
2556 msg = "stack overflow";
2557 }
2558 else
2559 {
2560 exception = &constraint_error;
2561 msg = "erroneous memory access";
2562 }
2563
2564 /* Reset the use of alt stack, so that the alt stack will be used
2565 for the next signal delivery.
2566 The stack can't be used in case of stack checking. */
2567 syscall (SYS_sigreturn, NULL, UC_RESET_ALT_STACK);
2568 break;
2569
2570 case SIGFPE:
2571 exception = &constraint_error;
2572 msg = "SIGFPE";
2573 break;
2574
2575 default:
2576 exception = &program_error;
2577 msg = "unhandled signal";
2578 }
2579
2580 Raise_From_Signal_Handler (exception, msg);
2581 }
2582
2583 static void
2584 __gnat_error_handler (int sig, siginfo_t *si, void *ucontext)
2585 {
2586 __gnat_adjust_context_for_raise (sig, ucontext);
2587
2588 /* The Darwin libc comes with a signal trampoline, except for ARM64. */
2589 #ifdef __arm64__
2590 __gnat_sigtramp (sig, (void *)si, ucontext,
2591 (__sigtramphandler_t *)&__gnat_map_signal);
2592 #else
2593 __gnat_map_signal (sig, si, ucontext);
2594 #endif
2595 }
2596
2597 void
2598 __gnat_install_handler (void)
2599 {
2600 struct sigaction act;
2601
2602 /* Set up signal handler to map synchronous signals to appropriate
2603 exceptions. Make sure that the handler isn't interrupted by another
2604 signal that might cause a scheduling event! Also setup an alternate
2605 stack region for the handler execution so that stack overflows can be
2606 handled properly, avoiding a SEGV generation from stack usage by the
2607 handler itself (and it is required by Darwin). */
2608
2609 stack_t stack;
2610 stack.ss_sp = __gnat_alternate_stack;
2611 stack.ss_size = sizeof (__gnat_alternate_stack);
2612 stack.ss_flags = 0;
2613 sigaltstack (&stack, NULL);
2614
2615 act.sa_flags = SA_NODEFER | SA_RESTART | SA_SIGINFO;
2616 act.sa_sigaction = __gnat_error_handler;
2617 sigemptyset (&act.sa_mask);
2618
2619 /* Do not install handlers if interrupt state is "System". */
2620 if (__gnat_get_interrupt_state (SIGABRT) != 's')
2621 sigaction (SIGABRT, &act, NULL);
2622 if (__gnat_get_interrupt_state (SIGFPE) != 's')
2623 sigaction (SIGFPE, &act, NULL);
2624 if (__gnat_get_interrupt_state (SIGILL) != 's')
2625 sigaction (SIGILL, &act, NULL);
2626
2627 act.sa_flags |= SA_ONSTACK;
2628 if (__gnat_get_interrupt_state (SIGSEGV) != 's')
2629 sigaction (SIGSEGV, &act, NULL);
2630 if (__gnat_get_interrupt_state (SIGBUS) != 's')
2631 sigaction (SIGBUS, &act, NULL);
2632
2633 __gnat_handler_installed = 1;
2634 }
2635
2636 #elif defined(__QNX__)
2637
2638 /***************/
2639 /* QNX Section */
2640 /***************/
2641
2642 #include <signal.h>
2643 #include <unistd.h>
2644 #include <string.h>
2645 #include <errno.h>
2646 #include "sigtramp.h"
2647
2648 #if defined (__ARMEL__) && !defined (__aarch64__)
2649
2650 /* ARM-QNX case with arm unwinding exceptions */
2651 #define HAVE_GNAT_ADJUST_CONTEXT_FOR_RAISE
2652
2653 #include <ucontext.h>
2654 #include <arm/cpu.h>
2655 #include <stdint.h>
2656
2657 void
2658 __gnat_adjust_context_for_raise (int signo ATTRIBUTE_UNUSED,
2659 void *sc ATTRIBUTE_UNUSED)
2660 {
2661 /* In case of ARM exceptions, the registers context have the PC pointing
2662 to the instruction that raised the signal. However the unwinder expects
2663 the instruction to be in the range [PC+2,PC+3]. */
2664 uintptr_t *pc_addr;
2665 mcontext_t *mcontext = &((ucontext_t *) sc)->uc_mcontext;
2666 pc_addr = (uintptr_t *)&mcontext->cpu.gpr [ARM_REG_PC];
2667
2668 /* ARM Bump has to be an even number because of odd/even architecture. */
2669 *pc_addr += 2;
2670 #ifdef __thumb2__
2671 /* For thumb, the return address must have the low order bit set, otherwise
2672 the unwinder will reset to "arm" mode upon return. As long as the
2673 compilation unit containing the landing pad is compiled with the same
2674 mode (arm vs thumb) as the signaling compilation unit, this works. */
2675 if (mcontext->cpu.spsr & ARM_CPSR_T)
2676 *pc_addr += 1;
2677 #endif
2678 }
2679 #endif /* ARMEL */
2680
2681 void
2682 __gnat_map_signal (int sig,
2683 siginfo_t *si ATTRIBUTE_UNUSED,
2684 void *mcontext ATTRIBUTE_UNUSED)
2685 {
2686 struct Exception_Data *exception;
2687 const char *msg;
2688
2689 switch(sig)
2690 {
2691 case SIGFPE:
2692 exception = &constraint_error;
2693 msg = "SIGFPE";
2694 break;
2695 case SIGILL:
2696 exception = &constraint_error;
2697 msg = "SIGILL";
2698 break;
2699 case SIGSEGV:
2700 exception = &storage_error;
2701 msg = "stack overflow or erroneous memory access";
2702 break;
2703 case SIGBUS:
2704 exception = &constraint_error;
2705 msg = "SIGBUS";
2706 break;
2707 default:
2708 exception = &program_error;
2709 msg = "unhandled signal";
2710 }
2711
2712 Raise_From_Signal_Handler (exception, msg);
2713 }
2714
2715 static void
2716 __gnat_error_handler (int sig, siginfo_t *si, void *ucontext)
2717 {
2718 #ifdef HAVE_GNAT_ADJUST_CONTEXT_FOR_RAISE
2719 /* We need to sometimes to adjust the PC in case of signals so that it
2720 doesn't reference the exception that actually raised the signal but the
2721 instruction before it. */
2722 __gnat_adjust_context_for_raise (sig, ucontext);
2723 #endif
2724
2725 __gnat_sigtramp (sig, (void *) si, (void *) ucontext,
2726 (__sigtramphandler_t *)&__gnat_map_signal);
2727 }
2728
2729 /* This must be in keeping with System.OS_Interface.Alternate_Stack_Size. */
2730 /* sigaltstack is currently not supported by QNX7 */
2731 char __gnat_alternate_stack[0];
2732
2733 void
2734 __gnat_install_handler (void)
2735 {
2736 struct sigaction act;
2737 int err;
2738
2739 act.sa_sigaction = __gnat_error_handler;
2740 act.sa_flags = SA_NODEFER | SA_SIGINFO;
2741 sigemptyset (&act.sa_mask);
2742
2743 /* Do not install handlers if interrupt state is "System" */
2744 if (__gnat_get_interrupt_state (SIGFPE) != 's') {
2745 err = sigaction (SIGFPE, &act, NULL);
2746 if (err == -1) {
2747 err = errno;
2748 perror ("error while attaching SIGFPE");
2749 perror (strerror (err));
2750 }
2751 }
2752 if (__gnat_get_interrupt_state (SIGILL) != 's') {
2753 err = sigaction (SIGILL, &act, NULL);
2754 if (err == -1) {
2755 err = errno;
2756 perror ("error while attaching SIGILL");
2757 perror (strerror (err));
2758 }
2759 }
2760 if (__gnat_get_interrupt_state (SIGSEGV) != 's') {
2761 err = sigaction (SIGSEGV, &act, NULL);
2762 if (err == -1) {
2763 err = errno;
2764 perror ("error while attaching SIGSEGV");
2765 perror (strerror (err));
2766 }
2767 }
2768 if (__gnat_get_interrupt_state (SIGBUS) != 's') {
2769 err = sigaction (SIGBUS, &act, NULL);
2770 if (err == -1) {
2771 err = errno;
2772 perror ("error while attaching SIGBUS");
2773 perror (strerror (err));
2774 }
2775 }
2776 __gnat_handler_installed = 1;
2777 }
2778
2779 /*****************/
2780 /* RTEMS Section */
2781 /*****************/
2782
2783 #elif defined(__rtems__)
2784
2785 #include <signal.h>
2786 #include <unistd.h>
2787
2788 static void
2789 __gnat_error_handler (int sig)
2790 {
2791 struct Exception_Data *exception;
2792 const char *msg;
2793
2794 switch(sig)
2795 {
2796 case SIGFPE:
2797 exception = &constraint_error;
2798 msg = "SIGFPE";
2799 break;
2800 case SIGILL:
2801 exception = &constraint_error;
2802 msg = "SIGILL";
2803 break;
2804 case SIGSEGV:
2805 exception = &storage_error;
2806 msg = "erroneous memory access";
2807 break;
2808 case SIGBUS:
2809 exception = &constraint_error;
2810 msg = "SIGBUS";
2811 break;
2812 default:
2813 exception = &program_error;
2814 msg = "unhandled signal";
2815 }
2816
2817 Raise_From_Signal_Handler (exception, msg);
2818 }
2819
2820 void
2821 __gnat_install_handler (void)
2822 {
2823 struct sigaction act;
2824
2825 act.sa_handler = __gnat_error_handler;
2826 sigemptyset (&act.sa_mask);
2827
2828 /* Do not install handlers if interrupt state is "System". */
2829 if (__gnat_get_interrupt_state (SIGFPE) != 's')
2830 sigaction (SIGFPE, &act, NULL);
2831 if (__gnat_get_interrupt_state (SIGILL) != 's')
2832 sigaction (SIGILL, &act, NULL);
2833 if (__gnat_get_interrupt_state (SIGSEGV) != 's')
2834 sigaction (SIGSEGV, &act, NULL);
2835 if (__gnat_get_interrupt_state (SIGBUS) != 's')
2836 sigaction (SIGBUS, &act, NULL);
2837
2838 __gnat_handler_installed = 1;
2839 }
2840
2841 #elif defined (__DJGPP__)
2842
2843 void
2844 __gnat_install_handler ()
2845 {
2846 __gnat_handler_installed = 1;
2847 }
2848
2849 #elif defined(__ANDROID__)
2850
2851 /*******************/
2852 /* Android Section */
2853 /*******************/
2854
2855 #include <signal.h>
2856 #include <sys/ucontext.h>
2857 #include "sigtramp.h"
2858
2859 #define HAVE_GNAT_ADJUST_CONTEXT_FOR_RAISE
2860
2861 void
2862 __gnat_adjust_context_for_raise (int signo ATTRIBUTE_UNUSED, void *ucontext)
2863 {
2864 #if defined(__arm__)
2865 mcontext_t *mcontext = &((ucontext_t *) ucontext)->uc_mcontext;
2866
2867 /* ARM Bump has to be an even number because of odd/even architecture. */
2868 ((mcontext_t *) mcontext)->arm_pc += 2;
2869 #endif
2870
2871 /* Other ports, based on dwarf2 unwinding, typically leverage
2872 kernel CFI coordinated with libgcc's explicit support for signal
2873 frames. */
2874 }
2875
2876 static void
2877 __gnat_map_signal (int sig,
2878 siginfo_t *si ATTRIBUTE_UNUSED,
2879 void *mcontext ATTRIBUTE_UNUSED)
2880 {
2881 struct Exception_Data *exception;
2882 const char *msg;
2883
2884 switch (sig)
2885 {
2886 case SIGSEGV:
2887 exception = &storage_error;
2888 msg = "stack overflow or erroneous memory access";
2889 break;
2890
2891 case SIGBUS:
2892 exception = &constraint_error;
2893 msg = "SIGBUS";
2894 break;
2895
2896 case SIGFPE:
2897 exception = &constraint_error;
2898 msg = "SIGFPE";
2899 break;
2900
2901 default:
2902 exception = &program_error;
2903 msg = "unhandled signal";
2904 }
2905
2906 Raise_From_Signal_Handler (exception, msg);
2907 }
2908
2909 static void
2910 __gnat_error_handler (int sig, siginfo_t *si, void *ucontext)
2911 {
2912 __gnat_adjust_context_for_raise (sig, ucontext);
2913 __gnat_sigtramp (sig, (void *) si, (void *) ucontext,
2914 (__sigtramphandler_t *)&__gnat_map_signal);
2915 }
2916
2917 /* This must be in keeping with System.OS_Interface.Alternate_Stack_Size. */
2918 char __gnat_alternate_stack[16 * 1024];
2919
2920 void
2921 __gnat_install_handler (void)
2922 {
2923 struct sigaction act;
2924
2925 /* Set up signal handler to map synchronous signals to appropriate
2926 exceptions. Make sure that the handler isn't interrupted by another
2927 signal that might cause a scheduling event! Also setup an alternate
2928 stack region for the handler execution so that stack overflows can be
2929 handled properly, avoiding a SEGV generation from stack usage by the
2930 handler itself. */
2931
2932 stack_t stack;
2933 stack.ss_sp = __gnat_alternate_stack;
2934 stack.ss_size = sizeof (__gnat_alternate_stack);
2935 stack.ss_flags = 0;
2936 sigaltstack (&stack, NULL);
2937
2938 act.sa_sigaction = __gnat_error_handler;
2939 act.sa_flags = SA_NODEFER | SA_RESTART | SA_SIGINFO;
2940 sigemptyset (&act.sa_mask);
2941
2942 sigaction (SIGABRT, &act, NULL);
2943 sigaction (SIGFPE, &act, NULL);
2944 sigaction (SIGILL, &act, NULL);
2945 sigaction (SIGBUS, &act, NULL);
2946 act.sa_flags |= SA_ONSTACK;
2947 sigaction (SIGSEGV, &act, NULL);
2948
2949 __gnat_handler_installed = 1;
2950 }
2951
2952 #else
2953
2954 /* For all other versions of GNAT, the handler does nothing. */
2955
2956 /*******************/
2957 /* Default Section */
2958 /*******************/
2959
2960 void
2961 __gnat_install_handler (void)
2962 {
2963 __gnat_handler_installed = 1;
2964 }
2965
2966 #endif
2967
2968 /*********************/
2969 /* __gnat_init_float */
2970 /*********************/
2971
2972 #if defined (_WIN32) || defined (__INTERIX) || defined (__linux__) \
2973 || defined (__Lynx__) || defined(__NetBSD__) || defined(__FreeBSD__) \
2974 || defined (__OpenBSD__) || defined (__DragonFly__) || defined(__QNX__)
2975
2976 #define HAVE_GNAT_INIT_FLOAT
2977
2978 void
2979 __gnat_init_float (void)
2980 {
2981 #if defined (__i386__) || defined (__x86_64__)
2982 /* This is used to properly initialize the FPU to 64-bit precision on an x86
2983 for each process thread and also for floating-point I/O. */
2984 asm ("finit");
2985 #endif
2986 }
2987 #endif
2988
2989 #ifndef HAVE_GNAT_INIT_FLOAT
2990
2991 /* All targets without a specific __gnat_init_float will use an empty one. */
2992 void
2993 __gnat_init_float (void)
2994 {
2995 }
2996 #endif
2997
2998 /***********************************/
2999 /* __gnat_adjust_context_for_raise */
3000 /***********************************/
3001
3002 #ifndef HAVE_GNAT_ADJUST_CONTEXT_FOR_RAISE
3003
3004 /* All targets without a specific version will use an empty one. */
3005
3006 /* Given UCONTEXT a pointer to a context structure received by a signal
3007 handler for SIGNO, perform the necessary adjustments to let the handler
3008 raise an exception. Calls to this routine are not conditioned by the
3009 propagation scheme in use. */
3010
3011 void
3012 __gnat_adjust_context_for_raise (int signo ATTRIBUTE_UNUSED,
3013 void *ucontext ATTRIBUTE_UNUSED)
3014 {
3015 /* We used to compensate here for the raised from call vs raised from signal
3016 exception discrepancy with the GCC ZCX scheme, but this now can be dealt
3017 with generically in the unwinder (see GCC PR other/26208). This however
3018 requires the use of the _Unwind_GetIPInfo routine in raise-gcc.c, which
3019 is predicated on the definition of HAVE_GETIPINFO at compile time. Only
3020 the VMS ports still do the compensation described in the few lines below.
3021
3022 *** Call vs signal exception discrepancy with GCC ZCX scheme ***
3023
3024 The GCC unwinder expects to be dealing with call return addresses, since
3025 this is the "nominal" case of what we retrieve while unwinding a regular
3026 call chain.
3027
3028 To evaluate if a handler applies at some point identified by a return
3029 address, the propagation engine needs to determine what region the
3030 corresponding call instruction pertains to. Because the return address
3031 may not be attached to the same region as the call, the unwinder always
3032 subtracts "some" amount from a return address to search the region
3033 tables, amount chosen to ensure that the resulting address is inside the
3034 call instruction.
3035
3036 When we raise an exception from a signal handler, e.g. to transform a
3037 SIGSEGV into Storage_Error, things need to appear as if the signal
3038 handler had been "called" by the instruction which triggered the signal,
3039 so that exception handlers that apply there are considered. What the
3040 unwinder will retrieve as the return address from the signal handler is
3041 what it will find as the faulting instruction address in the signal
3042 context pushed by the kernel. Leaving this address untouched looses, if
3043 the triggering instruction happens to be the very first of a region, as
3044 the later adjustments performed by the unwinder would yield an address
3045 outside that region. We need to compensate for the unwinder adjustments
3046 at some point, and this is what this routine is expected to do.
3047
3048 signo is passed because on some targets for some signals the PC in
3049 context points to the instruction after the faulting one, in which case
3050 the unwinder adjustment is still desired. */
3051 }
3052
3053 #endif
3054
3055 #ifdef __cplusplus
3056 }
3057 #endif