aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/libs/libc_compat/random/getentropy.c
blob: 50e9c2fae25d0291b3592e95469416552b00687e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#define _BSD_SOURCE
#include <unistd.h>
#include <sys/random.h>
#include <pthread.h>
#include <errno.h>

int getentropy(void *buffer, size_t len)
{
	int cs, ret = 0;
	char *pos = buffer;

	if (len > 256) {
		errno = EIO;
		return -1;
	}

#if defined(__linux__) && !defined(__ANDROID__)
	pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
#endif

	while (len) {
		ret = getrandom(pos, len, 0);
		if (ret < 0) {
			if (errno == EINTR) continue;
			else break;
		}
		pos += ret;
		len -= ret;
		ret = 0;
	}

#if defined(__linux__) && !defined(__ANDROID__)
	pthread_setcancelstate(cs, 0);
#endif

	return ret;
}