gpt4 book ai didi

c++ - __xstat 动态符号解决 64 位错误

转载 作者:太空宇宙 更新时间:2023-11-04 11:55:29 25 4
gpt4 key购买 nike

我正在尝试使用 dlopen 和 dlsym 动态加载 stat 函数。来自 stat 家族的函数被包装在相应的函数 __xstat, __xstat64 itp.

以下是代码片段,编译并在 32 位模式下编译时工作(包含 sys/stat.h 以获取 stat 结构作为示例)

#include <iostream>
#include <dlfcn.h>
#include <sys/stat.h>

typedef int (*xstat_f) (int __ver, const char *__filename, struct stat *__stat_buf);

int main()
{
auto* h = dlopen("libc.so.6", RTLD_LAZY);
if(!h)
{
return 1; // invalid handle
}

auto f = (xstat_f)dlsym(h, "__xstat");
if(!f)
{
return 1; // invalid handle
}

struct stat s = {};

const auto r = f(3, "/tmp", &s);

if (r != 0)
{
perror("stat");
return errno;
}

return 0;
}

g++ main.cpp -o main -ldl -m32

在 64 位机器上没有 -m32 开关编译的可执行文件返回 EINVAL(无效参数)。

这是什么原因?

我也做了一个最小的测试

#include <iostream>
#include <sys/stat.h>

int main(){
struct stat s;
const auto x = stat("/tmp", &s);
if(x != 0) return errno;
return 0;
}

并在 32 位和 64 位可执行文件上使用 objdump -T 显示 stat 被解析为 __xstat,所以我正在使用正确的符号。我还尝试了 __xstat/__xstat64struct stat/stat64 的组合,结果相同。

最佳答案

__xstat 声明如下:

int __xstat(int ver, const char *path, (struct stat *stat_buf))

在文档中参数 ver 被描述为 ver shall be 3 or the behavior of these functions is undefined ,这并不完全正确,因为在源代码中,_STAT_VER_LINUX 的定义如下:

#ifndef __x86_64__
# define _STAT_VER_LINUX 3
#else
# define _STAT_VER_LINUX 1
#endif

这就是为什么 __xstat调用 64 位失败,参数 ver在 32 位编译中应该设置为 1 和 3。

关于c++ - __xstat 动态符号解决 64 位错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54520101/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com