Gcc – wrap a function in a closed archive

Here is the situation : you have a function in an archive but you do not have the source code. And you would like to change the behavior of this function or intercept the call to this function.

This is possible with gcc and the -Wl,-wrap linker options. Thanks to this option you can create a new function starting by __wrap_ followed by the function name. This function will be called instead of the original one. In the function you can decide to call the original function by using its name starting by __real_

Here is an example:

The initial function is :

void TD_SIGFOX_SetChannel ( int16_t channel )

This function is in a private archive.

We can create a new function :

void __wrap_TD_SIGFOX_SetChannel ( int16_t channel ) {
 tfp_printf("[info] in function SetChannel %d \r\n",channel);
 __real_TD_SIGFOX_SetChannel( channel );
}

This function will intercept the call to the original function and add a print message.

Now to link this wrapped function to the original one we need to add the linker options :

-Wl,-wrap,TD_SIGFOX_SetChannel
or
-Wl,--wrap=TD_SIGFOX_SetChannel

 

This entry was posted in Programming and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *