GCC Signal Exceptions – Part 1

Fig. 1: proof-of-concept for handling segmentation fault signals in C as programmable exceptions

Signal Exceptions is a proof-of-concept extension to the C language with the goal of handling POSIX signals as programmable exceptions. This work is based on the GCC compiler and libgcc runtime for a Linux x86-64 platform. Only segmentation fault (SIGSEGV) signals are currently under the scope, but support for other signals can be added in the future using the same foundations. Source code and more documentation are available at end of this article.

With that said, I’ll briefly summarize some of the challenges and decisions taken while developing this project.

Continue reading “GCC Signal Exceptions – Part 1”

pthread_cancel and stack unwinding

Thread cancellation is a bit trickier than what one might expect. The reason is resources cleanup and maintaining a consistent state. Just as an example, a cancelled thread may need to unlock its mutex objects, free up memory, close file descriptors, delete named shared memory and the list can go on.

The idiom to make this work in pthread is cleanup handlers. These handlers work in a stack fashion, and can be pushed or popped at any time during run time. In case of thread cancellation by means of a call to pthread_cancel, handlers present in the stack will be automatically executed while the unwinding process occurs.

Here we have a piece of code showing how this API works:

Continue reading “pthread_cancel and stack unwinding”

Understanding the .gcc_except_table section in ELF binaries (GCC)

ELF binaries generated by the GCC compiler may contain a special section named .gcc_except_table, which is also known as LSDA (Language Specific Data Area). Despite of its name, it’s generated by GCC’s language-agnostic back-end and, thus, is language independent. In this article we will briefly describe it and answer when it is generated, what is in-there and how it is used.

.gcc_except_table section is related to exceptions in the sense of try-catch-finally control-flow blocks. Part of the information there is for handling the exception and the rest for cleanup code (i.e.: calling object destructors when the stack is unwinded).

In a nutshell, GCC language front-ends (such as C++) generate try-catch-finally nodes which are appended to the Abstract Syntax Tree (AST). These nodes are then transformed into back-end nodes and, after multiple passes, simplified into jumps and labels. Information about exception regions and landing pads is kept in annotations associated to each function.

Continue reading “Understanding the .gcc_except_table section in ELF binaries (GCC)”