1 /* Stack overflow handling.
3 Copyright (C) 2002 Free Software Foundation, Inc.
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)
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.
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. */
19 /* Written by Paul Eggert. */
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.
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.
35 No attempt has been made to deal with multithreaded applications.
37 If ! HAVE_XSI_STACK_OVERFLOW_HEURISTIC, the current implementation
38 assumes that, if the RLIMIT_STACK limit changes during execution,
39 then c_stack_action is invoked immediately afterwards. */
46 # if __GNUC__ < 3 || __STRICT_ANSI__
47 # define __attribute__(x)
52 #define _(msgid) gettext (msgid)
56 # define ENOTSUP EINVAL
59 # define EOVERFLOW EINVAL
63 #if ! HAVE_STACK_T && ! defined stack_t
64 typedef struct sigaltstack stack_t;
70 #if HAVE_SYS_RESOURCE_H
71 # include <sys/resource.h>
75 # include <ucontext.h>
82 # define STDERR_FILENO 2
92 extern char *program_name;
94 /* The user-specified action to take when a SEGV-related program error
95 or stack overflow occurs. */
96 static void (* volatile segv_action) (int);
98 /* Translated messages for program errors and stack overflow. Do not
99 translate them in the signal handler, since gettext is not
100 async-signal-safe. */
101 static char const * volatile program_error_message;
102 static char const * volatile stack_overflow_message;
104 /* Output an error message, then exit with status EXIT_FAILURE if it
105 appears to have been a stack overflow, or with a core dump
106 otherwise. This function is async-signal-safe. */
108 static void die (int) __attribute__ ((noreturn));
112 char const *message =
113 signo ? program_error_message : stack_overflow_message;
115 write (STDERR_FILENO, program_name, strlen (program_name));
116 write (STDERR_FILENO, ": ", 2);
117 write (STDERR_FILENO, message, strlen (message));
118 write (STDERR_FILENO, "\n", 1);
120 _exit (exit_failure);
121 kill (getpid (), signo);
125 #if HAVE_SIGALTSTACK && HAVE_DECL_SIGALTSTACK
127 /* Direction of the C runtime stack. This function is
128 async-signal-safe. */
131 # define find_stack_direction(ptr) STACK_DIRECTION
134 find_stack_direction (char const *addr)
137 return ! addr ? find_stack_direction (&dummy) : addr < &dummy ? 1 : -1;
141 # if HAVE_XSI_STACK_OVERFLOW_HEURISTIC
142 # define get_stack_location(argv) 0
145 # if defined RLIMIT_STACK && defined _SC_PAGESIZE
147 /* Return the minimum machine address deducible from ARGV. This
148 includes the addresses of all the strings that ARGV points at, as
149 well as the address of ARGV itself. */
152 min_address_from_argv (char * const *argv)
154 char const *min = (char const *) argv;
156 while ((p = *argv++))
162 /* Return the maximum machine address deducible from ARGV. */
165 max_address_from_argv (char * const *argv)
167 char const *max = *argv;
170 while ((p = *argv++))
173 max1 = (char const *) (argv + 1);
174 return max && max1 < max ? max + strlen (max) + 1 : max1;
178 /* The base and size of the stack, determined at startup. */
179 static char const * volatile stack_base;
180 static size_t volatile stack_size;
182 /* Store the base and size of the stack into the static variables
183 STACK_BASE and STACK_SIZE. The base is the numerically lowest
184 address in the stack. Return -1 (setting errno) if this cannot be
188 get_stack_location (char * const *argv)
190 # if ! (defined RLIMIT_STACK && defined _SC_PAGESIZE)
197 struct rlimit rlimit;
198 int r = getrlimit (RLIMIT_STACK, &rlimit);
202 size_t size = rlimit.rlim_cur;
203 extern char **environ;
204 size_t page_size = sysconf (_SC_PAGESIZE);
205 int stack_direction = find_stack_direction (0);
207 # if HAVE_GETCONTEXT && HAVE_DECL_GETCONTEXT
209 if (getcontext (&context) == 0)
211 base = context.uc_stack.ss_sp;
212 if (stack_direction < 0)
213 base -= size - context.uc_stack.ss_size;
218 if (stack_direction < 0)
220 char const *a = max_address_from_argv (argv);
221 char const *b = max_address_from_argv (environ);
222 base = (a < b ? b : a) - size;
223 base += - (size_t) base % page_size;
227 char const *a = min_address_from_argv (argv);
228 char const *b = min_address_from_argv (environ);
229 base = a < b ? a : b;
230 base -= (size_t) base % page_size;
234 if (size != rlimit.rlim_cur
235 || rlimit.rlim_cur < 0
236 || base + size < base
237 # ifdef RLIM_SAVED_CUR
238 || rlimit.rlim_cur == RLIM_SAVED_CUR
240 # ifdef RLIM_SAVED_MAX
241 || rlimit.rlim_cur == RLIM_SAVED_MAX
243 # ifdef RLIM_INFINITY
244 || rlimit.rlim_cur == RLIM_INFINITY
256 fprintf (stderr, "get_stack_location base=%p size=%lx\n",
257 base, (unsigned long) size);
267 /* Storage for the alternate signal stack. */
270 char buffer[SIGSTKSZ];
272 /* These other members are for proper alignment. There's no
273 standard way to guarantee stack alignment, but this seems enough
278 } alternate_signal_stack;
280 # if defined SA_ONSTACK && defined _SC_PAGESIZE
282 /* Handle a segmentation violation and exit. This function is
283 async-signal-safe. */
285 static void segv_handler (int, siginfo_t *, void *) __attribute__((noreturn));
287 segv_handler (int signo, siginfo_t *info,
288 void *context __attribute__ ((unused)))
290 /* Clear SIGNO if it seems to have been a stack overflow. */
291 if (0 < info->si_code)
293 /* If the faulting address is within the stack, or within one
294 page of the stack end, assume that it is a stack
296 # if HAVE_XSI_STACK_OVERFLOW_HEURISTIC
297 ucontext_t const *user_context = context;
298 char const *stack_base = user_context->uc_stack.ss_sp;
299 size_t stack_size = user_context->uc_stack.ss_size;
301 char const *faulting_address = info->si_addr;
302 size_t s = faulting_address - stack_base;
303 size_t page_size = sysconf (_SC_PAGESIZE);
304 if (find_stack_direction (0) < 0)
306 if (s < stack_size + page_size)
313 "segv_handler fault=%p base=%p size=%lx page=%lx signo=%d\n",
314 faulting_address, stack_base, (unsigned long) stack_size,
315 (unsigned long) page_size, signo);
316 write (STDERR_FILENO, buf, strlen (buf));
326 null_action (int signo __attribute__ ((unused)))
330 /* Assuming ARGV is the argument vector of `main', set up ACTION so
331 that it is invoked on C stack overflow. Return -1 (setting errno)
332 if this cannot be done.
334 When ACTION is called, it is passed an argument equal to SIGSEGV
335 for a segmentation violation that does not appear related to stack
336 overflow, and is passed zero otherwise.
338 A null ACTION acts like an action that does nothing.
340 ACTION must be async-signal-safe. ACTION together with its callees
341 must not require more than SIGSTKSZ bytes of stack space. */
344 c_stack_action (char * const *argv __attribute__ ((unused)),
345 void (*action) (int))
347 int r = get_stack_location (argv);
354 st.ss_sp = alternate_signal_stack.buffer;
355 st.ss_size = sizeof alternate_signal_stack.buffer;
356 r = sigaltstack (&st, 0);
361 segv_action = action ? action : null_action;
362 program_error_message = _("program error");
363 stack_overflow_message = _("stack overflow");
366 # if ! (defined SA_ONSTACK && defined _SC_PAGESIZE)
367 return signal (SIGSEGV, die) == SIG_ERR ? -1 : 0;
369 struct sigaction act;
370 sigemptyset (&act.sa_mask);
372 /* POSIX 1003.1-2001 says SA_RESETHAND implies SA_NODEFER, but
373 this is not true on Solaris 8 at least. It doesn't hurt to use
374 SA_NODEFER here, so leave it in. */
375 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
377 act.sa_sigaction = segv_handler;
379 return sigaction (SIGSEGV, &act, 0);
384 #else /* ! (HAVE_SIGALTSTACK && HAVE_DECL_SIGALTSTACK) */
387 c_stack_action (char * const *argv __attribute__ ((unused)),
388 void (*action) (int) __attribute__ ((unused)))
400 int volatile exit_failure;
407 return *p + recurse (array);
413 main (int argc __attribute__ ((unused)), char **argv)
415 program_name = argv[0];
416 fprintf (stderr, "The last line of output should be \"stack overflow\".\n");
417 if (c_stack_action (argv, 0) == 0)
418 return recurse ("\1");
419 perror ("c_stack_action");
427 compile-command: "gcc -DDEBUG -DHAVE_CONFIG_H -I.. -g -O -Wall -W c-stack.c"