9bf19ff56d9a2a80e4947eaf5872cc7b09f12603
[gnulib.git] / lib / c-stack.c
1 /* Stack overflow handling.
2
3    Copyright (C) 2002, 2004, 2006 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 || __STRICT_ANSI__
40 #  define __attribute__(x)
41 # endif
42 #endif
43
44 #include "gettext.h"
45 #define _(msgid) gettext (msgid)
46
47 #include <errno.h>
48 #ifndef ENOTSUP
49 # define ENOTSUP EINVAL
50 #endif
51 #ifndef EOVERFLOW
52 # define EOVERFLOW EINVAL
53 #endif
54
55 #include <signal.h>
56 #if ! HAVE_STACK_T && ! defined stack_t
57 typedef struct sigaltstack stack_t;
58 #endif
59
60 #include <stdlib.h>
61 #include <string.h>
62
63 #if HAVE_SYS_RESOURCE_H
64 /* Include sys/time.h here, because...
65    SunOS-4.1.x <sys/resource.h> fails to include <sys/time.h>.
66    This gives "incomplete type" errors for ru_utime and tu_stime.  */
67 # if HAVE_SYS_TIME_H
68 #  include <sys/time.h>
69 # endif
70 # include <sys/resource.h>
71 #endif
72
73 #if HAVE_UCONTEXT_H
74 # include <ucontext.h>
75 #endif
76
77 #include <unistd.h>
78 #ifndef STDERR_FILENO
79 # define STDERR_FILENO 2
80 #endif
81
82 #if DEBUG
83 # include <stdio.h>
84 #endif
85
86 #include "c-stack.h"
87 #include "exitfail.h"
88
89 #if (HAVE_STRUCT_SIGACTION_SA_SIGACTION && defined SA_NODEFER \
90      && defined SA_ONSTACK && defined SA_RESETHAND && defined SA_SIGINFO)
91 # define SIGACTION_WORKS 1
92 #else
93 # define SIGACTION_WORKS 0
94 #endif
95
96 extern char *program_name;
97
98 /* The user-specified action to take when a SEGV-related program error
99    or stack overflow occurs.  */
100 static void (* volatile segv_action) (int);
101
102 /* Translated messages for program errors and stack overflow.  Do not
103    translate them in the signal handler, since gettext is not
104    async-signal-safe.  */
105 static char const * volatile program_error_message;
106 static char const * volatile stack_overflow_message;
107
108 /* Output an error message, then exit with status EXIT_FAILURE if it
109    appears to have been a stack overflow, or with a core dump
110    otherwise.  This function is async-signal-safe.  */
111
112 static void die (int) __attribute__ ((noreturn));
113 static void
114 die (int signo)
115 {
116   char const *message;
117   segv_action (signo);
118   message = signo ? program_error_message : stack_overflow_message;
119   write (STDERR_FILENO, program_name, strlen (program_name));
120   write (STDERR_FILENO, ": ", 2);
121   write (STDERR_FILENO, message, strlen (message));
122   write (STDERR_FILENO, "\n", 1);
123   if (! signo)
124     _exit (exit_failure);
125   kill (getpid (), signo);
126   abort ();
127 }
128
129 #if HAVE_SIGALTSTACK && HAVE_DECL_SIGALTSTACK
130
131 /* Direction of the C runtime stack.  This function is
132    async-signal-safe.  */
133
134 # if STACK_DIRECTION
135 #  define find_stack_direction(ptr) STACK_DIRECTION
136 # else
137 static int
138 find_stack_direction (char const *addr)
139 {
140   char dummy;
141   return ! addr ? find_stack_direction (&dummy) : addr < &dummy ? 1 : -1;
142 }
143 # endif
144
145 /* Storage for the alternate signal stack.  */
146 static union
147 {
148   char buffer[SIGSTKSZ];
149
150   /* These other members are for proper alignment.  There's no
151      standard way to guarantee stack alignment, but this seems enough
152      in practice.  */
153   long double ld;
154   long l;
155   void *p;
156 } alternate_signal_stack;
157
158 # if SIGACTION_WORKS
159
160 /* Handle a segmentation violation and exit.  This function is
161    async-signal-safe.  */
162
163 static void segv_handler (int, siginfo_t *, void *) __attribute__((noreturn));
164 static void
165 segv_handler (int signo, siginfo_t *info,
166               void *context __attribute__ ((unused)))
167 {
168   /* Clear SIGNO if it seems to have been a stack overflow.  */
169   if (0 < info->si_code)
170     {
171 #  if ! HAVE_XSI_STACK_OVERFLOW_HEURISTIC
172       /* We can't easily determine whether it is a stack overflow; so
173          assume that the rest of our program is perfect (!) and that
174          this segmentation violation is a stack overflow.  */
175       signo = 0;
176 #  else
177       /* If the faulting address is within the stack, or within one
178          page of the stack end, assume that it is a stack
179          overflow.  */
180       ucontext_t const *user_context = context;
181       char const *stack_base = user_context->uc_stack.ss_sp;
182       size_t stack_size = user_context->uc_stack.ss_size;
183       char const *faulting_address = info->si_addr;
184       size_t s = faulting_address - stack_base;
185       size_t page_size = sysconf (_SC_PAGESIZE);
186       if (find_stack_direction (0) < 0)
187         s += page_size;
188       if (s < stack_size + page_size)
189         signo = 0;
190
191 #   if DEBUG
192       {
193         char buf[1024];
194         sprintf (buf,
195                  "segv_handler fault=%p base=%p size=%lx page=%lx signo=%d\n",
196                  faulting_address, stack_base, (unsigned long) stack_size,
197                  (unsigned long) page_size, signo);
198         write (STDERR_FILENO, buf, strlen (buf));
199       }
200 #   endif
201 #  endif
202     }
203
204   die (signo);
205 }
206 # endif
207
208 static void
209 null_action (int signo __attribute__ ((unused)))
210 {
211 }
212
213 /* Set up ACTION so that it is invoked on C stack overflow.  Return -1
214    (setting errno) if this cannot be done.
215
216    When ACTION is called, it is passed an argument equal to SIGSEGV
217    for a segmentation violation that does not appear related to stack
218    overflow, and is passed zero otherwise.  On many platforms it is
219    hard to tell; when in doubt, zero is passed.
220
221    A null ACTION acts like an action that does nothing.
222
223    ACTION must be async-signal-safe.  ACTION together with its callees
224    must not require more than SIGSTKSZ bytes of stack space.  */
225
226 int
227 c_stack_action (void (*action) (int))
228 {
229   int r;
230   stack_t st;
231   st.ss_flags = 0;
232   st.ss_sp = alternate_signal_stack.buffer;
233   st.ss_size = sizeof alternate_signal_stack.buffer;
234   r = sigaltstack (&st, 0);
235   if (r != 0)
236     return r;
237
238   segv_action = action ? action : null_action;
239   program_error_message = _("program error");
240   stack_overflow_message = _("stack overflow");
241
242   {
243 # if SIGACTION_WORKS
244     struct sigaction act;
245     sigemptyset (&act.sa_mask);
246
247     /* POSIX 1003.1-2001 says SA_RESETHAND implies SA_NODEFER, but
248        this is not true on Solaris 8 at least.  It doesn't hurt to use
249        SA_NODEFER here, so leave it in.  */
250     act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
251
252     act.sa_sigaction = segv_handler;
253
254     return sigaction (SIGSEGV, &act, 0);
255 # else
256     return signal (SIGSEGV, die) == SIG_ERR ? -1 : 0;
257 # endif
258   }
259 }
260
261 #else /* ! (HAVE_SIGALTSTACK && HAVE_DECL_SIGALTSTACK) */
262
263 int
264 c_stack_action (void (*action) (int)  __attribute__ ((unused)))
265 {
266   errno = ENOTSUP;
267   return -1;
268 }
269
270 #endif
271
272 \f
273
274 #if DEBUG
275
276 int volatile exit_failure;
277
278 static long
279 recurse (char *p)
280 {
281   char array[500];
282   array[0] = 1;
283   return *p + recurse (array);
284 }
285
286 char *program_name;
287
288 int
289 main (int argc __attribute__ ((unused)), char **argv)
290 {
291   program_name = argv[0];
292   fprintf (stderr,
293            "The last output line should contain \"stack overflow\".\n");
294   if (c_stack_action (0) == 0)
295     return recurse ("\1");
296   perror ("c_stack_action");
297   return 1;
298 }
299
300 #endif /* DEBUG */
301 \f
302 /*
303 Local Variables:
304 compile-command: "gcc -DDEBUG -g -O -Wall -W c-stack.c"
305 End:
306 */