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