This is an automated email from the ASF dual-hosted git repository. GUIDINGLI pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/nuttx.git
commit 0c2376fa74f16d61307319ac543b9be11f4d4a17 Author: Marco Casaroli <[email protected]> AuthorDate: Sun Nov 15 06:49:58 2026 +0100 libs/libc: Do not set errno in arc4random_buf(). arc4random_buf() read the random device with getrandom(), which sets errno when the open or the read fails. Thus kernel code that took random bytes, for example the first local port of a socket in bind(), changed the errno of the caller: ENOENT when /dev/random does not exist. In a kernel build errno is in the TLS of the caller, in user memory. Now arc4random_buf() opens and reads the device itself with the _NX_FILE macros. In the flat build and in the kernel copy of the protected and kernel builds they do not set errno. In the user copy of the protected and kernel builds they use open() and read(), as getrandom() did, so errno is set as before. The source of the bytes does not change. A read of 0 bytes now ends the loop with -EIO. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Marco Casaroli <[email protected]> --- libs/libc/stdlib/lib_arc4random.c | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/libs/libc/stdlib/lib_arc4random.c b/libs/libc/stdlib/lib_arc4random.c index 6c434f8ce7e..b1b760e69eb 100644 --- a/libs/libc/stdlib/lib_arc4random.c +++ b/libs/libc/stdlib/lib_arc4random.c @@ -25,13 +25,16 @@ ****************************************************************************/ #include <errno.h> +#include <fcntl.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <sys/param.h> #include <sys/random.h> #include <time.h> +#include <unistd.h> +#include <nuttx/fs/fs.h> #include <nuttx/hashtable.h> /**************************************************************************** @@ -42,26 +45,37 @@ static int getrandom_all(FAR void *buf, size_t size, int flags) { FAR char *tmp = buf; + _NX_FILE file; + ssize_t nread; + int ret; - while (size > 0) + ret = _NX_FILE_OPEN(&file, (flags & GRND_RANDOM) != 0 ? + "/dev/random" : "/dev/urandom", O_RDONLY, 0); + if (ret < 0) { - ssize_t ret = getrandom(tmp, size, flags); + return _NX_FILE_ERRVAL(ret); + } - if (ret < 0) + while (size > 0) + { + nread = _NX_FILE_READ(&file, tmp, size); + if (nread <= 0) { - if (get_errno() == EINTR) + ret = nread < 0 ? _NX_FILE_ERRVAL(nread) : -EIO; + if (ret == -EINTR) { continue; } - return ret; + break; } - tmp += ret; - size -= ret; + tmp += nread; + size -= nread; } - return 0; + _NX_FILE_CLOSE(&file); + return size > 0 ? ret : 0; } #endif
