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