2021-01-16 16:18:58 +00:00
|
|
|
/*
|
2024-10-04 11:19:50 +00:00
|
|
|
* Copyright (c) 2021, Andreas Kling <andreas@ladybird.org>
|
2021-01-16 16:18:58 +00:00
|
|
|
*
|
2021-04-22 08:24:48 +00:00
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
2021-01-16 16:18:58 +00:00
|
|
|
*/
|
|
|
|
|
2021-11-06 00:20:51 +00:00
|
|
|
#include <AK/Try.h>
|
2021-01-16 16:18:58 +00:00
|
|
|
#include <LibCore/AnonymousBuffer.h>
|
2022-02-08 09:42:15 +00:00
|
|
|
#include <LibCore/System.h>
|
2021-01-16 16:18:58 +00:00
|
|
|
#include <LibIPC/File.h>
|
|
|
|
#include <fcntl.h>
|
|
|
|
#include <sys/mman.h>
|
|
|
|
|
|
|
|
namespace Core {
|
|
|
|
|
2021-11-06 00:20:51 +00:00
|
|
|
ErrorOr<AnonymousBuffer> AnonymousBuffer::create_with_size(size_t size)
|
2021-01-16 16:18:58 +00:00
|
|
|
{
|
2022-02-08 09:42:15 +00:00
|
|
|
auto fd = TRY(Core::System::anon_create(size, O_CLOEXEC));
|
2021-01-16 16:18:58 +00:00
|
|
|
return create_from_anon_fd(fd, size);
|
|
|
|
}
|
|
|
|
|
2021-11-06 00:20:51 +00:00
|
|
|
ErrorOr<NonnullRefPtr<AnonymousBufferImpl>> AnonymousBufferImpl::create(int fd, size_t size)
|
2021-01-16 16:18:58 +00:00
|
|
|
{
|
2023-09-01 07:53:12 +00:00
|
|
|
auto* data = mmap(nullptr, round_up_to_power_of_two(size, PAGE_SIZE), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
|
2021-11-06 00:20:51 +00:00
|
|
|
if (data == MAP_FAILED)
|
2021-11-06 09:34:14 +00:00
|
|
|
return Error::from_errno(errno);
|
2021-11-06 00:20:51 +00:00
|
|
|
return AK::adopt_nonnull_ref_or_enomem(new (nothrow) AnonymousBufferImpl(fd, size, data));
|
2021-01-16 16:18:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
AnonymousBufferImpl::~AnonymousBufferImpl()
|
|
|
|
{
|
|
|
|
if (m_fd != -1) {
|
|
|
|
auto rc = close(m_fd);
|
2021-02-23 19:42:32 +00:00
|
|
|
VERIFY(rc == 0);
|
2021-01-16 16:18:58 +00:00
|
|
|
}
|
|
|
|
auto rc = munmap(m_data, round_up_to_power_of_two(m_size, PAGE_SIZE));
|
2021-02-23 19:42:32 +00:00
|
|
|
VERIFY(rc == 0);
|
2021-01-16 16:18:58 +00:00
|
|
|
}
|
|
|
|
|
2021-11-06 00:20:51 +00:00
|
|
|
ErrorOr<AnonymousBuffer> AnonymousBuffer::create_from_anon_fd(int fd, size_t size)
|
2021-01-16 16:18:58 +00:00
|
|
|
{
|
2021-11-06 00:20:51 +00:00
|
|
|
auto impl = TRY(AnonymousBufferImpl::create(fd, size));
|
|
|
|
return AnonymousBuffer(move(impl));
|
2021-01-16 16:18:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
AnonymousBufferImpl::AnonymousBufferImpl(int fd, size_t size, void* data)
|
|
|
|
: m_fd(fd)
|
|
|
|
, m_size(size)
|
|
|
|
, m_data(data)
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|