From 778fbfa82d33ae21efdb48d2dc7bce08db51f140 Mon Sep 17 00:00:00 2001 From: Tom Rebbert <109624508+trebbert-lutron@users.noreply.github.com> Date: Mon, 17 Oct 2022 19:57:50 -0600 Subject: [PATCH] [heap] move static heap construction to singleton accessor (#8242) Move static heap construction to singleton accessor to avoid non-trivial construction at global scope, which has an unpredictable ordering. --- src/core/common/instance.cpp | 15 ++++++++++++++- src/core/common/instance.hpp | 4 ++-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/core/common/instance.cpp b/src/core/common/instance.cpp index c93a510f5..f066da81c 100644 --- a/src/core/common/instance.cpp +++ b/src/core/common/instance.cpp @@ -50,7 +50,8 @@ OT_DEFINE_ALIGNED_VAR(gInstanceRaw, sizeof(Instance), uint64_t); #if OPENTHREAD_MTD || OPENTHREAD_FTD #if !OPENTHREAD_CONFIG_HEAP_EXTERNAL_ENABLE -Utils::Heap Instance::sHeap; +OT_DEFINE_ALIGNED_VAR(sHeapRaw, sizeof(Utils::Heap), uint64_t); +Utils::Heap *Instance::sHeap{nullptr}; #endif #if OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE bool Instance::sDnsNameCompressionEnabled = true; @@ -240,6 +241,18 @@ Instance::Instance(void) { } +#if (OPENTHREAD_MTD || OPENTHREAD_FTD) && !OPENTHREAD_CONFIG_HEAP_EXTERNAL_ENABLE +Utils::Heap &Instance::GetHeap(void) +{ + if (nullptr == sHeap) + { + sHeap = new (&sHeapRaw) Utils::Heap(); + } + + return *sHeap; +} +#endif + #if !OPENTHREAD_CONFIG_MULTIPLE_INSTANCE_ENABLE Instance &Instance::InitSingle(void) diff --git a/src/core/common/instance.hpp b/src/core/common/instance.hpp index 78e6d45e9..f03e8bee5 100644 --- a/src/core/common/instance.hpp +++ b/src/core/common/instance.hpp @@ -290,7 +290,7 @@ public: * @returns A reference to the Heap object. * */ - static Utils::Heap &GetHeap(void) { return sHeap; } + static Utils::Heap &GetHeap(void); #endif #if OPENTHREAD_CONFIG_COAP_API_ENABLE @@ -381,7 +381,7 @@ private: // Random::Manager is initialized before other objects. Note that it // requires MbedTls which itself may use Heap. #if !OPENTHREAD_CONFIG_HEAP_EXTERNAL_ENABLE - static Utils::Heap sHeap; + static Utils::Heap *sHeap; #endif Crypto::MbedTls mMbedTls; #endif // OPENTHREAD_MTD || OPENTHREAD_FTD