Skip to content

Instantly share code, notes, and snippets.

Created October 8, 2017 13:16
Show Gist options
  • Save anonymous/ecfd80885b9ddf6734192c056cf48bf4 to your computer and use it in GitHub Desktop.
Save anonymous/ecfd80885b9ddf6734192c056cf48bf4 to your computer and use it in GitHub Desktop.
Example (Appendix A-4, "Intercepting arbitrary functions ..."), tested on OSX 10.9
#!/usr/bin/env bash
# see also https://stackoverflow.com/questions/617554/override-a-function-call-in-c
# this script builds and runs Appendix A-4 example in:
# "Intercepting arbitrary functions on Windows, UNIX, and Macintosh OS X platforms", by Daniel S. Myers and Adam L. Bazinet, University of Maryland (2004)
THIS_SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
set -x
cd "$THIS_SCRIPT_DIR"
gcc -g -fno-common -c fopenwrap.c
gcc -dynamiclib -o libwrapper.dylib fopenwrap.o
gcc -g fopen.c -o fopentest.exe -L. -lwrapper
# create a file to be opened by fopentest.exe
cat > mytestfile.txt <<'EOF'
=== this is mytestfile.txt ===
Second line here...
Third line here...
EOF
DYLD_BIND_AT_LAUNCH=YES ./fopentest.exe ./mytestfile.txt
#include <stdio.h>
int main(int argc, char** argv) {
char buf[80];
FILE* fileptr = fopen(argv[1], "r");
do {
fgets(buf, 80, fileptr);
if (feof(fileptr)) {
break;
}
printf("%s", buf);
} while(1);
fclose(fileptr);
return 0;
}
// "Finally, we compile the test code and link it with the wrapper library:
// gcc fopen.c -o fopentest -L. -lwrapper
// Remember to set the DYLD_BIND_AT_LAUNCH environment variable when running the test code:
// DYLD_BIND_AT_LAUNCH=YES ./fopentest"
// "Once again, we wrap the fopen function. This example was tested on OS X 10.3.
// We use the same test code as before, in the file fopen.c. For the wrapper, we put the following in fopenwrap.c:"
#include <stdio.h>
#include <dlfcn.h>
FILE* fopen(const char *path, const char *mode)
{
printf("This is a wrapper function for fopen.\n");
FILE* (*real_fopen)(const char*, const char*) =
(FILE* (*)(const char*, const char*)) dlsym(RTLD_NEXT, "fopen");
return real_fopen (path, mode);
}
// "To compile the code, we issue the following two commands:
// gcc -fno-common -c fopenwrap.c
// gcc -dynamiclib -o libwrapper.dylib fopenwrap.o"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment