Skip to content

ftruncate on a writable fd fails when the file's mode lacks write bits #26709

@Ryan2026R

Description

@Ryan2026R

Version of emscripten/emsdk:

5.0.6

The write access is determined at open() time in POSIX: once a fd is opened O_WRONLY/O_RDWR, write() and ftruncate() must succeed regardless of the file's current mode bits. Under MEMFS, it seems that ftruncate() re-checks the mode via FS.nodePermissions(node, 'w') and fails with EACCES even though write() on the same fd succeeded.

Failing command line in full:

$ emcc -O0 -Wall ftrunc.c -o a.out.js
$ node a.out.js
write: ret=5 (expected 5)
ftruncate: ret=-1 errno=2

The same program on native Linux prints ftruncate: ret=0 errno=0.

Example code snippet:

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

int main(void) {
    mkdir("/tmp/xsv_test", 0755);
    int fd = open("/tmp/xsv_test/test_perm.txt",
                  O_WRONLY | O_CREAT | O_TRUNC, 0444); // read-only
    ssize_t w = write(fd, "hello", 5); // succeeds
    printf("write: ret=%zd (expected 5)\n", w);
    errno = 0;
    int ret = ftruncate(fd, 0); // fails on Emscripten MEMFS
    printf("ftruncate: ret=%d errno=%d\n", ret, errno);
    close(fd);
    return (ret == 0) ? 0 : 1;
}

Under -sNODERAWFS=1 the Node-backed ftruncate works correctly.

Metadata

Metadata

Assignees

No one assigned

    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