Skip to content

Instantly share code, notes, and snippets.

@dentmaged
Last active February 26, 2021 02:29
Show Gist options
  • Save dentmaged/d3e3737003562ca32be929a2761a72db to your computer and use it in GitHub Desktop.
Save dentmaged/d3e3737003562ca32be929a2761a72db to your computer and use it in GitHub Desktop.
Mac OS X - Demo of a .dylib unloading itself
clang -shared -undefined dynamic_lookup -o init.dylib lib.c
gcc main.c -o main
#include <stdio.h>
#include <dlfcn.h>
char* getAddress(void) {
Dl_info info;
if (dladdr(getAddress, &info)) {
printf("Loaded from path = %s\n", info.dli_fname);
} else {
printf("Failed to get path!\n");
}
return info.dli_fname;
}
__attribute__((constructor)) void ctor(void) {
void* handle = dlopen(getAddress(), RTLD_NOW);
if (!handle) {
printf("Library handle could not be found!\n");
return;
}
printf("Closing handle\n");
int ret = dlclose(handle);
printf("Instances left: %d\n", ret);
}
#include <stdio.h>
#include <dlfcn.h>
int main(void) {
printf("Loading init.dylib\n");
void* handle = dlopen("init.dylib", RTLD_NOW);
return 0;
}
@anonymouz4
Copy link

Doesn't work for me. Dladdr gets the right dylib path, and dlclose return 0, but it doesn't get unloaded when called from itself

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment