1 /*-
2 * Copyright (c) 2016 embedded brains GmbH
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
25 */
26
27 /*
28 * Newlib ports may override the default implementations via the following
29 * define and macros
30 * o _ARC4RANDOM_DATA,
31 * o _ARC4RANDOM_GETENTROPY_FAIL(),
32 * o _ARC4RANDOM_ALLOCATE(rsp, rspx), and
33 * o _ARC4RANDOM_FORKDETECT().
34 */
35 #include <machine/_arc4random.h>
36
37 #include <sys/lock.h>
38 #include <signal.h>
39
40 #define _ARC4_LOCK() __LIBC_LOCK()
41 #define _ARC4_UNLOCK() __LIBC_UNLOCK()
42
43 #ifdef _ARC4RANDOM_DATA
44 _ARC4RANDOM_DATA
45 #else
46 static struct {
47 struct _rs rs;
48 struct _rsx rsx;
49 } _arc4random_data;
50 #endif
51
52 static inline void
_getentropy_fail(void)53 _getentropy_fail(void)
54 {
55 #ifdef _ARC4RANDOM_GETENTROPY_FAIL
56 _ARC4RANDOM_GETENTROPY_FAIL();
57 #else
58 raise(SIGKILL);
59 #endif
60 }
61
62 static inline int
_rs_allocate(struct _rs ** rsp,struct _rsx ** rsxp)63 _rs_allocate(struct _rs **rsp, struct _rsx **rsxp)
64 {
65 #ifdef _ARC4RANDOM_ALLOCATE
66 _ARC4RANDOM_ALLOCATE(rsp, rsxp);
67 #else
68 *rsp = &_arc4random_data.rs;
69 *rsxp = &_arc4random_data.rsx;
70 return (0);
71 #endif
72 }
73
74 static inline void
_rs_forkdetect(void)75 _rs_forkdetect(void)
76 {
77 #ifdef _ARC4RANDOM_FORKDETECT
78 _ARC4RANDOM_FORKDETECT();
79 #endif
80 }
81