arc4random.h revision 6209c81d40e2b4e129a28bda3259150d79d507e8
1/* $OpenBSD: arc4random_linux.h,v 1.7 2014/07/20 20:51:13 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 <sys/mman.h> 26 27#include <pthread.h> 28#include <signal.h> 29 30// Android gets these from "thread_private.h". 31#include "thread_private.h" 32//static pthread_mutex_t arc4random_mtx = PTHREAD_MUTEX_INITIALIZER; 33//#define _ARC4_LOCK() pthread_mutex_lock(&arc4random_mtx) 34//#define _ARC4_UNLOCK() pthread_mutex_unlock(&arc4random_mtx) 35 36#ifdef __GLIBC__ 37extern void *__dso_handle; 38extern int __register_atfork(void (*)(void), void(*)(void), void (*)(void), void *); 39#define _ARC4_ATFORK(f) __register_atfork(NULL, NULL, (f), __dso_handle) 40#else 41#define _ARC4_ATFORK(f) pthread_atfork(NULL, NULL, (f)) 42#endif 43 44static inline void 45_getentropy_fail(void) 46{ 47 raise(SIGKILL); 48} 49 50static volatile sig_atomic_t _rs_forked; 51 52static inline void 53_rs_forkhandler(void) 54{ 55 _rs_forked = 1; 56} 57 58static inline void 59_rs_forkdetect(void) 60{ 61 static pid_t _rs_pid = 0; 62 pid_t pid = getpid(); 63 64 if (_rs_pid == 0 || _rs_pid != pid || _rs_forked) { 65 _rs_pid = pid; 66 _rs_forked = 0; 67 if (rs) 68 memset(rs, 0, sizeof(*rs)); 69 } 70} 71 72static inline int 73_rs_allocate(struct _rs **rsp, struct _rsx **rsxp) 74{ 75 if ((*rsp = mmap(NULL, sizeof(**rsp), PROT_READ|PROT_WRITE, 76 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) 77 return (-1); 78 79 if ((*rsxp = mmap(NULL, sizeof(**rsxp), PROT_READ|PROT_WRITE, 80 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) { 81 munmap(*rsxp, sizeof(**rsxp)); 82 return (-1); 83 } 84 85 _ARC4_ATFORK(_rs_forkhandler); 86 return (0); 87} 88