1 /*
2  * Copyright (c) 2024 Google LLC
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <errno.h>
8 
9 #include <zephyr/drivers/entropy.h>
10 #include <zephyr/kernel.h>
11 #include <zephyr/posix/unistd.h>
12 
13 #define ENTROPY_NODE DEVICE_DT_GET_OR_NULL(DT_CHOSEN(zephyr_entropy))
14 
getentropy(void * buffer,size_t length)15 int getentropy(void *buffer, size_t length)
16 {
17 	const struct device *const entropy = ENTROPY_NODE;
18 
19 	if (!buffer) {
20 		errno = EFAULT;
21 		return -1;
22 	}
23 
24 	if (length > 256) {
25 		errno = EIO;
26 		return -1;
27 	}
28 
29 	if (entropy == NULL || !device_is_ready(entropy)) {
30 		errno = EIO;
31 		return -1;
32 	}
33 
34 	/*
35 	 * getentropy() uses size_t to represent buffer size, but Zephyr uses
36 	 * uint16_t. The length check above allows us to safely cast without
37 	 * overflow.
38 	 */
39 	if (entropy_get_entropy(entropy, buffer, (uint16_t)length)) {
40 		errno = EIO;
41 		return -1;
42 	}
43 
44 	return 0;
45 }
46