aboutsummaryrefslogtreecommitdiffstats
path: root/stackoverflow-recovery.c
blob: 436c8c7218b233c3d3630e5ae0f5c32494e0d282 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/* See LICENSE file for copyright and license details. */
#include <setjmp.h>
#include <signal.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


unsigned volatile just_one = 1;

static jmp_buf jmpenv;


static void
sigsegv(int signo)
{
	(void) signo;

	siglongjmp(jmpenv, 1);
}


static unsigned
overflow2(size_t depth)
{
	if (!depth)
		return just_one;
	depth -= 1u;
	return overflow2(depth) + overflow2(depth);
}


static unsigned
overflow(void)
{
	return overflow2(SIZE_MAX);
}


int
main(void)
{
	volatile unsigned sum = 0;
	volatile int i;
	struct sigaction sa;
	stack_t ss;

	ss.ss_sp = malloc((size_t)SIGSTKSZ);
	if (!ss.ss_sp)
		return 1;
	ss.ss_size = (size_t)SIGSTKSZ;
	ss.ss_flags = 0;
	if (sigaltstack(&ss, NULL))
		return 2;

	memset(&sa, 0, sizeof(sa));
	sa.sa_flags = SA_ONSTACK;
	sa.sa_handler = &sigsegv;
	sigfillset(&sa.sa_mask);
	sigaction(SIGSEGV, &sa, NULL);

	for (i = 1; i <= 10; i++) {
		if (!sigsetjmp(jmpenv, 1)) {
			printf("%i: before overflow dereference\n", i);
			sum += overflow();
		} else {
			printf("%i: after overflow dereference\n", i);
		}
	}

	fflush(stdout);
	return (int)sum;
}