target : mock (main.c) without modified any original file (work.a)
objcopy work.a --add-symbol _real_test1=.text:00000000000126ed,weak --weaken work.a
00000000000126ed is test1 address by command (nm work.a)
override function and call real function in main.c without original file
it can work
#work.a
void test1(){
printf("old");
}
void test2(){
test1();
}
#main.c
int real_flag=0;
void test1(){
if(real_flag){
_real_test1();
}else{
printf("new");
}
}
int main(){
test2();//print new
real_flag=1;
test2();//print old
}
question : how can I make mutiple real_function
ex: test1,__real_test1 test2,__real_test2...
or other method to mock function
fail to try
fail to try: becuse it need modify original file work.a
void _real_test1() __attribute__((alias("test1")));
fail to try: becuse it just modify function name but not mock function
objcopy --redefine-syms
fail to try: becuse it just work in main.c,it still call old test1 in work.a
gcc -Wl,--wrap=test1
create mock function override test1 function
load real function by shared library