问题描述
我写了一个代码来生成系统调用
I write a code to generate system call
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.
and another program(details omitted) to catch the system call, but later I found all open()
turned out to call the sys_openat rather then sys_open.
以下文本是程序的输出:
The following text is the output of the program:
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)
here rax=257 means the sys_openat was called(for 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
系统调用条目仅保留用于向后二进制兼容性.
But why bother? SYS_openat
is the canonical system call now, open(2)
is just an API, and the SYS_open
system call entry is only kept for backward binary compatibility.
在较新的体系结构上,可能根本没有实际的SYS_open
系统调用.
On newer architectures, there may be no actual SYS_open
system call at all.
这篇关于调用open时如何调用sys_open而不是sys_openat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!