1 /****************************************************************************
3 * GNAT COMPILER COMPONENTS *
7 * C Implementation File *
9 * Copyright (C) 1992-2012, Free Software Foundation, Inc. *
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. *
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. *
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/>. *
27 * GNAT was originally developed by the GNAT team at New York University. *
28 * Extensive contributions were provided by Ada Core Technologies Inc. *
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). */
45 /* This file should be kept synchronized with 2sinit.ads, 2sinit.adb,
46 s-init-ae653-cert.adb and s-init-xi-sparc.adb. All these files implement
47 the required functionality for different targets. */
49 /* The following include is here to meet the published VxWorks requirement
50 that the __vxworks header appear before any other include. */
60 /* We don't have libiberty, so use malloc. */
61 #define xmalloc(S) malloc (S)
70 extern void __gnat_raise_program_error (const char *, int);
72 /* Addresses of exception data blocks for predefined exceptions. Tasking_Error
73 is not used in this unit, and the abort signal is only used on IRIX. */
74 extern struct Exception_Data constraint_error;
75 extern struct Exception_Data numeric_error;
76 extern struct Exception_Data program_error;
77 extern struct Exception_Data storage_error;
79 /* For the Cert run time we use the regular raise exception routine because
80 Raise_From_Signal_Handler is not available. */
82 #define Raise_From_Signal_Handler \
83 __gnat_raise_exception
84 extern void Raise_From_Signal_Handler (struct Exception_Data *, const char *);
86 #define Raise_From_Signal_Handler \
87 ada__exceptions__raise_from_signal_handler
88 extern void Raise_From_Signal_Handler (struct Exception_Data *, const char *);
91 /* Global values computed by the binder. */
92 int __gl_main_priority = -1;
93 int __gl_main_cpu = -1;
94 int __gl_time_slice_val = -1;
95 char __gl_wc_encoding = 'n';
96 char __gl_locking_policy = ' ';
97 char __gl_queuing_policy = ' ';
98 char __gl_task_dispatching_policy = ' ';
99 char *__gl_priority_specific_dispatching = 0;
100 int __gl_num_specific_dispatching = 0;
101 char *__gl_interrupt_states = 0;
102 int __gl_num_interrupt_states = 0;
103 int __gl_unreserve_all_interrupts = 0;
104 int __gl_exception_tracebacks = 0;
105 int __gl_zero_cost_exceptions = 0;
106 int __gl_detect_blocking = 0;
107 int __gl_default_stack_size = -1;
108 int __gl_leap_seconds_support = 0;
109 int __gl_canonical_streams = 0;
111 /* Indication of whether synchronous signal handler has already been
112 installed by a previous call to adainit. */
113 int __gnat_handler_installed = 0;
116 int __gnat_inside_elab_final_code = 0;
117 /* ??? This variable is obsolete since 2001-08-29 but is kept to allow
118 bootstrap from old GNAT versions (< 3.15). */
121 /* HAVE_GNAT_INIT_FLOAT must be set on every targets where a __gnat_init_float
122 is defined. If this is not set then a void implementation will be defined
123 at the end of this unit. */
124 #undef HAVE_GNAT_INIT_FLOAT
126 /******************************/
127 /* __gnat_get_interrupt_state */
128 /******************************/
130 char __gnat_get_interrupt_state (int);
132 /* This routine is called from the runtime as needed to determine the state
133 of an interrupt, as set by an Interrupt_State pragma appearing anywhere
134 in the current partition. The input argument is the interrupt number,
135 and the result is one of the following:
137 'n' this interrupt not set by any Interrupt_State pragma
138 'u' Interrupt_State pragma set state to User
139 'r' Interrupt_State pragma set state to Runtime
140 's' Interrupt_State pragma set state to System */
143 __gnat_get_interrupt_state (int intrup)
145 if (intrup >= __gl_num_interrupt_states)
148 return __gl_interrupt_states [intrup];
151 /***********************************/
152 /* __gnat_get_specific_dispatching */
153 /***********************************/
155 char __gnat_get_specific_dispatching (int);
157 /* This routine is called from the runtime as needed to determine the
158 priority specific dispatching policy, as set by a
159 Priority_Specific_Dispatching pragma appearing anywhere in the current
160 partition. The input argument is the priority number, and the result
161 is the upper case first character of the policy name, e.g. 'F' for
162 FIFO_Within_Priorities. A space ' ' is returned if no
163 Priority_Specific_Dispatching pragma is used in the partition. */
166 __gnat_get_specific_dispatching (int priority)
168 if (__gl_num_specific_dispatching == 0)
170 else if (priority >= __gl_num_specific_dispatching)
173 return __gl_priority_specific_dispatching [priority];
178 /**********************/
179 /* __gnat_set_globals */
180 /**********************/
182 /* This routine is kept for bootstrapping purposes, since the binder generated
183 file now sets the __gl_* variables directly. */
186 __gnat_set_globals (void)
199 #include <sys/time.h>
201 /* Some versions of AIX don't define SA_NODEFER. */
205 #endif /* SA_NODEFER */
207 /* Versions of AIX before 4.3 don't have nanosleep but provide
210 #ifndef _AIXVERSION_430
212 extern int nanosleep (struct timestruc_t *, struct timestruc_t *);
215 nanosleep (struct timestruc_t *Rqtp, struct timestruc_t *Rmtp)
217 return nsleep (Rqtp, Rmtp);
220 #endif /* _AIXVERSION_430 */
222 /* Version of AIX before 5.3 don't have pthread_condattr_setclock:
223 * supply it as a weak symbol here so that if linking on a 5.3 or newer
224 * machine, we get the real one.
227 #ifndef _AIXVERSION_530
228 #pragma weak pthread_condattr_setclock
230 pthread_condattr_setclock (pthread_condattr_t *attr, clockid_t cl) {
236 __gnat_error_handler (int sig,
237 siginfo_t *si ATTRIBUTE_UNUSED,
238 void *ucontext ATTRIBUTE_UNUSED)
240 struct Exception_Data *exception;
246 /* FIXME: we need to detect the case of a *real* SIGSEGV. */
247 exception = &storage_error;
248 msg = "stack overflow or erroneous memory access";
252 exception = &constraint_error;
257 exception = &constraint_error;
262 exception = &program_error;
263 msg = "unhandled signal";
266 Raise_From_Signal_Handler (exception, msg);
270 __gnat_install_handler (void)
272 struct sigaction act;
274 /* Set up signal handler to map synchronous signals to appropriate
275 exceptions. Make sure that the handler isn't interrupted by another
276 signal that might cause a scheduling event! */
278 act.sa_flags = SA_NODEFER | SA_RESTART | SA_SIGINFO;
279 act.sa_sigaction = __gnat_error_handler;
280 sigemptyset (&act.sa_mask);
282 /* Do not install handlers if interrupt state is "System". */
283 if (__gnat_get_interrupt_state (SIGABRT) != 's')
284 sigaction (SIGABRT, &act, NULL);
285 if (__gnat_get_interrupt_state (SIGFPE) != 's')
286 sigaction (SIGFPE, &act, NULL);
287 if (__gnat_get_interrupt_state (SIGILL) != 's')
288 sigaction (SIGILL, &act, NULL);
289 if (__gnat_get_interrupt_state (SIGSEGV) != 's')
290 sigaction (SIGSEGV, &act, NULL);
291 if (__gnat_get_interrupt_state (SIGBUS) != 's')
292 sigaction (SIGBUS, &act, NULL);
294 __gnat_handler_installed = 1;
301 #elif defined(__alpha__) && defined(__osf__)
304 #include <sys/siginfo.h>
306 extern char *__gnat_get_code_loc (struct sigcontext *);
307 extern void __gnat_set_code_loc (struct sigcontext *, char *);
308 extern size_t __gnat_machine_state_length (void);
310 #define HAVE_GNAT_ADJUST_CONTEXT_FOR_RAISE
313 __gnat_adjust_context_for_raise (int signo, void *ucontext)
315 struct sigcontext *sigcontext = (struct sigcontext *) ucontext;
317 /* The unwinder expects the signal context to contain the address of the
318 faulting instruction. For SIGFPE, this depends on the trap shadow
319 situation (see man ieee). We nonetheless always compensate for it,
320 considering that PC designates the instruction following the one that
321 trapped. This is not necessarily true but corresponds to what we have
328 __gnat_error_handler (int sig, siginfo_t *si, void *ucontext)
330 struct Exception_Data *exception;
331 static int recurse = 0;
334 /* Adjusting is required for every fault context, so adjust for this one
335 now, before we possibly trigger a recursive fault below. */
336 __gnat_adjust_context_for_raise (sig, ucontext);
338 /* If this was an explicit signal from a "kill", just resignal it. */
339 if (SI_FROMUSER (si))
341 signal (sig, SIG_DFL);
342 kill (getpid(), sig);
345 /* Otherwise, treat it as something we handle. */
349 /* If the problem was permissions, this is a constraint error.
350 Likewise if the failing address isn't maximally aligned or if
353 ??? Using a static variable here isn't task-safe, but it's
354 much too hard to do anything else and we're just determining
355 which exception to raise. */
356 if (si->si_code == SEGV_ACCERR
357 || (long) si->si_addr == 0
358 || (((long) si->si_addr) & 3) != 0
361 exception = &constraint_error;
366 /* See if the page before the faulting page is accessible. Do that
367 by trying to access it. We'd like to simply try to access
368 4096 + the faulting address, but it's not guaranteed to be
369 the actual address, just to be on the same page. */
372 ((long) si->si_addr & - getpagesize ()))[getpagesize ()];
373 exception = &storage_error;
374 msg = "stack overflow or erroneous memory access";
379 exception = &program_error;
384 exception = &constraint_error;
389 exception = &program_error;
390 msg = "unhandled signal";
394 Raise_From_Signal_Handler (exception, CONST_CAST (char *, msg));
398 __gnat_install_handler (void)
400 struct sigaction act;
402 /* Setup signal handler to map synchronous signals to appropriate
403 exceptions. Make sure that the handler isn't interrupted by another
404 signal that might cause a scheduling event! */
406 act.sa_handler = (void (*) (int)) __gnat_error_handler;
407 act.sa_flags = SA_RESTART | SA_NODEFER | SA_SIGINFO;
408 sigemptyset (&act.sa_mask);
410 /* Do not install handlers if interrupt state is "System". */
411 if (__gnat_get_interrupt_state (SIGABRT) != 's')
412 sigaction (SIGABRT, &act, NULL);
413 if (__gnat_get_interrupt_state (SIGFPE) != 's')
414 sigaction (SIGFPE, &act, NULL);
415 if (__gnat_get_interrupt_state (SIGILL) != 's')
416 sigaction (SIGILL, &act, NULL);
417 if (__gnat_get_interrupt_state (SIGSEGV) != 's')
418 sigaction (SIGSEGV, &act, NULL);
419 if (__gnat_get_interrupt_state (SIGBUS) != 's')
420 sigaction (SIGBUS, &act, NULL);
422 __gnat_handler_installed = 1;
425 /* Routines called by s-mastop-tru64.adb. */
430 __gnat_get_code_loc (struct sigcontext *context)
432 return (char *) context->sc_pc;
436 __gnat_set_code_loc (struct sigcontext *context, char *pc)
438 context->sc_pc = (long) pc;
442 __gnat_machine_state_length (void)
444 return sizeof (struct sigcontext);
451 #elif defined (__hpux__)
454 #include <sys/ucontext.h>
457 __gnat_error_handler (int sig,
458 siginfo_t *si ATTRIBUTE_UNUSED,
459 void *ucontext ATTRIBUTE_UNUSED)
461 struct Exception_Data *exception;
467 /* FIXME: we need to detect the case of a *real* SIGSEGV. */
468 exception = &storage_error;
469 msg = "stack overflow or erroneous memory access";
473 exception = &constraint_error;
478 exception = &constraint_error;
483 exception = &program_error;
484 msg = "unhandled signal";
487 Raise_From_Signal_Handler (exception, msg);
490 /* This must be in keeping with System.OS_Interface.Alternate_Stack_Size. */
491 #if defined (__hppa__)
492 char __gnat_alternate_stack[16 * 1024]; /* 2 * SIGSTKSZ */
494 char __gnat_alternate_stack[128 * 1024]; /* MINSIGSTKSZ */
498 __gnat_install_handler (void)
500 struct sigaction act;
502 /* Set up signal handler to map synchronous signals to appropriate
503 exceptions. Make sure that the handler isn't interrupted by another
504 signal that might cause a scheduling event! Also setup an alternate
505 stack region for the handler execution so that stack overflows can be
506 handled properly, avoiding a SEGV generation from stack usage by the
510 stack.ss_sp = __gnat_alternate_stack;
511 stack.ss_size = sizeof (__gnat_alternate_stack);
513 sigaltstack (&stack, NULL);
515 act.sa_sigaction = __gnat_error_handler;
516 act.sa_flags = SA_NODEFER | SA_RESTART | SA_SIGINFO;
517 sigemptyset (&act.sa_mask);
519 /* Do not install handlers if interrupt state is "System". */
520 if (__gnat_get_interrupt_state (SIGABRT) != 's')
521 sigaction (SIGABRT, &act, NULL);
522 if (__gnat_get_interrupt_state (SIGFPE) != 's')
523 sigaction (SIGFPE, &act, NULL);
524 if (__gnat_get_interrupt_state (SIGILL) != 's')
525 sigaction (SIGILL, &act, NULL);
526 if (__gnat_get_interrupt_state (SIGBUS) != 's')
527 sigaction (SIGBUS, &act, NULL);
528 act.sa_flags |= SA_ONSTACK;
529 if (__gnat_get_interrupt_state (SIGSEGV) != 's')
530 sigaction (SIGSEGV, &act, NULL);
532 __gnat_handler_installed = 1;
535 /*********************/
536 /* GNU/Linux Section */
537 /*********************/
539 #elif defined (linux)
543 #define __USE_GNU 1 /* required to get REG_EIP/RIP from glibc's ucontext.h */
544 #include <sys/ucontext.h>
546 /* GNU/Linux, which uses glibc, does not define NULL in included
550 #define NULL ((void *) 0)
555 /* MaRTE OS provides its own version of sigaction, sigfillset, and
556 sigemptyset (overriding these symbol names). We want to make sure that
557 the versions provided by the underlying C library are used here (these
558 versions are renamed by MaRTE to linux_sigaction, fake_linux_sigfillset,
559 and fake_linux_sigemptyset, respectively). The MaRTE library will not
560 always be present (it will not be linked if no tasking constructs are
561 used), so we use the weak symbol mechanism to point always to the symbols
562 defined within the C library. */
564 #pragma weak linux_sigaction
565 int linux_sigaction (int signum, const struct sigaction *act,
566 struct sigaction *oldact) {
567 return sigaction (signum, act, oldact);
569 #define sigaction(signum, act, oldact) linux_sigaction (signum, act, oldact)
571 #pragma weak fake_linux_sigfillset
572 void fake_linux_sigfillset (sigset_t *set) {
575 #define sigfillset(set) fake_linux_sigfillset (set)
577 #pragma weak fake_linux_sigemptyset
578 void fake_linux_sigemptyset (sigset_t *set) {
581 #define sigemptyset(set) fake_linux_sigemptyset (set)
585 #if defined (i386) || defined (__x86_64__) || defined (__ia64__)
587 #define HAVE_GNAT_ADJUST_CONTEXT_FOR_RAISE
590 __gnat_adjust_context_for_raise (int signo ATTRIBUTE_UNUSED, void *ucontext)
592 mcontext_t *mcontext = &((ucontext_t *) ucontext)->uc_mcontext;
594 /* On the i386 and x86-64 architectures, stack checking is performed by
595 means of probes with moving stack pointer, that is to say the probed
596 address is always the value of the stack pointer. Upon hitting the
597 guard page, the stack pointer therefore points to an inaccessible
598 address and an alternate signal stack is needed to run the handler.
599 But there is an additional twist: on these architectures, the EH
600 return code writes the address of the handler at the target CFA's
601 value on the stack before doing the jump. As a consequence, if
602 there is an active handler in the frame whose stack has overflowed,
603 the stack pointer must nevertheless point to an accessible address
604 by the time the EH return is executed.
606 We therefore adjust the saved value of the stack pointer by the size
607 of one page + a small dope of 4 words, in order to make sure that it
608 points to an accessible address in case it's used as the target CFA.
609 The stack checking code guarantees that this address is unused by the
610 time this happens. */
613 unsigned long *pc = (unsigned long *)mcontext->gregs[REG_EIP];
614 /* The pattern is "orl $0x0,(%esp)" for a probe in 32-bit mode. */
615 if (signo == SIGSEGV && pc && *pc == 0x00240c83)
616 mcontext->gregs[REG_ESP] += 4096 + 4 * sizeof (unsigned long);
617 #elif defined (__x86_64__)
618 unsigned long *pc = (unsigned long *)mcontext->gregs[REG_RIP];
619 /* The pattern is "orq $0x0,(%rsp)" for a probe in 64-bit mode. */
620 if (signo == SIGSEGV && pc && (*pc & 0xffffffffff) == 0x00240c8348)
621 mcontext->gregs[REG_RSP] += 4096 + 4 * sizeof (unsigned long);
622 #elif defined (__ia64__)
623 /* ??? The IA-64 unwinder doesn't compensate for signals. */
631 __gnat_error_handler (int sig, siginfo_t *si ATTRIBUTE_UNUSED, void *ucontext)
633 struct Exception_Data *exception;
636 /* Adjusting is required for every fault context, so adjust for this one
637 now, before we possibly trigger a recursive fault below. */
638 __gnat_adjust_context_for_raise (sig, ucontext);
643 /* Here we would like a discrimination test to see whether the page
644 before the faulting address is accessible. Unfortunately, Linux
645 seems to have no way of giving us the faulting address.
647 In old versions of init.c, we had a test of the page before the
651 ((long) si->esp_at_signal & - getpagesize ()))[getpagesize ()];
653 but that's wrong since it tests the stack pointer location and the
654 stack probing code may not move it until all probes succeed.
656 For now we simply do not attempt any discrimination at all. Note
657 that this is quite acceptable, since a "real" SIGSEGV can only
658 occur as the result of an erroneous program. */
659 exception = &storage_error;
660 msg = "stack overflow or erroneous memory access";
664 exception = &storage_error;
665 msg = "SIGBUS: possible stack overflow";
669 exception = &constraint_error;
674 exception = &program_error;
675 msg = "unhandled signal";
678 Raise_From_Signal_Handler (exception, msg);
681 #if defined (i386) || defined (__x86_64__) || defined (__powerpc__)
682 /* This must be in keeping with System.OS_Interface.Alternate_Stack_Size. */
683 char __gnat_alternate_stack[16 * 1024]; /* 2 * SIGSTKSZ */
687 #include <sys/mman.h>
688 #include <native/task.h>
694 __gnat_install_handler (void)
696 struct sigaction act;
701 if (__gl_main_priority == -1)
704 prio = __gl_main_priority;
706 /* Avoid memory swapping for this program */
708 mlockall (MCL_CURRENT|MCL_FUTURE);
710 /* Turn the current Linux task into a native Xenomai task */
712 rt_task_shadow(&main_task, "environment_task", prio, T_FPU);
715 /* Set up signal handler to map synchronous signals to appropriate
716 exceptions. Make sure that the handler isn't interrupted by another
717 signal that might cause a scheduling event! Also setup an alternate
718 stack region for the handler execution so that stack overflows can be
719 handled properly, avoiding a SEGV generation from stack usage by the
722 #if defined (i386) || defined (__x86_64__) || defined (__powerpc__)
724 stack.ss_sp = __gnat_alternate_stack;
725 stack.ss_size = sizeof (__gnat_alternate_stack);
727 sigaltstack (&stack, NULL);
730 act.sa_sigaction = __gnat_error_handler;
731 act.sa_flags = SA_NODEFER | SA_RESTART | SA_SIGINFO;
732 sigemptyset (&act.sa_mask);
734 /* Do not install handlers if interrupt state is "System". */
735 if (__gnat_get_interrupt_state (SIGABRT) != 's')
736 sigaction (SIGABRT, &act, NULL);
737 if (__gnat_get_interrupt_state (SIGFPE) != 's')
738 sigaction (SIGFPE, &act, NULL);
739 if (__gnat_get_interrupt_state (SIGILL) != 's')
740 sigaction (SIGILL, &act, NULL);
741 if (__gnat_get_interrupt_state (SIGBUS) != 's')
742 sigaction (SIGBUS, &act, NULL);
743 #if defined (i386) || defined (__x86_64__) || defined (__powerpc__)
744 act.sa_flags |= SA_ONSTACK;
746 if (__gnat_get_interrupt_state (SIGSEGV) != 's')
747 sigaction (SIGSEGV, &act, NULL);
749 __gnat_handler_installed = 1;
765 #define SIGADAABORT 48
766 #define SIGNAL_STACK_SIZE 4096
767 #define SIGNAL_STACK_ALIGNMENT 64
769 #define Check_Abort_Status \
770 system__soft_links__check_abort_status
771 extern int (*Check_Abort_Status) (void);
773 extern struct Exception_Data _abort_signal;
775 /* We are not setting the SA_SIGINFO bit in the sigaction flags when
776 connecting that handler, with the effects described in the sigaction
779 SA_SIGINFO If set and the signal is caught, sig is passed as the
780 first argument to the signal-catching function. If the
781 second argument is not equal to NULL, it points to a
782 siginfo_t structure containing the reason why the
783 signal was generated [see siginfo(5)]; the third
784 argument points to a ucontext_t structure containing
785 the receiving process's context when the signal was
786 delivered [see ucontext(5)]. If cleared and the signal
787 is caught, the first argument is also the signal number
788 but the second argument is the signal code identifying
789 the cause of the signal. The third argument points to a
790 sigcontext_t structure containing the receiving
791 process's context when the signal was delivered. This
792 is the default behavior (see signal(5) for more
793 details). Additionally, when SA_SIGINFO is set for a
794 signal, multiple occurrences of that signal will be
795 queued for delivery in FIFO order (see sigqueue(3) for
796 a more detailed explanation of this concept), if those
797 occurrences of that signal were generated using
801 __gnat_error_handler (int sig, siginfo_t *reason, void *uc ATTRIBUTE_UNUSED)
803 /* This handler is installed with SA_SIGINFO cleared, but there's no
804 prototype for the resulting alternative three-argument form, so we
805 have to hack around this by casting reason to the int actually
807 int code = (int) reason;
808 struct Exception_Data *exception;
816 exception = &program_error;
817 msg = "SIGSEGV: (Invalid virtual address)";
819 else if (code == ENXIO)
821 exception = &program_error;
822 msg = "SIGSEGV: (Read beyond mapped object)";
824 else if (code == ENOSPC)
826 exception = &program_error; /* ??? storage_error ??? */
827 msg = "SIGSEGV: (Autogrow for file failed)";
829 else if (code == EACCES || code == EEXIST)
831 /* ??? We handle stack overflows here, some of which do trigger
832 SIGSEGV + EEXIST on Irix 6.5 although EEXIST is not part of
833 the documented valid codes for SEGV in the signal(5) man
836 /* ??? Re-add smarts to further verify that we launched
837 the stack into a guard page, not an attempt to
838 write to .text or something. */
839 exception = &storage_error;
840 msg = "SIGSEGV: stack overflow or erroneous memory access";
844 /* Just in case the OS guys did it to us again. Sometimes
845 they fail to document all of the valid codes that are
846 passed to signal handlers, just in case someone depends
847 on knowing all the codes. */
848 exception = &program_error;
849 msg = "SIGSEGV: (Undocumented reason)";
854 /* Map all bus errors to Program_Error. */
855 exception = &program_error;
860 /* Map all fpe errors to Constraint_Error. */
861 exception = &constraint_error;
866 if ((*Check_Abort_Status) ())
868 exception = &_abort_signal;
877 /* Everything else is a Program_Error. */
878 exception = &program_error;
879 msg = "unhandled signal";
882 Raise_From_Signal_Handler (exception, msg);
886 __gnat_install_handler (void)
888 struct sigaction act;
890 /* Setup signal handler to map synchronous signals to appropriate
891 exceptions. Make sure that the handler isn't interrupted by another
892 signal that might cause a scheduling event!
894 The handler is installed with SA_SIGINFO cleared, but there's no
895 C++ prototype for the three-argument form, so fake it by using
896 sa_sigaction and casting the arguments instead. */
898 act.sa_sigaction = __gnat_error_handler;
899 act.sa_flags = SA_NODEFER + SA_RESTART;
900 sigfillset (&act.sa_mask);
901 sigemptyset (&act.sa_mask);
903 /* Do not install handlers if interrupt state is "System". */
904 if (__gnat_get_interrupt_state (SIGABRT) != 's')
905 sigaction (SIGABRT, &act, NULL);
906 if (__gnat_get_interrupt_state (SIGFPE) != 's')
907 sigaction (SIGFPE, &act, NULL);
908 if (__gnat_get_interrupt_state (SIGILL) != 's')
909 sigaction (SIGILL, &act, NULL);
910 if (__gnat_get_interrupt_state (SIGSEGV) != 's')
911 sigaction (SIGSEGV, &act, NULL);
912 if (__gnat_get_interrupt_state (SIGBUS) != 's')
913 sigaction (SIGBUS, &act, NULL);
914 if (__gnat_get_interrupt_state (SIGADAABORT) != 's')
915 sigaction (SIGADAABORT, &act, NULL);
917 __gnat_handler_installed = 1;
920 /*******************/
922 /*******************/
924 #elif defined (__Lynx__)
930 __gnat_error_handler (int sig)
932 struct Exception_Data *exception;
938 exception = &constraint_error;
942 exception = &constraint_error;
946 exception = &storage_error;
947 msg = "stack overflow or erroneous memory access";
950 exception = &constraint_error;
954 exception = &program_error;
955 msg = "unhandled signal";
958 Raise_From_Signal_Handler(exception, msg);
962 __gnat_install_handler(void)
964 struct sigaction act;
966 act.sa_handler = __gnat_error_handler;
968 sigemptyset (&act.sa_mask);
970 /* Do not install handlers if interrupt state is "System". */
971 if (__gnat_get_interrupt_state (SIGFPE) != 's')
972 sigaction (SIGFPE, &act, NULL);
973 if (__gnat_get_interrupt_state (SIGILL) != 's')
974 sigaction (SIGILL, &act, NULL);
975 if (__gnat_get_interrupt_state (SIGSEGV) != 's')
976 sigaction (SIGSEGV, &act, NULL);
977 if (__gnat_get_interrupt_state (SIGBUS) != 's')
978 sigaction (SIGBUS, &act, NULL);
980 __gnat_handler_installed = 1;
983 /*******************/
984 /* Solaris Section */
985 /*******************/
987 #elif defined (sun) && defined (__SVR4) && !defined (__vxworks)
991 #include <sys/ucontext.h>
992 #include <sys/regset.h>
994 /* The code below is common to SPARC and x86. Beware of the delay slot
995 differences for signal context adjustments. */
997 #if defined (__sparc)
998 #define RETURN_ADDR_OFFSET 8
1000 #define RETURN_ADDR_OFFSET 0
1004 __gnat_error_handler (int sig, siginfo_t *si, void *ucontext ATTRIBUTE_UNUSED)
1006 struct Exception_Data *exception;
1007 static int recurse = 0;
1013 /* If the problem was permissions, this is a constraint error.
1014 Likewise if the failing address isn't maximally aligned or if
1017 ??? Using a static variable here isn't task-safe, but it's
1018 much too hard to do anything else and we're just determining
1019 which exception to raise. */
1020 if (si->si_code == SEGV_ACCERR
1021 || (long) si->si_addr == 0
1022 || (((long) si->si_addr) & 3) != 0
1025 exception = &constraint_error;
1030 /* See if the page before the faulting page is accessible. Do that
1031 by trying to access it. We'd like to simply try to access
1032 4096 + the faulting address, but it's not guaranteed to be
1033 the actual address, just to be on the same page. */
1036 ((long) si->si_addr & - getpagesize ()))[getpagesize ()];
1037 exception = &storage_error;
1038 msg = "stack overflow or erroneous memory access";
1043 exception = &program_error;
1048 exception = &constraint_error;
1053 exception = &program_error;
1054 msg = "unhandled signal";
1058 Raise_From_Signal_Handler (exception, msg);
1062 __gnat_install_handler (void)
1064 struct sigaction act;
1066 /* Set up signal handler to map synchronous signals to appropriate
1067 exceptions. Make sure that the handler isn't interrupted by another
1068 signal that might cause a scheduling event! */
1070 act.sa_sigaction = __gnat_error_handler;
1071 act.sa_flags = SA_NODEFER | SA_RESTART | SA_SIGINFO;
1072 sigemptyset (&act.sa_mask);
1074 /* Do not install handlers if interrupt state is "System". */
1075 if (__gnat_get_interrupt_state (SIGABRT) != 's')
1076 sigaction (SIGABRT, &act, NULL);
1077 if (__gnat_get_interrupt_state (SIGFPE) != 's')
1078 sigaction (SIGFPE, &act, NULL);
1079 if (__gnat_get_interrupt_state (SIGSEGV) != 's')
1080 sigaction (SIGSEGV, &act, NULL);
1081 if (__gnat_get_interrupt_state (SIGBUS) != 's')
1082 sigaction (SIGBUS, &act, NULL);
1084 __gnat_handler_installed = 1;
1093 /* Routine called from binder to override default feature values. */
1094 void __gnat_set_features (void);
1095 int __gnat_features_set = 0;
1098 #define lib_get_curr_invo_context LIB$I64_GET_CURR_INVO_CONTEXT
1099 #define lib_get_prev_invo_context LIB$I64_GET_PREV_INVO_CONTEXT
1100 #define lib_get_invo_handle LIB$I64_GET_INVO_HANDLE
1102 #define lib_get_curr_invo_context LIB$GET_CURR_INVO_CONTEXT
1103 #define lib_get_prev_invo_context LIB$GET_PREV_INVO_CONTEXT
1104 #define lib_get_invo_handle LIB$GET_INVO_HANDLE
1107 /* Define macro symbols for the VMS conditions that become Ada exceptions.
1108 Most of these are also defined in the header file ssdef.h which has not
1109 yet been converted to be recognized by GNU C. */
1111 /* Defining these as macros, as opposed to external addresses, allows
1112 them to be used in a case statement below. */
1113 #define SS$_ACCVIO 12
1114 #define SS$_HPARITH 1284
1115 #define SS$_STKOVF 1364
1116 #define SS$_RESIGNAL 2328
1118 /* These codes are in standard message libraries. */
1119 extern int C$_SIGKILL;
1120 extern int SS$_DEBUG;
1121 extern int LIB$_KEYNOTFOU;
1122 extern int LIB$_ACTIMAGE;
1123 #define CMA$_EXIT_THREAD 4227492
1124 #define MTH$_FLOOVEMAT 1475268 /* Some ACVC_21 CXA tests */
1125 #define SS$_INTDIV 1156
1127 /* These codes are non standard, which is to say the author is
1128 not sure if they are defined in the standard message libraries
1129 so keep them as macros for now. */
1130 #define RDB$_STREAM_EOF 20480426
1131 #define FDL$_UNPRIKW 11829410
1133 struct cond_except {
1135 const struct Exception_Data *except;
1138 struct descriptor_s {
1139 unsigned short len, mbz;
1143 /* Conditions that don't have an Ada exception counterpart must raise
1144 Non_Ada_Error. Since this is defined in s-auxdec, it should only be
1145 referenced by user programs, not the compiler or tools. Hence the
1150 #define Status_Error ada__io_exceptions__status_error
1151 extern struct Exception_Data Status_Error;
1153 #define Mode_Error ada__io_exceptions__mode_error
1154 extern struct Exception_Data Mode_Error;
1156 #define Name_Error ada__io_exceptions__name_error
1157 extern struct Exception_Data Name_Error;
1159 #define Use_Error ada__io_exceptions__use_error
1160 extern struct Exception_Data Use_Error;
1162 #define Device_Error ada__io_exceptions__device_error
1163 extern struct Exception_Data Device_Error;
1165 #define End_Error ada__io_exceptions__end_error
1166 extern struct Exception_Data End_Error;
1168 #define Data_Error ada__io_exceptions__data_error
1169 extern struct Exception_Data Data_Error;
1171 #define Layout_Error ada__io_exceptions__layout_error
1172 extern struct Exception_Data Layout_Error;
1174 #define Non_Ada_Error system__aux_dec__non_ada_error
1175 extern struct Exception_Data Non_Ada_Error;
1177 #define Coded_Exception system__vms_exception_table__coded_exception
1178 extern struct Exception_Data *Coded_Exception (Exception_Code);
1180 #define Base_Code_In system__vms_exception_table__base_code_in
1181 extern Exception_Code Base_Code_In (Exception_Code);
1183 /* DEC Ada exceptions are not defined in a header file, so they
1184 must be declared. */
1186 #define ADA$_ALREADY_OPEN 0x0031a594
1187 #define ADA$_CONSTRAINT_ERRO 0x00318324
1188 #define ADA$_DATA_ERROR 0x003192c4
1189 #define ADA$_DEVICE_ERROR 0x003195e4
1190 #define ADA$_END_ERROR 0x00319904
1191 #define ADA$_FAC_MODE_MISMAT 0x0031a8b3
1192 #define ADA$_IOSYSFAILED 0x0031af04
1193 #define ADA$_KEYSIZERR 0x0031aa3c
1194 #define ADA$_KEY_MISMATCH 0x0031a8e3
1195 #define ADA$_LAYOUT_ERROR 0x00319c24
1196 #define ADA$_LINEXCMRS 0x0031a8f3
1197 #define ADA$_MAXLINEXC 0x0031a8eb
1198 #define ADA$_MODE_ERROR 0x00319f44
1199 #define ADA$_MRN_MISMATCH 0x0031a8db
1200 #define ADA$_MRS_MISMATCH 0x0031a8d3
1201 #define ADA$_NAME_ERROR 0x0031a264
1202 #define ADA$_NOT_OPEN 0x0031a58c
1203 #define ADA$_ORG_MISMATCH 0x0031a8bb
1204 #define ADA$_PROGRAM_ERROR 0x00318964
1205 #define ADA$_RAT_MISMATCH 0x0031a8cb
1206 #define ADA$_RFM_MISMATCH 0x0031a8c3
1207 #define ADA$_STAOVF 0x00318cac
1208 #define ADA$_STATUS_ERROR 0x0031a584
1209 #define ADA$_STORAGE_ERROR 0x00318c84
1210 #define ADA$_UNSUPPORTED 0x0031a8ab
1211 #define ADA$_USE_ERROR 0x0031a8a4
1213 /* DEC Ada specific conditions. */
1214 static const struct cond_except dec_ada_cond_except_table [] = {
1215 {ADA$_PROGRAM_ERROR, &program_error},
1216 {ADA$_USE_ERROR, &Use_Error},
1217 {ADA$_KEYSIZERR, &program_error},
1218 {ADA$_STAOVF, &storage_error},
1219 {ADA$_CONSTRAINT_ERRO, &constraint_error},
1220 {ADA$_IOSYSFAILED, &Device_Error},
1221 {ADA$_LAYOUT_ERROR, &Layout_Error},
1222 {ADA$_STORAGE_ERROR, &storage_error},
1223 {ADA$_DATA_ERROR, &Data_Error},
1224 {ADA$_DEVICE_ERROR, &Device_Error},
1225 {ADA$_END_ERROR, &End_Error},
1226 {ADA$_MODE_ERROR, &Mode_Error},
1227 {ADA$_NAME_ERROR, &Name_Error},
1228 {ADA$_STATUS_ERROR, &Status_Error},
1229 {ADA$_NOT_OPEN, &Use_Error},
1230 {ADA$_ALREADY_OPEN, &Use_Error},
1231 {ADA$_USE_ERROR, &Use_Error},
1232 {ADA$_UNSUPPORTED, &Use_Error},
1233 {ADA$_FAC_MODE_MISMAT, &Use_Error},
1234 {ADA$_ORG_MISMATCH, &Use_Error},
1235 {ADA$_RFM_MISMATCH, &Use_Error},
1236 {ADA$_RAT_MISMATCH, &Use_Error},
1237 {ADA$_MRS_MISMATCH, &Use_Error},
1238 {ADA$_MRN_MISMATCH, &Use_Error},
1239 {ADA$_KEY_MISMATCH, &Use_Error},
1240 {ADA$_MAXLINEXC, &constraint_error},
1241 {ADA$_LINEXCMRS, &constraint_error},
1246 /* Already handled by a pragma Import_Exception
1247 in Aux_IO_Exceptions */
1248 {ADA$_LOCK_ERROR, &Lock_Error},
1249 {ADA$_EXISTENCE_ERROR, &Existence_Error},
1250 {ADA$_KEY_ERROR, &Key_Error},
1255 /* Non-DEC Ada specific conditions. We could probably also put
1256 SS$_HPARITH here and possibly SS$_ACCVIO, SS$_STKOVF. */
1257 static const struct cond_except cond_except_table [] = {
1258 {MTH$_FLOOVEMAT, &constraint_error},
1259 {SS$_INTDIV, &constraint_error},
1263 /* To deal with VMS conditions and their mapping to Ada exceptions,
1264 the __gnat_error_handler routine below is installed as an exception
1265 vector having precedence over DEC frame handlers. Some conditions
1266 still need to be handled by such handlers, however, in which case
1267 __gnat_error_handler needs to return SS$_RESIGNAL. Consider for
1268 instance the use of a third party library compiled with DECAda and
1269 performing its own exception handling internally.
1271 To allow some user-level flexibility, which conditions should be
1272 resignaled is controlled by a predicate function, provided with the
1273 condition value and returning a boolean indication stating whether
1274 this condition should be resignaled or not.
1276 That predicate function is called indirectly, via a function pointer,
1277 by __gnat_error_handler, and changing that pointer is allowed to the
1278 user code by way of the __gnat_set_resignal_predicate interface.
1280 The user level function may then implement what it likes, including
1281 for instance the maintenance of a dynamic data structure if the set
1282 of to be resignalled conditions has to change over the program's
1285 ??? This is not a perfect solution to deal with the possible
1286 interactions between the GNAT and the DECAda exception handling
1287 models and better (more general) schemes are studied. This is so
1288 just provided as a convenient workaround in the meantime, and
1289 should be use with caution since the implementation has been kept
1293 resignal_predicate (int code);
1295 static const int * const cond_resignal_table [] = {
1297 (int *)CMA$_EXIT_THREAD,
1301 (int *) RDB$_STREAM_EOF,
1302 (int *) FDL$_UNPRIKW,
1306 static const int facility_resignal_table [] = {
1307 0x1380000, /* RDB */
1308 0x2220000, /* SQL */
1312 /* Default GNAT predicate for resignaling conditions. */
1315 __gnat_default_resignal_p (int code)
1319 for (i = 0; facility_resignal_table [i]; i++)
1320 if ((code & 0xfff0000) == facility_resignal_table [i])
1323 for (i = 0, iexcept = 0;
1324 cond_resignal_table [i]
1325 && !(iexcept = LIB$MATCH_COND (&code, &cond_resignal_table [i]));
1331 /* Static pointer to predicate that the __gnat_error_handler exception
1332 vector invokes to determine if it should resignal a condition. */
1334 static resignal_predicate *__gnat_resignal_p = __gnat_default_resignal_p;
1336 /* User interface to change the predicate pointer to PREDICATE. Reset to
1337 the default if PREDICATE is null. */
1340 __gnat_set_resignal_predicate (resignal_predicate *predicate)
1342 if (predicate == NULL)
1343 __gnat_resignal_p = __gnat_default_resignal_p;
1345 __gnat_resignal_p = predicate;
1348 /* Should match System.Parameters.Default_Exception_Msg_Max_Length. */
1349 #define Default_Exception_Msg_Max_Length 512
1351 /* Action routine for SYS$PUTMSG. There may be multiple
1352 conditions, each with text to be appended to MESSAGE
1353 and separated by line termination. */
1356 copy_msg (struct descriptor_s *msgdesc, char *message)
1358 int len = strlen (message);
1361 /* Check for buffer overflow and skip. */
1362 if (len > 0 && len <= Default_Exception_Msg_Max_Length - 3)
1364 strcat (message, "\r\n");
1368 /* Check for buffer overflow and truncate if necessary. */
1369 copy_len = (len + msgdesc->len <= Default_Exception_Msg_Max_Length - 1 ?
1371 Default_Exception_Msg_Max_Length - 1 - len);
1372 strncpy (&message [len], msgdesc->adr, copy_len);
1373 message [len + copy_len] = 0;
1379 __gnat_handle_vms_condition (int *sigargs, void *mechargs)
1381 struct Exception_Data *exception = 0;
1382 Exception_Code base_code;
1383 struct descriptor_s gnat_facility = {4, 0, "GNAT"};
1384 char message [Default_Exception_Msg_Max_Length];
1386 const char *msg = "";
1388 /* Check for conditions to resignal which aren't effected by pragma
1389 Import_Exception. */
1390 if (__gnat_resignal_p (sigargs [1]))
1391 return SS$_RESIGNAL;
1394 /* See if it's an imported exception. Beware that registered exceptions
1395 are bound to their base code, with the severity bits masked off. */
1396 base_code = Base_Code_In ((Exception_Code) sigargs[1]);
1397 exception = Coded_Exception (base_code);
1403 /* Subtract PC & PSL fields which messes with PUTMSG. */
1405 SYS$PUTMSG (sigargs, copy_msg, &gnat_facility, message);
1409 exception->Name_Length = 19;
1410 /* ??? The full name really should be get SYS$GETMSG returns. */
1411 exception->Full_Name = "IMPORTED_EXCEPTION";
1412 exception->Import_Code = base_code;
1415 /* Do not adjust the program counter as already points to the next
1416 instruction (just after the call to LIB$STOP). */
1417 Raise_From_Signal_Handler (exception, msg);
1426 if (sigargs[3] == 0)
1428 exception = &constraint_error;
1429 msg = "access zero";
1433 exception = &storage_error;
1434 msg = "stack overflow or erroneous memory access";
1436 __gnat_adjust_context_for_raise (SS$_ACCVIO, (void *)mechargs);
1440 exception = &storage_error;
1441 msg = "stack overflow";
1442 __gnat_adjust_context_for_raise (SS$_STKOVF, (void *)mechargs);
1447 return SS$_RESIGNAL; /* toplev.c handles for compiler */
1449 exception = &constraint_error;
1450 msg = "arithmetic error";
1451 __gnat_adjust_context_for_raise (SS$_HPARITH, (void *)mechargs);
1460 /* Scan the DEC Ada exception condition table for a match and fetch
1461 the associated GNAT exception pointer. */
1463 dec_ada_cond_except_table [i].cond &&
1464 !LIB$MATCH_COND (&sigargs [1],
1465 &dec_ada_cond_except_table [i].cond);
1467 exception = (struct Exception_Data *)
1468 dec_ada_cond_except_table [i].except;
1472 /* Scan the VMS standard condition table for a match and fetch
1473 the associated GNAT exception pointer. */
1475 cond_except_table[i].cond &&
1476 !LIB$MATCH_COND (&sigargs[1], &cond_except_table[i].cond);
1478 exception = (struct Exception_Data *)
1479 cond_except_table [i].except;
1482 /* User programs expect Non_Ada_Error to be raised, reference
1483 DEC Ada test CXCONDHAN. */
1484 exception = &Non_Ada_Error;
1488 exception = &program_error;
1491 /* Subtract PC & PSL fields which messes with PUTMSG. */
1493 SYS$PUTMSG (sigargs, copy_msg, &gnat_facility, message);
1499 Raise_From_Signal_Handler (exception, msg);
1503 __gnat_install_handler (void)
1505 long prvhnd ATTRIBUTE_UNUSED;
1507 #if !defined (IN_RTS)
1508 SYS$SETEXV (1, __gnat_handle_vms_condition, 3, &prvhnd);
1511 __gnat_handler_installed = 1;
1514 /* __gnat_adjust_context_for_raise for Alpha - see comments along with the
1515 default version later in this file. */
1517 #if defined (IN_RTS) && defined (__alpha__)
1519 #include <vms/chfctxdef.h>
1520 #include <vms/chfdef.h>
1522 #define HAVE_GNAT_ADJUST_CONTEXT_FOR_RAISE
1525 __gnat_adjust_context_for_raise (int signo ATTRIBUTE_UNUSED, void *ucontext)
1527 if (signo == SS$_HPARITH)
1529 /* Sub one to the address of the instruction signaling the condition,
1530 located in the sigargs array. */
1532 CHF$MECH_ARRAY * mechargs = (CHF$MECH_ARRAY *) ucontext;
1533 CHF$SIGNAL_ARRAY * sigargs
1534 = (CHF$SIGNAL_ARRAY *) mechargs->chf$q_mch_sig_addr;
1536 int vcount = sigargs->chf$is_sig_args;
1537 int * pc_slot = & (&sigargs->chf$l_sig_name)[vcount-2];
1545 /* __gnat_adjust_context_for_raise for ia64. */
1547 #if defined (IN_RTS) && defined (__IA64)
1549 #include <vms/chfctxdef.h>
1550 #include <vms/chfdef.h>
1552 #define HAVE_GNAT_ADJUST_CONTEXT_FOR_RAISE
1554 typedef unsigned long long u64;
1557 __gnat_adjust_context_for_raise (int signo ATTRIBUTE_UNUSED, void *ucontext)
1559 /* Add one to the address of the instruction signaling the condition,
1560 located in the 64bits sigargs array. */
1562 CHF$MECH_ARRAY * mechargs = (CHF$MECH_ARRAY *) ucontext;
1564 CHF64$SIGNAL_ARRAY *chfsig64
1565 = (CHF64$SIGNAL_ARRAY *) mechargs->chf$ph_mch_sig64_addr;
1568 = (u64 *)chfsig64 + 1 + chfsig64->chf64$l_sig_args;
1570 u64 * ih_pc_loc = post_sigarray - 2;
1577 /* Easier interface for LIB$GET_LOGICAL: put the equivalence of NAME into BUF,
1578 always NUL terminated. In case of error or if the result is longer than
1579 LEN (length of BUF) an empty string is written info BUF. */
1582 __gnat_vms_get_logical (const char *name, char *buf, int len)
1584 struct descriptor_s name_desc, result_desc;
1586 unsigned short rlen;
1588 /* Build the descriptor for NAME. */
1589 name_desc.len = strlen (name);
1591 name_desc.adr = (char *)name;
1593 /* Build the descriptor for the result. */
1594 result_desc.len = len;
1595 result_desc.mbz = 0;
1596 result_desc.adr = buf;
1598 status = LIB$GET_LOGICAL (&name_desc, &result_desc, &rlen);
1600 if ((status & 1) == 1 && rlen < len)
1606 /* Size of a page on ia64 and alpha VMS. */
1607 #define VMS_PAGESIZE 8192
1610 #define PSL__C_USER 3
1615 /* Descending region. */
1616 #define VA__M_DESCEND 1
1618 /* Get by virtual address. */
1619 #define VA___REGSUM_BY_VA 1
1621 /* Memory region summary. */
1624 unsigned long long q_region_id;
1625 unsigned int l_flags;
1626 unsigned int l_region_protection;
1628 unsigned long long q_region_size;
1629 void *pq_first_free_va;
1632 extern int SYS$GET_REGION_INFO (unsigned int, unsigned long long *,
1633 void *, void *, unsigned int,
1634 void *, unsigned int *);
1635 extern int SYS$EXPREG_64 (unsigned long long *, unsigned long long,
1636 unsigned int, unsigned int, void **,
1637 unsigned long long *);
1638 extern int SYS$SETPRT_64 (void *, unsigned long long, unsigned int,
1639 unsigned int, void **, unsigned long long *,
1641 extern int SYS$PUTMSG (void *, int (*)(), void *, unsigned long long);
1643 /* Add a guard page in the memory region containing ADDR at ADDR +/- SIZE.
1644 (The sign depends on the kind of the memory region). */
1647 __gnat_set_stack_guard_page (void *addr, unsigned long size)
1651 unsigned long long ret_len;
1652 unsigned int ret_prot;
1654 unsigned long long length;
1655 unsigned int retlen;
1656 struct regsum buffer;
1658 /* Get the region for ADDR. */
1659 status = SYS$GET_REGION_INFO
1660 (VA___REGSUM_BY_VA, NULL, addr, NULL, sizeof (buffer), &buffer, &retlen);
1662 if ((status & 1) != 1)
1665 /* Extend the region. */
1666 status = SYS$EXPREG_64 (&buffer.q_region_id,
1667 size, 0, 0, &start_va, &length);
1669 if ((status & 1) != 1)
1672 /* Create a guard page. */
1673 if (!(buffer.l_flags & VA__M_DESCEND))
1674 start_va = (void *)((unsigned long long)start_va + length - VMS_PAGESIZE);
1676 status = SYS$SETPRT_64 (start_va, VMS_PAGESIZE, PSL__C_USER, PRT__C_NA,
1677 &ret_va, &ret_len, &ret_prot);
1679 if ((status & 1) != 1)
1684 /* Read logicals to limit the stack(s) size. */
1687 __gnat_set_stack_limit (void)
1695 /* The main stack. */
1696 __gnat_vms_get_logical ("GNAT_STACK_SIZE", value, sizeof (value));
1697 size = strtoul (value, &e, 0);
1698 if (e > value && *e == 0)
1700 asm ("mov %0=sp" : "=r" (sp));
1701 __gnat_set_stack_guard_page (sp, size * 1024);
1704 /* The register stack. */
1705 __gnat_vms_get_logical ("GNAT_RBS_SIZE", value, sizeof (value));
1706 size = strtoul (value, &e, 0);
1707 if (e > value && *e == 0)
1709 asm ("mov %0=ar.bsp" : "=r" (sp));
1710 __gnat_set_stack_guard_page (sp, size * 1024);
1715 /* Feature logical name and global variable address pair.
1716 If we ever add another feature logical to this list, the
1717 feature struct will need to be enhanced to take into account
1718 possible values for *gl_addr. */
1724 /* Default values for GNAT features set by environment. */
1725 int __gl_heap_size = 64;
1727 /* Array feature logical names and global variable addresses. */
1728 static const struct feature features[] = {
1729 {"GNAT$NO_MALLOC_64", &__gl_heap_size},
1734 __gnat_set_features (void)
1739 /* Loop through features array and test name for enable/disable. */
1740 for (i = 0; features[i].name; i++)
1742 __gnat_vms_get_logical (features[i].name, buff, sizeof (buff));
1744 if (strcmp (buff, "ENABLE") == 0
1745 || strcmp (buff, "TRUE") == 0
1746 || strcmp (buff, "1") == 0)
1747 *features[i].gl_addr = 32;
1748 else if (strcmp (buff, "DISABLE") == 0
1749 || strcmp (buff, "FALSE") == 0
1750 || strcmp (buff, "0") == 0)
1751 *features[i].gl_addr = 64;
1754 /* Features to artificially limit the stack size. */
1755 __gnat_set_stack_limit ();
1757 __gnat_features_set = 1;
1760 /* Return true if the VMS version is 7.x. */
1762 extern unsigned int LIB$GETSYI (int *, ...);
1764 #define SYI$_VERSION 0x1000
1767 __gnat_is_vms_v7 (void)
1769 struct descriptor_s desc;
1772 int code = SYI$_VERSION;
1774 desc.len = sizeof (version);
1778 status = LIB$GETSYI (&code, 0, &desc);
1779 if ((status & 1) == 1 && version[1] == '7' && version[2] == '.')
1785 /*******************/
1786 /* FreeBSD Section */
1787 /*******************/
1789 #elif defined (__FreeBSD__)
1792 #include <sys/ucontext.h>
1796 __gnat_error_handler (int sig,
1797 siginfo_t *si ATTRIBUTE_UNUSED,
1798 void *ucontext ATTRIBUTE_UNUSED)
1800 struct Exception_Data *exception;
1806 exception = &constraint_error;
1811 exception = &constraint_error;
1816 exception = &storage_error;
1817 msg = "stack overflow or erroneous memory access";
1821 exception = &storage_error;
1822 msg = "SIGBUS: possible stack overflow";
1826 exception = &program_error;
1827 msg = "unhandled signal";
1830 Raise_From_Signal_Handler (exception, msg);
1834 __gnat_install_handler ()
1836 struct sigaction act;
1838 /* Set up signal handler to map synchronous signals to appropriate
1839 exceptions. Make sure that the handler isn't interrupted by another
1840 signal that might cause a scheduling event! */
1843 = (void (*)(int, struct __siginfo *, void*)) __gnat_error_handler;
1844 act.sa_flags = SA_NODEFER | SA_RESTART | SA_SIGINFO;
1845 (void) sigemptyset (&act.sa_mask);
1847 (void) sigaction (SIGILL, &act, NULL);
1848 (void) sigaction (SIGFPE, &act, NULL);
1849 (void) sigaction (SIGSEGV, &act, NULL);
1850 (void) sigaction (SIGBUS, &act, NULL);
1852 __gnat_handler_installed = 1;
1855 /*******************/
1856 /* VxWorks Section */
1857 /*******************/
1859 #elif defined(__vxworks)
1862 #include <taskLib.h>
1870 #include "private/vThreadsP.h"
1873 void __gnat_error_handler (int, void *, struct sigcontext *);
1877 /* Directly vectored Interrupt routines are not supported when using RTPs. */
1879 extern int __gnat_inum_to_ivec (int);
1881 /* This is needed by the GNAT run time to handle Vxworks interrupts. */
1883 __gnat_inum_to_ivec (int num)
1885 return INUM_TO_IVEC (num);
1889 #if !defined(__alpha_vxworks) && (_WRS_VXWORKS_MAJOR != 6) && !defined(__RTP__)
1891 /* getpid is used by s-parint.adb, but is not defined by VxWorks, except
1892 on Alpha VxWorks and VxWorks 6.x (including RTPs). */
1894 extern long getpid (void);
1899 return taskIdSelf ();
1903 /* VxWorks 653 vThreads expects the field excCnt to be zeroed when a signal is.
1904 handled. The VxWorks version of longjmp does this; GCC's builtin_longjmp
1907 __gnat_clear_exception_count (void)
1910 WIND_TCB *currentTask = (WIND_TCB *) taskIdSelf();
1912 currentTask->vThreads.excCnt = 0;
1916 /* Handle different SIGnal to exception mappings in different VxWorks
1919 __gnat_map_signal (int sig, void *si ATTRIBUTE_UNUSED,
1920 struct sigcontext *sc ATTRIBUTE_UNUSED)
1922 struct Exception_Data *exception;
1928 exception = &constraint_error;
1932 #ifdef __VXWORKSMILS__
1934 exception = &storage_error;
1935 msg = "SIGILL: possible stack overflow";
1938 exception = &storage_error;
1942 exception = &program_error;
1947 exception = &constraint_error;
1948 msg = "Floating point exception or SIGILL";
1951 exception = &storage_error;
1955 exception = &storage_error;
1956 msg = "SIGBUS: possible stack overflow";
1959 #elif (_WRS_VXWORKS_MAJOR == 6)
1961 exception = &constraint_error;
1965 /* In RTP mode a SIGSEGV is most likely due to a stack overflow,
1966 since stack checking uses the probing mechanism. */
1968 exception = &storage_error;
1969 msg = "SIGSEGV: possible stack overflow";
1972 exception = &program_error;
1976 /* VxWorks 6 kernel mode with probing. SIGBUS for guard page hit */
1978 exception = &storage_error;
1982 exception = &storage_error;
1983 msg = "SIGBUS: possible stack overflow";
1987 /* VxWorks 5: a SIGILL is most likely due to a stack overflow,
1988 since stack checking uses the stack limit mechanism. */
1990 exception = &storage_error;
1991 msg = "SIGILL: possible stack overflow";
1994 exception = &storage_error;
1998 exception = &program_error;
2003 exception = &program_error;
2004 msg = "unhandled signal";
2007 __gnat_clear_exception_count ();
2008 Raise_From_Signal_Handler (exception, msg);
2011 /* Tasking and Non-tasking signal handler. Map SIGnal to Ada exception
2012 propagation after the required low level adjustments. */
2015 __gnat_error_handler (int sig, void *si, struct sigcontext *sc)
2019 /* VxWorks will always mask out the signal during the signal handler and
2020 will reenable it on a longjmp. GNAT does not generate a longjmp to
2021 return from a signal handler so the signal will still be masked unless
2023 sigprocmask (SIG_SETMASK, NULL, &mask);
2024 sigdelset (&mask, sig);
2025 sigprocmask (SIG_SETMASK, &mask, NULL);
2027 #if defined (__PPC__) && defined(_WRS_KERNEL)
2028 /* On PowerPC, kernel mode, we process signals through a Call Frame Info
2029 trampoline, voiding the need for myriads of fallback_frame_state
2030 variants in the ZCX runtime. We have no simple way to distinguish ZCX
2031 from SJLJ here, so we do this for SJLJ as well even though this is not
2032 necessary. This only incurs a few extra instructions and a tiny
2033 amount of extra stack usage. */
2035 #include "sigtramp.h"
2037 __gnat_sigtramp (sig, (void *)si, (void *)sc,
2038 (sighandler_t *)&__gnat_map_signal);
2041 __gnat_map_signal (sig, si, sc);
2046 __gnat_install_handler (void)
2048 struct sigaction act;
2050 /* Setup signal handler to map synchronous signals to appropriate
2051 exceptions. Make sure that the handler isn't interrupted by another
2052 signal that might cause a scheduling event! */
2054 act.sa_handler = __gnat_error_handler;
2055 act.sa_flags = SA_SIGINFO | SA_ONSTACK;
2056 sigemptyset (&act.sa_mask);
2058 /* For VxWorks, install all signal handlers, since pragma Interrupt_State
2059 applies to vectored hardware interrupts, not signals. */
2060 sigaction (SIGFPE, &act, NULL);
2061 sigaction (SIGILL, &act, NULL);
2062 sigaction (SIGSEGV, &act, NULL);
2063 sigaction (SIGBUS, &act, NULL);
2065 __gnat_handler_installed = 1;
2068 #define HAVE_GNAT_INIT_FLOAT
2071 __gnat_init_float (void)
2073 /* Disable overflow/underflow exceptions on the PPC processor, needed
2074 to get correct Ada semantics. Note that for AE653 vThreads, the HW
2075 overflow settings are an OS configuration issue. The instructions
2076 below have no effect. */
2077 #if defined (_ARCH_PPC) && !defined (_SOFT_FLOAT) && (!defined (VTHREADS) || defined (__VXWORKSMILS__))
2078 #if defined (__SPE__)
2080 const unsigned long spefscr_mask = 0xfffffff3;
2081 unsigned long spefscr;
2082 asm ("mfspr %0, 512" : "=r" (spefscr));
2083 spefscr = spefscr & spefscr_mask;
2084 asm ("mtspr 512, %0\n\tisync" : : "r" (spefscr));
2092 #if (defined (__i386__) || defined (i386)) && !defined (VTHREADS)
2093 /* This is used to properly initialize the FPU on an x86 for each
2098 /* Similarly for SPARC64. Achieved by masking bits in the Trap Enable Mask
2099 field of the Floating-point Status Register (see the SPARC Architecture
2100 Manual Version 9, p 48). */
2101 #if defined (sparc64)
2103 #define FSR_TEM_NVM (1 << 27) /* Invalid operand */
2104 #define FSR_TEM_OFM (1 << 26) /* Overflow */
2105 #define FSR_TEM_UFM (1 << 25) /* Underflow */
2106 #define FSR_TEM_DZM (1 << 24) /* Division by Zero */
2107 #define FSR_TEM_NXM (1 << 23) /* Inexact result */
2111 __asm__("st %%fsr, %0" : "=m" (fsr));
2112 fsr &= ~(FSR_TEM_OFM | FSR_TEM_UFM);
2113 __asm__("ld %0, %%fsr" : : "m" (fsr));
2118 /* This subprogram is called by System.Task_Primitives.Operations.Enter_Task
2119 (if not null) when a new task is created. It is initialized by
2120 System.Stack_Checking.Operations.Initialize_Stack_Limit.
2121 The use of a hook avoids to drag stack checking subprograms if stack
2122 checking is not used. */
2123 void (*__gnat_set_stack_limit_hook)(void) = (void (*)(void))0;
2125 /******************/
2126 /* NetBSD Section */
2127 /******************/
2129 #elif defined(__NetBSD__)
2135 __gnat_error_handler (int sig)
2137 struct Exception_Data *exception;
2143 exception = &constraint_error;
2147 exception = &constraint_error;
2151 exception = &storage_error;
2152 msg = "stack overflow or erroneous memory access";
2155 exception = &constraint_error;
2159 exception = &program_error;
2160 msg = "unhandled signal";
2163 Raise_From_Signal_Handler(exception, msg);
2167 __gnat_install_handler(void)
2169 struct sigaction act;
2171 act.sa_handler = __gnat_error_handler;
2172 act.sa_flags = SA_NODEFER | SA_RESTART;
2173 sigemptyset (&act.sa_mask);
2175 /* Do not install handlers if interrupt state is "System". */
2176 if (__gnat_get_interrupt_state (SIGFPE) != 's')
2177 sigaction (SIGFPE, &act, NULL);
2178 if (__gnat_get_interrupt_state (SIGILL) != 's')
2179 sigaction (SIGILL, &act, NULL);
2180 if (__gnat_get_interrupt_state (SIGSEGV) != 's')
2181 sigaction (SIGSEGV, &act, NULL);
2182 if (__gnat_get_interrupt_state (SIGBUS) != 's')
2183 sigaction (SIGBUS, &act, NULL);
2185 __gnat_handler_installed = 1;
2188 /*******************/
2189 /* OpenBSD Section */
2190 /*******************/
2192 #elif defined(__OpenBSD__)
2198 __gnat_error_handler (int sig)
2200 struct Exception_Data *exception;
2206 exception = &constraint_error;
2210 exception = &constraint_error;
2214 exception = &storage_error;
2215 msg = "stack overflow or erroneous memory access";
2218 exception = &constraint_error;
2222 exception = &program_error;
2223 msg = "unhandled signal";
2226 Raise_From_Signal_Handler(exception, msg);
2230 __gnat_install_handler(void)
2232 struct sigaction act;
2234 act.sa_handler = __gnat_error_handler;
2235 act.sa_flags = SA_NODEFER | SA_RESTART;
2236 sigemptyset (&act.sa_mask);
2238 /* Do not install handlers if interrupt state is "System" */
2239 if (__gnat_get_interrupt_state (SIGFPE) != 's')
2240 sigaction (SIGFPE, &act, NULL);
2241 if (__gnat_get_interrupt_state (SIGILL) != 's')
2242 sigaction (SIGILL, &act, NULL);
2243 if (__gnat_get_interrupt_state (SIGSEGV) != 's')
2244 sigaction (SIGSEGV, &act, NULL);
2245 if (__gnat_get_interrupt_state (SIGBUS) != 's')
2246 sigaction (SIGBUS, &act, NULL);
2248 __gnat_handler_installed = 1;
2251 /******************/
2252 /* Darwin Section */
2253 /******************/
2255 #elif defined(__APPLE__)
2258 #include <sys/syscall.h>
2259 #include <mach/mach_vm.h>
2260 #include <mach/mach_init.h>
2261 #include <mach/vm_statistics.h>
2263 /* This must be in keeping with System.OS_Interface.Alternate_Stack_Size. */
2264 char __gnat_alternate_stack[32 * 1024]; /* 1 * MINSIGSTKSZ */
2266 /* Defined in xnu unix_signal.c.
2267 Tell the kernel to re-use alt stack when delivering a signal. */
2268 #define UC_RESET_ALT_STACK 0x80000000
2270 /* Return true if ADDR is within a stack guard area. */
2272 __gnat_is_stack_guard (mach_vm_address_t addr)
2275 vm_region_submap_info_data_64_t info;
2276 mach_vm_address_t start;
2277 mach_vm_size_t size;
2279 mach_msg_type_number_t count;
2281 count = VM_REGION_SUBMAP_INFO_COUNT_64;
2285 kret = mach_vm_region_recurse (mach_task_self (), &start, &size, &depth,
2286 (vm_region_recurse_info_t) &info, &count);
2287 if (kret == KERN_SUCCESS
2288 && addr >= start && addr < (start + size)
2289 && info.protection == VM_PROT_NONE
2290 && info.user_tag == VM_MEMORY_STACK)
2295 #define HAVE_GNAT_ADJUST_CONTEXT_FOR_RAISE
2298 __gnat_adjust_context_for_raise (int signo ATTRIBUTE_UNUSED,
2299 void *ucontext ATTRIBUTE_UNUSED)
2301 #if defined (__x86_64__)
2302 /* Work around radar #10302855/pr50678, where the unwinders (libunwind or
2303 libgcc_s depending on the system revision) and the DWARF unwind data for
2304 the sigtramp have different ideas about register numbering (causing rbx
2305 and rdx to be transposed).. */
2306 ucontext_t *uc = (ucontext_t *)ucontext ;
2307 unsigned long t = uc->uc_mcontext->__ss.__rbx;
2309 uc->uc_mcontext->__ss.__rbx = uc->uc_mcontext->__ss.__rdx;
2310 uc->uc_mcontext->__ss.__rdx = t;
2315 __gnat_error_handler (int sig, siginfo_t *si, void *ucontext)
2317 struct Exception_Data *exception;
2320 __gnat_adjust_context_for_raise (sig, ucontext);
2326 if (__gnat_is_stack_guard ((unsigned long)si->si_addr))
2328 exception = &storage_error;
2329 msg = "stack overflow";
2333 exception = &constraint_error;
2334 msg = "erroneous memory access";
2336 /* Reset the use of alt stack, so that the alt stack will be used
2337 for the next signal delivery.
2338 The stack can't be used in case of stack checking. */
2339 syscall (SYS_sigreturn, NULL, UC_RESET_ALT_STACK);
2343 exception = &constraint_error;
2348 exception = &program_error;
2349 msg = "unhandled signal";
2352 Raise_From_Signal_Handler (exception, msg);
2356 __gnat_install_handler (void)
2358 struct sigaction act;
2360 /* Set up signal handler to map synchronous signals to appropriate
2361 exceptions. Make sure that the handler isn't interrupted by another
2362 signal that might cause a scheduling event! Also setup an alternate
2363 stack region for the handler execution so that stack overflows can be
2364 handled properly, avoiding a SEGV generation from stack usage by the
2365 handler itself (and it is required by Darwin). */
2368 stack.ss_sp = __gnat_alternate_stack;
2369 stack.ss_size = sizeof (__gnat_alternate_stack);
2371 sigaltstack (&stack, NULL);
2373 act.sa_flags = SA_NODEFER | SA_RESTART | SA_SIGINFO;
2374 act.sa_sigaction = __gnat_error_handler;
2375 sigemptyset (&act.sa_mask);
2377 /* Do not install handlers if interrupt state is "System". */
2378 if (__gnat_get_interrupt_state (SIGABRT) != 's')
2379 sigaction (SIGABRT, &act, NULL);
2380 if (__gnat_get_interrupt_state (SIGFPE) != 's')
2381 sigaction (SIGFPE, &act, NULL);
2382 if (__gnat_get_interrupt_state (SIGILL) != 's')
2383 sigaction (SIGILL, &act, NULL);
2385 act.sa_flags |= SA_ONSTACK;
2386 if (__gnat_get_interrupt_state (SIGSEGV) != 's')
2387 sigaction (SIGSEGV, &act, NULL);
2388 if (__gnat_get_interrupt_state (SIGBUS) != 's')
2389 sigaction (SIGBUS, &act, NULL);
2391 __gnat_handler_installed = 1;
2396 /* For all other versions of GNAT, the handler does nothing. */
2398 /*******************/
2399 /* Default Section */
2400 /*******************/
2403 __gnat_install_handler (void)
2405 __gnat_handler_installed = 1;
2410 /*********************/
2411 /* __gnat_init_float */
2412 /*********************/
2414 /* This routine is called as each process thread is created, for possible
2415 initialization of the FP processor. This version is used under INTERIX
2418 #if defined (_WIN32) || defined (__INTERIX) \
2419 || defined (__Lynx__) || defined(__NetBSD__) || defined(__FreeBSD__) \
2420 || defined (__OpenBSD__)
2422 #define HAVE_GNAT_INIT_FLOAT
2425 __gnat_init_float (void)
2427 #if defined (__i386__) || defined (i386) || defined (__x86_64)
2429 /* This is used to properly initialize the FPU on an x86 for each
2434 #endif /* Defined __i386__ */
2438 #ifndef HAVE_GNAT_INIT_FLOAT
2440 /* All targets without a specific __gnat_init_float will use an empty one. */
2442 __gnat_init_float (void)
2447 /***********************************/
2448 /* __gnat_adjust_context_for_raise */
2449 /***********************************/
2451 #ifndef HAVE_GNAT_ADJUST_CONTEXT_FOR_RAISE
2453 /* All targets without a specific version will use an empty one. */
2455 /* Given UCONTEXT a pointer to a context structure received by a signal
2456 handler for SIGNO, perform the necessary adjustments to let the handler
2457 raise an exception. Calls to this routine are not conditioned by the
2458 propagation scheme in use. */
2461 __gnat_adjust_context_for_raise (int signo ATTRIBUTE_UNUSED,
2462 void *ucontext ATTRIBUTE_UNUSED)
2464 /* We used to compensate here for the raised from call vs raised from signal
2465 exception discrepancy with the GCC ZCX scheme, but this now can be dealt
2466 with generically in the unwinder (see GCC PR other/26208). This however
2467 requires the use of the _Unwind_GetIPInfo routine in raise-gcc.c, which
2468 is predicated on the definition of HAVE_GETIPINFO at compile time. Only
2469 the VMS ports still do the compensation described in the few lines below.
2471 *** Call vs signal exception discrepancy with GCC ZCX scheme ***
2473 The GCC unwinder expects to be dealing with call return addresses, since
2474 this is the "nominal" case of what we retrieve while unwinding a regular
2477 To evaluate if a handler applies at some point identified by a return
2478 address, the propagation engine needs to determine what region the
2479 corresponding call instruction pertains to. Because the return address
2480 may not be attached to the same region as the call, the unwinder always
2481 subtracts "some" amount from a return address to search the region
2482 tables, amount chosen to ensure that the resulting address is inside the
2485 When we raise an exception from a signal handler, e.g. to transform a
2486 SIGSEGV into Storage_Error, things need to appear as if the signal
2487 handler had been "called" by the instruction which triggered the signal,
2488 so that exception handlers that apply there are considered. What the
2489 unwinder will retrieve as the return address from the signal handler is
2490 what it will find as the faulting instruction address in the signal
2491 context pushed by the kernel. Leaving this address untouched looses, if
2492 the triggering instruction happens to be the very first of a region, as
2493 the later adjustments performed by the unwinder would yield an address
2494 outside that region. We need to compensate for the unwinder adjustments
2495 at some point, and this is what this routine is expected to do.
2497 signo is passed because on some targets for some signals the PC in
2498 context points to the instruction after the faulting one, in which case
2499 the unwinder adjustment is still desired. */