A quick thought experiment before getting to the question. Imagine someone is implementing std::malloc (say, one of the JEMalloc or TCMalloc folks). One of the very basic things they would need is the ability to know that the program will not call back into malloc once execution has entered the implementation of std::malloc.
For example,
void* malloc(...) {
auto lck = std::unique_lock{malloc_mutex};
// .. memory allocation business logic
}
Now if there is a signal in between the lock and the business logic for the allocation, we can deadlock if the signal handler calls back into std::malloc. It is not designed to be re-entrant, the C++ standard requires that a signal handler registered with std::signal does not call back into operator new (which can possibly call back into malloc, therefore it is required that a user-defined signal handler not call back into malloc if it is to be considered portable across all implementations of the language).
§[support.signal]p3
in the most recent version of the standard outlines this requirement
- An evaluation is signal-safe unless it includes one of the following:
a call to any standard library function, except for plain lock-free atomic operations and functions explicitly identified as signal-safe. [ Note: This implicitly excludes the use of new and delete expressions that rely on a library-provided memory allocator. — end note ]
However, the C++ standard seemingly says nothing about how function stacks are to be implemented for threads of execution (see this question: C++ threads stack address range), this means that a function dispatch within std::malloc's implementation might call into operator new
if the program is compiled with segmented stacks.
How can one possibly implement a function like std::malloc
in that case? If indeed, the C++ standard offers no such guarantees, then what does? How can we know that the implementation of a regular function goes through the regular stack allocation process (stack pointer increment)? Which standard (eg. ABI, compiler, POSIX) covers this?