xref: /freebsd/lib/libc/gen/arc4random.h (revision d34048812292b714a0bf99967270d18fe3097c62)
1 /*	$OpenBSD: arc4random.h,v 1.4 2015/01/15 06:57:18 deraadt 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  * Copyright (c) 2014, Theo de Raadt <deraadt@openbsd.org>
8  *
9  * Permission to use, copy, modify, and distribute this software for any
10  * purpose with or without fee is hereby granted, provided that the above
11  * copyright notice and this permission notice appear in all copies.
12  *
13  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
14  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
15  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
16  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
17  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
19  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20  *
21  * $FreeBSD$
22  */
23 
24 /*
25  * Stub functions for portability.
26  */
27 #include <sys/mman.h>
28 
29 #include <signal.h>
30 
31 static pthread_mutex_t	arc4random_mtx = PTHREAD_MUTEX_INITIALIZER;
32 #define	_ARC4_LOCK()						\
33 	do {							\
34 		if (__isthreaded)				\
35 			_pthread_mutex_lock(&arc4random_mtx);	\
36 	} while (0)
37 
38 #define	_ARC4_UNLOCK()						\
39 	do {							\
40 		if (__isthreaded)				\
41 			_pthread_mutex_unlock(&arc4random_mtx);	\
42 	} while (0)
43 
44 static inline void
45 _getentropy_fail(void)
46 {
47 	raise(SIGKILL);
48 }
49 
50 static inline int
51 _rs_allocate(struct _rs **rsp, struct _rsx **rsxp)
52 {
53 	struct {
54 		struct _rs rs;
55 		struct _rsx rsx;
56 	} *p;
57 
58 	if ((p = mmap(NULL, sizeof(*p), PROT_READ|PROT_WRITE,
59 	    MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED)
60 		return (-1);
61 	if (minherit(p, sizeof(*p), INHERIT_ZERO) == -1) {
62 		munmap(p, sizeof(*p));
63 		return (-1);
64 	}
65 
66 	*rsp = &p->rs;
67 	*rsxp = &p->rsx;
68 	return (0);
69 }
70 
71 static inline void
72 _rs_forkdetect(void)
73 {
74 }
75