Created
February 3, 2024 17:52
-
-
Save akoskovacs/03bcaa7456e797c18b67d93265f5e6cc to your computer and use it in GitHub Desktop.
Monkey patching in C (Linux/Unix)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Let's redefine rand() by simply compiling creating an position-independent object code: | |
* $ gcc -c -fPIC libmyrand.c -o libmyrand.o | |
* | |
* Then create a shared library object from it: | |
* $ gcc libmyrand.o -shared -o libmyrand.so | |
* | |
* As a last step, load this dynamic library, so the dynamic linker will link this rand(), | |
* instead of the one inside the standard library: | |
* $ export LD_PRELOAD=./libmyrand.so | |
* | |
* After this every, program using rand() will be using our function. :) | |
*/ | |
int rand(void) | |
{ | |
return 4; // chosen by a fair dice roll. | |
} | |
// https://xkcd.com/221/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Compile this via: | |
* $ gcc myrandtest.c -o myrandtest | |
* | |
* Test the monkey patching, by setting and unsetting LD_PRELOAD as mentioned previously: | |
* $ ./myrandtest | |
* $ export LD_PRELOAD=./libmyrand.so | |
* $ ./myrandtest | |
*/ | |
#include <stdio.h> | |
#include <time.h> | |
#include <stdlib.h> | |
int main(int argc, char *argv[]) | |
{ | |
printf("Seeding by time...\n"); | |
srand(time(NULL)); | |
int i; | |
for (i = 0; i < 10; i++) { | |
printf("%d\n", (int)rand()); | |
} | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment