Reading through my book Expert C Programming, I came across the chapter on function interpositioning and how it can lead to some serious hard to find bugs if done unintentionally.
The example given in the book is the following:
mktemp() { ... }
main() {
mktemp();
getwd();
}
mktemp(){ ... }
getwd(){ ...; mktemp(); ... }
According to the book, what happens in main()
is that mktemp()
(a standard C library function) is interposed by the implementation in my_source.c. Although having main()
call my implementation of mktemp()
is intended behavior, having getwd()
(another C library function) also call my implementation of mktemp()
is not.
Apparently, this example was a real life bug that existed in SunOS 4.0.3's version of lpr
. The book goes on to explain the fix was to add the keyword static
to the definition of mktemp()
in my_source.c; although changing the name altogether should have fixed this problem as well.
This chapter leaves me with some unresolved questions that I hope you guys could answer:
static
in front of all functions that we don't want to be exposed?Thanks for the help.
I should note that my question is not just aimed at interposing over standard C library functions, but also functions contained in other libraries, perhaps 3rd party, perhaps ones created in-house. Essentially, I want to catch any instance of interpositioning regardless of where the interposed function resides.
This is really a linker issue.
When you compile a bunch of C source files the compiler will create an object file for each one. Each .o file will contain a list of the public functions in this module, plus a list of functions that are called by code in the module, but are not actually defined there i.e. functions that this module is expecting some library to provide.
When you link a bunch of .o files together to make an executable the linker must resolve all of these missing references. This is the point where interposing can happen. If there are unresolved references to a function called "mktemp" and several libraries provide a public function with that name, which version should it use? There's no easy answer to this and yes odd things can happen if the wrong one is chosen
So yes, it's a good idea in C to "static" everything unless you really do need to use it from other source files. In fact in many other languages this is the default behavior and you have to mark things "public" if you want them accessible from outside.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With