This project demonstrates how to wrap a C function -- specifically, printf(3)
.
Here's how it works:
-
WrappedLibc
exports aprintf
function whose prototype matches the one declared instdio.h
. -
WrappedLibc
'sprintf
callsdlsym
with the module handleRTLD_NEXT
to find the originalprintf
at runtime and invoke it with its own arguments. It can't invoke it with the original arguments becauseprintf
is variadic. So it creates ava_list
and callsvprintf
instead. -
WrappedLibc
'sOTHER_LDFLAGS
includes-sub_library libSystem
, which makeslibWrappedLibc.dylib
reexport all the symbols fromlibSystem
(to whichlibc
is an alias on OS X). -
WrapperTester
links againstlibWrappedLibc.dylib
. It does not link againstlibSystem
---LINK_WITH_STANDARD_LIBRARIES
is set toNO
. This causes it to look up all standard library functions as indirect symbols vialibWrappedLibc
.