Skip to content
Tech News
← Back to articles

Memory Safe Context Switching

read original more articles
Why This Matters

The introduction of memory-safe support for context switching APIs like ucontext in Fil-C enhances the reliability and security of applications that rely on coroutines, fibers, and exception handling. By preventing common misuse errors such as stack corruption, this development benefits both developers and consumers by promoting safer, more stable software implementations in the C ecosystem.

Key Takeaways

Memory Safe Context Switching

Support for ucontext APIs is new since release 0.680. If you want to play with setcontext , getcontext , makecontext , and swapcontext then you have to build from source.

This document describes how Fil-C supports longjmp , setjmp , setcontext , getcontext , makecontext , and swapcontext in a totally memory-safe way. In particular, no misuse of those APIs in Fil-C can lead to stack corruption or any other violation of Fil-C's capability model.

These APIs are widely used:

longjmp and setjmp are used in C programs to implement exception handling. It's especially common to use them to implement exceptions "thrown" from signal handlers.

getcontext , setcontext , makecontext , and swapcontext (aka the ucontext APIs) are used to implement coroutines and fibers. For example, Boost uses ucontext as part of its fiber implementation.

The ucontext APIs are less commonly used than longjmp / setjmp and some OSes (like Darwin) have deprecated them. However, they remain well supported in glibc.

Implementing these APIs in a way that preserves memory safety is hard since their misuse can result in restoring a dangling stack. For example, you could either setjmp or getcontext within some function, and then do any of the following things:

Return from that function. At this point, the context that was saved will attempt to restore a stack frame that no longer exists.

Exit from the thread. At this point, the context that was saved will attempt to restore execution on a stack that has been freed.

... continue reading