好好活就是有意义的事,有意义的事就是好好活
linux手册翻译 dlsym(3)
linux手册翻译 dlsym(3)

linux手册翻译 dlsym(3)

\color{#A00000}{NAME}

dlsym, dlvsym – obtain address of a symbol in a shared object or executable

\color{#A00000}{SYNOPSIS}
#include <dlfcn.h>
void *dlsym(void *restrict handle, const char *restrict symbol);

#define _GNU_SOURCE
#include <dlfcn.h>
void *dlvsym(void *restrict handle, const char *restrict symbol,
             const char *restrict version);
Link with -ldl.

注意,我将手册中 shared object 译为了动态链接库

\color{#A00000}{DESCRIPTION}

函数dlsym(),以dlopen(3) 返回的动态加载的链接库“句柄”以及符号名为参数,返回该符号加载到内存中的地址。如果在指定的链接库或在加载该链接库时由 dlopen(3) 自动加载的任何其他链接库中都找不到此符号,则 dlsym() 将返回 NULL。(dlsym() 执行的搜索是通过这些共享对象的依赖关系树进行的广度优先搜索。)

在特殊的情况下(见NOTES),符号的值实际上可能是 NULL。 因此,从 dlsym() 返回 NULL 不一定表示错误。 区分错误和值为 NULL 的符号的正确方法是首先调用 dlerror(3) 清除所有旧的错误条件,然后在调用 dlsym(),最后再次调用 dlerror(3),检查最后一次dlerror(3)的值是否为 NULL。

在 handle 中可以指定两个特殊的伪句柄:

  • RTLD_DEFAULT
    Find the first occurrence of the desired symbol using the default shared object search order. The search will include global symbols in the executable and its dependencies, as well as symbols in shared objects that were dynamically loaded with the RTLD_GLOBAL flag.
  • RTLD_NEXT
    Find the next occurrence of the desired symbol in the search order after the current object. This allows one to provide a wrapper around a function in another shared object, so that, for example, the definition of a function in a preloaded shared object (see LD_PRELOAD in ld.so(8)) can find and invoke the “real” function provided in another shared object (or for that matter, the “next” definition of the function in cases where there are multiple layers of preloading).

必须定义 _GNU_SOURCE 功能测试宏,以便从 <dlfcn.h> 获取 RTLD_DEFAULT 和 RTLD_NEXT 的定义。

函数 dlvsym() 的作用与 dlsym() 相同,但将版本字符串作为附加参数。

\color{#A00000}{RETURN VALUE}

成功时,这些函数返回与符号关联的地址。 失败时,它们返回 NULL; 可以使用 dlerror(3) 诊断错误的原因。

\color{#A00000}{VERSIONS}

dlsym() is present in glibc 2.0 and later. dlvsym() first appeared in glibc 2.1.

\color{#A00000}{ATTRIBUTES}
InterfaceAttributeValue
dlsym(), dlvsym()Thread safetyMT-Safe
\color{#A00000}{CONFORMING TO}

POSIX.1-2001 描述了 dlsym()。 dlvsym() 函数是 GNU 扩展。

\color{#A00000}{NOTES}

There are several scenarios when the address of a global symbol is NULL. For example, a symbol can be placed at zero address by the linker, via a linker script or with –defsym command-line option. Undefined weak symbols also have NULL value. Finally, the symbol value may be the result of a GNU indirect function (IFUNC) resolver function that returns NULL as the resolved value. In the latter case, dlsym() also returns NULL without error. However, in the former two cases, the behavior of GNU dynamic linker is inconsistent: relocation processing succeeds and the symbol can be observed to have NULL value, but dlsym() fails and dlerror() indicates a lookup error.

History

dlsym() 函数是 dlopen API 的一部分,派生自 SunOS。 该系统没有 dlvsym()。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注