xref: /haiku/src/system/libroot/os/stack_protector.cpp (revision abba71575e34f84c3d75be9d29d6e6caa6c033db)
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 
12 
13 extern "C" {
14 
15 long __stack_chk_guard = 0;
16 
17 
18 void
19 __init_stack_protector()
20 {
21 	if (__stack_chk_guard != 0)
22 		return;
23 
24 	bool done = false;
25 	int fd = open("/dev/random", O_RDONLY, 0);
26 	if (fd >= 0) {
27 		done = read(fd, &__stack_chk_guard, sizeof(__stack_chk_guard))
28 			== sizeof(__stack_chk_guard);
29 		close(fd);
30 	}
31 
32 	if (!done) {
33 		((unsigned char *)(void *)__stack_chk_guard)[0] = 0;
34 		((unsigned char *)(void *)__stack_chk_guard)[1] = 0;
35 		((unsigned char *)(void *)__stack_chk_guard)[2] = '\n';
36 		((unsigned char *)(void *)__stack_chk_guard)[3] = 0xff;
37 	}
38 }
39 
40 
41 void
42 __stack_chk_fail()
43 {
44 	sigset_t mask;
45 	sigfillset(&mask);
46 	sigdelset(&mask, SIGABRT);
47 	sigprocmask(SIG_BLOCK, &mask, NULL);
48 
49 	abort();
50 }
51 
52 }
53 
54 
55 #if __GNUC__ >= 4
56 extern "C" void __stack_chk_fail_local() __attribute__((visibility("hidden")));
57 __weak_reference(__stack_chk_fail, __stack_chk_fail_local);
58 #endif
59