git.iko.soy/typeable/entropy
on 2f047cf help sign in
55 lines 1.3 kB history raw
1#ifdef HAVE_RDRAND
3#include <stdint.h>
4#include <stdlib.h>
6int cpu_has_rdrand()
7{
8 uint32_t ax,bx,cx,dx,func=1;
9 __asm__ volatile ("cpuid":\
10 "=a" (ax), "=b" (bx), "=c" (cx), "=d" (dx) : "a" (func));
11 return (cx & 0x40000000);
14// Returns 1 on success
15inline int _rdrand64_step(uint64_t *therand)
17 unsigned char err;
18 asm volatile("rdrand %0 ; setc %1"
19 : "=r" (*therand), "=qm" (err));
20 return (int) err;
23// Returns 0 on success, non-zero on failure.
24int get_rand_bytes(uint8_t *therand, size_t len)
26 int cnt;
27 int fail=0;
28 uint8_t *p = therand;
29 uint8_t *end = therand + len;
30 if((uint64_t)p%8 != 0) {
31 uint64_t tmp;
32 fail |= !_rdrand64_step(&tmp);
33 while((uint64_t)p%8 != 0 && p != end) {
34 *p = (uint8_t)(tmp & 0xFF);
35 tmp = tmp >> 8;
36 p++;
37 }
38 }
39 for(; p <= end - sizeof(uint64_t); p+=sizeof(uint64_t)) {
40 fail |= !_rdrand64_step((uint64_t *)p);
41 }
42 if(p != end) {
43 uint64_t tmp;
44 int cnt;
45 fail |= !_rdrand64_step(&tmp);
46 while(p != end) {
47 *p = (uint8_t)(tmp & 0xFF);
48 tmp = tmp >> 8;
49 p++;
50 }
51 }
52 return fail;
55#endif // RDRAND