#if HAVE_CONFIG_H
# include <config.h>
#endif
#include "gettext.h"
#define _(msgid) gettext (msgid)
#include <errno.h>
#ifndef ENOTSUP
# define ENOTSUP EINVAL
#endif
#if HAVE_INTTYPES_H
# include <inttypes.h>
#else
# if HAVE_STDINT_H
# include <stdint.h>
# endif
#endif
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#if HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifndef STDERR_FILENO
# define STDERR_FILENO 2
#endif
#include "c-stack.h"
#include "exitfail.h"
extern char *program_name;
#if HAVE_XSI_STACK_OVERFLOW_HEURISTIC
# include <ucontext.h>
static union
{
char buffer[SIGSTKSZ];
long double ld;
uintmax_t u;
void *p;
} alternate_signal_stack;
# if STACK_DIRECTION
# define find_stack_direction(ptr) STACK_DIRECTION
# else
static int
find_stack_direction (char const *addr)
{
char dummy;
return ! addr ? find_stack_direction (&dummy) : addr < &dummy ? 1 : -1;
}
# endif
static void (* volatile segv_action) (int, siginfo_t *, void *);
static void
segv_handler (int signo, siginfo_t *info, void *context)
{
if (0 < info->si_code)
{
ucontext_t const *user_context = context;
char const *stack_min = user_context->uc_stack.ss_sp;
size_t stack_size = user_context->uc_stack.ss_size;
char const *faulting_address = info->si_addr;
size_t s = faulting_address - stack_min;
size_t page_size = sysconf (_SC_PAGESIZE);
if (find_stack_direction (0) < 0)
s += page_size;
if (s < stack_size + page_size)
signo = 0;
}
segv_action (signo, info, context);
}
#endif
static char const * volatile program_error_message;
static char const * volatile stack_overflow_message;
void
c_stack_die (int signo, siginfo_t *info, void *context)
{
char const *message =
signo ? program_error_message : stack_overflow_message;
write (STDERR_FILENO, program_name, strlen (program_name));
write (STDERR_FILENO, ": ", 2);
write (STDERR_FILENO, message, strlen (message));
write (STDERR_FILENO, "\n", 1);
if (! signo)
_exit (exit_failure);
#if HAVE_SIGINFO_T
if (context && info && 0 <= info->si_code)
{
char *addr = info->si_addr;
*addr = 0;
}
#endif
kill (getpid (), signo);
}
int
c_stack_action (void (*action) (int, siginfo_t *, void *))
{
#if ! HAVE_XSI_STACK_OVERFLOW_HEURISTIC
errno = ENOTSUP;
return -1;
#else
struct sigaction act;
stack_t st;
int r;
st.ss_flags = 0;
st.ss_sp = alternate_signal_stack.buffer;
st.ss_size = sizeof alternate_signal_stack.buffer;
r = sigaltstack (&st, 0);
if (r != 0)
return r;
program_error_message = _("program error");
stack_overflow_message = _("stack overflow");
segv_action = action;
sigemptyset (&act.sa_mask);
act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
act.sa_sigaction = segv_handler;
return sigaction (SIGSEGV, &act, 0);
#endif
}
#if DEBUG
#include <stdio.h>
int volatile exit_failure;
static long
recurse (char *p)
{
char array[500];
array[0] = 1;
return *p + recurse (array);
}
char *program_name;
int
main (int argc, char **argv)
{
program_name = argv[0];
c_stack_action (c_stack_die);
return recurse ("\1");
}
#endif