how to call sys_open rather than sys_openat when calling open

Viewed 835

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;
}

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!

here rax=257 means the sys_openat was called(for sys_open, rax=2)

1 Answers

You call via the syscall(2) wrapper: 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);
}

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.

On newer architectures, there may be no actual SYS_open system call at all.

Related