Skip to content

Writing to an unlinked file causes errors #6128

@zebreus

Description

@zebreus

Describe the bug

Writing to a file descriptor of an unlinked file causes an error with the reason that the file does not exist. On POSIX systems this should work.

For temporary files it is a common pattern to create the temporary file, obtain a fd, unlink the path, and then just use the fd. For example python does it that way.

Steps to reproduce

Using the following test file

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>

int main() {
    int fd = open("/tmp/test.txt", O_CREAT | O_WRONLY | O_TRUNC, 0644);
    if (fd == -1) {
        perror("open");
        return 1;
    }
    printf("open succeeded\n");

    // 1. The file needs to be unlinked
    unlink("/tmp/test.txt");
    if (errno != 0) {
        perror("unlink");
        return 1;
    }
    printf("unlink succeeded\n");

    FILE* fp = fdopen(fd, "wr");
    if (fp == NULL) {
        perror("fdopen");
        return 1;
    }
    printf("fdopen succeeded\n");

    // 2. The write must be larger than 1024 bytes. Smaller writes succeed for some reason.
    char memory_buffer[1025];
    size_t n = fwrite(memory_buffer, 1, 1025, fp);
    if (ferror(fp)) {
        perror("fwrite");
        return 1;
    }
    printf("writing succeeded\n");

    close(fd);
    return 0;
}

with the above file stored as repro.c, run

wasixcc repro.c -o repro
cargo run -p wasmer-cli --features llvm,wasmer-artifact-create,static-artifact-create,wasmer-artifact-load,static-artifact-load -- ./repro

Expected behavior

The program exits with 0 and outputs:

open succeeded
unlink succeeded
fdopen succeeded
writing succeeded

Actual behavior

The program exits with 1 and outputs:

open succeeded
unlink succeeded
fdopen succeeded
fwrite: No such file or directory

Additional context

You can verify the expected behaviour by compiling and running it as native code.

clang repro.c -o repro.bin
./repro.bin

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions