通过其在 C 中的偏移量调用函数

Call Function By Its Offset In C

本文关键字:偏移量 调用 函数      更新时间:2023-10-16

我正在尝试动态加载具有dlopen的共享库,并通过其在库二进制文件中的偏移量调用非导出函数。但是,我无法弄清楚具体如何?不过我知道函数的签名。

void *lib_ref = dlopen("libany.so", RTLD_NOW | RTLD_GLOBAL);
if (lib_ref != NULL) {
const char *(*Ref_0000ABCC)(int *, const char *);
Ref_0000ABCC = dlsym(lib_ref, "0000ABCC");
if (Ref_0000ABCC != NULL) {
int ok;
Ref_0000ABCC(&ok, "Something");
} else {
// could not get reference
}
dlclose(lib_ref);
} else {
// could not load library
}

谁能帮忙?

编辑:我组装了下面的代码,它抛出Fatal signal 11 (SIGSEGV), code 1

void *lib_ref = dlopen("libany.so", RTLD_NOW | RTLD_GLOBAL);
if (lib_ref != NULL) {
Dl_info lib_info;
dladdr(lib_ref, &lib_info);
size_t lib_addr = (size_t) lib_info.dli_fbase;
size_t func_addr = lib_addr + 0x0000ABCC;
const char *(*Ref_0000ABCC)(int *, const char *) = (const char *(*)(int *, const char *))(func_addr);
if (Ref_0000ABCC != NULL) {
int ok;
const char *result = Ref_0000ABCC(&ok, "Something");
} else {
// could not find reference
}
dlclose(lib_ref);
} else {
// could not load library
}

如果您正在处理的库libany.so具有导出的符号,这可能很容易。如果库导出一个名为int some_exported_func(const char *)函数,您可以在IDA中检查偏移量(例如,(我们假设是0x000075AC。您正在寻找的功能根据 IDA0x0000ABCC。因此,现在您可以计算这两个偏移量之间的差异,在运行时找到命名函数,然后将该差异添加到其偏移量以获得所需的函数。

示例代码如下:

void *lib_ref = dlopen("libany.so", RTLD_NOW | RTLD_GLOBAL);
if (lib_ref != NULL) {
int (*func_named)(const char *) = dlsym(lib_ref, "some_exported_func");
if (func_named != NULL) {
Dl_info func_info;
dladdr(func_named, &func_info);
size_t addr_named = (size_t) func_info.dli_saddr;
int difference = 0x0000ABCC - 0x000075AC;
size_t addr_ABCC = addr_named + difference;
const char *(*func_ABCC)(int *, const char *) = (const char *(*)(int *, const char *))(addr_ABCC);
if (func_ABCC != NULL) {
int ok;
const char *result = func_ABCC(&ok, "Something");
} else {
// could not find reference
}
}
dlclose(lib_ref);
} else {
// could not load library
}