Parent directory
Makefile
main-dlopen.c
main.c
mymalloc.c
sum.c
CC=gcc
CFLAGS=-Wall -fpic
main-dyn: main.o libsum.so
gcc -o main-dyn main.o libsum.so
main-no-pie: main.o libsum.so
gcc -no-pie -o main-no-pie main.o libsum.so
main-static-pie: main.o sum.o
gcc -static-pie -o main-static-pie main.o sum.o
main-static: main.o sum.o
gcc -static -o main-static main.o sum.o
libsum.so: sum.o
gcc -shared -o libsum.so sum.o
main.o sum.o:
.PHONY: clean
clean:
rm -f *.o *.so a.out main-dyn main-no-pie main-static-pie main-static
.PHONY: all
all: clean main-dyn
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
void *handle = dlopen("libsum.so", RTLD_LAZY);
if (!handle) {
fprintf(stderr, "%s\n", dlerror());
exit(1);
}
// clear any existing error
dlerror();
// declare func ptr to: long sum_array(long *p, int n);
long (*f)(long *p, int n);
f = dlsym(handle, "sum_array");
char *error = dlerror();
if (error != NULL) {
fprintf(stderr, "%s\n", error);
exit(1);
}
long a[5] = {0, 1, 2, 3, 4};
long sum = f(a, 5);
printf("sum=%ld\n", sum);
dlclose(handle);
}
#include <stdio.h>
long sum_array(long *p, int n);
int main() {
long a[5] = {0, 1, 2, 3, 4};
long sum = sum_array(a, 5);
printf("sum=%ld\n", sum);
}
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
/* malloc wrapper function */
void *malloc(size_t size)
{
void *(*mallocp)(size_t size);
char *error;
mallocp = dlsym(RTLD_NEXT, "malloc"); /* Get address of libc malloc */
if ((error = dlerror()) != NULL) {
fputs(error, stderr);
exit(1);
}
char *ptr = mallocp(size); /* Call libc malloc */
fputs("malloc wrapper called\n", stderr);
return ptr;
}
/* free wrapper function */
void free(void *ptr)
{
void (*freep)(void *) = NULL;
char *error;
if (!ptr) {
return;
}
freep = dlsym(RTLD_NEXT, "free"); /* Get address of libc free */
if ((error = dlerror()) != NULL) {
fputs(error, stderr);
exit(1);
}
freep(ptr); /* Call libc free */
fputs("free wrapper called\n", stderr);
}
long sum(long a, long b) {
return a + b;
}
long sum_array(long *p, int n) {
long s = 0;
for (int i = 0; i < n; i++) {
s = sum(s, p[i]);
}
return s;
}