From 7b8f69404fbd524bd1155633f7fc0db302aa62ba Mon Sep 17 00:00:00 2001 From: Ivan Grokhotkov Date: Fri, 15 Dec 2023 13:50:48 +0100 Subject: [PATCH] feat(linux): provide getrandom implementation for macOS This makes getrandom(2) usable when compiling with IDF_TARGET=linux on a macOS host. --- components/linux/CMakeLists.txt | 7 ++++++- components/linux/getrandom.c | 28 +++++++++++++++++++++++++++ components/linux/include/sys/random.h | 15 ++++++++++++++ 3 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 components/linux/getrandom.c create mode 100644 components/linux/include/sys/random.h diff --git a/components/linux/CMakeLists.txt b/components/linux/CMakeLists.txt index b7d2bd46a7..e29218d213 100644 --- a/components/linux/CMakeLists.txt +++ b/components/linux/CMakeLists.txt @@ -3,5 +3,10 @@ if(NOT "${target}" STREQUAL "linux") return() endif() +if(CMAKE_HOST_SYSTEM_NAME STREQUAL "Darwin") + list(APPEND srcs getrandom.c) +endif() + idf_component_register(INCLUDE_DIRS include - REQUIRED_IDF_TARGETS linux) + REQUIRED_IDF_TARGETS linux + SRCS ${srcs}) diff --git a/components/linux/getrandom.c b/components/linux/getrandom.c new file mode 100644 index 0000000000..5f068ee3fd --- /dev/null +++ b/components/linux/getrandom.c @@ -0,0 +1,28 @@ +/* + * SPDX-FileCopyrightText: 2023 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "sys/random.h" +#include +#include +#include +#include + + +// getrandom() is not available on macOS, so we read from /dev/urandom instead. + +int getrandom(void *buf, size_t buflen, unsigned int flags) +{ + int fd = open("/dev/urandom", O_RDONLY); + if (fd < 0) { + return -1; + } + ssize_t ret = read(fd, buf, buflen); + close(fd); + if (ret < 0) { + return -1; + } + return 0; +} diff --git a/components/linux/include/sys/random.h b/components/linux/include/sys/random.h new file mode 100644 index 0000000000..b495f327bc --- /dev/null +++ b/components/linux/include/sys/random.h @@ -0,0 +1,15 @@ +/* + * SPDX-FileCopyrightText: 2023 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include_next "sys/random.h" + +#if __APPLE__ +#include + +int getrandom(void *buf, size_t buflen, unsigned int flags); + +#endif // __APPLE__