1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
use super::*;
use libc::{
c_uint,
memfd_create,
MFD_CLOEXEC,
MFD_HUGETLB,
ftruncate,
};
use std::{
ffi::CStr,
borrow::{
Borrow,
BorrowMut,
},
ops,
};
use hugetlb::{
MapHugeFlag,
HugePage,
};
static UNNAMED: &'static CStr = unsafe {
CStr::from_bytes_with_nul_unchecked(b"<unnamed memory file>\0")
};
const DEFAULT_FLAGS: c_uint = MFD_CLOEXEC;
#[inline(always)]
pub unsafe fn create_raw(name: impl AsRef<CStr>, flags: c_uint) -> io::Result<UnmanagedFD>
{
UnmanagedFD::new_raw(memfd_create(name.as_ref().as_ptr(), flags)).ok_or_else(|| io::Error::last_os_error())
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct MemoryFile(ManagedFD);
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct NamedMemoryFile(Box<CStr>, MemoryFile);
impl Borrow<MemoryFile> for NamedMemoryFile
{
#[inline]
fn borrow(&self) -> &MemoryFile {
&self.1
}
}
impl BorrowMut<MemoryFile> for NamedMemoryFile
{
#[inline]
fn borrow_mut(&mut self) -> &mut MemoryFile {
&mut self.1
}
}
impl ops::DerefMut for NamedMemoryFile
{
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.1
}
}
impl ops::Deref for NamedMemoryFile
{
type Target = MemoryFile;
#[inline]
fn deref(&self) -> &Self::Target {
&self.1
}
}
impl MemoryFile
{
pub fn new() -> io::Result<Self>
{
let managed = unsafe {
match memfd_create(UNNAMED.as_ptr(), DEFAULT_FLAGS) {
-1 => return Err(io::Error::last_os_error()),
fd => ManagedFD::take_unchecked(fd),
}
};
Ok(Self(managed))
}
#[inline]
pub fn resize(&mut self, value: usize) -> io::Result<()>
{
if 0 == unsafe { ftruncate(self.as_raw_fd(), value.try_into().map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?) } {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
pub fn with_hugetlb(hugetlb: MapHugeFlag) -> io::Result<Self>
{
unsafe { create_raw(UNNAMED, DEFAULT_FLAGS | (hugetlb.get_mask() as c_uint)) }
.map(ManagedFD::take)
.map(Self)
}
pub fn with_size(size: usize) -> io::Result<Self>
{
let mut this = Self(unsafe { create_raw(UNNAMED, DEFAULT_FLAGS) }.map(ManagedFD::take)?);
this.resize(size)?;
Ok(this)
}
#[inline]
pub fn with_size_hugetlb(size: usize, hugetlb: MapHugeFlag) -> io::Result<Self>
{
let mut this = Self::with_hugetlb(hugetlb)?;
this.resize(size)?;
Ok(this)
}
}
fn alloc_cstring(string: &str) -> std::ffi::CString
{
#[cold]
fn _contains_nul(mut bytes: Vec<u8>) -> std::ffi::CString
{
let len = unsafe {
memchr::memchr(0, &bytes[..]).unwrap_unchecked()
};
bytes.truncate(len);
unsafe {
std::ffi::CString::from_vec_with_nul_unchecked(bytes)
}
}
let mut bytes = Vec::with_capacity(string.len()+1);
bytes.extend_from_slice(string.as_bytes());
bytes.push(0);
match std::ffi::CString::from_vec_with_nul(bytes) {
Ok(v) => v,
Err(cn) => {
_contains_nul(cn.into_bytes())
}
}
}
impl NamedMemoryFile
{
#[inline]
pub fn new(name: impl AsRef<str>) -> io::Result<Self>
{
let name: Box<CStr> = alloc_cstring(name.as_ref()).into();
let managed = unsafe {
match memfd_create(name.as_ptr(), DEFAULT_FLAGS) {
-1 => return Err(io::Error::last_os_error()),
fd => ManagedFD::take_unchecked(fd),
}
};
Ok(Self(name, MemoryFile(managed)))
}
pub fn with_hugetlb(name: impl AsRef<str>, hugetlb: MapHugeFlag) -> io::Result<Self>
{
let name: Box<CStr> = alloc_cstring(name.as_ref()).into();
let memfd = MemoryFile(unsafe { create_raw(&name, DEFAULT_FLAGS | (hugetlb.get_mask() as c_uint)) }
.map(ManagedFD::take)?);
Ok(Self(name, memfd))
}
pub fn with_size(name: impl AsRef<str>, size: usize) -> io::Result<Self>
{
let name: Box<CStr> = alloc_cstring(name.as_ref()).into();
let mut this = MemoryFile(unsafe { create_raw(&name, DEFAULT_FLAGS) }.map(ManagedFD::take)?);
this.resize(size)?;
Ok(Self(name, this))
}
#[inline]
pub fn with_size_hugetlb(name: impl AsRef<str>, size: usize, hugetlb: MapHugeFlag) -> io::Result<Self>
{
let mut this = Self::with_hugetlb(name, hugetlb)?;
this.resize(size)?;
Ok(this)
}
}
impl AsRawFd for MemoryFile
{
#[inline]
fn as_raw_fd(&self) -> RawFd {
self.0.as_raw_fd()
}
}
impl FromRawFd for MemoryFile
{
#[inline]
unsafe fn from_raw_fd(fd: RawFd) -> Self {
Self(ManagedFD::from_raw_fd(fd))
}
}
impl IntoRawFd for MemoryFile
{
#[inline]
fn into_raw_fd(self) -> RawFd {
self.0.into_raw_fd()
}
}
impl From<MemoryFile> for ManagedFD
{
#[inline]
fn from(from: MemoryFile) -> Self
{
from.0
}
}
impl From<MemoryFile> for std::fs::File
{
#[inline]
fn from(from: MemoryFile) -> Self
{
from.0.into()
}
}