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