1 /* Some auxiliary stuff for defining an alternate stack.
2 Copyright (C) 2010 Eric Blake <eblake@redhat.com>
3 Copyright (C) 2010-2021 Bruno Haible <bruno@clisp.org>
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 of the License, or
8 (at your option) any later version.
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, see <https://www.gnu.org/licenses/>. */
18 #include <stdint.h> /* uintptr_t */
19 #include <string.h> /* for memset */
21 #define MYSTACK_SIZE (1 << 24)
23 /* glibc says: Users should use SIGSTKSZ as the size of user-supplied
24 buffers. We want to detect stack overflow of the alternate stack
25 in a nicer manner than just crashing, so we overallocate in
26 comparison to what we hand libsigsegv. Also, we intentionally hand
27 an unaligned pointer, to ensure the alternate stack still ends up
29 #define MYSTACK_CRUMPLE_ZONE 8192
30 static char mystack_storage[MYSTACK_SIZE + 2 * MYSTACK_CRUMPLE_ZONE + 31];
31 static char *mystack; /* MYSTACK_SIZE bytes in the middle of storage. */
34 prepare_alternate_stack (void)
37 if (MYSTACK_SIZE < SIGSTKSZ)
39 size_t size = SIGSTKSZ;
40 printf ("SIGSTKSZ=%zu exceeds MYSTACK_SIZE=%d\n", size, MYSTACK_SIZE);
44 memset (mystack_storage, 's', sizeof mystack_storage);
45 mystack = (char *) ((uintptr_t) (mystack_storage + MYSTACK_CRUMPLE_ZONE) | 31);
49 check_alternate_stack_no_overflow (void)
53 for (i = MYSTACK_CRUMPLE_ZONE; i > 0; i--)
54 if (*(mystack - i) != 's')
56 printf ("Alternate stack was exceeded by %u bytes!!\n", i);
59 for (i = MYSTACK_CRUMPLE_ZONE; i > 0; i--)
60 if (*(mystack + MYSTACK_SIZE - 1 + i) != 's')
62 printf ("Alternate stack was exceeded by %u bytes!!\n", i);