Repository navigation
fs.ftruncate silently accepts negative offsets rather than failing with ERR_INVALID #35632
Description
Activity
Maybe removing
len = MathMax(0, len);would fix the issue, or by explicitly handling the negative value case before calling the internal method. Had experienced this issue, a week back ! I solved this by explicitly checking thelenbefore passing it down to theftruncateSync()What about adding this sort of a change?
- len = MathMax(0, len); + if (len < 0) { + throw new ERR_FS_FILE_TOO_SMALL(len); + } else if (len > kIoMaxLength) { + throw new ERR_FS_FILE_TOO_LARGE(len); + }
where,
ERR_FS_FILE_TOO_LARGEalready exists and we make a new error codeERR_FS_FILE_TOO_SMALLfor negative sizes and this is all aboutkIoMaxLength:
Lines 27 to 29 in 999e7d7
// Most platforms don't allow reads or writes >= 2 GB. // See https://github.com/libuv/libuv/pull/1501. const kIoMaxLength = 2 ** 31 - 1;
This would take care of both the upper and the lower limits for the allowed size inftruncate.Reacted by Narasimha Prasanna HN and Igor Luiz Halfeld- addedfsIssues and PRs related to file-system APIs and the fs module.Issues and PRs related to file-system APIs and the fs module.confirmed-bugIssues and PRs for confirmed bugs.Issues and PRs for confirmed bugs.
on Oct 14, 2020 I'm not familiar with node code but isn't there already the simple equivalent of
EINVAL? Is it a good idea to add more error codes?Node
8.xx.xxthrowsEINVALproperly for negative offset. Maybe there is no need to handle explicitly. Evenlen = MathMax(0, len)is not required. The internal system call itself terminates withEINVALwhen it sees negative offset. So no need to handle anything explicitly. If you check the source code of8.xx.xxthere is no explicit validation being done.Reacted by Sam Clegg and Darshan SenPR: #37483
- added a commit that references this issue
on Feb 23, 2021 - added a commit that references this issue
on Feb 28, 2021 - added a commit that references this issue
on Sep 4, 2021 - added a commit that references this issue
on May 22, 2026
fs.ftruncate and fd.ftruncateSync both silently ignore negative offsets:
node/lib/fs.js
Line 840 in 2cfdf28
This didn't always do behave like this.. looks like it was introduced in 8974df1
What steps will reproduce the bug?
What is the expected behavior?
The ftruncate POSIX function is described as returning EINVAL when given a negative offset:
https://linux.die.net/man/2/ftruncate
In emscripten we emulate a POSIX environment on top of the Web and on top of node and expect ftruncate to fail in the same way.
We can obviously add a check to our code as a workaround but this does seem like a bug in node.
What do you see instead?
Silently assumed
0length is what the caller really wants.