同名全局变量造成的冲突

0x0 问题

程序运行时崩溃。

0x1 调试

经过调试发现,程序本身、和它所依赖的动态库里,有同名的全局变量,Loader 表示很凌乱。。

0x2 解决

默认链接生成动态库时,所有符号都会导出。对于这里的情况,只需要把导出符号定义清楚,就可以避免运行时的冲突。

Linux

使用 LD Version Scripts链接 1, 链接 2),在编译和链接生成动态库时,指定哪些是全局导出的符号,哪些是局部符号,比如:

{
    global:
        func_a;
        func_b;

    local:
        *;
};

然后在链接时添加类似于 LFLAGS += -Wl,--version-script=xxx.map 的参数。

Windows

对于 Windows 环境,可以定义类似功能的 def 文件,比如:

LIBRARY xxx

EXPORTS
    func_a
    func_b

然后在链接时添加类似于 ModuleDefinitionFile="xxx.def" 的参数。

0x3 查看导出符号

使用 nm 工具 查看:

# nm -C <module-name> | grep <name>
<addr> D <name>

使用 version script 并重新编译后:

# nm -C <module-name> | grep <name>
<addr> d <name>

其中的区别,是从 D 变成了 d。根据手册里的解释:

1. D: The symbol is in the initialized data section.
2. If lowercase, the symbol is local; if uppercase, the symbol is global (external).

Read More: