c-stack: work around libsigsegv 2.8 bug
[gnulib.git] / lib / c-stack.c
1 /* Stack overflow handling.
2
3    Copyright (C) 2002, 2004, 2006, 2008, 2009, 2010 Free Software Foundation,
4    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
50 #include <signal.h>
51 #if ! HAVE_STACK_T && ! defined stack_t
52 typedef struct sigaltstack stack_t;
53 #endif
54 #ifndef SIGSTKSZ
55 # define SIGSTKSZ 16384
56 #elif HAVE_LIBSIGSEGV && SIGSTKSZ < 16384
57 /* libsigsegv 2.6 through 2.8 have a bug where some architectures use
58    more than the Linux default of an 8k alternate stack when deciding
59    if a fault was caused by stack overflow.  */
60 # undef SIGSTKSZ
61 # define SIGSTKSZ 16384
62 #endif
63
64 #include <stdlib.h>
65 #include <string.h>
66
67 /* Posix 2001 declares ucontext_t in <ucontext.h>, Posix 200x in
68    <signal.h>.  */
69 #if HAVE_UCONTEXT_H
70 # include <ucontext.h>
71 #endif
72
73 #include <unistd.h>
74
75 #if HAVE_LIBSIGSEGV
76 # include <sigsegv.h>
77 #endif
78
79 #include "c-stack.h"
80 #include "exitfail.h"
81 #include "ignore-value.h"
82
83 #if defined SA_ONSTACK && defined SA_SIGINFO
84 # define SIGACTION_WORKS 1
85 #else
86 # define SIGACTION_WORKS 0
87 # ifndef SA_ONSTACK
88 #  define SA_ONSTACK 0
89 # endif
90 #endif
91
92 extern char *program_name;
93
94 /* The user-specified action to take when a SEGV-related program error
95    or stack overflow occurs.  */
96 static void (* volatile segv_action) (int);
97
98 /* Translated messages for program errors and stack overflow.  Do not
99    translate them in the signal handler, since gettext is not
100    async-signal-safe.  */
101 static char const * volatile program_error_message;
102 static char const * volatile stack_overflow_message;
103
104 /* Output an error message, then exit with status EXIT_FAILURE if it
105    appears to have been a stack overflow, or with a core dump
106    otherwise.  This function is async-signal-safe.  */
107
108 static void die (int) __attribute__ ((noreturn));
109 static void
110 die (int signo)
111 {
112   char const *message;
113   segv_action (signo);
114   message = signo ? program_error_message : stack_overflow_message;
115   ignore_value (write (STDERR_FILENO, program_name, strlen (program_name)));
116   ignore_value (write (STDERR_FILENO, ": ", 2));
117   ignore_value (write (STDERR_FILENO, message, strlen (message)));
118   ignore_value (write (STDERR_FILENO, "\n", 1));
119   if (! signo)
120     _exit (exit_failure);
121   raise (signo);
122   abort ();
123 }
124
125 #if (HAVE_SIGALTSTACK && HAVE_DECL_SIGALTSTACK \
126      && HAVE_STACK_OVERFLOW_HANDLING) || HAVE_LIBSIGSEGV
127
128 /* Storage for the alternate signal stack.  */
129 static union
130 {
131   char buffer[SIGSTKSZ];
132
133   /* These other members are for proper alignment.  There's no
134      standard way to guarantee stack alignment, but this seems enough
135      in practice.  */
136   long double ld;
137   long l;
138   void *p;
139 } alternate_signal_stack;
140
141 static void
142 null_action (int signo __attribute__ ((unused)))
143 {
144 }
145
146 #endif /* SIGALTSTACK || LIBSIGSEGV */
147
148 /* Only use libsigsegv if we need it; platforms like Solaris can
149    detect stack overflow without the overhead of an external
150    library.  */
151 #if HAVE_LIBSIGSEGV && ! HAVE_XSI_STACK_OVERFLOW_HEURISTIC
152
153 /* Nonzero if general segv handler could not be installed.  */
154 static volatile int segv_handler_missing;
155
156 /* Handle a segmentation violation and exit if it cannot be stack
157    overflow.  This function is async-signal-safe.  */
158
159 static int segv_handler (void *address __attribute__ ((unused)),
160                          int serious)
161 {
162 # if DEBUG
163   {
164     char buf[1024];
165     sprintf (buf, "segv_handler serious=%d\n", serious);
166     write (STDERR_FILENO, buf, strlen (buf));
167   }
168 # endif
169
170   /* If this fault is not serious, return 0 to let the stack overflow
171      handler take a shot at it.  */
172   if (!serious)
173     return 0;
174   die (SIGSEGV);
175 }
176
177 /* Handle a segmentation violation that is likely to be a stack
178    overflow and exit.  This function is async-signal-safe.  */
179
180 static void overflow_handler (int, stackoverflow_context_t)
181   __attribute__ ((noreturn));
182 static void
183 overflow_handler (int emergency,
184                   stackoverflow_context_t context __attribute__ ((unused)))
185 {
186 # if DEBUG
187   {
188     char buf[1024];
189     sprintf (buf, "overflow_handler emergency=%d segv_handler_missing=%d\n",
190              emergency, segv_handler_missing);
191     write (STDERR_FILENO, buf, strlen (buf));
192   }
193 # endif
194
195   die ((!emergency || segv_handler_missing) ? 0 : SIGSEGV);
196 }
197
198 int
199 c_stack_action (void (*action) (int))
200 {
201   segv_action = action ? action : null_action;
202   program_error_message = _("program error");
203   stack_overflow_message = _("stack overflow");
204
205   /* Always install the overflow handler.  */
206   if (stackoverflow_install_handler (overflow_handler,
207                                      alternate_signal_stack.buffer,
208                                      sizeof alternate_signal_stack.buffer))
209     {
210       errno = ENOTSUP;
211       return -1;
212     }
213   /* Try installing a general handler; if it fails, then treat all
214      segv as stack overflow.  */
215   segv_handler_missing = sigsegv_install_handler (segv_handler);
216   return 0;
217 }
218
219 #elif HAVE_SIGALTSTACK && HAVE_DECL_SIGALTSTACK && HAVE_STACK_OVERFLOW_HANDLING
220
221 /* Direction of the C runtime stack.  This function is
222    async-signal-safe.  */
223
224 # if STACK_DIRECTION
225 #  define find_stack_direction(ptr) STACK_DIRECTION
226 # else
227 #  if ! SIGACTION_WORKS || HAVE_XSI_STACK_OVERFLOW_HEURISTIC
228 static int
229 find_stack_direction (char const *addr)
230 {
231   char dummy;
232   return ! addr ? find_stack_direction (&dummy) : addr < &dummy ? 1 : -1;
233 }
234 #  endif
235 # endif
236
237 # if SIGACTION_WORKS
238
239 /* Handle a segmentation violation and exit.  This function is
240    async-signal-safe.  */
241
242 static void segv_handler (int, siginfo_t *, void *) __attribute__((noreturn));
243 static void
244 segv_handler (int signo, siginfo_t *info,
245               void *context __attribute__ ((unused)))
246 {
247   /* Clear SIGNO if it seems to have been a stack overflow.  */
248 #  if ! HAVE_XSI_STACK_OVERFLOW_HEURISTIC
249   /* We can't easily determine whether it is a stack overflow; so
250      assume that the rest of our program is perfect (!) and that
251      this segmentation violation is a stack overflow.
252
253      Note that although both Linux and Solaris provide
254      sigaltstack, SA_ONSTACK, and SA_SIGINFO, currently only
255      Solaris satisfies the XSI heueristic.  This is because
256      Solaris populates uc_stack with the details of the
257      interrupted stack, while Linux populates it with the details
258      of the current stack.  */
259   signo = 0;
260 #  else
261   if (0 < info->si_code)
262     {
263       /* If the faulting address is within the stack, or within one
264          page of the stack end, assume that it is a stack
265          overflow.  */
266       ucontext_t const *user_context = context;
267       char const *stack_base = user_context->uc_stack.ss_sp;
268       size_t stack_size = user_context->uc_stack.ss_size;
269       char const *faulting_address = info->si_addr;
270       size_t s = faulting_address - stack_base;
271       size_t page_size = sysconf (_SC_PAGESIZE);
272       if (find_stack_direction (NULL) < 0)
273         s += page_size;
274       if (s < stack_size + page_size)
275         signo = 0;
276
277 #   if DEBUG
278       {
279         char buf[1024];
280         sprintf (buf,
281                  "segv_handler fault=%p base=%p size=%lx page=%lx signo=%d\n",
282                  faulting_address, stack_base, (unsigned long) stack_size,
283                  (unsigned long) page_size, signo);
284         write (STDERR_FILENO, buf, strlen (buf));
285       }
286 #   endif
287     }
288 #  endif
289
290   die (signo);
291 }
292 # endif
293
294 int
295 c_stack_action (void (*action) (int))
296 {
297   int r;
298   stack_t st;
299   struct sigaction act;
300   st.ss_flags = 0;
301 # if SIGALTSTACK_SS_REVERSED
302   /* Irix mistakenly treats ss_sp as the upper bound, rather than
303      lower bound, of the alternate stack.  */
304   st.ss_sp = alternate_signal_stack.buffer + SIGSTKSZ - sizeof (void *);
305   st.ss_size = sizeof alternate_signal_stack.buffer - sizeof (void *);
306 # else
307   st.ss_sp = alternate_signal_stack.buffer;
308   st.ss_size = sizeof alternate_signal_stack.buffer;
309 # endif
310   r = sigaltstack (&st, NULL);
311   if (r != 0)
312     return r;
313
314   segv_action = action ? action : null_action;
315   program_error_message = _("program error");
316   stack_overflow_message = _("stack overflow");
317
318   sigemptyset (&act.sa_mask);
319
320 # if SIGACTION_WORKS
321   /* POSIX 1003.1-2001 says SA_RESETHAND implies SA_NODEFER, but
322      this is not true on Solaris 8 at least.  It doesn't hurt to use
323      SA_NODEFER here, so leave it in.  */
324   act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
325   act.sa_sigaction = segv_handler;
326 # else
327   act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;
328   act.sa_handler = die;
329 # endif
330
331 # if FAULT_YIELDS_SIGBUS
332   if (sigaction (SIGBUS, &act, NULL) < 0)
333     return -1;
334 # endif
335   return sigaction (SIGSEGV, &act, NULL);
336 }
337
338 #else /* ! ((HAVE_SIGALTSTACK && HAVE_DECL_SIGALTSTACK
339              && HAVE_STACK_OVERFLOW_HANDLING) || HAVE_LIBSIGSEGV) */
340
341 int
342 c_stack_action (void (*action) (int)  __attribute__ ((unused)))
343 {
344   errno = ENOTSUP;
345   return -1;
346 }
347
348 #endif