| 1 |
// SPDX-License-Identifier: MPL-2.0 |
| 2 |
// (c) Hare authors <https://harelang.org> |
| 3 |
|
| 4 |
use errors; |
| 5 |
use io; |
| 6 |
use rt; |
| 7 |
|
| 8 |
// Flags for [[memfd]]. |
| 9 |
export type memfd_flag = enum uint { |
| 10 |
NONE = 0, |
| 11 |
// Unsets the close-on-exec flag when creating a memfd. |
| 12 |
NOCLOEXEC = 1, |
| 13 |
// Allows sealing operations on this file. |
| 14 |
ALLOW_SEALING = 2, |
| 15 |
}; |
| 16 |
|
| 17 |
// Creates a new anonymous [[io::file]] backed by memory. |
| 18 |
// |
| 19 |
// The initial file size is zero. It can be written to normally, or the size can |
| 20 |
// be set manually with [[io::trunc]]. |
| 21 |
// |
| 22 |
// This function is available on Linux and FreeBSD. |
| 23 |
export fn memfd( |
| 24 |
name: str, |
| 25 |
flags: memfd_flag = memfd_flag::NONE, |
| 26 |
) (io::file | errors::error) = { |
| 27 |
let oflag = rt::O_RDWR | rt::O_CLOEXEC; |
| 28 |
let shm_flag = rt::SHM_GROW_ON_WRITE; |
| 29 |
if (flags & memfd_flag::NOCLOEXEC != 0) { |
| 30 |
oflag &= ~rt::O_CLOEXEC; |
| 31 |
}; |
| 32 |
if (flags & memfd_flag::ALLOW_SEALING != 0) { |
| 33 |
shm_flag |= rt::SHM_ALLOW_SEALING; |
| 34 |
}; |
| 35 |
|
| 36 |
match (rt::shm_open(rt::SHM_ANON, oflag, 0, shm_flag, name)) { |
| 37 |
case let fd: int => |
| 38 |
return fd: io::file; |
| 39 |
case let err: rt::errno => |
| 40 |
return errors::errno(err); |
| 41 |
}; |
| 42 |
}; |