linux-support 0.0.25

Comprehensive Linux support for namespaces, cgroups, processes, scheduling, parsing /proc, parsing /sys, signals, hyper threads, CPUS, NUMA nodes, unusual file descriptors, PCI devices and much, much more
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
// This file is part of linux-support. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-support/master/COPYRIGHT. No part of linux-support, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2020 The developers of linux-support. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-support/master/COPYRIGHT.


/// A memfd, which wraps a File but supports sealing.
#[derive(Debug)]
pub struct MemoryFileDescriptor(File);

impl IntoRawFd for MemoryFileDescriptor
{
	#[inline(always)]
	fn into_raw_fd(self) -> RawFd
	{
		self.0.into_raw_fd()
	}
}

impl FromRawFd for MemoryFileDescriptor
{
	#[inline(always)]
	unsafe fn from_raw_fd(fd: RawFd) -> Self
	{
		Self(File::from_raw_fd(fd))
	}
}

impl AsRawFd for MemoryFileDescriptor
{
	#[inline(always)]
	fn as_raw_fd(&self) -> RawFd
	{
		self.0.as_raw_fd()
	}
}

impl FileDescriptor for MemoryFileDescriptor
{
}

impl MemoryMappableFileDescriptor for MemoryFileDescriptor
{
}

impl SeekableFileDescriptor for MemoryFileDescriptor
{
}

impl Read for MemoryFileDescriptor
{
	#[inline(always)]
	fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>
	{
		self.0.read(buf)
	}

	#[inline(always)]
	fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize>
	{
		Read::read_vectored(&mut self.0, bufs)
	}

	#[inline(always)]
	unsafe fn initializer(&self) -> Initializer
	{
		self.0.initializer()
	}
}

impl Seek for MemoryFileDescriptor
{
	#[inline(always)]
	fn seek(&mut self, pos: SeekFrom) -> io::Result<u64>
	{
		self.0.seek(pos)
	}
}

impl Write for MemoryFileDescriptor
{
	#[inline(always)]
	fn write(&mut self, buf: &[u8]) -> io::Result<usize>
	{
		self.0.write(buf)
	}

	#[inline(always)]
	fn write_vectored(&mut self, bufs: &[IoSlice]) -> io::Result<usize>
	{
		Write::write_vectored(&mut self.0, bufs)
	}

	#[inline(always)]
	fn flush(&mut self) -> io::Result<()>
	{
		Ok(())
	}

	#[inline(always)]
	fn write_all(&mut self, buf: &[u8]) -> io::Result<()>
	{
		self.0.write_all(buf)
	}

	#[inline(always)]
	fn write_fmt(&mut self, fmt: Arguments) -> io::Result<()>
	{
		self.0.write_fmt(fmt)
	}
}

impl FileExt for MemoryFileDescriptor
{
	#[inline(always)]
	fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize>
	{
		self.0.read_at(buf, offset)
	}

	#[inline(always)]
	fn read_exact_at(&self, buf: &mut [u8], offset: u64) -> io::Result<()>
	{
		self.0.read_exact_at(buf, offset)
	}

	#[inline(always)]
	fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize>
	{
		self.0.write_at(buf, offset)
	}

	#[inline(always)]
	fn write_all_at(&self, buf: &[u8], offset: u64) -> io::Result<()>
	{
		self.0.write_all_at(buf, offset)
	}
}

impl ExtendedSeek for MemoryFileDescriptor
{
}

#[allow(deprecated)]
impl AdvisoryWholeFileLocking for MemoryFileDescriptor
{
}

#[allow(deprecated)]
impl PerProcessAdvisoryFileRecordLocking for MemoryFileDescriptor
{
}

impl OpenFileDescriptionAdvisoryFileRecordLocking for MemoryFileDescriptor
{
}

impl CopyFileRange for MemoryFileDescriptor
{
}

impl Leasing for MemoryFileDescriptor
{
}

impl Into<File> for MemoryFileDescriptor
{
	#[inline(always)]
	fn into(self) -> File
	{
		self.0
	}
}

