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