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__