xref: /openbsd-src/lib/libcrypto/arc4random/arc4random_linux.h (revision 50b7afb2c2c0993b0894d4e34bf857cb13ed9c80)
1 /*	$OpenBSD: arc4random_linux.h,v 1.6 2014/07/19 15:29:25 bcook Exp $	*/
2 
3 /*
4  * Copyright (c) 1996, David Mazieres <dm@uun.org>
5  * Copyright (c) 2008, Damien Miller <djm@openbsd.org>
6  * Copyright (c) 2013, Markus Friedl <markus@openbsd.org>
7  *
8  * Permission to use, copy, modify, and distribute this software for any
9  * purpose with or without fee is hereby granted, provided that the above
10  * copyright notice and this permission notice appear in all copies.
11  *
12  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19  */
20 
21 /*
22  * Stub functions for portability.
23  */
24 
25 #include <pthread.h>
26 
27 static pthread_mutex_t arc4random_mtx = PTHREAD_MUTEX_INITIALIZER;
28 #define _ARC4_LOCK()   pthread_mutex_lock(&arc4random_mtx)
29 #define _ARC4_UNLOCK() pthread_mutex_unlock(&arc4random_mtx)
30 
31 #ifdef __GLIBC__
32 extern void *__dso_handle;
33 extern int __register_atfork(void (*)(void), void(*)(void), void (*)(void), void *);
34 #define _ARC4_ATFORK(f) __register_atfork(NULL, NULL, (f), __dso_handle)
35 #else
36 #define _ARC4_ATFORK(f) pthread_atfork(NULL, NULL, (f))
37 #endif
38 
39 static volatile sig_atomic_t _rs_forked;
40 
41 static inline void
42 _rs_forkhandler(void)
43 {
44 	_rs_forked = 1;
45 }
46 
47 static inline void
48 _rs_forkdetect(void)
49 {
50 	static pid_t _rs_pid = 0;
51 	pid_t pid = getpid();
52 
53 	if (_rs_pid == 0 || _rs_pid != pid || _rs_forked) {
54 		_rs_pid = pid;
55 		_rs_forked = 0;
56 		if (rs)
57 			memset(rs, 0, sizeof(*rs));
58 	}
59 }
60 
61 static inline int
62 _rs_allocate(struct _rs **rsp, struct _rsx **rsxp)
63 {
64 	if ((*rsp = mmap(NULL, sizeof(**rsp), PROT_READ|PROT_WRITE,
65 	    MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED)
66 		return (-1);
67 
68 	if ((*rsxp = mmap(NULL, sizeof(**rsxp), PROT_READ|PROT_WRITE,
69 	    MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
70 		munmap(*rsxp, sizeof(**rsxp));
71 		return (-1);
72 	}
73 
74 	_ARC4_ATFORK(_rs_forkhandler);
75 	return (0);
76 }
77