emscripten-core / emscripten-core/emscripten
ftruncate on a writable fd fails when the file's mode lacks write bits
- Dominant language
- C++
- Stars
- 27.6k
- Forks
- 3.6k
- Avg merge
- 1d 1h
- Merged PRs (30d)
- 105
Description
**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:**
```c
#include
#include
#include
#include
#include
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.
Contributor guide
Assessment
This issue has not been assessed yet.