简体   繁体   English

获取被覆盖的弱符号的地址

[英]Getting the address of a overwritten weak symbol

My question assumes gcc or clang for x86 or x86_64.我的问题假设 x86 或 x86_64 的 gcc 或 clang。

Let's say I have the following files:假设我有以下文件:

// weak.c

#include <stdio.h>

__attribute__((weak))
void i_am_weak(void)
{
    printf("I am weak\n");
}

int main()
{
    i_am_weak();
    return 0;
}
// not_weak.c

#include <stdio.h>

void i_am_weak(void)
{
    printf("I am not weak\n");
}

If I compile just weak.c : cc weak.c -o weak and then I run it I get the message "I am weak".如果我只编译weak.c : cc weak.c -o weak然后我运行它,我会收到消息“我很弱”。 In turn, if I compile and link both: cc weak.c not_weak.c I get the message "I am not weak".反过来,如果我编译并链接两者: cc weak.c not_weak.c我会收到消息“我不弱”。 Which is to be expected.这是可以预料的。

Can I somehow obtain the address of the weak symbol?我能以某种方式获得弱符号的地址吗? Let's say that I want to invoke i_am_weak from weak.c from not_weak.c , similar to how I can use __real_i_am_weak from __wrap_i_am_weak when using the --wrap linker flag.比方说,我想要调用i_am_weakweak.cnot_weak.c ,类似于如何我可以使用__real_i_am_weak__wrap_i_am_weak使用时--wrap链接标志。

Can I somehow obtain the address of the weak symbol?我能以某种方式获得弱符号的地址吗?

The usual technique is to use a strong internal symbol, to which i_am_weak is a weak alias ( documentation ):通常的技术是使用强内部符号, i_am_weak是弱别名( 文档):

#include <stdio.h>

void i_am_internal(void)
{
    printf("I am weak\n");
}

void i_am_weak(void) __attribute__((weak, alias("i_am_internal"))) 

int main()
{
    i_am_weak();
    i_am_internal();
    return 0;
}
$ gcc weak.c && ./a.out
I am weak
I am weak

$ gcc weak.c not_weak.c && ./a.out
I am not weak
I am weak

You can now also take address of weak and non-weak symbols.您现在还可以获取弱符号和非弱符号的地址。

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

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