Last active
February 26, 2021 02:29
-
-
Save dentmaged/d3e3737003562ca32be929a2761a72db to your computer and use it in GitHub Desktop.
Mac OS X - Demo of a .dylib unloading itself
This file contains hidden or 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
clang -shared -undefined dynamic_lookup -o init.dylib lib.c | |
gcc main.c -o main |
This file contains hidden or 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
#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); | |
} |
This file contains hidden or 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
#include <stdio.h> | |
#include <dlfcn.h> | |
int main(void) { | |
printf("Loading init.dylib\n"); | |
void* handle = dlopen("init.dylib", RTLD_NOW); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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