PR rtl-optimization/82913
[official-gcc.git] / gcc / ada / init.c
blob608f41fd748f2a2361210ee7a5775fa763931b76
1 /****************************************************************************
2 * *
3 * GNAT COMPILER COMPONENTS *
4 * *
5 * I N I T *
6 * *
7 * C Implementation File *
8 * *
9 * Copyright (C) 1992-2017, 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 ****************************************************************************/
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). */
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. */
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
52 #ifdef __ANDROID__
53 #undef __linux__
54 #endif
56 #ifdef IN_RTS
57 #include "tconfig.h"
58 #include "tsystem.h"
59 #include <sys/stat.h>
61 /* We don't have libiberty, so use malloc. */
62 #define xmalloc(S) malloc (S)
63 #else
64 #include "config.h"
65 #include "system.h"
66 #endif
68 #include "adaint.h"
69 #include "raise.h"
71 #ifdef __cplusplus
72 extern "C" {
73 #endif
75 extern void __gnat_raise_program_error (const char *, int);
77 /* Addresses of exception data blocks for predefined exceptions. Tasking_Error
78 is not used in this unit, and the abort signal is only used on IRIX.
79 ??? Revisit this part since IRIX is no longer supported. */
80 extern struct Exception_Data constraint_error;
81 extern struct Exception_Data numeric_error;
82 extern struct Exception_Data program_error;
83 extern struct Exception_Data storage_error;
85 /* For the Cert run time we use the regular raise exception routine because
86 Raise_From_Signal_Handler is not available. */
87 #ifdef CERT
88 #define Raise_From_Signal_Handler \
89 __gnat_raise_exception
90 extern void Raise_From_Signal_Handler (struct Exception_Data *, const char *);
91 #else
92 #define Raise_From_Signal_Handler \
93 ada__exceptions__raise_from_signal_handler
94 extern void Raise_From_Signal_Handler (struct Exception_Data *, const char *);
95 #endif
97 /* Global values computed by the binder. Note that these variables are
98 declared here, not in the binder file, to avoid having unresolved
99 references in the shared libgnat. */
100 int __gl_main_priority = -1;
101 int __gl_main_cpu = -1;
102 int __gl_time_slice_val = -1;
103 char __gl_wc_encoding = 'n';
104 char __gl_locking_policy = ' ';
105 char __gl_queuing_policy = ' ';
106 char __gl_task_dispatching_policy = ' ';
107 char *__gl_priority_specific_dispatching = 0;
108 int __gl_num_specific_dispatching = 0;
109 char *__gl_interrupt_states = 0;
110 int __gl_num_interrupt_states = 0;
111 int __gl_unreserve_all_interrupts = 0;
112 int __gl_exception_tracebacks = 0;
113 int __gl_exception_tracebacks_symbolic = 0;
114 int __gl_detect_blocking = 0;
115 int __gl_default_stack_size = -1;
116 int __gl_leap_seconds_support = 0;
117 int __gl_canonical_streams = 0;
118 char *__gl_bind_env_addr = NULL;
120 /* This value is not used anymore, but kept for bootstrapping purpose. */
121 int __gl_zero_cost_exceptions = 0;
123 /* Indication of whether synchronous signal handler has already been
124 installed by a previous call to adainit. */
125 int __gnat_handler_installed = 0;
127 #ifndef IN_RTS
128 int __gnat_inside_elab_final_code = 0;
129 /* ??? This variable is obsolete since 2001-08-29 but is kept to allow
130 bootstrap from old GNAT versions (< 3.15). */
131 #endif
133 /* HAVE_GNAT_INIT_FLOAT must be set on every targets where a __gnat_init_float
134 is defined. If this is not set then a void implementation will be defined
135 at the end of this unit. */
136 #undef HAVE_GNAT_INIT_FLOAT
138 /******************************/
139 /* __gnat_get_interrupt_state */
140 /******************************/
142 char __gnat_get_interrupt_state (int);
144 /* This routine is called from the runtime as needed to determine the state
145 of an interrupt, as set by an Interrupt_State pragma appearing anywhere
146 in the current partition. The input argument is the interrupt number,
147 and the result is one of the following:
149 'n' this interrupt not set by any Interrupt_State pragma
150 'u' Interrupt_State pragma set state to User
151 'r' Interrupt_State pragma set state to Runtime
152 's' Interrupt_State pragma set state to System */
154 char
155 __gnat_get_interrupt_state (int intrup)
157 if (intrup >= __gl_num_interrupt_states)
158 return 'n';
159 else
160 return __gl_interrupt_states [intrup];
163 /***********************************/
164 /* __gnat_get_specific_dispatching */
165 /***********************************/
167 char __gnat_get_specific_dispatching (int);
169 /* This routine is called from the runtime as needed to determine the
170 priority specific dispatching policy, as set by a
171 Priority_Specific_Dispatching pragma appearing anywhere in the current
172 partition. The input argument is the priority number, and the result
173 is the upper case first character of the policy name, e.g. 'F' for
174 FIFO_Within_Priorities. A space ' ' is returned if no
175 Priority_Specific_Dispatching pragma is used in the partition. */
177 char
178 __gnat_get_specific_dispatching (int priority)
180 if (__gl_num_specific_dispatching == 0)
181 return ' ';
182 else if (priority >= __gl_num_specific_dispatching)
183 return 'F';
184 else
185 return __gl_priority_specific_dispatching [priority];
188 #ifndef IN_RTS
190 /**********************/
191 /* __gnat_set_globals */
192 /**********************/
194 /* This routine is kept for bootstrapping purposes, since the binder generated
195 file now sets the __gl_* variables directly. */
197 void
198 __gnat_set_globals (void)
202 #endif
204 /***************/
205 /* AIX Section */
206 /***************/
208 #if defined (_AIX)
210 #include <signal.h>
211 #include <sys/time.h>
213 /* Some versions of AIX don't define SA_NODEFER. */
215 #ifndef SA_NODEFER
216 #define SA_NODEFER 0
217 #endif /* SA_NODEFER */
219 /* Versions of AIX before 4.3 don't have nanosleep but provide
220 nsleep instead. */
222 #ifndef _AIXVERSION_430
224 extern int nanosleep (struct timestruc_t *, struct timestruc_t *);
227 nanosleep (struct timestruc_t *Rqtp, struct timestruc_t *Rmtp)
229 return nsleep (Rqtp, Rmtp);
232 #endif /* _AIXVERSION_430 */
234 static void
235 __gnat_error_handler (int sig,
236 siginfo_t *si ATTRIBUTE_UNUSED,
237 void *ucontext ATTRIBUTE_UNUSED)
239 struct Exception_Data *exception;
240 const char *msg;
242 switch (sig)
244 case SIGSEGV:
245 /* FIXME: we need to detect the case of a *real* SIGSEGV. */
246 exception = &storage_error;
247 msg = "stack overflow or erroneous memory access";
248 break;
250 case SIGBUS:
251 exception = &constraint_error;
252 msg = "SIGBUS";
253 break;
255 case SIGFPE:
256 exception = &constraint_error;
257 msg = "SIGFPE";
258 break;
260 default:
261 exception = &program_error;
262 msg = "unhandled signal";
265 Raise_From_Signal_Handler (exception, msg);
268 void
269 __gnat_install_handler (void)
271 struct sigaction act;
273 /* Set up signal handler to map synchronous signals to appropriate
274 exceptions. Make sure that the handler isn't interrupted by another
275 signal that might cause a scheduling event! */
277 act.sa_flags = SA_NODEFER | SA_RESTART | SA_SIGINFO;
278 act.sa_sigaction = __gnat_error_handler;
279 sigemptyset (&act.sa_mask);
281 /* Do not install handlers if interrupt state is "System". */
282 if (__gnat_get_interrupt_state (SIGABRT) != 's')
283 sigaction (SIGABRT, &act, NULL);
284 if (__gnat_get_interrupt_state (SIGFPE) != 's')
285 sigaction (SIGFPE, &act, NULL);
286 if (__gnat_get_interrupt_state (SIGILL) != 's')
287 sigaction (SIGILL, &act, NULL);
288 if (__gnat_get_interrupt_state (SIGSEGV) != 's')
289 sigaction (SIGSEGV, &act, NULL);
290 if (__gnat_get_interrupt_state (SIGBUS) != 's')
291 sigaction (SIGBUS, &act, NULL);
293 __gnat_handler_installed = 1;
296 /*****************/
297 /* HP-UX section */
298 /*****************/
300 #elif defined (__hpux__)
302 #include <signal.h>
303 #include <sys/ucontext.h>
305 #if defined (IN_RTS) && defined (__ia64__)
307 #include <sys/uc_access.h>
309 #define HAVE_GNAT_ADJUST_CONTEXT_FOR_RAISE
311 void
312 __gnat_adjust_context_for_raise (int signo ATTRIBUTE_UNUSED, void *ucontext)
314 ucontext_t *uc = (ucontext_t *) ucontext;
315 uint64_t ip;
317 /* Adjust on itanium, as GetIPInfo is not supported. */
318 __uc_get_ip (uc, &ip);
319 __uc_set_ip (uc, ip + 1);
321 #endif /* IN_RTS && __ia64__ */
323 /* Tasking and Non-tasking signal handler. Map SIGnal to Ada exception
324 propagation after the required low level adjustments. */
326 static void
327 __gnat_error_handler (int sig, siginfo_t *si ATTRIBUTE_UNUSED, void *ucontext)
329 struct Exception_Data *exception;
330 const char *msg;
332 __gnat_adjust_context_for_raise (sig, ucontext);
334 switch (sig)
336 case SIGSEGV:
337 /* FIXME: we need to detect the case of a *real* SIGSEGV. */
338 exception = &storage_error;
339 msg = "stack overflow or erroneous memory access";
340 break;
342 case SIGBUS:
343 exception = &constraint_error;
344 msg = "SIGBUS";
345 break;
347 case SIGFPE:
348 exception = &constraint_error;
349 msg = "SIGFPE";
350 break;
352 default:
353 exception = &program_error;
354 msg = "unhandled signal";
357 Raise_From_Signal_Handler (exception, msg);
360 /* This must be in keeping with System.OS_Interface.Alternate_Stack_Size. */
361 #if defined (__hppa__)
362 char __gnat_alternate_stack[16 * 1024]; /* 2 * SIGSTKSZ */
363 #else
364 char __gnat_alternate_stack[128 * 1024]; /* MINSIGSTKSZ */
365 #endif
367 void
368 __gnat_install_handler (void)
370 struct sigaction act;
372 /* Set up signal handler to map synchronous signals to appropriate
373 exceptions. Make sure that the handler isn't interrupted by another
374 signal that might cause a scheduling event! Also setup an alternate
375 stack region for the handler execution so that stack overflows can be
376 handled properly, avoiding a SEGV generation from stack usage by the
377 handler itself. */
379 stack_t stack;
380 stack.ss_sp = __gnat_alternate_stack;
381 stack.ss_size = sizeof (__gnat_alternate_stack);
382 stack.ss_flags = 0;
383 sigaltstack (&stack, NULL);
385 act.sa_sigaction = __gnat_error_handler;
386 act.sa_flags = SA_NODEFER | SA_RESTART | SA_SIGINFO;
387 sigemptyset (&act.sa_mask);
389 /* Do not install handlers if interrupt state is "System". */
390 if (__gnat_get_interrupt_state (SIGABRT) != 's')
391 sigaction (SIGABRT, &act, NULL);
392 if (__gnat_get_interrupt_state (SIGFPE) != 's')
393 sigaction (SIGFPE, &act, NULL);
394 if (__gnat_get_interrupt_state (SIGILL) != 's')
395 sigaction (SIGILL, &act, NULL);
396 if (__gnat_get_interrupt_state (SIGBUS) != 's')
397 sigaction (SIGBUS, &act, NULL);
398 act.sa_flags |= SA_ONSTACK;
399 if (__gnat_get_interrupt_state (SIGSEGV) != 's')
400 sigaction (SIGSEGV, &act, NULL);
402 __gnat_handler_installed = 1;
405 /*********************/
406 /* GNU/Linux Section */
407 /*********************/
409 #elif defined (__linux__)
411 #include <signal.h>
413 #define __USE_GNU 1 /* required to get REG_EIP/RIP from glibc's ucontext.h */
414 #include <sys/ucontext.h>
416 /* GNU/Linux, which uses glibc, does not define NULL in included
417 header files. */
419 #if !defined (NULL)
420 #define NULL ((void *) 0)
421 #endif
423 #if defined (MaRTE)
425 /* MaRTE OS provides its own version of sigaction, sigfillset, and
426 sigemptyset (overriding these symbol names). We want to make sure that
427 the versions provided by the underlying C library are used here (these
428 versions are renamed by MaRTE to linux_sigaction, fake_linux_sigfillset,
429 and fake_linux_sigemptyset, respectively). The MaRTE library will not
430 always be present (it will not be linked if no tasking constructs are
431 used), so we use the weak symbol mechanism to point always to the symbols
432 defined within the C library. */
434 #pragma weak linux_sigaction
435 int linux_sigaction (int signum, const struct sigaction *act,
436 struct sigaction *oldact)
438 return sigaction (signum, act, oldact);
440 #define sigaction(signum, act, oldact) linux_sigaction (signum, act, oldact)
442 #pragma weak fake_linux_sigfillset
443 void fake_linux_sigfillset (sigset_t *set)
445 sigfillset (set);
447 #define sigfillset(set) fake_linux_sigfillset (set)
449 #pragma weak fake_linux_sigemptyset
450 void fake_linux_sigemptyset (sigset_t *set)
452 sigemptyset (set);
454 #define sigemptyset(set) fake_linux_sigemptyset (set)
456 #endif
458 #if defined (__i386__) || defined (__x86_64__) || defined (__ia64__) \
459 || defined (__ARMEL__)
461 #define HAVE_GNAT_ADJUST_CONTEXT_FOR_RAISE
463 void
464 __gnat_adjust_context_for_raise (int signo ATTRIBUTE_UNUSED, void *ucontext)
466 mcontext_t *mcontext = &((ucontext_t *) ucontext)->uc_mcontext;
468 /* On the i386 and x86-64 architectures, stack checking is performed by
469 means of probes with moving stack pointer, that is to say the probed
470 address is always the value of the stack pointer. Upon hitting the
471 guard page, the stack pointer therefore points to an inaccessible
472 address and an alternate signal stack is needed to run the handler.
473 But there is an additional twist: on these architectures, the EH
474 return code writes the address of the handler at the target CFA's
475 value on the stack before doing the jump. As a consequence, if
476 there is an active handler in the frame whose stack has overflowed,
477 the stack pointer must nevertheless point to an accessible address
478 by the time the EH return is executed.
480 We therefore adjust the saved value of the stack pointer by the size
481 of one page + a small dope of 4 words, in order to make sure that it
482 points to an accessible address in case it's used as the target CFA.
483 The stack checking code guarantees that this address is unused by the
484 time this happens. */
486 #if defined (__i386__)
487 unsigned long *pc = (unsigned long *)mcontext->gregs[REG_EIP];
488 /* The pattern is "orl $0x0,(%esp)" for a probe in 32-bit mode. */
489 if (signo == SIGSEGV && pc && *pc == 0x00240c83)
490 mcontext->gregs[REG_ESP] += 4096 + 4 * sizeof (unsigned long);
491 #elif defined (__x86_64__)
492 unsigned long long *pc = (unsigned long long *)mcontext->gregs[REG_RIP];
493 if (signo == SIGSEGV && pc
494 /* The pattern is "orq $0x0,(%rsp)" for a probe in 64-bit mode. */
495 && ((*pc & 0xffffffffffLL) == 0x00240c8348LL
496 /* The pattern may also be "orl $0x0,(%esp)" for a probe in
497 x32 mode. */
498 || (*pc & 0xffffffffLL) == 0x00240c83LL))
499 mcontext->gregs[REG_RSP] += 4096 + 4 * sizeof (unsigned long);
500 #elif defined (__ia64__)
501 /* ??? The IA-64 unwinder doesn't compensate for signals. */
502 mcontext->sc_ip++;
503 #elif defined (__ARMEL__)
504 /* ARM Bump has to be an even number because of odd/even architecture. */
505 mcontext->arm_pc+=2;
506 #ifdef __thumb2__
507 #define CPSR_THUMB_BIT 5
508 /* For thumb, the return address much have the low order bit set, otherwise
509 the unwinder will reset to "arm" mode upon return. As long as the
510 compilation unit containing the landing pad is compiled with the same
511 mode (arm vs thumb) as the signaling compilation unit, this works. */
512 if (mcontext->arm_cpsr & (1<<CPSR_THUMB_BIT))
513 mcontext->arm_pc+=1;
514 #endif
515 #endif
518 #endif
520 static void
521 __gnat_error_handler (int sig, siginfo_t *si ATTRIBUTE_UNUSED, void *ucontext)
523 struct Exception_Data *exception;
524 const char *msg;
526 /* Adjusting is required for every fault context, so adjust for this one
527 now, before we possibly trigger a recursive fault below. */
528 __gnat_adjust_context_for_raise (sig, ucontext);
530 switch (sig)
532 case SIGSEGV:
533 /* Here we would like a discrimination test to see whether the page
534 before the faulting address is accessible. Unfortunately, Linux
535 seems to have no way of giving us the faulting address.
537 In old versions of init.c, we had a test of the page before the
538 stack pointer:
540 ((volatile char *)
541 ((long) si->esp_at_signal & - getpagesize ()))[getpagesize ()];
543 but that's wrong since it tests the stack pointer location and the
544 stack probing code may not move it until all probes succeed.
546 For now we simply do not attempt any discrimination at all. Note
547 that this is quite acceptable, since a "real" SIGSEGV can only
548 occur as the result of an erroneous program. */
549 exception = &storage_error;
550 msg = "stack overflow or erroneous memory access";
551 break;
553 case SIGBUS:
554 exception = &storage_error;
555 msg = "SIGBUS: possible stack overflow";
556 break;
558 case SIGFPE:
559 exception = &constraint_error;
560 msg = "SIGFPE";
561 break;
563 default:
564 exception = &program_error;
565 msg = "unhandled signal";
568 Raise_From_Signal_Handler (exception, msg);
571 #ifndef __ia64__
572 #define HAVE_GNAT_ALTERNATE_STACK 1
573 /* This must be in keeping with System.OS_Interface.Alternate_Stack_Size.
574 It must be larger than MINSIGSTKSZ and hopefully near 2 * SIGSTKSZ. */
575 # if 16 * 1024 < MINSIGSTKSZ
576 # error "__gnat_alternate_stack too small"
577 # endif
578 char __gnat_alternate_stack[16 * 1024];
579 #endif
581 #ifdef __XENO__
582 #include <sys/mman.h>
583 #include <native/task.h>
585 RT_TASK main_task;
586 #endif
588 void
589 __gnat_install_handler (void)
591 struct sigaction act;
593 #ifdef __XENO__
594 int prio;
596 if (__gl_main_priority == -1)
597 prio = 49;
598 else
599 prio = __gl_main_priority;
601 /* Avoid memory swapping for this program */
603 mlockall (MCL_CURRENT|MCL_FUTURE);
605 /* Turn the current Linux task into a native Xenomai task */
607 rt_task_shadow (&main_task, "environment_task", prio, T_FPU);
608 #endif
610 /* Set up signal handler to map synchronous signals to appropriate
611 exceptions. Make sure that the handler isn't interrupted by another
612 signal that might cause a scheduling event! Also setup an alternate
613 stack region for the handler execution so that stack overflows can be
614 handled properly, avoiding a SEGV generation from stack usage by the
615 handler itself. */
617 act.sa_sigaction = __gnat_error_handler;
618 act.sa_flags = SA_NODEFER | SA_RESTART | SA_SIGINFO;
619 sigemptyset (&act.sa_mask);
621 /* Do not install handlers if interrupt state is "System". */
622 if (__gnat_get_interrupt_state (SIGABRT) != 's')
623 sigaction (SIGABRT, &act, NULL);
624 if (__gnat_get_interrupt_state (SIGFPE) != 's')
625 sigaction (SIGFPE, &act, NULL);
626 if (__gnat_get_interrupt_state (SIGILL) != 's')
627 sigaction (SIGILL, &act, NULL);
628 if (__gnat_get_interrupt_state (SIGBUS) != 's')
629 sigaction (SIGBUS, &act, NULL);
630 if (__gnat_get_interrupt_state (SIGSEGV) != 's')
632 #ifdef HAVE_GNAT_ALTERNATE_STACK
633 /* Setup an alternate stack region for the handler execution so that
634 stack overflows can be handled properly, avoiding a SEGV generation
635 from stack usage by the handler itself. */
636 stack_t stack;
638 stack.ss_sp = __gnat_alternate_stack;
639 stack.ss_size = sizeof (__gnat_alternate_stack);
640 stack.ss_flags = 0;
641 sigaltstack (&stack, NULL);
643 act.sa_flags |= SA_ONSTACK;
644 #endif
645 sigaction (SIGSEGV, &act, NULL);
648 __gnat_handler_installed = 1;
651 /*******************/
652 /* LynxOS Section */
653 /*******************/
655 #elif defined (__Lynx__)
657 #include <signal.h>
658 #include <unistd.h>
660 static void
661 __gnat_error_handler (int sig)
663 struct Exception_Data *exception;
664 const char *msg;
666 switch(sig)
668 case SIGFPE:
669 exception = &constraint_error;
670 msg = "SIGFPE";
671 break;
672 case SIGILL:
673 exception = &constraint_error;
674 msg = "SIGILL";
675 break;
676 case SIGSEGV:
677 exception = &storage_error;
678 msg = "stack overflow or erroneous memory access";
679 break;
680 case SIGBUS:
681 exception = &constraint_error;
682 msg = "SIGBUS";
683 break;
684 default:
685 exception = &program_error;
686 msg = "unhandled signal";
689 Raise_From_Signal_Handler (exception, msg);
692 void
693 __gnat_install_handler (void)
695 struct sigaction act;
697 act.sa_handler = __gnat_error_handler;
698 act.sa_flags = 0x0;
699 sigemptyset (&act.sa_mask);
701 /* Do not install handlers if interrupt state is "System". */
702 if (__gnat_get_interrupt_state (SIGFPE) != 's')
703 sigaction (SIGFPE, &act, NULL);
704 if (__gnat_get_interrupt_state (SIGILL) != 's')
705 sigaction (SIGILL, &act, NULL);
706 if (__gnat_get_interrupt_state (SIGSEGV) != 's')
707 sigaction (SIGSEGV, &act, NULL);
708 if (__gnat_get_interrupt_state (SIGBUS) != 's')
709 sigaction (SIGBUS, &act, NULL);
711 __gnat_handler_installed = 1;
714 /*******************/
715 /* Solaris Section */
716 /*******************/
718 #elif defined (__sun__) && !defined (__vxworks)
720 #include <signal.h>
721 #include <siginfo.h>
722 #include <sys/ucontext.h>
723 #include <sys/regset.h>
725 static void
726 __gnat_error_handler (int sig, siginfo_t *si, void *ucontext ATTRIBUTE_UNUSED)
728 struct Exception_Data *exception;
729 static int recurse = 0;
730 const char *msg;
732 switch (sig)
734 case SIGSEGV:
735 /* If the problem was permissions, this is a constraint error.
736 Likewise if the failing address isn't maximally aligned or if
737 we've recursed.
739 ??? Using a static variable here isn't task-safe, but it's
740 much too hard to do anything else and we're just determining
741 which exception to raise. */
742 if (si->si_code == SEGV_ACCERR
743 || (long) si->si_addr == 0
744 || (((long) si->si_addr) & 3) != 0
745 || recurse)
747 exception = &constraint_error;
748 msg = "SIGSEGV";
750 else
752 /* See if the page before the faulting page is accessible. Do that
753 by trying to access it. We'd like to simply try to access
754 4096 + the faulting address, but it's not guaranteed to be
755 the actual address, just to be on the same page. */
756 recurse++;
757 ((volatile char *)
758 ((long) si->si_addr & - getpagesize ()))[getpagesize ()];
759 exception = &storage_error;
760 msg = "stack overflow or erroneous memory access";
762 break;
764 case SIGBUS:
765 exception = &program_error;
766 msg = "SIGBUS";
767 break;
769 case SIGFPE:
770 exception = &constraint_error;
771 msg = "SIGFPE";
772 break;
774 default:
775 exception = &program_error;
776 msg = "unhandled signal";
779 recurse = 0;
780 Raise_From_Signal_Handler (exception, msg);
783 void
784 __gnat_install_handler (void)
786 struct sigaction act;
788 /* Set up signal handler to map synchronous signals to appropriate
789 exceptions. Make sure that the handler isn't interrupted by another
790 signal that might cause a scheduling event! */
792 act.sa_sigaction = __gnat_error_handler;
793 act.sa_flags = SA_NODEFER | SA_RESTART | SA_SIGINFO;
794 sigemptyset (&act.sa_mask);
796 /* Do not install handlers if interrupt state is "System". */
797 if (__gnat_get_interrupt_state (SIGABRT) != 's')
798 sigaction (SIGABRT, &act, NULL);
799 if (__gnat_get_interrupt_state (SIGFPE) != 's')
800 sigaction (SIGFPE, &act, NULL);
801 if (__gnat_get_interrupt_state (SIGSEGV) != 's')
802 sigaction (SIGSEGV, &act, NULL);
803 if (__gnat_get_interrupt_state (SIGBUS) != 's')
804 sigaction (SIGBUS, &act, NULL);
806 __gnat_handler_installed = 1;
809 /***************/
810 /* VMS Section */
811 /***************/
813 #elif defined (VMS)
815 /* Routine called from binder to override default feature values. */
816 void __gnat_set_features (void);
817 int __gnat_features_set = 0;
818 void (*__gnat_ctrl_c_handler) (void) = 0;
820 #ifdef __IA64
821 #define lib_get_curr_invo_context LIB$I64_GET_CURR_INVO_CONTEXT
822 #define lib_get_prev_invo_context LIB$I64_GET_PREV_INVO_CONTEXT
823 #define lib_get_invo_handle LIB$I64_GET_INVO_HANDLE
824 #else
825 #define lib_get_curr_invo_context LIB$GET_CURR_INVO_CONTEXT
826 #define lib_get_prev_invo_context LIB$GET_PREV_INVO_CONTEXT
827 #define lib_get_invo_handle LIB$GET_INVO_HANDLE
828 #endif
830 /* Masks for facility identification. */
831 #define FAC_MASK 0x0fff0000
832 #define DECADA_M_FACILITY 0x00310000
834 /* Define macro symbols for the VMS conditions that become Ada exceptions.
835 It would be better to just include <ssdef.h> */
837 #define SS$_CONTINUE 1
838 #define SS$_ACCVIO 12
839 #define SS$_HPARITH 1284
840 #define SS$_INTDIV 1156
841 #define SS$_STKOVF 1364
842 #define SS$_CONTROLC 1617
843 #define SS$_RESIGNAL 2328
845 #define MTH$_FLOOVEMAT 1475268 /* Some ACVC_21 CXA tests */
847 /* The following codes must be resignalled, and not handled here. */
849 /* These codes are in standard message libraries. */
850 extern int C$_SIGKILL;
851 extern int C$_SIGINT;
852 extern int SS$_DEBUG;
853 extern int LIB$_KEYNOTFOU;
854 extern int LIB$_ACTIMAGE;
856 /* These codes are non standard, which is to say the author is
857 not sure if they are defined in the standard message libraries
858 so keep them as macros for now. */
859 #define RDB$_STREAM_EOF 20480426
860 #define FDL$_UNPRIKW 11829410
861 #define CMA$_EXIT_THREAD 4227492
863 struct cond_sigargs
865 unsigned int sigarg;
866 unsigned int sigargval;
869 struct cond_subtests
871 unsigned int num;
872 const struct cond_sigargs sigargs[];
875 struct cond_except
877 unsigned int cond;
878 const struct Exception_Data *except;
879 unsigned int needs_adjust; /* 1 = adjust PC, 0 = no adjust */
880 const struct cond_subtests *subtests;
883 struct descriptor_s
885 unsigned short len, mbz;
886 __char_ptr32 adr;
889 /* Conditions that don't have an Ada exception counterpart must raise
890 Non_Ada_Error. Since this is defined in s-auxdec, it should only be
891 referenced by user programs, not the compiler or tools. Hence the
892 #ifdef IN_RTS. */
894 #ifdef IN_RTS
896 #define Status_Error ada__io_exceptions__status_error
897 extern struct Exception_Data Status_Error;
899 #define Mode_Error ada__io_exceptions__mode_error
900 extern struct Exception_Data Mode_Error;
902 #define Name_Error ada__io_exceptions__name_error
903 extern struct Exception_Data Name_Error;
905 #define Use_Error ada__io_exceptions__use_error
906 extern struct Exception_Data Use_Error;
908 #define Device_Error ada__io_exceptions__device_error
909 extern struct Exception_Data Device_Error;
911 #define End_Error ada__io_exceptions__end_error
912 extern struct Exception_Data End_Error;
914 #define Data_Error ada__io_exceptions__data_error
915 extern struct Exception_Data Data_Error;
917 #define Layout_Error ada__io_exceptions__layout_error
918 extern struct Exception_Data Layout_Error;
920 #define Non_Ada_Error system__aux_dec__non_ada_error
921 extern struct Exception_Data Non_Ada_Error;
923 #define Coded_Exception system__vms_exception_table__coded_exception
924 extern struct Exception_Data *Coded_Exception (void *);
926 #define Base_Code_In system__vms_exception_table__base_code_in
927 extern void *Base_Code_In (void *);
929 /* DEC Ada exceptions are not defined in a header file, so they
930 must be declared. */
932 #define ADA$_ALREADY_OPEN 0x0031a594
933 #define ADA$_CONSTRAINT_ERRO 0x00318324
934 #define ADA$_DATA_ERROR 0x003192c4
935 #define ADA$_DEVICE_ERROR 0x003195e4
936 #define ADA$_END_ERROR 0x00319904
937 #define ADA$_FAC_MODE_MISMAT 0x0031a8b3
938 #define ADA$_IOSYSFAILED 0x0031af04
939 #define ADA$_KEYSIZERR 0x0031aa3c
940 #define ADA$_KEY_MISMATCH 0x0031a8e3
941 #define ADA$_LAYOUT_ERROR 0x00319c24
942 #define ADA$_LINEXCMRS 0x0031a8f3
943 #define ADA$_MAXLINEXC 0x0031a8eb
944 #define ADA$_MODE_ERROR 0x00319f44
945 #define ADA$_MRN_MISMATCH 0x0031a8db
946 #define ADA$_MRS_MISMATCH 0x0031a8d3
947 #define ADA$_NAME_ERROR 0x0031a264
948 #define ADA$_NOT_OPEN 0x0031a58c
949 #define ADA$_ORG_MISMATCH 0x0031a8bb
950 #define ADA$_PROGRAM_ERROR 0x00318964
951 #define ADA$_RAT_MISMATCH 0x0031a8cb
952 #define ADA$_RFM_MISMATCH 0x0031a8c3
953 #define ADA$_STAOVF 0x00318cac
954 #define ADA$_STATUS_ERROR 0x0031a584
955 #define ADA$_STORAGE_ERROR 0x00318c84
956 #define ADA$_UNSUPPORTED 0x0031a8ab
957 #define ADA$_USE_ERROR 0x0031a8a4
959 /* DEC Ada specific conditions. */
960 static const struct cond_except dec_ada_cond_except_table [] =
962 {ADA$_PROGRAM_ERROR, &program_error, 0, 0},
963 {ADA$_USE_ERROR, &Use_Error, 0, 0},
964 {ADA$_KEYSIZERR, &program_error, 0, 0},
965 {ADA$_STAOVF, &storage_error, 0, 0},
966 {ADA$_CONSTRAINT_ERRO, &constraint_error, 0, 0},
967 {ADA$_IOSYSFAILED, &Device_Error, 0, 0},
968 {ADA$_LAYOUT_ERROR, &Layout_Error, 0, 0},
969 {ADA$_STORAGE_ERROR, &storage_error, 0, 0},
970 {ADA$_DATA_ERROR, &Data_Error, 0, 0},
971 {ADA$_DEVICE_ERROR, &Device_Error, 0, 0},
972 {ADA$_END_ERROR, &End_Error, 0, 0},
973 {ADA$_MODE_ERROR, &Mode_Error, 0, 0},
974 {ADA$_NAME_ERROR, &Name_Error, 0, 0},
975 {ADA$_STATUS_ERROR, &Status_Error, 0, 0},
976 {ADA$_NOT_OPEN, &Use_Error, 0, 0},
977 {ADA$_ALREADY_OPEN, &Use_Error, 0, 0},
978 {ADA$_USE_ERROR, &Use_Error, 0, 0},
979 {ADA$_UNSUPPORTED, &Use_Error, 0, 0},
980 {ADA$_FAC_MODE_MISMAT, &Use_Error, 0, 0},
981 {ADA$_ORG_MISMATCH, &Use_Error, 0, 0},
982 {ADA$_RFM_MISMATCH, &Use_Error, 0, 0},
983 {ADA$_RAT_MISMATCH, &Use_Error, 0, 0},
984 {ADA$_MRS_MISMATCH, &Use_Error, 0, 0},
985 {ADA$_MRN_MISMATCH, &Use_Error, 0, 0},
986 {ADA$_KEY_MISMATCH, &Use_Error, 0, 0},
987 {ADA$_MAXLINEXC, &constraint_error, 0, 0},
988 {ADA$_LINEXCMRS, &constraint_error, 0, 0},
990 #if 0
991 /* Already handled by a pragma Import_Exception
992 in Aux_IO_Exceptions */
993 {ADA$_LOCK_ERROR, &Lock_Error, 0, 0},
994 {ADA$_EXISTENCE_ERROR, &Existence_Error, 0, 0},
995 {ADA$_KEY_ERROR, &Key_Error, 0, 0},
996 #endif
998 {0, 0, 0, 0}
1001 #endif /* IN_RTS */
1003 /* Non-DEC Ada specific conditions that map to Ada exceptions. */
1005 /* Subtest for ACCVIO Constraint_Error, kept for compatibility,
1006 in hindsight should have just made ACCVIO == Storage_Error. */
1007 #define ACCVIO_VIRTUAL_ADDR 3
1008 static const struct cond_subtests accvio_c_e =
1009 {1, /* number of subtests below */
1011 { ACCVIO_VIRTUAL_ADDR, 0 }
1015 /* Macro flag to adjust PC which gets off by one for some conditions,
1016 not sure if this is reliably true, PC could be off by more for
1017 HPARITH for example, unless a trapb is inserted. */
1018 #define NEEDS_ADJUST 1
1020 static const struct cond_except system_cond_except_table [] =
1022 {MTH$_FLOOVEMAT, &constraint_error, 0, 0},
1023 {SS$_INTDIV, &constraint_error, 0, 0},
1024 {SS$_HPARITH, &constraint_error, NEEDS_ADJUST, 0},
1025 {SS$_ACCVIO, &constraint_error, NEEDS_ADJUST, &accvio_c_e},
1026 {SS$_ACCVIO, &storage_error, NEEDS_ADJUST, 0},
1027 {SS$_STKOVF, &storage_error, NEEDS_ADJUST, 0},
1028 {0, 0, 0, 0}
1031 /* To deal with VMS conditions and their mapping to Ada exceptions,
1032 the __gnat_error_handler routine below is installed as an exception
1033 vector having precedence over DEC frame handlers. Some conditions
1034 still need to be handled by such handlers, however, in which case
1035 __gnat_error_handler needs to return SS$_RESIGNAL. Consider for
1036 instance the use of a third party library compiled with DECAda and
1037 performing its own exception handling internally.
1039 To allow some user-level flexibility, which conditions should be
1040 resignaled is controlled by a predicate function, provided with the
1041 condition value and returning a boolean indication stating whether
1042 this condition should be resignaled or not.
1044 That predicate function is called indirectly, via a function pointer,
1045 by __gnat_error_handler, and changing that pointer is allowed to the
1046 user code by way of the __gnat_set_resignal_predicate interface.
1048 The user level function may then implement what it likes, including
1049 for instance the maintenance of a dynamic data structure if the set
1050 of to be resignalled conditions has to change over the program's
1051 lifetime.
1053 ??? This is not a perfect solution to deal with the possible
1054 interactions between the GNAT and the DECAda exception handling
1055 models and better (more general) schemes are studied. This is so
1056 just provided as a convenient workaround in the meantime, and
1057 should be use with caution since the implementation has been kept
1058 very simple. */
1060 typedef int resignal_predicate (int code);
1062 static const int * const cond_resignal_table [] =
1064 &C$_SIGKILL,
1065 (int *)CMA$_EXIT_THREAD,
1066 &SS$_DEBUG,
1067 &LIB$_KEYNOTFOU,
1068 &LIB$_ACTIMAGE,
1069 (int *) RDB$_STREAM_EOF,
1070 (int *) FDL$_UNPRIKW,
1074 static const int facility_resignal_table [] =
1076 0x1380000, /* RDB */
1077 0x2220000, /* SQL */
1081 /* Default GNAT predicate for resignaling conditions. */
1083 static int
1084 __gnat_default_resignal_p (int code)
1086 int i, iexcept;
1088 for (i = 0; facility_resignal_table [i]; i++)
1089 if ((code & FAC_MASK) == facility_resignal_table [i])
1090 return 1;
1092 for (i = 0, iexcept = 0;
1093 cond_resignal_table [i]
1094 && !(iexcept = LIB$MATCH_COND (&code, &cond_resignal_table [i]));
1095 i++);
1097 return iexcept;
1100 /* Static pointer to predicate that the __gnat_error_handler exception
1101 vector invokes to determine if it should resignal a condition. */
1103 static resignal_predicate *__gnat_resignal_p = __gnat_default_resignal_p;
1105 /* User interface to change the predicate pointer to PREDICATE. Reset to
1106 the default if PREDICATE is null. */
1108 void
1109 __gnat_set_resignal_predicate (resignal_predicate *predicate)
1111 if (predicate == NULL)
1112 __gnat_resignal_p = __gnat_default_resignal_p;
1113 else
1114 __gnat_resignal_p = predicate;
1117 /* Should match System.Parameters.Default_Exception_Msg_Max_Length. */
1118 #define Default_Exception_Msg_Max_Length 512
1120 /* Action routine for SYS$PUTMSG. There may be multiple
1121 conditions, each with text to be appended to MESSAGE
1122 and separated by line termination. */
1123 static int
1124 copy_msg (struct descriptor_s *msgdesc, char *message)
1126 int len = strlen (message);
1127 int copy_len;
1129 /* Check for buffer overflow and skip. */
1130 if (len > 0 && len <= Default_Exception_Msg_Max_Length - 3)
1132 strcat (message, "\r\n");
1133 len += 2;
1136 /* Check for buffer overflow and truncate if necessary. */
1137 copy_len = (len + msgdesc->len <= Default_Exception_Msg_Max_Length - 1 ?
1138 msgdesc->len :
1139 Default_Exception_Msg_Max_Length - 1 - len);
1140 strncpy (&message [len], msgdesc->adr, copy_len);
1141 message [len + copy_len] = 0;
1143 return 0;
1146 /* Scan TABLE for a match for the condition contained in SIGARGS,
1147 and return the entry, or the empty entry if no match found. */
1148 static const struct cond_except *
1149 scan_conditions ( int *sigargs, const struct cond_except *table [])
1151 int i;
1152 struct cond_except entry;
1154 /* Scan the exception condition table for a match and fetch
1155 the associated GNAT exception pointer. */
1156 for (i = 0; (*table) [i].cond; i++)
1158 unsigned int match = LIB$MATCH_COND (&sigargs [1], &(*table) [i].cond);
1159 const struct cond_subtests *subtests = (*table) [i].subtests;
1161 if (match)
1163 if (!subtests)
1165 return &(*table) [i];
1167 else
1169 unsigned int ii;
1170 int num = (*subtests).num;
1172 /* Perform subtests to differentiate exception. */
1173 for (ii = 0; ii < num; ii++)
1175 unsigned int arg = (*subtests).sigargs [ii].sigarg;
1176 unsigned int argval = (*subtests).sigargs [ii].sigargval;
1178 if (sigargs [arg] != argval)
1180 num = 0;
1181 break;
1185 /* All subtests passed. */
1186 if (num == (*subtests).num)
1187 return &(*table) [i];
1192 /* No match, return the null terminating entry. */
1193 return &(*table) [i];
1196 /* __gnat_handle_vms_condtition is both a frame based handler
1197 for the runtime, and an exception vector for the compiler. */
1198 long
1199 __gnat_handle_vms_condition (int *sigargs, void *mechargs)
1201 struct Exception_Data *exception = 0;
1202 unsigned int needs_adjust = 0;
1203 void *base_code;
1204 struct descriptor_s gnat_facility = {4, 0, "GNAT"};
1205 char message [Default_Exception_Msg_Max_Length];
1207 const char *msg = "";
1209 /* Check for conditions to resignal which aren't effected by pragma
1210 Import_Exception. */
1211 if (__gnat_resignal_p (sigargs [1]))
1212 return SS$_RESIGNAL;
1213 #ifndef IN_RTS
1214 /* toplev.c handles this for compiler. */
1215 if (sigargs [1] == SS$_HPARITH)
1216 return SS$_RESIGNAL;
1217 #endif
1219 #ifdef IN_RTS
1220 /* See if it's an imported exception. Beware that registered exceptions
1221 are bound to their base code, with the severity bits masked off. */
1222 base_code = Base_Code_In ((void *) sigargs[1]);
1223 exception = Coded_Exception (base_code);
1224 #endif
1226 if (exception == 0)
1227 #ifdef IN_RTS
1229 int i;
1230 struct cond_except cond;
1231 const struct cond_except *cond_table;
1232 const struct cond_except *cond_tables [] = {dec_ada_cond_except_table,
1233 system_cond_except_table,
1235 unsigned int ctrlc = SS$_CONTROLC;
1236 unsigned int *sigint = &C$_SIGINT;
1237 int ctrlc_match = LIB$MATCH_COND (&sigargs [1], &ctrlc);
1238 int sigint_match = LIB$MATCH_COND (&sigargs [1], &sigint);
1240 extern int SYS$DCLAST (void (*astadr)(), unsigned long long astprm,
1241 unsigned int acmode);
1243 /* If SS$_CONTROLC has been imported as an exception, it will take
1244 priority over a Ctrl/C handler. See above. SIGINT has a
1245 different condition value due to it's DECCCRTL roots and it's
1246 the condition that gets raised for a "kill -INT". */
1247 if ((ctrlc_match || sigint_match) && __gnat_ctrl_c_handler)
1249 SYS$DCLAST (__gnat_ctrl_c_handler, 0, 0);
1250 return SS$_CONTINUE;
1253 i = 0;
1254 while ((cond_table = cond_tables[i++]) && !exception)
1256 cond = *scan_conditions (sigargs, &cond_table);
1257 exception = (struct Exception_Data *) cond.except;
1260 if (exception)
1261 needs_adjust = cond.needs_adjust;
1262 else
1263 /* User programs expect Non_Ada_Error to be raised if no match,
1264 reference DEC Ada test CXCONDHAN. */
1265 exception = &Non_Ada_Error;
1267 #else
1269 /* Pretty much everything is just a program error in the compiler */
1270 exception = &program_error;
1272 #endif
1274 message[0] = 0;
1275 /* Subtract PC & PSL fields as per ABI for SYS$PUTMSG. */
1276 sigargs[0] -= 2;
1278 extern int SYS$PUTMSG (void *, int (*)(), void *, unsigned long long);
1280 /* If it was a DEC Ada specific condtiion, make it GNAT otherwise
1281 keep the old facility. */
1282 if (sigargs [1] & FAC_MASK == DECADA_M_FACILITY)
1283 SYS$PUTMSG (sigargs, copy_msg, &gnat_facility,
1284 (unsigned long long ) message);
1285 else
1286 SYS$PUTMSG (sigargs, copy_msg, 0,
1287 (unsigned long long ) message);
1289 /* Add back PC & PSL fields as per ABI for SYS$PUTMSG. */
1290 sigargs[0] += 2;
1291 msg = message;
1293 if (needs_adjust)
1294 __gnat_adjust_context_for_raise (sigargs [1], (void *)mechargs);
1296 Raise_From_Signal_Handler (exception, msg);
1299 #if defined (IN_RTS) && defined (__IA64)
1300 /* Called only from adasigio.b32. This is a band aid to avoid going
1301 through the VMS signal handling code which results in a 0x8000 per
1302 handled exception memory leak in P2 space (see VMS source listing
1303 sys/lis/exception.lis) due to the allocation of working space that
1304 is expected to be deallocated upon return from the condition handler,
1305 which doesn't return in GNAT compiled code. */
1306 void
1307 GNAT$STOP (int *sigargs)
1309 /* Note that there are no mechargs. We rely on the fact that condtions
1310 raised from DEClib I/O do not require an "adjust". Also the count
1311 will be off by 2, since LIB$STOP didn't get a chance to add the
1312 PC and PSL fields, so we bump it so PUTMSG comes out right. */
1313 sigargs [0] += 2;
1314 __gnat_handle_vms_condition (sigargs, 0);
1316 #endif
1318 void
1319 __gnat_install_handler (void)
1321 long prvhnd ATTRIBUTE_UNUSED;
1323 #if !defined (IN_RTS)
1324 extern int SYS$SETEXV (unsigned int vector, int (*addres)(),
1325 unsigned int accmode, void *(*(prvhnd)));
1326 SYS$SETEXV (1, __gnat_handle_vms_condition, 3, &prvhnd);
1327 #endif
1329 __gnat_handler_installed = 1;
1332 /* __gnat_adjust_context_for_raise for Alpha - see comments along with the
1333 default version later in this file. */
1335 #if defined (IN_RTS) && defined (__alpha__)
1337 #include <vms/chfctxdef.h>
1338 #include <vms/chfdef.h>
1340 #define HAVE_GNAT_ADJUST_CONTEXT_FOR_RAISE
1342 void
1343 __gnat_adjust_context_for_raise (int signo ATTRIBUTE_UNUSED, void *ucontext)
1345 if (signo == SS$_HPARITH)
1347 /* Sub one to the address of the instruction signaling the condition,
1348 located in the sigargs array. */
1350 CHF$MECH_ARRAY * mechargs = (CHF$MECH_ARRAY *) ucontext;
1351 CHF$SIGNAL_ARRAY * sigargs
1352 = (CHF$SIGNAL_ARRAY *) mechargs->chf$q_mch_sig_addr;
1354 int vcount = sigargs->chf$is_sig_args;
1355 int * pc_slot = & (&sigargs->chf$l_sig_name)[vcount-2];
1357 (*pc_slot)--;
1361 #endif
1363 /* __gnat_adjust_context_for_raise for ia64. */
1365 #if defined (IN_RTS) && defined (__IA64)
1367 #include <vms/chfctxdef.h>
1368 #include <vms/chfdef.h>
1370 #define HAVE_GNAT_ADJUST_CONTEXT_FOR_RAISE
1372 typedef unsigned long long u64;
1374 void
1375 __gnat_adjust_context_for_raise (int signo ATTRIBUTE_UNUSED, void *ucontext)
1377 /* Add one to the address of the instruction signaling the condition,
1378 located in the 64bits sigargs array. */
1380 CHF$MECH_ARRAY * mechargs = (CHF$MECH_ARRAY *) ucontext;
1382 CHF64$SIGNAL_ARRAY *chfsig64
1383 = (CHF64$SIGNAL_ARRAY *) mechargs->chf$ph_mch_sig64_addr;
1385 u64 * post_sigarray
1386 = (u64 *)chfsig64 + 1 + chfsig64->chf64$l_sig_args;
1388 u64 * ih_pc_loc = post_sigarray - 2;
1390 (*ih_pc_loc) ++;
1393 #endif
1395 /* Easier interface for LIB$GET_LOGICAL: put the equivalence of NAME into BUF,
1396 always NUL terminated. In case of error or if the result is longer than
1397 LEN (length of BUF) an empty string is written info BUF. */
1399 static void
1400 __gnat_vms_get_logical (const char *name, char *buf, int len)
1402 struct descriptor_s name_desc, result_desc;
1403 int status;
1404 unsigned short rlen;
1406 /* Build the descriptor for NAME. */
1407 name_desc.len = strlen (name);
1408 name_desc.mbz = 0;
1409 name_desc.adr = (char *)name;
1411 /* Build the descriptor for the result. */
1412 result_desc.len = len;
1413 result_desc.mbz = 0;
1414 result_desc.adr = buf;
1416 status = LIB$GET_LOGICAL (&name_desc, &result_desc, &rlen);
1418 if ((status & 1) == 1 && rlen < len)
1419 buf[rlen] = 0;
1420 else
1421 buf[0] = 0;
1424 /* Size of a page on ia64 and alpha VMS. */
1425 #define VMS_PAGESIZE 8192
1427 /* User mode. */
1428 #define PSL__C_USER 3
1430 /* No access. */
1431 #define PRT__C_NA 0
1433 /* Descending region. */
1434 #define VA__M_DESCEND 1
1436 /* Get by virtual address. */
1437 #define VA___REGSUM_BY_VA 1
1439 /* Memory region summary. */
1440 struct regsum
1442 unsigned long long q_region_id;
1443 unsigned int l_flags;
1444 unsigned int l_region_protection;
1445 void *pq_start_va;
1446 unsigned long long q_region_size;
1447 void *pq_first_free_va;
1450 extern int SYS$GET_REGION_INFO (unsigned int, unsigned long long *,
1451 void *, void *, unsigned int,
1452 void *, unsigned int *);
1453 extern int SYS$EXPREG_64 (unsigned long long *, unsigned long long,
1454 unsigned int, unsigned int, void **,
1455 unsigned long long *);
1456 extern int SYS$SETPRT_64 (void *, unsigned long long, unsigned int,
1457 unsigned int, void **, unsigned long long *,
1458 unsigned int *);
1460 /* Add a guard page in the memory region containing ADDR at ADDR +/- SIZE.
1461 (The sign depends on the kind of the memory region). */
1463 static int
1464 __gnat_set_stack_guard_page (void *addr, unsigned long size)
1466 int status;
1467 void *ret_va;
1468 unsigned long long ret_len;
1469 unsigned int ret_prot;
1470 void *start_va;
1471 unsigned long long length;
1472 unsigned int retlen;
1473 struct regsum buffer;
1475 /* Get the region for ADDR. */
1476 status = SYS$GET_REGION_INFO
1477 (VA___REGSUM_BY_VA, NULL, addr, NULL, sizeof (buffer), &buffer, &retlen);
1479 if ((status & 1) != 1)
1480 return -1;
1482 /* Extend the region. */
1483 status = SYS$EXPREG_64 (&buffer.q_region_id,
1484 size, 0, 0, &start_va, &length);
1486 if ((status & 1) != 1)
1487 return -1;
1489 /* Create a guard page. */
1490 if (!(buffer.l_flags & VA__M_DESCEND))
1491 start_va = (void *)((unsigned long long)start_va + length - VMS_PAGESIZE);
1493 status = SYS$SETPRT_64 (start_va, VMS_PAGESIZE, PSL__C_USER, PRT__C_NA,
1494 &ret_va, &ret_len, &ret_prot);
1496 if ((status & 1) != 1)
1497 return -1;
1498 return 0;
1501 /* Read logicals to limit the stack(s) size. */
1503 static void
1504 __gnat_set_stack_limit (void)
1506 #ifdef __ia64__
1507 void *sp;
1508 unsigned long size;
1509 char value[16];
1510 char *e;
1512 /* The main stack. */
1513 __gnat_vms_get_logical ("GNAT_STACK_SIZE", value, sizeof (value));
1514 size = strtoul (value, &e, 0);
1515 if (e > value && *e == 0)
1517 asm ("mov %0=sp" : "=r" (sp));
1518 __gnat_set_stack_guard_page (sp, size * 1024);
1521 /* The register stack. */
1522 __gnat_vms_get_logical ("GNAT_RBS_SIZE", value, sizeof (value));
1523 size = strtoul (value, &e, 0);
1524 if (e > value && *e == 0)
1526 asm ("mov %0=ar.bsp" : "=r" (sp));
1527 __gnat_set_stack_guard_page (sp, size * 1024);
1529 #endif
1532 #ifdef IN_RTS
1533 extern int SYS$IEEE_SET_FP_CONTROL (void *, void *, void *);
1534 #define K_TRUE 1
1535 #define __int64 long long
1536 #define __NEW_STARLET
1537 #include <vms/ieeedef.h>
1538 #endif
1540 /* Feature logical name and global variable address pair.
1541 If we ever add another feature logical to this list, the
1542 feature struct will need to be enhanced to take into account
1543 possible values for *gl_addr. */
1544 struct feature {
1545 const char *name;
1546 int *gl_addr;
1549 /* Default values for GNAT features set by environment or binder. */
1550 int __gl_heap_size = 64;
1552 /* Default float format is 'I' meaning IEEE. If gnatbind detetcts that a
1553 VAX Float format is specified, it will set this global variable to 'V'.
1554 Subsequently __gnat_set_features will test the variable and if set for
1555 VAX Float will call a Starlet function to enable trapping for invalid
1556 operation, drivide by zero, and overflow. This will prevent the VMS runtime
1557 (specifically OTS$CHECK_FP_MODE) from complaining about inconsistent
1558 floating point settings in a mixed language program. Ideally the setting
1559 would be determined at link time based on setttings in the object files,
1560 however the VMS linker seems to take the setting from the first object
1561 in the link, e.g. pcrt0.o which is float representation neutral. */
1562 char __gl_float_format = 'I';
1564 /* Array feature logical names and global variable addresses. */
1565 static const struct feature features[] =
1567 {"GNAT$NO_MALLOC_64", &__gl_heap_size},
1568 {0, 0}
1571 void
1572 __gnat_set_features (void)
1574 int i;
1575 char buff[16];
1576 #ifdef IN_RTS
1577 IEEE clrmsk, setmsk, prvmsk;
1579 clrmsk.ieee$q_flags = 0LL;
1580 setmsk.ieee$q_flags = 0LL;
1581 #endif
1583 /* Loop through features array and test name for enable/disable. */
1584 for (i = 0; features[i].name; i++)
1586 __gnat_vms_get_logical (features[i].name, buff, sizeof (buff));
1588 if (strcmp (buff, "ENABLE") == 0
1589 || strcmp (buff, "TRUE") == 0
1590 || strcmp (buff, "1") == 0)
1591 *features[i].gl_addr = 32;
1592 else if (strcmp (buff, "DISABLE") == 0
1593 || strcmp (buff, "FALSE") == 0
1594 || strcmp (buff, "0") == 0)
1595 *features[i].gl_addr = 64;
1598 /* Features to artificially limit the stack size. */
1599 __gnat_set_stack_limit ();
1601 #ifdef IN_RTS
1602 if (__gl_float_format == 'V')
1604 setmsk.ieee$v_trap_enable_inv = K_TRUE;
1605 setmsk.ieee$v_trap_enable_dze = K_TRUE;
1606 setmsk.ieee$v_trap_enable_ovf = K_TRUE;
1607 SYS$IEEE_SET_FP_CONTROL (&clrmsk, &setmsk, &prvmsk);
1609 #endif
1611 __gnat_features_set = 1;
1614 /* Return true if the VMS version is 7.x. */
1616 extern unsigned int LIB$GETSYI (int *, ...);
1618 #define SYI$_VERSION 0x1000
1621 __gnat_is_vms_v7 (void)
1623 struct descriptor_s desc;
1624 char version[8];
1625 int status;
1626 int code = SYI$_VERSION;
1628 desc.len = sizeof (version);
1629 desc.mbz = 0;
1630 desc.adr = version;
1632 status = LIB$GETSYI (&code, 0, &desc);
1633 if ((status & 1) == 1 && version[1] == '7' && version[2] == '.')
1634 return 1;
1635 else
1636 return 0;
1639 /*******************/
1640 /* FreeBSD Section */
1641 /*******************/
1643 #elif defined (__FreeBSD__) || defined (__DragonFly__)
1645 #include <signal.h>
1646 #include <sys/ucontext.h>
1647 #include <unistd.h>
1649 static void
1650 __gnat_error_handler (int sig,
1651 siginfo_t *si ATTRIBUTE_UNUSED,
1652 void *ucontext ATTRIBUTE_UNUSED)
1654 struct Exception_Data *exception;
1655 const char *msg;
1657 switch (sig)
1659 case SIGFPE:
1660 exception = &constraint_error;
1661 msg = "SIGFPE";
1662 break;
1664 case SIGILL:
1665 exception = &constraint_error;
1666 msg = "SIGILL";
1667 break;
1669 case SIGSEGV:
1670 exception = &storage_error;
1671 msg = "stack overflow or erroneous memory access";
1672 break;
1674 case SIGBUS:
1675 exception = &storage_error;
1676 msg = "SIGBUS: possible stack overflow";
1677 break;
1679 default:
1680 exception = &program_error;
1681 msg = "unhandled signal";
1684 Raise_From_Signal_Handler (exception, msg);
1687 void
1688 __gnat_install_handler (void)
1690 struct sigaction act;
1692 /* Set up signal handler to map synchronous signals to appropriate
1693 exceptions. Make sure that the handler isn't interrupted by another
1694 signal that might cause a scheduling event! */
1696 act.sa_sigaction
1697 = (void (*)(int, struct __siginfo *, void*)) __gnat_error_handler;
1698 act.sa_flags = SA_NODEFER | SA_RESTART | SA_SIGINFO;
1699 (void) sigemptyset (&act.sa_mask);
1701 (void) sigaction (SIGILL, &act, NULL);
1702 (void) sigaction (SIGFPE, &act, NULL);
1703 (void) sigaction (SIGSEGV, &act, NULL);
1704 (void) sigaction (SIGBUS, &act, NULL);
1706 __gnat_handler_installed = 1;
1709 /*************************************/
1710 /* VxWorks Section (including Vx653) */
1711 /*************************************/
1713 #elif defined(__vxworks)
1715 #include <signal.h>
1716 #include <taskLib.h>
1717 #if (defined (__i386__) || defined (__x86_64__)) && !defined (VTHREADS)
1718 #include <sysLib.h>
1719 #endif
1721 #include "sigtramp.h"
1723 #ifndef __RTP__
1724 #include <intLib.h>
1725 #include <iv.h>
1726 #endif
1728 #if ((defined (ARMEL) && (_WRS_VXWORKS_MAJOR == 6)) || defined (__x86_64__)) && !defined(__RTP__)
1729 #define VXWORKS_FORCE_GUARD_PAGE 1
1730 #include <vmLib.h>
1731 extern size_t vxIntStackOverflowSize;
1732 #define INT_OVERFLOW_SIZE vxIntStackOverflowSize
1733 #endif
1735 #ifdef VTHREADS
1736 #include "private/vThreadsP.h"
1737 #endif
1739 #ifndef __RTP__
1741 /* Directly vectored Interrupt routines are not supported when using RTPs. */
1743 extern void * __gnat_inum_to_ivec (int);
1745 /* This is needed by the GNAT run time to handle Vxworks interrupts. */
1746 void *
1747 __gnat_inum_to_ivec (int num)
1749 return (void *) INUM_TO_IVEC (num);
1751 #endif
1753 #if !defined(__alpha_vxworks) && ((_WRS_VXWORKS_MAJOR != 6) && (_WRS_VXWORKS_MAJOR != 7)) && !defined(__RTP__)
1755 /* getpid is used by s-parint.adb, but is not defined by VxWorks, except
1756 on Alpha VxWorks and VxWorks 6.x (including RTPs). */
1758 extern long getpid (void);
1760 long
1761 getpid (void)
1763 return taskIdSelf ();
1765 #endif
1767 /* When stack checking is performed by probing a guard page on the stack,
1768 sometimes this guard page is not properly reset on VxWorks. We need to
1769 manually reset it in this case.
1770 This function returns TRUE in case the guard page was hit by the
1771 signal. */
1772 static int
1773 __gnat_reset_guard_page (int sig)
1775 /* On ARM VxWorks 6.x and x86_64 VxWorks 7, the guard page is left un-armed
1776 by the kernel after being violated, so subsequent violations aren't
1777 detected.
1778 So we retrieve the address of the guard page from the TCB and compare it
1779 with the page that is violated and re-arm that page if there's a match. */
1780 #if defined (VXWORKS_FORCE_GUARD_PAGE)
1782 /* Ignore signals that are not stack overflow signals */
1783 if (sig != SIGSEGV && sig != SIGBUS && sig != SIGILL) return FALSE;
1785 /* If the target does not support guard pages, INT_OVERFLOW_SIZE will be 0 */
1786 if (INT_OVERFLOW_SIZE == 0) return FALSE;
1788 TASK_ID tid = taskIdSelf ();
1789 WIND_TCB *pTcb = taskTcb (tid);
1790 VIRT_ADDR guardPage = (VIRT_ADDR) pTcb->pStackEnd - INT_OVERFLOW_SIZE;
1791 UINT stateMask = VM_STATE_MASK_VALID;
1792 UINT guardState = VM_STATE_VALID_NOT;
1794 #if (_WRS_VXWORKS_MAJOR >= 7)
1795 stateMask |= MMU_ATTR_SPL_MSK;
1796 guardState |= MMU_ATTR_NO_BLOCK;
1797 #endif
1799 UINT nState;
1800 vmStateGet (NULL, guardPage, &nState);
1801 if ((nState & VM_STATE_MASK_VALID) != VM_STATE_VALID_NOT)
1803 /* If the guard page has a valid state, we need to reset to
1804 invalid state here */
1805 vmStateSet (NULL, guardPage, INT_OVERFLOW_SIZE, stateMask, guardState);
1806 return TRUE;
1808 #endif /* VXWORKS_FORCE_GUARD_PAGE */
1809 return FALSE;
1812 /* VxWorks 653 vThreads expects the field excCnt to be zeroed when a signal is.
1813 handled. The VxWorks version of longjmp does this; GCC's builtin_longjmp
1814 doesn't. */
1815 void
1816 __gnat_clear_exception_count (void)
1818 #ifdef VTHREADS
1819 WIND_TCB *currentTask = (WIND_TCB *) taskIdSelf();
1821 currentTask->vThreads.excCnt = 0;
1822 #endif
1825 /* Handle different SIGnal to exception mappings in different VxWorks
1826 versions. */
1827 void
1828 __gnat_map_signal (int sig,
1829 siginfo_t *si ATTRIBUTE_UNUSED,
1830 void *sc ATTRIBUTE_UNUSED)
1832 struct Exception_Data *exception;
1833 const char *msg;
1835 switch (sig)
1837 case SIGFPE:
1838 exception = &constraint_error;
1839 msg = "SIGFPE";
1840 break;
1841 #ifdef VTHREADS
1842 #ifdef __VXWORKSMILS__
1843 case SIGILL:
1844 exception = &storage_error;
1845 msg = "SIGILL: possible stack overflow";
1846 break;
1847 case SIGSEGV:
1848 exception = &storage_error;
1849 msg = "SIGSEGV";
1850 break;
1851 case SIGBUS:
1852 exception = &program_error;
1853 msg = "SIGBUS";
1854 break;
1855 #else
1856 case SIGILL:
1857 exception = &constraint_error;
1858 msg = "Floating point exception or SIGILL";
1859 break;
1860 case SIGSEGV:
1861 exception = &storage_error;
1862 msg = "SIGSEGV";
1863 break;
1864 case SIGBUS:
1865 exception = &storage_error;
1866 msg = "SIGBUS: possible stack overflow";
1867 break;
1868 #endif
1869 #elif (_WRS_VXWORKS_MAJOR >= 6)
1870 case SIGILL:
1871 exception = &constraint_error;
1872 msg = "SIGILL";
1873 break;
1874 #ifdef __RTP__
1875 /* In RTP mode a SIGSEGV is most likely due to a stack overflow,
1876 since stack checking uses the probing mechanism. */
1877 case SIGSEGV:
1878 exception = &storage_error;
1879 msg = "SIGSEGV: possible stack overflow";
1880 break;
1881 case SIGBUS:
1882 exception = &program_error;
1883 msg = "SIGBUS";
1884 break;
1885 #else
1886 /* VxWorks 6 kernel mode with probing. SIGBUS for guard page hit */
1887 case SIGSEGV:
1888 exception = &storage_error;
1889 msg = "SIGSEGV";
1890 break;
1891 case SIGBUS:
1892 exception = &storage_error;
1893 msg = "SIGBUS: possible stack overflow";
1894 break;
1895 #endif
1896 #else
1897 /* VxWorks 5: a SIGILL is most likely due to a stack overflow,
1898 since stack checking uses the stack limit mechanism. */
1899 case SIGILL:
1900 exception = &storage_error;
1901 msg = "SIGILL: possible stack overflow";
1902 break;
1903 case SIGSEGV:
1904 exception = &storage_error;
1905 msg = "SIGSEGV";
1906 break;
1907 case SIGBUS:
1908 exception = &program_error;
1909 msg = "SIGBUS";
1910 break;
1911 #endif
1912 default:
1913 exception = &program_error;
1914 msg = "unhandled signal";
1917 if (__gnat_reset_guard_page (sig))
1919 /* Set the exception message: we know for sure that we have a
1920 stack overflow here */
1921 exception = &storage_error;
1923 switch (sig)
1925 case SIGSEGV:
1926 msg = "SIGSEGV: stack overflow";
1927 break;
1928 case SIGBUS:
1929 msg = "SIGBUS: stack overflow";
1930 break;
1931 case SIGILL:
1932 msg = "SIGILL: stack overflow";
1933 break;
1936 __gnat_clear_exception_count ();
1937 Raise_From_Signal_Handler (exception, msg);
1940 #if defined (ARMEL) && (_WRS_VXWORKS_MAJOR >= 7)
1942 /* ARM-vx7 case with arm unwinding exceptions */
1943 #define HAVE_GNAT_ADJUST_CONTEXT_FOR_RAISE
1945 #include <arch/../regs.h>
1946 #ifndef __RTP__
1947 #include <sigLib.h>
1948 #else
1949 #include <signal.h>
1950 #include <regs.h>
1951 #include <ucontext.h>
1952 #endif /* __RTP__ */
1954 void
1955 __gnat_adjust_context_for_raise (int signo ATTRIBUTE_UNUSED,
1956 void *sc ATTRIBUTE_UNUSED)
1958 /* In case of ARM exceptions, the registers context have the PC pointing
1959 to the instruction that raised the signal. However the unwinder expects
1960 the instruction to be in the range ]PC,PC+1]. */
1961 uintptr_t *pc_addr;
1962 #ifdef __RTP__
1963 mcontext_t *mcontext = &((ucontext_t *) sc)->uc_mcontext;
1964 pc_addr = (uintptr_t*)&mcontext->regs.pc;
1965 #else
1966 struct sigcontext * sctx = (struct sigcontext *) sc;
1967 pc_addr = (uintptr_t*)&sctx->sc_pregs->pc;
1968 #endif
1969 /* ARM Bump has to be an even number because of odd/even architecture. */
1970 *pc_addr += 2;
1972 #endif /* ARMEL && _WRS_VXWORKS_MAJOR >= 7 */
1974 /* Tasking and Non-tasking signal handler. Map SIGnal to Ada exception
1975 propagation after the required low level adjustments. */
1977 static void
1978 __gnat_error_handler (int sig, siginfo_t *si, void *sc)
1980 sigset_t mask;
1982 /* VxWorks on e500v2 clears the SPE bit of the MSR when entering CPU
1983 exception state. To allow the handler and exception to work properly
1984 when they contain SPE instructions, we need to set it back before doing
1985 anything else.
1986 This mechanism is only need in kernel mode. */
1987 #if !(defined (__RTP__) || defined (VTHREADS)) && ((CPU == PPCE500V2) || (CPU == PPC85XX))
1988 register unsigned msr;
1989 /* Read the MSR value */
1990 asm volatile ("mfmsr %0" : "=r" (msr));
1991 /* Force the SPE bit if not set. */
1992 if ((msr & 0x02000000) == 0)
1994 msr |= 0x02000000;
1995 /* Store to MSR */
1996 asm volatile ("mtmsr %0" : : "r" (msr));
1998 #endif
2000 /* VxWorks will always mask out the signal during the signal handler and
2001 will reenable it on a longjmp. GNAT does not generate a longjmp to
2002 return from a signal handler so the signal will still be masked unless
2003 we unmask it. */
2004 sigprocmask (SIG_SETMASK, NULL, &mask);
2005 sigdelset (&mask, sig);
2006 sigprocmask (SIG_SETMASK, &mask, NULL);
2008 #if defined (__ARMEL__) || defined (__PPC__) || defined (__i386__) || defined (__x86_64__)
2009 /* On certain targets, kernel mode, we process signals through a Call Frame
2010 Info trampoline, voiding the need for myriads of fallback_frame_state
2011 variants in the ZCX runtime. We have no simple way to distinguish ZCX
2012 from SJLJ here, so we do this for SJLJ as well even though this is not
2013 necessary. This only incurs a few extra instructions and a tiny
2014 amount of extra stack usage. */
2016 #ifdef HAVE_GNAT_ADJUST_CONTEXT_FOR_RAISE
2017 /* We need to sometimes to adjust the PC in case of signals so that it
2018 doesn't reference the exception that actually raised the signal but the
2019 instruction before it. */
2020 __gnat_adjust_context_for_raise (sig, sc);
2021 #endif
2023 __gnat_sigtramp (sig, (void *)si, (void *)sc,
2024 (__sigtramphandler_t *)&__gnat_map_signal);
2026 #else
2027 __gnat_map_signal (sig, si, sc);
2028 #endif
2031 #if defined(__leon__) && defined(_WRS_KERNEL)
2032 /* For LEON VxWorks we need to install a trap handler for stack overflow */
2034 extern void excEnt (void);
2035 /* VxWorks exception handler entry */
2037 struct trap_entry {
2038 unsigned long inst_first;
2039 unsigned long inst_second;
2040 unsigned long inst_third;
2041 unsigned long inst_fourth;
2043 /* Four instructions representing entries in the trap table */
2045 struct trap_entry *trap_0_entry;
2046 /* We will set the location of the entry for software trap 0 in the trap
2047 table. */
2048 #endif
2050 void
2051 __gnat_install_handler (void)
2053 struct sigaction act;
2055 /* Setup signal handler to map synchronous signals to appropriate
2056 exceptions. Make sure that the handler isn't interrupted by another
2057 signal that might cause a scheduling event! */
2059 act.sa_sigaction = __gnat_error_handler;
2060 act.sa_flags = SA_SIGINFO | SA_ONSTACK;
2061 sigemptyset (&act.sa_mask);
2063 /* For VxWorks, install all signal handlers, since pragma Interrupt_State
2064 applies to vectored hardware interrupts, not signals. */
2065 sigaction (SIGFPE, &act, NULL);
2066 sigaction (SIGILL, &act, NULL);
2067 sigaction (SIGSEGV, &act, NULL);
2068 sigaction (SIGBUS, &act, NULL);
2070 #if defined(__leon__) && defined(_WRS_KERNEL)
2071 /* Specific to the LEON VxWorks kernel run-time library */
2073 /* For stack checking the compiler triggers a software trap 0 (ta 0) in
2074 case of overflow (we use the stack limit mechanism). We need to install
2075 the trap handler here for this software trap (the OS does not handle
2076 it) as if it were a data_access_exception (trap 9). We do the same as
2077 if we put in the trap table a VXSPARC_BAD_TRAP(9). Software trap 0 is
2078 located at vector 0x80, and each entry takes 4 words. */
2080 trap_0_entry = (struct trap_entry *)(intVecBaseGet () + 0x80 * 4);
2082 /* mov 0x9, %l7 */
2084 trap_0_entry->inst_first = 0xae102000 + 9;
2086 /* sethi %hi(excEnt), %l6 */
2088 /* The 22 most significant bits of excEnt are obtained shifting 10 times
2089 to the right. */
2091 trap_0_entry->inst_second = 0x2d000000 + ((unsigned long)excEnt >> 10);
2093 /* jmp %l6+%lo(excEnt) */
2095 /* The 10 least significant bits of excEnt are obtained by masking */
2097 trap_0_entry->inst_third = 0x81c5a000 + ((unsigned long)excEnt & 0x3ff);
2099 /* rd %psr, %l0 */
2101 trap_0_entry->inst_fourth = 0xa1480000;
2102 #endif
2104 #ifdef __HANDLE_VXSIM_SC
2105 /* By experiment, found that sysModel () returns the following string
2106 prefix for vxsim when running on Linux and Windows. */
2108 char *model = sysModel ();
2109 if ((strncmp (model, "Linux", 5) == 0)
2110 || (strncmp (model, "Windows", 7) == 0)
2111 || (strncmp (model, "SIMLINUX", 8) == 0) /* vx7 */
2112 || (strncmp (model, "SIMNT", 5) == 0)) /* ditto */
2113 __gnat_set_is_vxsim (TRUE);
2115 #endif
2117 __gnat_handler_installed = 1;
2120 #define HAVE_GNAT_INIT_FLOAT
2122 void
2123 __gnat_init_float (void)
2125 /* Disable overflow/underflow exceptions on the PPC processor, needed
2126 to get correct Ada semantics. Note that for AE653 vThreads, the HW
2127 overflow settings are an OS configuration issue. The instructions
2128 below have no effect. */
2129 #if defined (_ARCH_PPC) && !defined (_SOFT_FLOAT) && (!defined (VTHREADS) || defined (__VXWORKSMILS__))
2130 #if defined (__SPE__)
2132 /* For e500v2, do nothing and leave the responsibility to install the
2133 handler and enable the exceptions to the BSP. */
2135 #else
2136 asm ("mtfsb0 25");
2137 asm ("mtfsb0 26");
2138 #endif
2139 #endif
2141 #if (defined (__i386__) || defined (__x86_64__)) && !defined (VTHREADS)
2142 /* This is used to properly initialize the FPU on an x86 for each
2143 process thread. */
2144 asm ("finit");
2145 #endif
2147 /* Similarly for SPARC64. Achieved by masking bits in the Trap Enable Mask
2148 field of the Floating-point Status Register (see the SPARC Architecture
2149 Manual Version 9, p 48). */
2150 #if defined (sparc64)
2152 #define FSR_TEM_NVM (1 << 27) /* Invalid operand */
2153 #define FSR_TEM_OFM (1 << 26) /* Overflow */
2154 #define FSR_TEM_UFM (1 << 25) /* Underflow */
2155 #define FSR_TEM_DZM (1 << 24) /* Division by Zero */
2156 #define FSR_TEM_NXM (1 << 23) /* Inexact result */
2158 unsigned int fsr;
2160 __asm__("st %%fsr, %0" : "=m" (fsr));
2161 fsr &= ~(FSR_TEM_OFM | FSR_TEM_UFM);
2162 __asm__("ld %0, %%fsr" : : "m" (fsr));
2164 #endif
2167 /* This subprogram is called by System.Task_Primitives.Operations.Enter_Task
2168 (if not null) when a new task is created. It is initialized by
2169 System.Stack_Checking.Operations.Initialize_Stack_Limit.
2170 The use of a hook avoids to drag stack checking subprograms if stack
2171 checking is not used. */
2172 void (*__gnat_set_stack_limit_hook)(void) = (void (*)(void))0;
2174 /******************/
2175 /* NetBSD Section */
2176 /******************/
2178 #elif defined(__NetBSD__)
2180 #include <signal.h>
2181 #include <unistd.h>
2183 static void
2184 __gnat_error_handler (int sig)
2186 struct Exception_Data *exception;
2187 const char *msg;
2189 switch(sig)
2191 case SIGFPE:
2192 exception = &constraint_error;
2193 msg = "SIGFPE";
2194 break;
2195 case SIGILL:
2196 exception = &constraint_error;
2197 msg = "SIGILL";
2198 break;
2199 case SIGSEGV:
2200 exception = &storage_error;
2201 msg = "stack overflow or erroneous memory access";
2202 break;
2203 case SIGBUS:
2204 exception = &constraint_error;
2205 msg = "SIGBUS";
2206 break;
2207 default:
2208 exception = &program_error;
2209 msg = "unhandled signal";
2212 Raise_From_Signal_Handler (exception, msg);
2215 void
2216 __gnat_install_handler (void)
2218 struct sigaction act;
2220 act.sa_handler = __gnat_error_handler;
2221 act.sa_flags = SA_NODEFER | SA_RESTART;
2222 sigemptyset (&act.sa_mask);
2224 /* Do not install handlers if interrupt state is "System". */
2225 if (__gnat_get_interrupt_state (SIGFPE) != 's')
2226 sigaction (SIGFPE, &act, NULL);
2227 if (__gnat_get_interrupt_state (SIGILL) != 's')
2228 sigaction (SIGILL, &act, NULL);
2229 if (__gnat_get_interrupt_state (SIGSEGV) != 's')
2230 sigaction (SIGSEGV, &act, NULL);
2231 if (__gnat_get_interrupt_state (SIGBUS) != 's')
2232 sigaction (SIGBUS, &act, NULL);
2234 __gnat_handler_installed = 1;
2237 /*******************/
2238 /* OpenBSD Section */
2239 /*******************/
2241 #elif defined(__OpenBSD__)
2243 #include <signal.h>
2244 #include <unistd.h>
2246 static void
2247 __gnat_error_handler (int sig)
2249 struct Exception_Data *exception;
2250 const char *msg;
2252 switch(sig)
2254 case SIGFPE:
2255 exception = &constraint_error;
2256 msg = "SIGFPE";
2257 break;
2258 case SIGILL:
2259 exception = &constraint_error;
2260 msg = "SIGILL";
2261 break;
2262 case SIGSEGV:
2263 exception = &storage_error;
2264 msg = "stack overflow or erroneous memory access";
2265 break;
2266 case SIGBUS:
2267 exception = &constraint_error;
2268 msg = "SIGBUS";
2269 break;
2270 default:
2271 exception = &program_error;
2272 msg = "unhandled signal";
2275 Raise_From_Signal_Handler (exception, msg);
2278 void
2279 __gnat_install_handler (void)
2281 struct sigaction act;
2283 act.sa_handler = __gnat_error_handler;
2284 act.sa_flags = SA_NODEFER | SA_RESTART;
2285 sigemptyset (&act.sa_mask);
2287 /* Do not install handlers if interrupt state is "System" */
2288 if (__gnat_get_interrupt_state (SIGFPE) != 's')
2289 sigaction (SIGFPE, &act, NULL);
2290 if (__gnat_get_interrupt_state (SIGILL) != 's')
2291 sigaction (SIGILL, &act, NULL);
2292 if (__gnat_get_interrupt_state (SIGSEGV) != 's')
2293 sigaction (SIGSEGV, &act, NULL);
2294 if (__gnat_get_interrupt_state (SIGBUS) != 's')
2295 sigaction (SIGBUS, &act, NULL);
2297 __gnat_handler_installed = 1;
2300 /******************/
2301 /* Darwin Section */
2302 /******************/
2304 #elif defined(__APPLE__)
2306 #include <TargetConditionals.h>
2307 #include <signal.h>
2308 #include <stdlib.h>
2309 #include <sys/syscall.h>
2310 #include <sys/sysctl.h>
2312 /* This must be in keeping with System.OS_Interface.Alternate_Stack_Size. */
2313 char __gnat_alternate_stack[32 * 1024]; /* 1 * MINSIGSTKSZ */
2315 /* Defined in xnu unix_signal.c.
2316 Tell the kernel to re-use alt stack when delivering a signal. */
2317 #define UC_RESET_ALT_STACK 0x80000000
2319 #if !(defined (__arm__) || defined (__arm64__) || TARGET_IPHONE_SIMULATOR)
2320 #include <mach/mach_vm.h>
2321 #include <mach/mach_init.h>
2322 #include <mach/vm_statistics.h>
2323 #endif
2325 #ifdef __arm64__
2326 #include <sys/ucontext.h>
2327 #include "sigtramp.h"
2328 #endif
2330 /* Return true if ADDR is within a stack guard area. */
2331 static int
2332 __gnat_is_stack_guard (mach_vm_address_t addr)
2334 #if !(defined (__arm__) || defined (__arm64__) || TARGET_IPHONE_SIMULATOR)
2335 kern_return_t kret;
2336 vm_region_submap_info_data_64_t info;
2337 mach_vm_address_t start;
2338 mach_vm_size_t size;
2339 natural_t depth;
2340 mach_msg_type_number_t count;
2342 count = VM_REGION_SUBMAP_INFO_COUNT_64;
2343 start = addr;
2344 size = -1;
2345 depth = 9999;
2346 kret = mach_vm_region_recurse (mach_task_self (), &start, &size, &depth,
2347 (vm_region_recurse_info_t) &info, &count);
2348 if (kret == KERN_SUCCESS
2349 && addr >= start && addr < (start + size)
2350 && info.protection == VM_PROT_NONE
2351 && info.user_tag == VM_MEMORY_STACK)
2352 return 1;
2353 return 0;
2354 #else
2355 /* Pagezero for arm. */
2356 return addr >= 4096;
2357 #endif
2360 #define HAVE_GNAT_ADJUST_CONTEXT_FOR_RAISE
2362 #if defined (__x86_64__)
2363 static int
2364 __darwin_major_version (void)
2366 static int cache = -1;
2367 if (cache < 0)
2369 int mib[2] = {CTL_KERN, KERN_OSRELEASE};
2370 size_t len;
2372 /* Find out how big the buffer needs to be (and set cache to 0
2373 on failure). */
2374 if (sysctl (mib, 2, NULL, &len, NULL, 0) == 0)
2376 char release[len];
2377 sysctl (mib, 2, release, &len, NULL, 0);
2378 /* Darwin releases are of the form L.M.N where L is the major
2379 version, so strtol will return L. */
2380 cache = (int) strtol (release, NULL, 10);
2382 else
2384 cache = 0;
2387 return cache;
2389 #endif
2391 void
2392 __gnat_adjust_context_for_raise (int signo ATTRIBUTE_UNUSED,
2393 void *ucontext ATTRIBUTE_UNUSED)
2395 #if defined (__x86_64__)
2396 if (__darwin_major_version () < 12)
2398 /* Work around radar #10302855, where the unwinders (libunwind or
2399 libgcc_s depending on the system revision) and the DWARF unwind
2400 data for sigtramp have different ideas about register numbering,
2401 causing rbx and rdx to be transposed. */
2402 ucontext_t *uc = (ucontext_t *)ucontext;
2403 unsigned long t = uc->uc_mcontext->__ss.__rbx;
2405 uc->uc_mcontext->__ss.__rbx = uc->uc_mcontext->__ss.__rdx;
2406 uc->uc_mcontext->__ss.__rdx = t;
2408 #elif defined(__arm64__)
2409 /* Even though the CFI is marked as a signal frame, we need this. */
2410 ucontext_t *uc = (ucontext_t *)ucontext;
2411 uc->uc_mcontext->__ss.__pc++;
2412 #endif
2415 static void
2416 __gnat_map_signal (int sig, siginfo_t *si, void *mcontext ATTRIBUTE_UNUSED)
2418 struct Exception_Data *exception;
2419 const char *msg;
2421 switch (sig)
2423 case SIGSEGV:
2424 case SIGBUS:
2425 if (__gnat_is_stack_guard ((unsigned long)si->si_addr))
2427 #ifdef __arm64__
2428 /* ??? This is a kludge to make stack checking work. The problem is
2429 that the trampoline doesn't restore LR and, consequently, doesn't
2430 make it possible to unwind past an interrupted frame which hasn"t
2431 saved LR on the stack yet. Therefore, for probes in the prologue
2432 (32-bit probes as opposed to standard 64-bit probes), we make the
2433 unwinder skip the not-yet-established frame altogether. */
2434 mcontext_t mc = (mcontext_t)mcontext;
2435 if (!(*(unsigned int *)(mc->__ss.__pc-1) & ((unsigned int)1 << 30)))
2436 mc->__ss.__pc = mc->__ss.__lr;
2437 #endif
2438 exception = &storage_error;
2439 msg = "stack overflow";
2441 else
2443 exception = &constraint_error;
2444 msg = "erroneous memory access";
2447 /* Reset the use of alt stack, so that the alt stack will be used
2448 for the next signal delivery.
2449 The stack can't be used in case of stack checking. */
2450 syscall (SYS_sigreturn, NULL, UC_RESET_ALT_STACK);
2451 break;
2453 case SIGFPE:
2454 exception = &constraint_error;
2455 msg = "SIGFPE";
2456 break;
2458 default:
2459 exception = &program_error;
2460 msg = "unhandled signal";
2463 Raise_From_Signal_Handler (exception, msg);
2466 static void
2467 __gnat_error_handler (int sig, siginfo_t *si, void *ucontext)
2469 __gnat_adjust_context_for_raise (sig, ucontext);
2471 /* The Darwin libc comes with a signal trampoline, except for ARM64. */
2472 #ifdef __arm64__
2473 __gnat_sigtramp (sig, (void *)si, ucontext,
2474 (__sigtramphandler_t *)&__gnat_map_signal);
2475 #else
2476 __gnat_map_signal (sig, si, ucontext);
2477 #endif
2480 void
2481 __gnat_install_handler (void)
2483 struct sigaction act;
2485 /* Set up signal handler to map synchronous signals to appropriate
2486 exceptions. Make sure that the handler isn't interrupted by another
2487 signal that might cause a scheduling event! Also setup an alternate
2488 stack region for the handler execution so that stack overflows can be
2489 handled properly, avoiding a SEGV generation from stack usage by the
2490 handler itself (and it is required by Darwin). */
2492 stack_t stack;
2493 stack.ss_sp = __gnat_alternate_stack;
2494 stack.ss_size = sizeof (__gnat_alternate_stack);
2495 stack.ss_flags = 0;
2496 sigaltstack (&stack, NULL);
2498 act.sa_flags = SA_NODEFER | SA_RESTART | SA_SIGINFO;
2499 act.sa_sigaction = __gnat_error_handler;
2500 sigemptyset (&act.sa_mask);
2502 /* Do not install handlers if interrupt state is "System". */
2503 if (__gnat_get_interrupt_state (SIGABRT) != 's')
2504 sigaction (SIGABRT, &act, NULL);
2505 if (__gnat_get_interrupt_state (SIGFPE) != 's')
2506 sigaction (SIGFPE, &act, NULL);
2507 if (__gnat_get_interrupt_state (SIGILL) != 's')
2508 sigaction (SIGILL, &act, NULL);
2510 act.sa_flags |= SA_ONSTACK;
2511 if (__gnat_get_interrupt_state (SIGSEGV) != 's')
2512 sigaction (SIGSEGV, &act, NULL);
2513 if (__gnat_get_interrupt_state (SIGBUS) != 's')
2514 sigaction (SIGBUS, &act, NULL);
2516 __gnat_handler_installed = 1;
2519 #elif defined(__QNX__)
2521 /***************/
2522 /* QNX Section */
2523 /***************/
2525 #include <signal.h>
2526 #include <unistd.h>
2527 #include <string.h>
2528 #include "sigtramp.h"
2530 void
2531 __gnat_map_signal (int sig,
2532 siginfo_t *si ATTRIBUTE_UNUSED,
2533 void *mcontext ATTRIBUTE_UNUSED)
2535 struct Exception_Data *exception;
2536 const char *msg;
2538 switch(sig)
2540 case SIGFPE:
2541 exception = &constraint_error;
2542 msg = "SIGFPE";
2543 break;
2544 case SIGILL:
2545 exception = &constraint_error;
2546 msg = "SIGILL";
2547 break;
2548 case SIGSEGV:
2549 exception = &storage_error;
2550 msg = "stack overflow or erroneous memory access";
2551 break;
2552 case SIGBUS:
2553 exception = &constraint_error;
2554 msg = "SIGBUS";
2555 break;
2556 default:
2557 exception = &program_error;
2558 msg = "unhandled signal";
2561 Raise_From_Signal_Handler (exception, msg);
2564 static void
2565 __gnat_error_handler (int sig, siginfo_t *si, void *ucontext)
2567 __gnat_sigtramp (sig, (void *) si, (void *) ucontext,
2568 (__sigtramphandler_t *)&__gnat_map_signal);
2571 /* This must be in keeping with System.OS_Interface.Alternate_Stack_Size. */
2572 /* sigaltstack is currently not supported by QNX7 */
2573 char __gnat_alternate_stack[0];
2575 void
2576 __gnat_install_handler (void)
2578 struct sigaction act;
2579 int err;
2581 act.sa_handler = __gnat_error_handler;
2582 act.sa_flags = SA_NODEFER | SA_SIGINFO;
2583 sigemptyset (&act.sa_mask);
2585 /* Do not install handlers if interrupt state is "System" */
2586 if (__gnat_get_interrupt_state (SIGFPE) != 's') {
2587 err = sigaction (SIGFPE, &act, NULL);
2588 if (err == -1) {
2589 err = errno;
2590 perror ("error while attaching SIGFPE");
2591 perror (strerror (err));
2594 if (__gnat_get_interrupt_state (SIGILL) != 's') {
2595 sigaction (SIGILL, &act, NULL);
2596 if (err == -1) {
2597 err = errno;
2598 perror ("error while attaching SIGFPE");
2599 perror (strerror (err));
2602 if (__gnat_get_interrupt_state (SIGSEGV) != 's') {
2603 sigaction (SIGSEGV, &act, NULL);
2604 if (err == -1) {
2605 err = errno;
2606 perror ("error while attaching SIGFPE");
2607 perror (strerror (err));
2610 if (__gnat_get_interrupt_state (SIGBUS) != 's') {
2611 sigaction (SIGBUS, &act, NULL);
2612 if (err == -1) {
2613 err = errno;
2614 perror ("error while attaching SIGFPE");
2615 perror (strerror (err));
2618 __gnat_handler_installed = 1;
2621 #elif defined (__DJGPP__)
2623 void
2624 __gnat_install_handler ()
2626 __gnat_handler_installed = 1;
2629 #elif defined(__ANDROID__)
2631 /*******************/
2632 /* Android Section */
2633 /*******************/
2635 #include <signal.h>
2636 #include <sys/ucontext.h>
2637 #include "sigtramp.h"
2639 #define HAVE_GNAT_ADJUST_CONTEXT_FOR_RAISE
2641 void
2642 __gnat_adjust_context_for_raise (int signo ATTRIBUTE_UNUSED, void *ucontext)
2644 mcontext_t *mcontext = &((ucontext_t *) ucontext)->uc_mcontext;
2646 /* ARM Bump has to be an even number because of odd/even architecture. */
2647 ((mcontext_t *) mcontext)->arm_pc += 2;
2650 static void
2651 __gnat_map_signal (int sig,
2652 siginfo_t *si ATTRIBUTE_UNUSED,
2653 void *mcontext ATTRIBUTE_UNUSED)
2655 struct Exception_Data *exception;
2656 const char *msg;
2658 switch (sig)
2660 case SIGSEGV:
2661 exception = &storage_error;
2662 msg = "stack overflow or erroneous memory access";
2663 break;
2665 case SIGBUS:
2666 exception = &constraint_error;
2667 msg = "SIGBUS";
2668 break;
2670 case SIGFPE:
2671 exception = &constraint_error;
2672 msg = "SIGFPE";
2673 break;
2675 default:
2676 exception = &program_error;
2677 msg = "unhandled signal";
2680 Raise_From_Signal_Handler (exception, msg);
2683 static void
2684 __gnat_error_handler (int sig, siginfo_t *si, void *ucontext)
2686 __gnat_adjust_context_for_raise (sig, ucontext);
2688 __gnat_sigtramp (sig, (void *) si, (void *) ucontext,
2689 (__sigtramphandler_t *)&__gnat_map_signal);
2692 /* This must be in keeping with System.OS_Interface.Alternate_Stack_Size. */
2693 char __gnat_alternate_stack[16 * 1024];
2695 void
2696 __gnat_install_handler (void)
2698 struct sigaction act;
2700 /* Set up signal handler to map synchronous signals to appropriate
2701 exceptions. Make sure that the handler isn't interrupted by another
2702 signal that might cause a scheduling event! Also setup an alternate
2703 stack region for the handler execution so that stack overflows can be
2704 handled properly, avoiding a SEGV generation from stack usage by the
2705 handler itself. */
2707 stack_t stack;
2708 stack.ss_sp = __gnat_alternate_stack;
2709 stack.ss_size = sizeof (__gnat_alternate_stack);
2710 stack.ss_flags = 0;
2711 sigaltstack (&stack, NULL);
2713 act.sa_sigaction = __gnat_error_handler;
2714 act.sa_flags = SA_NODEFER | SA_RESTART | SA_SIGINFO;
2715 sigemptyset (&act.sa_mask);
2717 sigaction (SIGABRT, &act, NULL);
2718 sigaction (SIGFPE, &act, NULL);
2719 sigaction (SIGILL, &act, NULL);
2720 sigaction (SIGBUS, &act, NULL);
2721 act.sa_flags |= SA_ONSTACK;
2722 sigaction (SIGSEGV, &act, NULL);
2724 __gnat_handler_installed = 1;
2727 #else
2729 /* For all other versions of GNAT, the handler does nothing. */
2731 /*******************/
2732 /* Default Section */
2733 /*******************/
2735 void
2736 __gnat_install_handler (void)
2738 __gnat_handler_installed = 1;
2741 #endif
2743 /*********************/
2744 /* __gnat_init_float */
2745 /*********************/
2747 /* This routine is called as each process thread is created, for possible
2748 initialization of the FP processor. This version is used under INTERIX
2749 and WIN32. */
2751 #if defined (_WIN32) || defined (__INTERIX) \
2752 || defined (__Lynx__) || defined(__NetBSD__) || defined(__FreeBSD__) \
2753 || defined (__OpenBSD__) || defined (__DragonFly__) || defined(__QNX__)
2755 #define HAVE_GNAT_INIT_FLOAT
2757 void
2758 __gnat_init_float (void)
2760 #if defined (__i386__) || defined (__x86_64__)
2762 /* This is used to properly initialize the FPU on an x86 for each
2763 process thread. */
2765 asm ("finit");
2767 #endif /* Defined __i386__ */
2769 #endif
2771 #ifndef HAVE_GNAT_INIT_FLOAT
2773 /* All targets without a specific __gnat_init_float will use an empty one. */
2774 void
2775 __gnat_init_float (void)
2778 #endif
2780 /***********************************/
2781 /* __gnat_adjust_context_for_raise */
2782 /***********************************/
2784 #ifndef HAVE_GNAT_ADJUST_CONTEXT_FOR_RAISE
2786 /* All targets without a specific version will use an empty one. */
2788 /* Given UCONTEXT a pointer to a context structure received by a signal
2789 handler for SIGNO, perform the necessary adjustments to let the handler
2790 raise an exception. Calls to this routine are not conditioned by the
2791 propagation scheme in use. */
2793 void
2794 __gnat_adjust_context_for_raise (int signo ATTRIBUTE_UNUSED,
2795 void *ucontext ATTRIBUTE_UNUSED)
2797 /* We used to compensate here for the raised from call vs raised from signal
2798 exception discrepancy with the GCC ZCX scheme, but this now can be dealt
2799 with generically in the unwinder (see GCC PR other/26208). This however
2800 requires the use of the _Unwind_GetIPInfo routine in raise-gcc.c, which
2801 is predicated on the definition of HAVE_GETIPINFO at compile time. Only
2802 the VMS ports still do the compensation described in the few lines below.
2804 *** Call vs signal exception discrepancy with GCC ZCX scheme ***
2806 The GCC unwinder expects to be dealing with call return addresses, since
2807 this is the "nominal" case of what we retrieve while unwinding a regular
2808 call chain.
2810 To evaluate if a handler applies at some point identified by a return
2811 address, the propagation engine needs to determine what region the
2812 corresponding call instruction pertains to. Because the return address
2813 may not be attached to the same region as the call, the unwinder always
2814 subtracts "some" amount from a return address to search the region
2815 tables, amount chosen to ensure that the resulting address is inside the
2816 call instruction.
2818 When we raise an exception from a signal handler, e.g. to transform a
2819 SIGSEGV into Storage_Error, things need to appear as if the signal
2820 handler had been "called" by the instruction which triggered the signal,
2821 so that exception handlers that apply there are considered. What the
2822 unwinder will retrieve as the return address from the signal handler is
2823 what it will find as the faulting instruction address in the signal
2824 context pushed by the kernel. Leaving this address untouched looses, if
2825 the triggering instruction happens to be the very first of a region, as
2826 the later adjustments performed by the unwinder would yield an address
2827 outside that region. We need to compensate for the unwinder adjustments
2828 at some point, and this is what this routine is expected to do.
2830 signo is passed because on some targets for some signals the PC in
2831 context points to the instruction after the faulting one, in which case
2832 the unwinder adjustment is still desired. */
2835 #endif
2837 #ifdef __cplusplus
2839 #endif