xref: /haiku/src/system/libroot/os/stack_protector.cpp (revision 610f99c838cb661ff85377789ffd3ad4ff672a08)
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 *)(void *)__stack_chk_guard)[0] = 0;
36 		((unsigned char *)(void *)__stack_chk_guard)[1] = 0;
37 		((unsigned char *)(void *)__stack_chk_guard)[2] = '\n';
38 		((unsigned char *)(void *)__stack_chk_guard)[3] = 0xff;
39 	}
40 }
41 
42 
43 void
44 __stack_chk_fail()
45 {
46 	HIDDEN_FUNCTION(__stack_chk_fail_local);
47 	sigset_t mask;
48 	sigfillset(&mask);
49 	sigdelset(&mask, SIGABRT);
50 	sigprocmask(SIG_BLOCK, &mask, NULL);
51 
52 	abort();
53 }
54 
55 }
56 
57 extern "C" void __stack_chk_fail_local() HIDDEN_FUNCTION_ATTRIBUTE;
58 __weak_reference(__stack_chk_fail, __stack_chk_fail_local);
59