Skip to main content

hermit/fd/
mod.rs

1use alloc::sync::Arc;
2use core::future::{self, Future};
3use core::mem::MaybeUninit;
4use core::pin::pin;
5use core::task::Poll::{Pending, Ready};
6use core::time::Duration;
7
8#[cfg(feature = "net")]
9use smoltcp::wire::{IpEndpoint, IpListenEndpoint};
10
11pub(crate) use self::delegate::Fd;
12use crate::arch::kernel::core_local::core_scheduler;
13use crate::errno::Errno;
14use crate::executor::block_on;
15use crate::fs::{FileAttr, SeekWhence};
16use crate::io;
17
18mod delegate;
19mod eventfd;
20#[cfg(any(feature = "net", feature = "virtio-vsock"))]
21pub(crate) mod socket;
22pub(crate) mod stdio;
23
24pub(crate) const STDIN_FILENO: RawFd = 0;
25pub(crate) const STDOUT_FILENO: RawFd = 1;
26pub(crate) const STDERR_FILENO: RawFd = 2;
27
28#[cfg(any(feature = "net", feature = "virtio-vsock"))]
29#[derive(Debug)]
30pub(crate) enum Endpoint {
31	#[cfg(feature = "net")]
32	Ip(IpEndpoint),
33	#[cfg(feature = "virtio-vsock")]
34	Vsock(socket::vsock::VsockEndpoint),
35}
36
37#[cfg(any(feature = "net", feature = "virtio-vsock"))]
38#[derive(Debug)]
39pub(crate) enum ListenEndpoint {
40	#[cfg(feature = "net")]
41	Ip(IpListenEndpoint),
42	#[cfg(feature = "virtio-vsock")]
43	Vsock(socket::vsock::VsockListenEndpoint),
44}
45
46#[allow(dead_code)]
47#[derive(Debug, PartialEq)]
48pub(crate) enum SocketOption {
49	TcpNoDelay,
50}
51
52pub(crate) type RawFd = i32;
53
54bitflags! {
55	/// Options for opening files
56	#[derive(Debug, Copy, Clone, Default)]
57	pub struct OpenOption: i32 {
58		const O_RDONLY = 0o0000;
59		const O_WRONLY = 0o0001;
60		const O_RDWR = 0o0002;
61		const O_CREAT = 0o0100;
62		const O_EXCL = 0o0200;
63		const O_TRUNC = 0o1000;
64		const O_APPEND = StatusFlags::O_APPEND.bits();
65		const O_NONBLOCK = StatusFlags::O_NONBLOCK.bits();
66		const O_DIRECT = 0o40000;
67		const O_DIRECTORY = 0o200_000;
68		/// `O_CLOEXEC` has no functionality in Hermit and will be silently ignored
69		const O_CLOEXEC = 0o2_000_000;
70	}
71}
72
73bitflags! {
74	/// Options for checking file permissions or existence
75	#[derive(Debug, Copy, Clone, Default, Eq, PartialEq)]
76	pub struct AccessOption: i32 {
77		/// Test for read permission
78		const R_OK = 4;
79		/// Test for write permission
80		const W_OK = 2;
81		/// Test for execution permission
82		const X_OK = 1;
83		/// Test for existence
84		const F_OK = 0;
85	}
86}
87
88impl AccessOption {
89	/// Verifies if the current access options are all valid for the provided file access permissions
90	pub fn can_access(&self, access_permissions: AccessPermission) -> bool {
91		if self.contains(AccessOption::R_OK)
92			&& !access_permissions.contains(AccessPermission::S_IRUSR)
93			&& !access_permissions.contains(AccessPermission::S_IRGRP)
94			&& !access_permissions.contains(AccessPermission::S_IROTH)
95		{
96			return false;
97		}
98
99		if self.contains(AccessOption::W_OK)
100			&& !access_permissions.contains(AccessPermission::S_IWUSR)
101			&& !access_permissions.contains(AccessPermission::S_IWGRP)
102			&& !access_permissions.contains(AccessPermission::S_IWOTH)
103		{
104			return false;
105		}
106
107		if self.contains(AccessOption::X_OK)
108			&& !access_permissions.contains(AccessPermission::S_IXUSR)
109			&& !access_permissions.contains(AccessPermission::S_IXGRP)
110			&& !access_permissions.contains(AccessPermission::S_IXOTH)
111		{
112			return false;
113		}
114
115		true
116	}
117}
118
119bitflags! {
120	/// File status flags.
121	#[derive(Debug, Copy, Clone, Default)]
122	pub struct StatusFlags: i32 {
123		const O_APPEND = 0o2000;
124		const O_NONBLOCK = 0o4000;
125	}
126}
127
128bitflags! {
129	#[derive(Debug, Copy, Clone, Default)]
130	pub struct PollEvent: i16 {
131		const POLLIN = 0x1;
132		const POLLPRI = 0x2;
133		const POLLOUT = 0x4;
134		const POLLERR = 0x8;
135		const POLLHUP = 0x10;
136		const POLLNVAL = 0x20;
137		const POLLRDNORM = 0x040;
138		const POLLRDBAND = 0x080;
139		const POLLWRNORM = 0x0100;
140		const POLLWRBAND = 0x0200;
141		const POLLRDHUP = 0x2000;
142	}
143}
144
145#[repr(C)]
146#[derive(Debug, Default, Copy, Clone)]
147pub struct PollFd {
148	/// File descriptor
149	pub fd: i32,
150	/// Events to look for
151	pub events: PollEvent,
152	/// Events returned
153	pub revents: PollEvent,
154}
155
156bitflags! {
157	#[derive(Debug, Default, Copy, Clone)]
158	pub struct EventFlags: i16 {
159		const EFD_SEMAPHORE = 0o1;
160		const EFD_NONBLOCK = 0o4000;
161		const EFD_CLOEXEC = 0o40000;
162	}
163}
164
165bitflags! {
166	#[derive(Debug, Copy, Clone)]
167	pub struct AccessPermission: u32 {
168		const S_IFMT = 0o170_000;
169		const S_IFSOCK = 0o140_000;
170		const S_IFLNK = 0o120_000;
171		const S_IFREG = 0o100_000;
172		const S_IFBLK = 0o060_000;
173		const S_IFDIR = 0o040_000;
174		const S_IFCHR = 0o020_000;
175		const S_IFIFO = 0o010_000;
176		const S_IRUSR = 0o400;
177		const S_IWUSR = 0o200;
178		const S_IXUSR = 0o100;
179		const S_IRWXU = 0o700;
180		const S_IRGRP = 0o040;
181		const S_IWGRP = 0o020;
182		const S_IXGRP = 0o010;
183		const S_IRWXG = 0o070;
184		const S_IROTH = 0o004;
185		const S_IWOTH = 0o002;
186		const S_IXOTH = 0o001;
187		const S_IRWXO = 0o007;
188		// Allow bits unknown to us to be set externally. See bitflags documentation for further explanation.
189		const _ = !0;
190	}
191}
192
193impl Default for AccessPermission {
194	fn default() -> Self {
195		AccessPermission::from_bits(0o666).unwrap()
196	}
197}
198
199pub(crate) trait ObjectInterface: Sync + Send {
200	/// Check if an IO event is possible
201	async fn poll(&self, _event: PollEvent) -> io::Result<PollEvent> {
202		Ok(PollEvent::empty())
203	}
204
205	/// `async_read` attempts to read `len` bytes from the object references
206	/// by the descriptor
207	async fn read(&self, _buf: &mut [u8]) -> io::Result<usize> {
208		Err(Errno::Nosys)
209	}
210
211	/// `async_write` attempts to write `len` bytes to the object references
212	/// by the descriptor
213	async fn write(&self, _buf: &[u8]) -> io::Result<usize> {
214		Err(Errno::Nosys)
215	}
216
217	/// `lseek` function repositions the offset of the file descriptor fildes
218	async fn lseek(&self, _offset: isize, _whence: SeekWhence) -> io::Result<isize> {
219		Err(Errno::Inval)
220	}
221
222	/// `fstat`
223	async fn fstat(&self) -> io::Result<FileAttr> {
224		Err(Errno::Inval)
225	}
226
227	/// `getdents` fills the given buffer `_buf` with [`Dirent64`](crate::syscalls::Dirent64)
228	/// formatted entries of a directory, imitating the Linux `getdents64` syscall.
229	/// On success, the number of bytes read is returned.  On end of directory, 0 is returned.  On error, -1 is returned
230	async fn getdents(&self, _buf: &mut [MaybeUninit<u8>]) -> io::Result<usize> {
231		Err(Errno::Inval)
232	}
233
234	/// `accept` a connection on a socket
235	#[cfg(any(feature = "net", feature = "virtio-vsock"))]
236	async fn accept(&mut self) -> io::Result<(Arc<async_lock::RwLock<Fd>>, Endpoint)> {
237		Err(Errno::Inval)
238	}
239
240	/// initiate a connection on a socket
241	#[cfg(any(feature = "net", feature = "virtio-vsock"))]
242	async fn connect(&mut self, _endpoint: Endpoint) -> io::Result<()> {
243		Err(Errno::Inval)
244	}
245
246	/// `bind` a name to a socket
247	#[cfg(any(feature = "net", feature = "virtio-vsock"))]
248	async fn bind(&mut self, _name: ListenEndpoint) -> io::Result<()> {
249		Err(Errno::Inval)
250	}
251
252	/// `listen` for connections on a socket
253	#[cfg(any(feature = "net", feature = "virtio-vsock"))]
254	async fn listen(&mut self, _backlog: i32) -> io::Result<()> {
255		Err(Errno::Inval)
256	}
257
258	/// `setsockopt` sets options on sockets
259	#[cfg(any(feature = "net", feature = "virtio-vsock"))]
260	async fn setsockopt(&self, _opt: SocketOption, _optval: bool) -> io::Result<()> {
261		Err(Errno::Notsock)
262	}
263
264	/// `getsockopt` gets options on sockets
265	#[cfg(any(feature = "net", feature = "virtio-vsock"))]
266	async fn getsockopt(&self, _opt: SocketOption) -> io::Result<bool> {
267		Err(Errno::Notsock)
268	}
269
270	/// `getsockname` gets socket name
271	#[cfg(any(feature = "net", feature = "virtio-vsock"))]
272	async fn getsockname(&self) -> io::Result<Option<Endpoint>> {
273		Ok(None)
274	}
275
276	/// `getpeername` get address of connected peer
277	#[cfg(any(feature = "net", feature = "virtio-vsock"))]
278	#[allow(dead_code)]
279	async fn getpeername(&self) -> io::Result<Option<Endpoint>> {
280		Ok(None)
281	}
282
283	/// Receive a message from a socket
284	#[cfg(any(feature = "net", feature = "virtio-vsock"))]
285	async fn recvfrom(&self, _buffer: &mut [MaybeUninit<u8>]) -> io::Result<(usize, Endpoint)> {
286		Err(Errno::Nosys)
287	}
288
289	/// Send a message from a socket
290	///
291	/// The sendto() function shall send a message.
292	/// If the socket is a connectionless-mode socket, the message shall
293	/// If a peer address has been prespecified, either the message shall
294	/// be sent to the address specified by dest_addr (overriding the pre-specified peer
295	/// address).
296	#[cfg(any(feature = "net", feature = "virtio-vsock"))]
297	async fn sendto(&self, _buffer: &[u8], _endpoint: Endpoint) -> io::Result<usize> {
298		Err(Errno::Nosys)
299	}
300
301	/// Shut down part of a full-duplex connection
302	#[cfg(any(feature = "net", feature = "virtio-vsock"))]
303	async fn shutdown(&self, _how: i32) -> io::Result<()> {
304		Err(Errno::Nosys)
305	}
306
307	/// Returns the file status flags.
308	async fn status_flags(&self) -> io::Result<StatusFlags> {
309		Err(Errno::Nosys)
310	}
311
312	/// Sets the file status flags.
313	async fn set_status_flags(&mut self, _status_flags: StatusFlags) -> io::Result<()> {
314		Err(Errno::Nosys)
315	}
316
317	/// Truncates the file
318	async fn truncate(&self, _size: usize) -> io::Result<()> {
319		Err(Errno::Nosys)
320	}
321
322	/// Changes access permissions to the file
323	async fn chmod(&self, _access_permission: AccessPermission) -> io::Result<()> {
324		Err(Errno::Nosys)
325	}
326
327	/// `isatty` returns `true` for a terminal device
328	async fn isatty(&self) -> io::Result<bool> {
329		Ok(false)
330	}
331}
332
333pub(crate) fn read(fd: RawFd, buf: &mut [u8]) -> io::Result<usize> {
334	let obj = get_object(fd)?;
335
336	if buf.is_empty() {
337		return Ok(0);
338	}
339
340	block_on(async { obj.read().await.read(buf).await }, None)
341}
342
343pub(crate) fn lseek(fd: RawFd, offset: isize, whence: SeekWhence) -> io::Result<isize> {
344	let obj = get_object(fd)?;
345
346	block_on(async { obj.read().await.lseek(offset, whence).await }, None)
347}
348
349pub(crate) fn chmod(fd: RawFd, mode: AccessPermission) -> io::Result<()> {
350	let obj = get_object(fd)?;
351
352	block_on(async { obj.read().await.chmod(mode).await }, None)
353}
354
355pub(crate) fn write(fd: RawFd, buf: &[u8]) -> io::Result<usize> {
356	let obj = get_object(fd)?;
357
358	if buf.is_empty() {
359		return Ok(0);
360	}
361
362	block_on(async { obj.read().await.write(buf).await }, None)
363}
364
365pub(crate) fn truncate(fd: RawFd, length: usize) -> io::Result<()> {
366	let obj = get_object(fd)?;
367	block_on(async { obj.read().await.truncate(length).await }, None)
368}
369
370async fn poll_fds(fds: &mut [PollFd]) -> io::Result<u64> {
371	future::poll_fn(|cx| {
372		let mut counter: u64 = 0;
373
374		for poll_fd in &mut *fds {
375			let fd = poll_fd.fd;
376			poll_fd.revents = PollEvent::empty();
377			let Ok(obj) = core_scheduler().get_object(fd) else {
378				continue;
379			};
380
381			let mut pinned = pin!(async { obj.read().await.poll(poll_fd.events).await });
382			if let Ready(Ok(e)) = pinned.as_mut().poll(cx)
383				&& !e.is_empty()
384			{
385				counter += 1;
386				poll_fd.revents = e;
387			}
388		}
389
390		if counter > 0 {
391			Ready(Ok(counter))
392		} else {
393			Pending
394		}
395	})
396	.await
397}
398
399/// Wait for some event on a file descriptor.
400///
401/// The unix-like `poll` waits for one of a set of file descriptors
402/// to become ready to perform I/O. The set of file descriptors to be
403/// monitored is specified in the `fds` argument, which is an array
404/// of structs of `PollFd`.
405pub fn poll(fds: &mut [PollFd], timeout: Option<Duration>) -> io::Result<u64> {
406	let result = block_on(poll_fds(fds), timeout);
407	if let Err(ref e) = result
408		&& timeout.is_some()
409	{
410		// A return value of zero indicates that the system call timed out
411		if *e == Errno::Again {
412			return Ok(0);
413		}
414	}
415
416	result
417}
418
419pub fn fstat(fd: RawFd) -> io::Result<FileAttr> {
420	let obj = get_object(fd)?;
421	block_on(async { obj.read().await.fstat().await }, None)
422}
423
424/// Wait for some event on a file descriptor.
425///
426/// `eventfd` creates an linux-like "eventfd object" that can be used
427/// as an event wait/notify mechanism by user-space applications, and by
428/// the kernel to notify user-space applications of events. The
429/// object contains an unsigned 64-bit integer counter
430/// that is maintained by the kernel. This counter is initialized
431/// with the value specified in the argument `initval`.
432///
433/// As its return value, `eventfd` returns a new file descriptor that
434/// can be used to refer to the eventfd object.
435///
436/// The following values may be bitwise set in flags to change the
437/// behavior of `eventfd`:
438///
439/// `EFD_NONBLOCK`: Set the file descriptor in non-blocking mode
440/// `EFD_SEMAPHORE`: Provide semaphore-like semantics for reads
441/// from the new file descriptor.
442pub fn eventfd(initval: u64, flags: EventFlags) -> io::Result<RawFd> {
443	let obj = self::eventfd::EventFd::new(initval, flags);
444
445	let fd = core_scheduler().insert_object(Arc::new(async_lock::RwLock::new(obj.into())))?;
446
447	Ok(fd)
448}
449
450pub(crate) fn get_object(fd: RawFd) -> io::Result<Arc<async_lock::RwLock<Fd>>> {
451	core_scheduler().get_object(fd)
452}
453
454pub(crate) fn insert_object(obj: Arc<async_lock::RwLock<Fd>>) -> io::Result<RawFd> {
455	core_scheduler().insert_object(obj)
456}
457
458// The dup system call allocates a new file descriptor that refers
459// to the same open file description as the descriptor oldfd. The new
460// file descriptor number is guaranteed to be the lowest-numbered
461// file descriptor that was unused in the calling process.
462pub(crate) fn dup_object(fd: RawFd) -> io::Result<RawFd> {
463	core_scheduler().dup_object(fd)
464}
465
466pub(crate) fn dup_object2(fd1: RawFd, fd2: RawFd) -> io::Result<RawFd> {
467	core_scheduler().dup_object2(fd1, fd2)
468}
469
470pub(crate) fn remove_object(fd: RawFd) -> io::Result<Arc<async_lock::RwLock<Fd>>> {
471	core_scheduler().remove_object(fd)
472}
473
474pub(crate) fn isatty(fd: RawFd) -> io::Result<bool> {
475	let obj = get_object(fd)?;
476	block_on(async { obj.read().await.isatty().await }, None)
477}