Luna/libos/src/SharedMemory.cpp
apio 73a7d4f2a1
All checks were successful
continuous-integration/drone/push Build is passing
wind+libui: Run wind as a separate user
2023-11-22 21:31:08 +01:00

78 lines
2.2 KiB
C++

/**
* @file SharedMemory.cpp
* @author apio (cloudapio.eu)
* @brief Create and map areas of memory shared between processes.
*
* @copyright Copyright (c) 2023, the Luna authors.
*
*/
#include <errno.h>
#include <luna/Alignment.h>
#include <os/File.h>
#include <os/SharedMemory.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
namespace os::SharedMemory
{
Result<u8*> create(StringView path, usize size)
{
int fd = shm_open(path.chars(), O_RDWR | O_CREAT | O_EXCL, 0660);
if (fd < 0)
{
int olderr = errno;
os::eprintln("os: could not create shared memory region: shm_open failed (%s) - %s", path,
strerror(olderr));
return err(olderr);
}
size = align_up<PAGE_SIZE>(size);
if (ftruncate(fd, size) < 0)
{
int olderr = errno;
os::eprintln("os: could not create shared memory region: ftruncate failed (%d, %zu) - %s", fd, size,
strerror(olderr));
shm_unlink(path.chars());
close(fd);
return err(olderr);
}
void* p = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (p == MAP_FAILED)
{
int olderr = errno;
os::eprintln("os: could not create shared memory region: mmap failed (%zu, %d) - %s", size, fd,
strerror(olderr));
shm_unlink(path.chars());
close(fd);
return err(olderr);
}
close(fd);
return (u8*)p;
}
Result<u8*> adopt(StringView path, usize size, bool delete_fs)
{
int fd = shm_open(path.chars(), O_RDWR, 0660);
if (delete_fs) shm_unlink(path.chars());
if (fd < 0) return err(errno);
void* p = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (p == MAP_FAILED)
{
int olderr = errno;
os::eprintln("os: could not adopt shared memory region: mmap failed (%zu, %d) - %s", size, fd,
strerror(olderr));
close(fd);
return 0;
}
close(fd);
return (u8*)p;
}
}