Skip to content

Instantly share code, notes, and snippets.

@shakna-israel
Created October 28, 2024 22:40
Show Gist options
  • Save shakna-israel/61a212517b1da57d460851accbc49576 to your computer and use it in GitHub Desktop.
Save shakna-israel/61a212517b1da57d460851accbc49576 to your computer and use it in GitHub Desktop.
dlopen'ing a program's own self.
#include <dlfcn.h>
#include <stdio.h>
double worker(double x) {
return x * 2;
}
int main(int argc, char* argv[]) {
void* self = dlopen(NULL, RTLD_NOW | RTLD_LOCAL);
if(!self || dlerror() != NULL) {
perror("dlopen");
return 1;
} else
{
printf("Loaded library: %p\n", self);
}
// Clear global load errors.
dlerror();
double (*thing)(double);
*(void **) (&thing) = dlsym(self, "worker");
if(!thing || dlerror() != NULL) {
perror("loading thing");
return 1;
} else {
printf("Run: %f\n", thing(12.1));
}
return 0;
}
huh: huh.c
gcc -Wall -pedantic -rdynamic huh.c -o huh -ldl -export-dynamic
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment