1 /* Copyright (c) 2015, Google Inc.
2 *
3 * Permission to use, copy, modify, and/or distribute this software for any
4 * purpose with or without fee is hereby granted, provided that the above
5 * copyright notice and this permission notice appear in all copies.
6 *
7 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14
15 #include <openssl/rand.h>
16
17 #include <stdlib.h>
18 #include <string.h>
19
20 #include <openssl/cpu.h>
21
22
23 #if defined(OPENSSL_X86_64) && !defined(OPENSSL_NO_ASM)
24
CRYPTO_have_hwrand(void)25 int CRYPTO_have_hwrand(void) {
26 return (OPENSSL_ia32cap_P[1] & (1u << 30)) != 0;
27 }
28
29 /* CRYPTO_rdrand is defined in asm/rdrand-x86_64.pl */
30 extern uint64_t CRYPTO_rdrand(void);
31
CRYPTO_hwrand(uint8_t * buf,size_t len)32 void CRYPTO_hwrand(uint8_t *buf, size_t len) {
33 while (len >= 8) {
34 uint64_t rand = CRYPTO_rdrand();
35 memcpy(buf, &rand, sizeof(rand));
36 len -= sizeof(rand);
37 buf += sizeof(rand);
38 }
39
40 if (len > 0) {
41 uint64_t rand = CRYPTO_rdrand();
42 memcpy(buf, &rand, len);
43 }
44 }
45
46 #else
47
CRYPTO_have_hwrand(void)48 int CRYPTO_have_hwrand(void) {
49 return 0;
50 }
51
CRYPTO_hwrand(uint8_t * buf,size_t len)52 void CRYPTO_hwrand(uint8_t *buf, size_t len) {
53 abort();
54 }
55
56 #endif
57