impl Deref for MemoryFileDescriptor
{
	type Target = File;

	#[inline(always)]
	fn deref(&self) -> &Self::Target
	{
		&self.0
	}
}

impl DerefMut for MemoryFileDescriptor
{
	#[inline(always)]
	fn deref_mut(&mut self) -> &mut Self::Target
	{
		&mut self.0
	}
}

impl AsRef<File> for MemoryFileDescriptor
{
	#[inline(always)]
	fn as_ref(&self) -> &File
	{
		&self.0
	}
}

impl AsMut<File> for MemoryFileDescriptor
{
	#[inline(always)]
	fn as_mut(&mut self) -> &mut File
	{
		&mut self.0
	}
}

impl Borrow<File> for MemoryFileDescriptor
{
	#[inline(always)]
	fn borrow(&self) -> &File
	{
		&self.0
	}
}

impl BorrowMut<File> for MemoryFileDescriptor
{
	#[inline(always)]
	fn borrow_mut(&mut self) -> &mut File
	{
		&mut self.0
	}
}

impl SpliceRecipient for MemoryFileDescriptor
{
}

impl SpliceSender for MemoryFileDescriptor
{
}

impl VectoredRead for MemoryFileDescriptor
{
	#[inline(always)]
	fn read_vectored(&self, buffers: &[&mut [u8]]) -> io::Result<usize>
	{
		self.0.read_vectored(buffers)
	}
}

impl VectoredWrite for MemoryFileDescriptor
{
	#[inline(always)]
	fn write_vectored(&self, buffers: &[&[u8]]) -> io::Result<usize>
	{
		self.0.write_vectored(buffers)
	}
}

impl SendFile for MemoryFileDescriptor
{
	#[inline(always)]
	fn write_output_from_file<F: AsRef<File>>(&self, from_file: &F, maximum_number_of_bytes_to_transfer: usize) -> Result<usize, StructWriteError>
	{
		self.0.write_output_from_file(from_file, maximum_number_of_bytes_to_transfer)
	}

	#[inline(always)]
	fn write_output_from_file_with_offset<F: AsRef<File>>(&self, from_file: &F, offset: i64, maximum_number_of_bytes_to_transfer: usize) -> Result<(usize, i64), StructWriteError>
	{
		self.0.write_output_from_file_with_offset(from_file, offset, maximum_number_of_bytes_to_transfer)
	}
}

