On MacOS Ventura, obtaining a handle to the dynamic loader using dlopen(NULL, 0) returns a handle containing the entire executable's symbol table. Using this handle, one can obtain pointers to symbol data, access and modify their contents, and these changes will permeate across the program. However, attempting this with functions pointers does not work the same way.
For example, the following code:
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
int my_var = 0;
int main() {
void *handle = dlopen(NULL, 0);
int *a = dlsym(handle, "my_var");
*a = 5;
printf("%d", my_var);
return 0;
}
will print 5 instead of 0. However, when attempting something similiar with function pointers:
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
typedef void (*ftype)(void);
void fun1() {
printf("a");
}
void fun2() {
printf("b");
}
int main() {
void *handle = dlopen(NULL, 0);
ftype f1ptr;
*(void **)(&f1ptr) = dlsym(handle, "fun1");
f1ptr = fun2;
fun1();
return 0;
}
will print a instead of b. Is there anyway to perform an operation similar to the first code segment with function pointers? Essentially, I would like fun1 to now point to the code that fun2 points to. Swapping f1ptr's type to "ftype *" and then performing "*f1ptr = fun2" causes a bus fault.
my_var, not the address of it. Since the code offun1is read-only, you cannot change it. -- So, what do you really want to achieve? Please note that the callfun1()does not use the entry in the symbol table to find the entry point.