Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify "__cxa_allocate_exception" that no malloc is used

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:

  • Using a static buffer, which will lead to problems in multitask / multicore applications, so I can not do that.
  • Writing on the heap will also cause some trouble because the heap might be full (Out of memory throw wont work).
  • Finally, maybe I could allocate (for example) 16kb of the task stack space and every exception object will have a constant size of 1kb. That way, I can handle up to 16 exceptions. My understanding of the stack is sadly to low, to rate it, if it makes any sense or is even possible.
like image 715
xMutzelx Avatar asked Mar 16 '17 10:03

xMutzelx


2 Answers

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++.

like image 73
Brett Hale Avatar answered Sep 23 '22 16:09

Brett Hale


We released an open source library which implements an memory pool for exception handling: https://github.com/ApexAI/static_exception

like image 25
Andreas Pasternak Avatar answered Sep 22 '22 16:09

Andreas Pasternak