简体   繁体   中英

Preinitialized function pointers in compiled binary?

I am currently trying to understand the translation of some simple C-Code into assembly by the clang compiler. However the following behaviour is confusing to me:

int a(void);
int b(void);

int a() {
    return 1;
}

int b() {
    return 2;
}
int c(){
    return 3;
}

int main(int argc, char **argv) {
     int (*procs[])(void) = {a,b};
     int (*procs2[])(void) = {c,b};
...

gets translated to:

在此处输入图片说明 I figured out that the values at the addresses 0x4006XX hold the respective addresses of functions a, b and c. However I wonder why this extra step of using the 0x4006XX addresses is necessary (why not just use the literal address?). And even more curious as to why it uses two different addresses for the address of b. I know this is probably an obscure question but any help is appreciated :)

It appears that your compiler generates position independent code. Position independent code can be loaded to an arbitrary address at runtime, making the addresses of functions and static variables unpredictable at compile time. The one thing that is predictable is the distance from the variable or function to the current instruction. The compiler uses the lea instruction to add the content of rip , the instruction pointer, to this distance to get the actual address. That's what you are seeing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM