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
15extern "C" {
16
17long __stack_chk_guard = 0;
18
19
20void
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
44void
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
58extern "C" void __stack_chk_fail_local() HIDDEN_FUNCTION_ATTRIBUTE;
59__weak_reference(__stack_chk_fail, __stack_chk_fail_local);
60