Skip to content

Instantly share code, notes, and snippets.

@SpotlightKid
Last active January 12, 2026 10:34
Show Gist options
  • Select an option

  • Save SpotlightKid/dbe9ea0857b6a825b7b8777bea84bdd2 to your computer and use it in GitHub Desktop.

Select an option

Save SpotlightKid/dbe9ea0857b6a825b7b8777bea84bdd2 to your computer and use it in GitHub Desktop.
Test dynamic library loading and (de-) initialisation
/*
* Test program for https://github.com/nim-lang/Nim/issues/21403
*
* Build: make LDFLAGS="-ldl" CFLAGS="-g -O0" lib_loader
*
* Run: heaptrack lib_loader libmylib.so [<iterations>]
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <dlfcn.h>
static int parse_loop_count(int argc, char** argv) {
long loops = 100; // default
if (argc >= 3) {
char* end = NULL;
loops = strtol(argv[2], &end, 10);
if (end == argv[2] || *end != '\0' || loops <= 0 || loops > INT_MAX) {
fprintf(stderr, "Invalid loop count '%s', using default 100\n", argv[2]);
loops = 100;
}
}
return (int)loops;
}
int main(int argc, char** argv) {
if (argc < 2) {
fprintf(stderr, "Usage: %s /path/to/library.so [loop_count]\n", argv[0]);
return 1;
}
const char* lib_path = argv[1];
int loops = parse_loop_count(argc, argv);
printf("Running %d iterations...\n", loops);
for (int i = 0; i < loops; ++i) {
void* so = dlopen(lib_path, RTLD_NOW | RTLD_LOCAL);
if (!so) {
fprintf(stderr, "dlopen failed: %s\n", dlerror());
return 2;
}
dlerror(); // Clear errors
typedef void (*init_fn_t)(void);
typedef void (*deinit_fn_t)(void);
init_fn_t init_fn = (init_fn_t)dlsym(so, "dynlib_init");
const char* err = dlerror();
if (err || !init_fn) {
fprintf(stderr, "dlsym('dynlib_init') failed: %s\n", err ? err : "symbol not found");
dlclose(so);
return 3;
}
dlerror();
deinit_fn_t deinit_fn = (deinit_fn_t)dlsym(so, "dynlib_deinit");
err = dlerror();
if (err || !deinit_fn) {
fprintf(stderr, "dlsym('dynlib_deinit') failed: %s\n", err ? err : "symbol not found");
dlclose(so);
return 4;
}
init_fn();
deinit_fn();
// Unload shared library
dlclose(so);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment