1 /* $OpenBSD: callstack.c,v 1.1 2019/09/23 08:34:07 bluhm Exp $ */
2 /*
3 * Copyright (c) 2018 Todd Mortimer <mortimer@openbsd.org>
4 * Copyright (c) 2019 Alexander Bluhm <bluhm@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18
19 #include <err.h>
20 #include <stdlib.h>
21 #include <signal.h>
22 #include <unistd.h>
23
24 #include "pivot.h"
25
26 void handler(int);
27 void doexit(void);
28
29 int
main(int argc,char * argv[])30 main(int argc, char *argv[])
31 {
32 stack_t ss;
33 struct sigaction act;
34 void (**newstack)(void);
35 long pagesize;
36
37 ss.ss_sp = malloc(SIGSTKSZ);
38 if (ss.ss_sp == NULL)
39 err(1, "malloc sigstack");
40 ss.ss_size = SIGSTKSZ;
41 ss.ss_flags = 0;
42 if (sigaltstack(&ss, NULL) == -1)
43 err(1, "sigaltstack");
44
45 act.sa_handler = handler;
46 sigemptyset(&act.sa_mask);
47 act.sa_flags = SA_ONSTACK;
48
49 /* set up an alt stack on the heap that just calls doexit */
50 pagesize = sysconf(_SC_PAGESIZE);
51 if (pagesize == -1)
52 err(1, "sysconf");
53 newstack = malloc(pagesize > SIGSTKSZ ? pagesize : SIGSTKSZ);
54 if (newstack == NULL)
55 err(1, "malloc newstack");
56 /* allow stack to change half a page up and down. */
57 newstack[pagesize/sizeof(*newstack)/2] = doexit;
58
59 if (sigaction(SIGSEGV, &act, NULL) == -1)
60 err(1, "sigaction");
61 pivot(&newstack[pagesize/sizeof(*newstack)/2]);
62 return 3;
63 }
64
65 void
handler(int signum)66 handler(int signum)
67 {
68 _exit(0);
69 }
70
71 void
doexit(void)72 doexit(void)
73 {
74 exit(2);
75 }
76