Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

wrapper - How to wrap existing function in C

I am trying to wrap existing function.

below code is perfectly worked.

#include<stdio.h>

int __real_main();

int __wrap_main()
{
    printf("Wrapped main
");
    return __real_main();
}

int main()
{
    printf("main
");
    return 0;
}

command:

gcc main.c -Wl,-wrap,main

output:

Wrapped main
main

So i have changed main function with temp. my goal is to wrap temp() function.

Below is the code

temp.c

#include<stdio.h>

int temp();

int __real_temp();

int __wrap_temp()
{
    printf("Wrapped temp
");
    return __real_temp();
}

int temp()
{
    printf("temp
");
    return 0;
}

int main()
{
    temp();
    return 0;
}

command:

gcc temp.c -Wl,-wrap,temp

output:

temp

Wrapped temp is not printing. please guide me to wrap funciton temp.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The manpage for ld says:

   --wrap=symbol
       Use a wrapper function for symbol.  Any undefined reference to symbol will be resolved to "__wrap_symbol".  Any
       undefined reference to "__real_symbol" will be resolved to symbol.

The keyword here is undefined.

If you put the definition temp in the same translation unit as the code that uses it, it will not be undefined in the code that uses it.

You need to split the code definition and the code that uses it:

#!/bin/sh

cat > user.c  <<'EOF'
#include<stdio.h>

int temp(void);

int __real_temp(void);

int __wrap_temp()
{
    printf("Wrapped temp
");
    return __real_temp();
}
int main()
{
    temp();
    return 0;
}
EOF

cat > temp.c <<'EOF'
#include<stdio.h>
int temp()
{
    printf("temp
");
    return 0;
}
EOF


gcc user.c  -Wl,-wrap,temp temp.c  # OK
./a.out

Splitting the build into two separate compiles perhaps makes it clearer:

$ gcc -c user.c
$ gcc -c temp.c
$ nm user.o temp.o

temp.o:
                 U puts
0000000000000000 T temp

user.o:
0000000000000015 T main
                 U puts
                 U __real_temp
                 U temp
0000000000000000 T __wrap_temp

Now since temp is undefined in user.c, the linker can do its __real_/__wrap_magic on it.

$ gcc  user.o temp.o  -Wl,-wrap=temp
$ ./a.out
  Wrapped temp
  temp

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...