From 7f3642e05c6b59aa972ef3b2db3ac68d5475c287 Mon Sep 17 00:00:00 2001 From: Matthew Parkinson Date: Thu, 2 Dec 2021 10:39:44 +0000 Subject: [PATCH] Change external thread_alloc example. (#424) On Open Enclave having the `local_alloc` directly in thread-local storage was causing a crash. This changes the `local_alloc` to be indirected, and thus puts less pressure on the thread-local storage. The test also has deals with how to allocate before a thread-local storage has been established. --- .../thread_alloc_external.cc | 37 +++++++++++++++++-- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/src/test/func/thread_alloc_external/thread_alloc_external.cc b/src/test/func/thread_alloc_external/thread_alloc_external.cc index 832d400..bc0952e 100644 --- a/src/test/func/thread_alloc_external/thread_alloc_external.cc +++ b/src/test/func/thread_alloc_external/thread_alloc_external.cc @@ -20,19 +20,48 @@ using namespace snmalloc; class ThreadAllocExternal { public: + static Alloc*& get_inner() + { + static thread_local Alloc* alloc; + return alloc; + } + static Alloc& get() { - static thread_local Alloc alloc; - return alloc; + return *get_inner(); } }; #include +void allocator_thread_init(void) +{ + void* aptr; + { + // Create bootstrap allocator + auto a = snmalloc::ScopedAllocator(); + // Create storage for the thread-local allocator + aptr = a->alloc(sizeof(snmalloc::Alloc)); + } + // Initialize the thread-local allocator + ThreadAllocExternal::get_inner() = new (aptr) snmalloc::Alloc(); + ThreadAllocExternal::get().init(); +} + +void allocator_thread_cleanup(void) +{ + // Teardown the thread-local allocator + ThreadAllocExternal::get().teardown(); + // Need a bootstrap allocator to deallocate the thread-local allocator + auto a = snmalloc::ScopedAllocator(); + // Deallocate the storage for the thread local allocator + a->dealloc(ThreadAllocExternal::get_inner()); +} + int main() { setup(); - ThreadAlloc::get().init(); + allocator_thread_init(); auto& a = ThreadAlloc::get(); @@ -55,4 +84,6 @@ int main() a2->dealloc(r1); } + + allocator_thread_cleanup(); }