xref: /haiku/src/system/libroot/os/stack_protector.cpp (revision ba0223da5d79c5cd27496ee0e5712921cebb7642)
1 /*
2  * Copyright 2021, Jérôme Duval, jerome.duval@gmail.com.
3  * Distributed under the terms of the MIT License.
4  */
5 
6 
7 #include <fcntl.h>
8 #include <signal.h>
9 #include <stdlib.h>
10 #include <sys/cdefs.h>
11 #include <syscalls.h>
12 
13 #include "private/system/random_defs.h"
14 #include "private/system/symbol_visibility.h"
15 
16 
17 extern "C" {
18 
19 long __stack_chk_guard = 0;
20 
21 
22 void
23 __init_stack_protector()
24 {
25 	if (__stack_chk_guard != 0)
26 		return;
27 
28 	struct random_get_entropy_args args;
29 	args.buffer = &__stack_chk_guard;
30 	args.length = sizeof(__stack_chk_guard);
31 
32 	status_t status = _kern_generic_syscall(RANDOM_SYSCALLS, RANDOM_GET_ENTROPY,
33 		&args, sizeof(args));
34 
35 	if (status != B_OK || args.length != sizeof(__stack_chk_guard)) {
36 		unsigned char* p = (unsigned char *)&__stack_chk_guard;
37 		p[0] = 0;
38 		p[1] = 0;
39 		p[2] = '\n';
40 		p[3] = 0xff;
41 	}
42 }
43 
44 
45 void
46 __stack_chk_fail()
47 {
48 	HIDDEN_FUNCTION(__stack_chk_fail_local);
49 	sigset_t mask;
50 	sigfillset(&mask);
51 	sigdelset(&mask, SIGABRT);
52 	sigprocmask(SIG_BLOCK, &mask, NULL);
53 
54 	abort();
55 }
56 
57 }
58 
59 extern "C" void __stack_chk_fail_local() HIDDEN_FUNCTION_ATTRIBUTE;
60 __weak_reference(__stack_chk_fail, __stack_chk_fail_local);
61