undefined reference
undefined reference

GNU C __attribute__

Written by bcopos on July 20, 2014.

The GNU C __attribute__ feature is a mechanism not many know but can be super useful. The mechanism allows you to attach various characteristics to a function declaration. For my purposes, I used the __attribute__ mechanism to add a signal handler for segmentation fault signals to an already built program.

To do this, we're going to use the __attribute__((constructor)) attribute in the function's header and we're going to add it to a simple function that calls signal . Here is an example:

                            void catch() __attribute__((constructor));
                            void catch() 
                            {
                                signal(SIGSEGV, handler);            
                            }
                            

Besides that function, we also need the handler function (i.e. signal ) which defines the behavior when the segmentaion fault signal is received. With these two functions, we can build a shared object and load it dynamically to a binary using the LD_PRELOAD environment variable. VOILA!

The __attribute__ directive has a number of other useful attributes besides "constructor". Definitely check them out if you have time!