ladybird/Kernel/Syscalls/pipe.cpp
Andreas Kling b6d0636656 Kernel: Don't leak file descriptors in sys$pipe()
If the final copy_to_user() call fails when writing the file descriptors
to the output array, we have to make sure the file descriptors don't
remain in the process file descriptor table. Otherwise they are
basically leaked, as userspace is not aware of them.

This matches the behavior of our sys$socketpair() implementation.
2022-08-16 20:35:32 +02:00

62 lines
1.8 KiB
C++

/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <Kernel/FileSystem/FIFO.h>
#include <Kernel/Process.h>
namespace Kernel {
ErrorOr<FlatPtr> Process::sys$pipe(Userspace<int*> pipefd, int flags)
{
VERIFY_NO_PROCESS_BIG_LOCK(this)
TRY(require_promise(Pledge::stdio));
// Reject flags other than O_CLOEXEC, O_NONBLOCK
if ((flags & (O_CLOEXEC | O_NONBLOCK)) != flags)
return EINVAL;
u32 fd_flags = (flags & O_CLOEXEC) ? FD_CLOEXEC : 0;
auto fifo = TRY(FIFO::try_create(uid()));
ScopedDescriptionAllocation reader_fd_allocation;
ScopedDescriptionAllocation writer_fd_allocation;
TRY(m_fds.with_exclusive([&](auto& fds) -> ErrorOr<void> {
reader_fd_allocation = TRY(fds.allocate());
writer_fd_allocation = TRY(fds.allocate());
return {};
}));
auto reader_description = TRY(fifo->open_direction(FIFO::Direction::Reader));
auto writer_description = TRY(fifo->open_direction(FIFO::Direction::Writer));
reader_description->set_readable(true);
writer_description->set_writable(true);
if (flags & O_NONBLOCK) {
reader_description->set_blocking(false);
writer_description->set_blocking(false);
}
TRY(m_fds.with_exclusive([&](auto& fds) -> ErrorOr<void> {
fds[reader_fd_allocation.fd].set(move(reader_description), fd_flags);
fds[writer_fd_allocation.fd].set(move(writer_description), fd_flags);
int fds_for_userspace[2] = {
reader_fd_allocation.fd,
writer_fd_allocation.fd,
};
if (copy_to_user(pipefd, fds_for_userspace, sizeof(fds_for_userspace)).is_error()) {
fds[reader_fd_allocation.fd] = {};
fds[writer_fd_allocation.fd] = {};
return EFAULT;
}
return {};
}));
return 0;
}
}