From cc5f1cfe9f257c56c7f27003a9e6c24814e85b3d Mon Sep 17 00:00:00 2001 From: Matthew Parkinson Date: Fri, 26 Mar 2021 16:28:41 +0000 Subject: [PATCH] Expose entropy on POSIX platforms This provides a common definition for many POSIX platforms. It can be disabled. --- src/pal/pal_haiku.h | 5 ++++- src/pal/pal_posix.h | 34 +++++++++++++++++++++++++++++++++- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/src/pal/pal_haiku.h b/src/pal/pal_haiku.h index 1b7cc1e..0fcb8a8 100644 --- a/src/pal/pal_haiku.h +++ b/src/pal/pal_haiku.h @@ -18,8 +18,11 @@ namespace snmalloc * Bitmap of PalFeatures flags indicating the optional features that this * PAL supports. * + * Disable the POSIX default implementation of Entropy as not supported on + * Haiku. */ - static constexpr uint64_t pal_features = PALPOSIX::pal_features; + static constexpr uint64_t pal_features = + PALPOSIX::pal_features & ~(Entropy); /** * Haiku requires an explicit no-reserve flag in `mmap` to guarantee lazy diff --git a/src/pal/pal_posix.h b/src/pal/pal_posix.h index 9e38c36..954cc06 100644 --- a/src/pal/pal_posix.h +++ b/src/pal/pal_posix.h @@ -12,6 +12,12 @@ #include #include #include +#if __has_include() +# include +#endif +#if __has_include() +# include +#endif extern "C" int puts(const char* str); @@ -113,7 +119,7 @@ namespace snmalloc * * POSIX systems are assumed to support lazy commit. */ - static constexpr uint64_t pal_features = LazyCommit; + static constexpr uint64_t pal_features = LazyCommit | Entropy; static constexpr size_t page_size = Aal::smallest_page_size; @@ -264,5 +270,31 @@ namespace snmalloc OS::error("Out of memory"); } + + /** + * Source of Entropy + * + * This is a default that works on many POSIX platforms. + */ + static uint64_t get_entropy64() + { + if constexpr (!pal_supports) + { + // Derived Pal does not provide entropy. + return 0; + } + else if constexpr (OS::get_entropy64 != get_entropy64) + { + // Derived Pal has provided a custom definition. + return OS::get_entropy64(); + } + else + { + uint64_t result; + if (getentropy(&result, sizeof(result)) != 0) + error("Failed to get system randomness"); + return result; + } + } }; } // namespace snmalloc