I am working in an safe embedded system, and I want to modify the exception handling a bit. __cxa_allocate_exception is using malloc() to allocate memory for the exception object. malloc/new is not allowed in safe applications, so I have to rewrite it.
Now my question: Is there a way to avoid malloc in this case?
Some alternatives would be:
Have a look at: gcc-6.3.0/libstdc++-v3/libsupc++/eh_alloc.cc (or a later version). A pool (memory) class is specified and instantiated as emergency_pool in an anonymous namespace. You could tweak the EMERGENCY macro values, or replace the implementation entirely - as long as you account for thread-safety in using the pool.
If you have prior knowledge of your call stack depth, you could fix values for the pool buffer that will always be sufficient. Again, you may need sync primitives here for thread-safety.
In the event that this isn't enough, __cxa_allocate_exception calls std::terminate if allocation fails. Here's where std::set_terminate might provide you with a last chance of salvaging critical info.
For thread-safety, use the same __gnu_cxx::__mutex object as the pool does, along with the __gnu_cxx::__scoped_lock idiom. That way you're not relying on anything libsupc++ doesn't rely on, like the standard library atomics or std::mutex, or std::lock_guard - i.e., creating a dependency on libstdc++.
We released an open source library which implements an memory pool for exception handling: https://github.com/ApexAI/static_exception
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With