简体   繁体   English

有趣的GCC链接

[英]Interesting GCC Linking

I was playing around with symbols and function pointers recently and noticed that though the following code runs fine: 我最近在玩符号和函数指针,并注意到尽管以下代码运行良好:

#include <stdio.h>
int main(int argc, const char * argv[]) {
    printf("%p\n",printf); // <--this line makes it work
    int (*printfptr)(const char * restrict, ...);
    printfptr = 0x1001fe910;
    (*printfptr)("Hello world\n");
    return 0;
}

This does not: 这不是:

#include <stdio.h>
int main(int argc, const char * argv[]) {
    // printf("%p\n",printf); // <-- commenting this out breaks it
    int (*printfptr)(const char * restrict, ...);
    printfptr = 0x1001fe910;
    (*printfptr)("Hello world\n");
    return 0;
}

(EXC_BAD_ACCESS) (EXC_BAD_ACCESS)

How come dereferencing the exact same pointer causes issues when there is no reference to printf in the code? 当代码中没有引用printf时,为什么取消引用完全相同的指针会导致问题? Even this works fine: 即使这样也可以:

#include <stdio.h>    
int main(int argc, const char * argv[]) {
    int (*printfptr)(const char * restrict, ...);
    printfptr = 0x1001fe910;
    (*printfptr)("Hello world\n");
    return 0;
}
void *_ = printf; // <-- because of this

Why is this? 为什么是这样?

On shared objects (.so) the symbols are really resolved only at the moment of first use. 在共享对象(.so)上,仅在首次使用时才真正解析符号。 By default the linker sets the option -z lazy which tells: 缺省情况下,链接器设置选项-z lazy ,该选项告知:

       When generating an executable or shared  library,  mark  it  to
       tell  the  dynamic  linker to defer function call resolution to
       the point when the function is called  (lazy  binding),  rather
       than at load time.  Lazy binding is the default.

You can change that behaviour by providing option -z now . 您可以通过-z now提供选项-z now来更改该行为。

man ld for all gory details. man ld了解所有血腥细节。

EDIT: Resolving a symbol is done with dynamic link API on POSIX systems. 编辑:使用POSIX系统上的动态链接API可以解决符号。 Functions dlsym() , dlopen() , dlclose() and dlerror() defined in <dlfcn.h> . <dlfcn.h>定义的函数dlsym()dlopen()dlclose()dlerror() This edition added so that you can search for these names. 添加了此版本,以便您可以搜索这些名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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