Skip to content

Instantly share code, notes, and snippets.

@andreygursky
Created June 21, 2012 22:11
Show Gist options
  • Save andreygursky/2968897 to your computer and use it in GitHub Desktop.
Save andreygursky/2968897 to your computer and use it in GitHub Desktop.
simple test for memory allocation for global variables in dynamically loaded lib
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define __USE_GNU
#include <dlfcn.h> // Dl_info, dladdr()
#ifdef linux
#ifdef PATH_MAX
#define _MAX_PATH PATH_MAX
#else
#define _MAX_PATH 4096
#endif
#endif
static int *a;
void func(void)
{
a = (int*)malloc(1*sizeof(int));
printf("addr_a=%p, a=%d\n", a, *a);
*a = 111;
printf("new a=%d\n", *a);
free(a); // can be commented out
}
__attribute__((constructor))
void on_dlopen(void) {
char library_path[_MAX_PATH] = {0};
Dl_info dl_info;
dladdr(on_dlopen, &dl_info);
strcpy(library_path, dl_info.dli_fname);
printf("module %s opened\n", dl_info.dli_fname);
}
__attribute__((destructor))
void on_dlclose(void) {
char library_path[_MAX_PATH] = {0};
Dl_info dl_info;
dladdr(on_dlclose, &dl_info);
strcpy(library_path, dl_info.dli_fname);
printf("module %s closed\n", dl_info.dli_fname);
}
CC=gcc
CFLAGS=-Wall -g
all: libdl_func.so.1.0.0 test_dl
libdl_func.so.1.0.0: dl_func.o
rm -f libdl_func.so
rm -f libdl_func.so.1
$(CC) -o $@ $^ -shared -Wl,-soname,libdl_func.so.1
ln -s libdl_func.so.1.0.0 libdl_func.so
ln -s libdl_func.so.1.0.0 libdl_func.so.1
dl_func.o: dl_func.c
$(CC) $(CFLAGS) -fPIC -c $<
test_dl: test_dl.o
$(CC) -o $@ $^ -ldl
test_dl.o: test_dl.c
$(CC) $(CFLAGS) -c $<
clean:
rm -f libdl_func.so.1.0.0 libdl_func.so.1 libdl_func.so dl_func.o test_dl.o test_dl
module ./libdl_func.so.1.0.0 opened
addr_a=0x86523b0, a=0
new a=111
module ./libdl_func.so.1.0.0 closed
module ./libdl_func.so.1.0.0 opened
addr_a=0x86523b0, a=0
new a=111
module ./libdl_func.so.1.0.0 closed
to continue press ENTER
------------------------------------
or if free(a) is commented out:
module ./libdl_func.so.1.0.0 opened
addr_a=0x8e093b0, a=0
new a=111
module ./libdl_func.so.1.0.0 closed
module ./libdl_func.so.1.0.0 opened
addr_a=0x8e093c0, a=0
new a=111
module ./libdl_func.so.1.0.0 closed
// run: LD_LIBRARY_PATH=. ./test_dl
#include <stdio.h>
#include <dlfcn.h>
typedef void (*Func)(void);
const char *filename = "libdl_func.so.1.0.0";
int main(int argc, char *argv[], char **env)
{
void *plugin_handle;
int i;
for (i = 0; i < 2; i++) {
plugin_handle = dlopen(filename, RTLD_LAZY);
if (!plugin_handle) {
printf("failed to load library!\n");
return 1;
}
Func func = (Func) dlsym(plugin_handle, "func");
func();
dlclose(plugin_handle);
}
printf("to continue press ENTER\n");
getchar();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment