gpt4 book ai didi

c - 调用open时如何调用sys_open而不是sys_openat

转载 作者:行者123 更新时间:2023-12-03 09:53:50 27 4
gpt4 key购买 nike

我写了一个代码来生成系统调用

void open_test(int fd, const char *filepath) {
if (fd == -1) {
printf("Open \"%s\" Failed!\n", filepath);
} else {
printf("Successfully Open \"%s\"!\n", filepath);
write(fd, "successfully open!", sizeof("successfully open!") - 1);
close(fd);
}
fflush(stdout);
}

int main(int argc, char const *argv[]) {
const char fp1[] = "whatever.txt", fp2[] = "./not-exist.txt";
int fd1 = open(fp1, O_CREAT | O_WRONLY | O_TRUNC, S_IRWXU);
int fd2 = open(fp2, O_WRONLY | O_TRUNC, S_IRWXU);
open_test(fd1, fp1);
open_test(fd2, fp2);
return 0;
}

和另一个程序(细节省略)来捕捉系统调用,但后来我发现所有的open()竟然调用了sys_openat而不是sys_open。

下面的文字是程序的输出:

Detect system call open, %rax is 257, Addr is 0x00007fefef78aec8, Pathname is /etc/ld.so.cache
Detect system call open, %rax is 257, Addr is 0x00007fefef78aec8, Pathname is /etc/ld.so.cache
Detect system call open, %rax is 257, Addr is 0x00007fefef993dd0, Pathname is /lib/x86_64-linux-gnu/libc.so.6
Detect system call open, %rax is 257, Addr is 0x00007fefef993dd0, Pathname is /lib/x86_64-linux-gnu/libc.so.6
Detect system call open, %rax is 257, Addr is 0x00007fffd44e38e3, Pathname is whatever.txt
Detect system call open, %rax is 257, Addr is 0x00007fffd44e38e3, Pathname is whatever.txt
Detect system call open, %rax is 257, Addr is 0x00007fffd44e38f0, Pathname is ./not-exist.txt
Detect system call open, %rax is 257, Addr is 0x00007fffd44e38f0, Pathname is ./not-exist.txt
Successfully Open "whatever.txt"!
Open "./not-exist.txt" Failed!

这里 rax=257 表示调用了 sys_openat(对于 sys_open,rax=2)

最佳答案

您通过 syscall(2) 包装器调用:syscall(SYS_open, ...):

#define _GNU_SOURCE
#include <unistd.h>
#include <fcntl.h>
#include <err.h>
#include <sys/syscall.h>

int main(void){
char *path = "whatever.txt";
int fd = syscall(SYS_open, path, O_RDONLY, 0);
if(fd == -1) err(1, "SYS_open %s", path);
}

但何必呢? SYS_openat 是现在规范的系统调用,open(2) 只是一个 API,SYS_open 系统调用入口只为后向二进制保留兼容性。

在较新的架构上,可能根本没有实际的 SYS_open 系统调用。

关于c - 调用open时如何调用sys_open而不是sys_openat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64084547/

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