impl MemoryFileDescriptor
{
	/// Opens a memfd.
	///
	/// There are two uses:-
	///
	/// * As an alternative to using `/tmp`, `tmpfs` or `O_TMPFILE` if there is no intention to link a file into the file system;
	/// * To use file sealing (see <http://man7.org/linux/man-pages/man2/fcntl.2.html>); particularly `F_SEAL_FUTURE_WRITE` for a shared memory buffer.
	///
	/// The file can be mmap'd and the file descriptor passed to other processes like any other.
	///
	/// The initial size of the file is set to 0.
	///
	/// Following the call, the file size should be set using `ftruncate()`, or writes made using `write()` or the like.
	///
	/// `non_unique_name_for_debugging_purposes` can be seen under `/proc/self/fd` prefixed with `memfd:`.
	/// It does not have to be unique.
	///
	/// `allow_sealing_operations`:  If true, then the `fcntl()` `F_ADD_SEALS` and `F_GET_SEALS` operations are supported; the initial set of seals is empty.
	/// If not specifed, then the initial set of seals will be `F_SEAL_SEAL`, meaning that no other seals can be set on the file.
	///
	/// `huge_page_size` supports the following:-
	///
	/// * `None`: No huge pages.
	/// * `Some(None)`: Use the system default huge page size.
	/// * `Some(Some(huge_page_size))`: Use the specific `huge_page_size` huge page size.
	///
	/// If the defaults indicate `huge_page_size` `Some(Some(huge_page_size))` is not supported, they will try to find a smaller supported huge page size; if there are not supported huge pages, then the MemoryFileDescriptor will not use huge pages.
	/// If the defaults indicate `huge_page_size` `Some(None)` is not supported, they then the MemoryFileDescriptor will not use huge pages.
	///
	/// The resultant file descriptor will have the close-on-exec flag set (as do all file descriptors created in the super module, `file_descriptors`).
	///
	/// Supported since Linux 3.17.
	/// However, support for `allow_sealing_operations` with `huge_page_size` has only existed since Linux 4.16.
	pub fn open_anonymous_memory_as_file(non_unique_name_for_debugging_purposes: &CStr, allow_sealing_operations: bool, page_size_or_huge_page_size_settings: &PageSizeOrHugePageSizeSettings) -> Result<Self, CreationError>
	{
		const MFD_CLOEXEC: u32 = 0x0001;
		const MFD_ALLOW_SEALING: u32 = 0x0002;

		extern "C"
		{
			fn memfd_create(name: *const c_char, flags: c_uint) -> c_int;
		}

		let sealing_flags = if allow_sealing_operations
		{
			MFD_ALLOW_SEALING
		}
		else
		{
			0
		};
		
		let (huge_page_size_flags, _page_size_or_huge_page_size) = page_size_or_huge_page_size_settings.memfd_flag_bits_and_page_size();

		let flags = MFD_CLOEXEC | sealing_flags | huge_page_size_flags as u32;

		let result = unsafe { memfd_create(non_unique_name_for_debugging_purposes.as_ptr() as *const _, flags as u32) };

		if likely!(result == 0)
		{
			return Ok(unsafe { Self::from_raw_fd(result) })
		}
		else if likely!(result == -1)
		{
			use self::CreationError::*;

			match errno().0
			{
				EMFILE => Err(PerProcessLimitOnNumberOfFileDescriptorsWouldBeExceeded),

				ENFILE => Err(SystemWideLimitOnTotalNumberOfFileDescriptorsWouldBeExceeded),

				ENOMEM => Err(KernelWouldBeOutOfMemory),

				ENOENT => panic!("No queue with this name exists"),

				EINVAL => panic!("The address in name points to invalid memory, or, flags included unknown bits, or, name was too long (The limit is 249 bytes, excluding the
  terminating null byte), or, both  MFD_HUGETLB and MFD_ALLOW_SEALING were specified in flags before Linux 4.16"),

				_ => unreachable_code(format_args!("")),
			}
		}
		else
		{
			panic!("Unexpected result {}", result)
		}
	}

	/// Return `Err(())` if permission is denied.
	#[inline(always)]
	pub fn add_file_seals(&self, file_seals: FileSeals) -> Result<(), ()>
	{
		let result = unsafe { fcntl(self.as_raw_fd(), F_ADD_SEALS, file_seals.bits) };
		if likely!(result == 0)
		{
			Ok(())
		}
		else if likely!(result == -1)
		{
			match errno().0
			{
				EPERM => Err(()),

				EINVAL => panic!("This is not a memfd"),

				unexpected @ _ => panic!("Unexpected error `{:?}`", unexpected)
			}
		}
		else
		{
			unreachable_code(format_args!("Unexpected result from fcntl F_ADD_SEALS of `{}`", result))
		}
	}

	/// Get seals.
	#[inline(always)]
	pub fn get_file_seals(&self) -> FileSeals
	{
		let result = unsafe { fcntl(self.as_raw_fd(), F_GET_SEALS) };
		if likely!(result == 0)
		{
			FileSeals::from_bits_truncate(result)
		}
		else if likely!(result == -1)
		{
			match errno().0
			{
				EINVAL => panic!("This is not a memfd"),

				unexpected @ _ => panic!("Unexpected error `{:?}`", unexpected)
			}
		}
		else
		{
			unreachable_code(format_args!("Unexpected result from fcntl F_ADD_SEALS of `{}`", result))
		}
	}
	
	/// Set length to a non-zero amount.
	#[inline(always)]
	pub fn set_non_zero_length(&self, length: NonZeroU64) -> io::Result<()>
	{
		self.deref().set_len(length.get())
	}
}