Kernel: Validate ftruncate(fd, length) syscall inputs

- EINVAL if 'length' is negative
- EBADF if 'fd' is not open for writing
This commit is contained in:
Andreas Kling 2020-01-07 14:42:56 +01:00
parent bb9db9d430
commit 6a4b376021
Notes: sideshowbarker 2024-07-19 10:17:16 +09:00
2 changed files with 24 additions and 1 deletions

View File

@ -3424,10 +3424,13 @@ int Process::sys$rename(const char* oldpath, const char* newpath)
int Process::sys$ftruncate(int fd, off_t length)
{
if (length < 0)
return -EINVAL;
auto* description = file_description(fd);
if (!description)
return -EBADF;
// FIXME: Check that fd is writable, otherwise EINVAL.
if (!description->is_writable())
return -EBADF;
return description->truncate(length);
}

View File

@ -87,6 +87,24 @@ void test_read_past_eof()
ASSERT(rc == 0);
}
void test_ftruncate_readonly()
{
int fd = open("/tmp/trunctest", O_RDONLY | O_CREAT, 0666);
ASSERT(fd >= 0);
int rc;
EXPECT_ERROR_2(EBADF, ftruncate, fd, 0);
close(fd);
}
void test_ftruncate_negative()
{
int fd = open("/tmp/trunctest", O_RDWR | O_CREAT, 0666);
ASSERT(fd >= 0);
int rc;
EXPECT_ERROR_2(EINVAL, ftruncate, fd, -1);
close(fd);
}
int main(int, char**)
{
int rc;
@ -103,6 +121,8 @@ int main(int, char**)
test_read_from_writeonly();
test_write_to_readonly();
test_read_past_eof();
test_ftruncate_readonly();
test_ftruncate_negative();
return 0;
}