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