1 | /* Helper function to allocate shadow stack. |
2 | Copyright (C) 2023-2024 Free Software Foundation, Inc. |
3 | This file is part of the GNU C Library. |
4 | |
5 | The GNU C Library is free software; you can redistribute it and/or |
6 | modify it under the terms of the GNU Lesser General Public |
7 | License as published by the Free Software Foundation; either |
8 | version 2.1 of the License, or (at your option) any later version. |
9 | |
10 | The GNU C Library 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 GNU |
13 | Lesser General Public License for more details. |
14 | |
15 | You should have received a copy of the GNU Lesser General Public |
16 | License along with the GNU C Library; if not, see |
17 | <https://www.gnu.org/licenses/>. */ |
18 | |
19 | #include <sysdep.h> |
20 | #include <stdint.h> |
21 | #include <errno.h> |
22 | #include <sys/mman.h> |
23 | #include <libc-pointer-arith.h> |
24 | #include <allocate-shadow-stack.h> |
25 | |
26 | /* NB: This can be treated as a syscall by caller. */ |
27 | |
28 | long int |
29 | __allocate_shadow_stack (size_t stack_size, |
30 | shadow_stack_size_t *child_stack) |
31 | { |
32 | #ifdef __NR_map_shadow_stack |
33 | size_t shadow_stack_size |
34 | = stack_size >> STACK_SIZE_TO_SHADOW_STACK_SIZE_SHIFT; |
35 | /* Align shadow stack to 8 bytes. */ |
36 | shadow_stack_size = ALIGN_UP (shadow_stack_size, 8); |
37 | /* Since sigaltstack shares shadow stack with the current context in |
38 | the thread, add extra 20 stack frames in shadow stack for signal |
39 | handlers. */ |
40 | shadow_stack_size += 20 * 8; |
41 | void *shadow_stack = (void *)INLINE_SYSCALL_CALL |
42 | (map_shadow_stack, NULL, shadow_stack_size, SHADOW_STACK_SET_TOKEN); |
43 | /* Report the map_shadow_stack error. */ |
44 | if (shadow_stack == MAP_FAILED) |
45 | return -errno; |
46 | |
47 | /* Save the shadow stack base and size on child stack. */ |
48 | child_stack[0] = (uintptr_t) shadow_stack; |
49 | child_stack[1] = shadow_stack_size; |
50 | |
51 | return 0; |
52 | #else |
53 | return -ENOSYS; |
54 | #endif |
55 | } |
56 | |