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

FUT*_*CH6 2 c linux gcc system-calls linux-kernel

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

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;
}
Run Code Online (Sandbox Code Playgroud)

和另一个程序(细节省略)来捕捉系统调用,但后来我发现所有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!
Run Code Online (Sandbox Code Playgroud)

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

use*_*777 5

您通过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);
}
Run Code Online (Sandbox Code Playgroud)

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

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

  • 是的,openat 可能会在某个时候被 openat2 取代。open(2) 库 API 是在较新的系统上通过 openat 实现的(以及通过克隆 fork(2) 等)。您应该查看 [uapi/asm/unistd.h](https://github.com/torvalds/linux/blob/master/include/uapi/asm-generic/unistd.h) 以获取当前“非-legacy”系统调用,新架构应该实现。随着新接口的添加和改进,旧的接口将从该列表中删除,同时保留现有架构上的入口点以与现有用户空间程序兼容。 (2认同)