unistd: guarantee STDIN_FILENO here, for OS/2 EMX
[gnulib.git] / lib / c-stack.c
1 /* Stack overflow handling.
2
3    Copyright (C) 2002, 2004, 2006, 2008, 2009 Free Software
4    Foundation, Inc.
5
6    This program is free software: you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
18
19 /* Written by Paul Eggert.  */
20
21 /* NOTES:
22
23    A program that uses alloca, dynamic arrays, or large local
24    variables may extend the stack by more than a page at a time.  If
25    so, when the stack overflows the operating system may not detect
26    the overflow until the program uses the array, and this module may
27    incorrectly report a program error instead of a stack overflow.
28
29    To avoid this problem, allocate only small objects on the stack; a
30    program should be OK if it limits single allocations to a page or
31    less.  Allocate larger arrays in static storage, or on the heap
32    (e.g., with malloc).  Yes, this is a pain, but we don't know of any
33    better solution that is portable.
34
35    No attempt has been made to deal with multithreaded applications.  */
36
37 #include <config.h>
38
39 #ifndef __attribute__
40 # if __GNUC__ < 3
41 #  define __attribute__(x)
42 # endif
43 #endif
44
45 #include "gettext.h"
46 #define _(msgid) gettext (msgid)
47
48 #include <errno.h>
49 #ifndef ENOTSUP
50 # define ENOTSUP EINVAL
51 #endif
52
53 #include <signal.h>
54 #if ! HAVE_STACK_T && ! defined stack_t
55 typedef struct sigaltstack stack_t;
56 #endif
57 #ifndef SIGSTKSZ
58 # define SIGSTKSZ 16384
59 #endif
60
61 #include <stdlib.h>
62 #include <string.h>
63
64 /* Posix 2001 declares ucontext_t in <ucontext.h>, Posix 200x in
65    <signal.h>.  */
66 #if HAVE_UCONTEXT_H
67 # include <ucontext.h>
68 #endif
69
70 #include <unistd.h>
71
72 #if HAVE_LIBSIGSEGV
73 # include <sigsegv.h>
74 #endif
75
76 #include "c-stack.h"
77 #include "exitfail.h"
78
79 #if defined SA_ONSTACK && defined SA_SIGINFO
80 # define SIGACTION_WORKS 1
81 #else
82 # define SIGACTION_WORKS 0
83 # ifndef SA_ONSTACK
84 #  define SA_ONSTACK 0
85 # endif
86 #endif
87
88 extern char *program_name;
89
90 /* The user-specified action to take when a SEGV-related program error
91    or stack overflow occurs.  */
92 static void (* volatile segv_action) (int);
93
94 /* Translated messages for program errors and stack overflow.  Do not
95    translate them in the signal handler, since gettext is not
96    async-signal-safe.  */
97 static char const * volatile program_error_message;
98 static char const * volatile stack_overflow_message;
99
100 /* Output an error message, then exit with status EXIT_FAILURE if it
101    appears to have been a stack overflow, or with a core dump
102    otherwise.  This function is async-signal-safe.  */
103
104 static void die (int) __attribute__ ((noreturn));
105 static void
106 die (int signo)
107 {
108   char const *message;
109   segv_action (signo);
110   message = signo ? program_error_message : stack_overflow_message;
111   write (STDERR_FILENO, program_name, strlen (program_name));
112   write (STDERR_FILENO, ": ", 2);
113   write (STDERR_FILENO, message, strlen (message));
114   write (STDERR_FILENO, "\n", 1);
115   if (! signo)
116     _exit (exit_failure);
117   raise (signo);
118   abort ();
119 }
120
121 #if (HAVE_SIGALTSTACK && HAVE_DECL_SIGALTSTACK \
122      && HAVE_STACK_OVERFLOW_HANDLING) || HAVE_LIBSIGSEGV
123
124 /* Storage for the alternate signal stack.  */
125 static union
126 {
127   char buffer[SIGSTKSZ];
128
129   /* These other members are for proper alignment.  There's no
130      standard way to guarantee stack alignment, but this seems enough
131      in practice.  */
132   long double ld;
133   long l;
134   void *p;
135 } alternate_signal_stack;
136
137 static void
138 null_action (int signo __attribute__ ((unused)))
139 {
140 }
141
142 #endif /* SIGALTSTACK || LIBSIGSEGV */
143
144 /* Only use libsigsegv if we need it; platforms like Solaris can
145    detect stack overflow without the overhead of an external
146    library.  */
147 #if HAVE_LIBSIGSEGV && ! HAVE_XSI_STACK_OVERFLOW_HEURISTIC
148
149 /* Nonzero if general segv handler could not be installed.  */
150 static volatile int segv_handler_missing;
151
152 /* Handle a segmentation violation and exit if it cannot be stack
153    overflow.  This function is async-signal-safe.  */
154
155 static int segv_handler (void *address __attribute__ ((unused)),
156                          int serious)
157 {
158 # if DEBUG
159   {
160     char buf[1024];
161     sprintf (buf, "segv_handler serious=%d\n", serious);
162     write (STDERR_FILENO, buf, strlen (buf));
163   }
164 # endif
165
166   /* If this fault is not serious, return 0 to let the stack overflow
167      handler take a shot at it.  */
168   if (!serious)
169     return 0;
170   die (SIGSEGV);
171 }
172
173 /* Handle a segmentation violation that is likely to be a stack
174    overflow and exit.  This function is async-signal-safe.  */
175
176 static void overflow_handler (int, stackoverflow_context_t)
177   __attribute__ ((noreturn));
178 static void
179 overflow_handler (int emergency,
180                   stackoverflow_context_t context __attribute__ ((unused)))
181 {
182 # if DEBUG
183   {
184     char buf[1024];
185     sprintf (buf, "overflow_handler emergency=%d segv_handler_missing=%d\n",
186              emergency, segv_handler_missing);
187     write (STDERR_FILENO, buf, strlen (buf));
188   }
189 # endif
190
191   die ((!emergency || segv_handler_missing) ? 0 : SIGSEGV);
192 }
193
194 int
195 c_stack_action (void (*action) (int))
196 {
197   segv_action = action ? action : null_action;
198   program_error_message = _("program error");
199   stack_overflow_message = _("stack overflow");
200
201   /* Always install the overflow handler.  */
202   if (stackoverflow_install_handler (overflow_handler,
203                                      alternate_signal_stack.buffer,
204                                      sizeof alternate_signal_stack.buffer))
205     {
206       errno = ENOTSUP;
207       return -1;
208     }
209   /* Try installing a general handler; if it fails, then treat all
210      segv as stack overflow.  */
211   segv_handler_missing = sigsegv_install_handler (segv_handler);
212   return 0;
213 }
214
215 #elif HAVE_SIGALTSTACK && HAVE_DECL_SIGALTSTACK && HAVE_STACK_OVERFLOW_HANDLING
216
217 /* Direction of the C runtime stack.  This function is
218    async-signal-safe.  */
219
220 # if STACK_DIRECTION
221 #  define find_stack_direction(ptr) STACK_DIRECTION
222 # else
223 static int
224 find_stack_direction (char const *addr)
225 {
226   char dummy;
227   return ! addr ? find_stack_direction (&dummy) : addr < &dummy ? 1 : -1;
228 }
229 # endif
230
231 # if SIGACTION_WORKS
232
233 /* Handle a segmentation violation and exit.  This function is
234    async-signal-safe.  */
235
236 static void segv_handler (int, siginfo_t *, void *) __attribute__((noreturn));
237 static void
238 segv_handler (int signo, siginfo_t *info,
239               void *context __attribute__ ((unused)))
240 {
241   /* Clear SIGNO if it seems to have been a stack overflow.  */
242   if (0 < info->si_code)
243     {
244 #  if ! HAVE_XSI_STACK_OVERFLOW_HEURISTIC
245       /* We can't easily determine whether it is a stack overflow; so
246          assume that the rest of our program is perfect (!) and that
247          this segmentation violation is a stack overflow.
248
249          Note that although both Linux and Solaris provide
250          sigaltstack, SA_ONSTACK, and SA_SIGINFO, currently only
251          Solaris satisfies the XSI heueristic.  This is because
252          Solaris populates uc_stack with the details of the
253          interrupted stack, while Linux populates it with the details
254          of the current stack.  */
255       signo = 0;
256 #  else
257       /* If the faulting address is within the stack, or within one
258          page of the stack end, assume that it is a stack
259          overflow.  */
260       ucontext_t const *user_context = context;
261       char const *stack_base = user_context->uc_stack.ss_sp;
262       size_t stack_size = user_context->uc_stack.ss_size;
263       char const *faulting_address = info->si_addr;
264       size_t s = faulting_address - stack_base;
265       size_t page_size = sysconf (_SC_PAGESIZE);
266       if (find_stack_direction (NULL) < 0)
267         s += page_size;
268       if (s < stack_size + page_size)
269         signo = 0;
270
271 #   if DEBUG
272       {
273         char buf[1024];
274         sprintf (buf,
275                  "segv_handler fault=%p base=%p size=%lx page=%lx signo=%d\n",
276                  faulting_address, stack_base, (unsigned long) stack_size,
277                  (unsigned long) page_size, signo);
278         write (STDERR_FILENO, buf, strlen (buf));
279       }
280 #   endif
281 #  endif
282     }
283
284   die (signo);
285 }
286 # endif
287
288 int
289 c_stack_action (void (*action) (int))
290 {
291   int r;
292   stack_t st;
293   struct sigaction act;
294   st.ss_flags = 0;
295 # if SIGALTSTACK_SS_REVERSED
296   /* Irix mistakenly treats ss_sp as the upper bound, rather than
297      lower bound, of the alternate stack.  */
298   st.ss_sp = alternate_signal_stack.buffer + SIGSTKSZ - sizeof (void *);
299   st.ss_size = sizeof alternate_signal_stack.buffer - sizeof (void *);
300 # else
301   st.ss_sp = alternate_signal_stack.buffer;
302   st.ss_size = sizeof alternate_signal_stack.buffer;
303 # endif
304   r = sigaltstack (&st, NULL);
305   if (r != 0)
306     return r;
307
308   segv_action = action ? action : null_action;
309   program_error_message = _("program error");
310   stack_overflow_message = _("stack overflow");
311
312   sigemptyset (&act.sa_mask);
313
314 # if SIGACTION_WORKS
315   /* POSIX 1003.1-2001 says SA_RESETHAND implies SA_NODEFER, but
316      this is not true on Solaris 8 at least.  It doesn't hurt to use
317      SA_NODEFER here, so leave it in.  */
318   act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
319   act.sa_sigaction = segv_handler;
320 # else
321   act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;
322   act.sa_handler = die;
323 # endif
324
325 # if FAULT_YIELDS_SIGBUS
326   if (sigaction (SIGBUS, &act, NULL) < 0)
327     return -1;
328 # endif
329   return sigaction (SIGSEGV, &act, NULL);
330 }
331
332 #else /* ! ((HAVE_SIGALTSTACK && HAVE_DECL_SIGALTSTACK
333              && HAVE_STACK_OVERFLOW_HANDLING) || HAVE_LIBSIGSEGV) */
334
335 int
336 c_stack_action (void (*action) (int)  __attribute__ ((unused)))
337 {
338   errno = ENOTSUP;
339   return -1;
340 }
341
342 #endif