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