ziglang / zig

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
https://ziglang.org
MIT License
33.84k stars 2.48k forks source link

selfExeDir doesn't always work #2570

Open daurnimator opened 5 years ago

daurnimator commented 5 years ago

check that stack overflow link wink

I didn't see the answer in there. FWIW I tried it with the following C program:

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

char elf[] = {
#include "elf.xxd"
};

int main() {
    int fd = memfd_create("foo", MFD_CLOEXEC);
    if (fd==-1) return 1;
    if (write(fd, elf, sizeof elf) < 0) return 2;
    if (fd != 3) return 3;
    fd = open("/proc/self/fd/3", O_RDONLY);
    if (-1 == fd) return 4;
    if (-1 == close(3)) return 5;
    char *cmd[] = { "ls", "-l", "/proc/self/fd/", "/proc/self/exe", NULL };
    char *env[] = { NULL };
    if (-1 == fexecve(fd, cmd, env)) return 6;
    return 7;
}

Where elf.xxd is created with xxd -i < /usr/bin/ls > elf.xxd

And I see:

lrwxrwxrwx 1 root root 0 May 27 16:15 /proc/self/exe -> '/memfd:foo (deleted)'

/proc/self/fd:
total 0
lrwx------ 1 root root 64 May 27 16:15 0 -> /dev/pts/1
lrwx------ 1 root root 64 May 27 16:15 1 -> /dev/pts/1
lrwx------ 1 root root 64 May 27 16:15 2 -> /dev/pts/1
lr-x------ 1 root root 64 May 27 16:15 3 -> /proc/18364/fd
lr-x------ 1 root root 64 May 27 16:15 4 -> '/memfd:foo (deleted)'

Originally posted by @daurnimator in https://github.com/ziglang/zig/pull/2527

shawnl commented 5 years ago

/memfd:foo

What a horrible design decision on the behalf of Linux (and Lennart Poettering/Greg KH that overlooked kdbus that memfd came from).... There should be two forward slashes // so that this is not ambiguous....., or perhaps start with a null byte, but that can be problematic even if it is not ambiguous.