hermit/fd/
mod.rs

1use alloc::boxed::Box;
2use alloc::sync::Arc;
3use core::future::{self, Future};
4use core::mem::MaybeUninit;
5use core::task::Poll::{Pending, Ready};
6use core::time::Duration;
7
8use async_trait::async_trait;
9#[cfg(any(feature = "tcp", feature = "udp"))]
10use smoltcp::wire::{IpEndpoint, IpListenEndpoint};
11
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 eventfd;
19#[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
20pub(crate) mod socket;
21pub(crate) mod stdio;
22
23pub(crate) const STDIN_FILENO: FileDescriptor = 0;
24pub(crate) const STDOUT_FILENO: FileDescriptor = 1;
25pub(crate) const STDERR_FILENO: FileDescriptor = 2;
26
27#[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
28#[derive(Debug)]
29pub(crate) enum Endpoint {
30	#[cfg(any(feature = "tcp", feature = "udp"))]
31	Ip(IpEndpoint),
32	#[cfg(feature = "vsock")]
33	Vsock(socket::vsock::VsockEndpoint),
34}
35
36#[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
37#[derive(Debug)]
38pub(crate) enum ListenEndpoint {
39	#[cfg(any(feature = "tcp", feature = "udp"))]
40	Ip(IpListenEndpoint),
41	#[cfg(feature = "vsock")]
42	Vsock(socket::vsock::VsockListenEndpoint),
43}
44
45#[allow(dead_code)]
46#[derive(Debug, PartialEq)]
47pub(crate) enum SocketOption {
48	TcpNoDelay,
49}
50
51pub(crate) type FileDescriptor = i32;
52
53bitflags! {
54	/// Options for opening files
55	#[derive(Debug, Copy, Clone, Default)]
56	pub struct OpenOption: i32 {
57		const O_RDONLY = 0o0000;
58		const O_WRONLY = 0o0001;
59		const O_RDWR = 0o0002;
60		const O_CREAT = 0o0100;
61		const O_EXCL = 0o0200;
62		const O_TRUNC = 0o1000;
63		const O_APPEND = StatusFlags::O_APPEND.bits();
64		const O_NONBLOCK = StatusFlags::O_NONBLOCK.bits();
65		const O_DIRECT = 0o40000;
66		const O_DIRECTORY = 0o200_000;
67		/// `O_CLOEXEC` has no functionality in Hermit and will be silently ignored
68		const O_CLOEXEC = 0o2_000_000;
69	}
70}
71
72bitflags! {
73	/// Options for checking file permissions or existence
74	#[derive(Debug, Copy, Clone, Default, Eq, PartialEq)]
75	pub struct AccessOption: i32 {
76		/// Test for read permission
77		const R_OK = 4;
78		/// Test for write permission
79		const W_OK = 2;
80		/// Test for execution permission
81		const X_OK = 1;
82		/// Test for existence
83		const F_OK = 0;
84	}
85}
86
87impl AccessOption {
88	/// Verifies if the current access options are all valid for the provided file access permissions
89	pub fn can_access(&self, access_permissions: AccessPermission) -> bool {
90		if self.contains(AccessOption::R_OK)
91			&& !access_permissions.contains(AccessPermission::S_IRUSR)
92			&& !access_permissions.contains(AccessPermission::S_IRGRP)
93			&& !access_permissions.contains(AccessPermission::S_IROTH)
94		{
95			return false;
96		}
97
98		if self.contains(AccessOption::W_OK)
99			&& !access_permissions.contains(AccessPermission::S_IWUSR)
100			&& !access_permissions.contains(AccessPermission::S_IWGRP)
101			&& !access_permissions.contains(AccessPermission::S_IWOTH)
102		{
103			return false;
104		}
105
106		if self.contains(AccessOption::X_OK)
107			&& !access_permissions.contains(AccessPermission::S_IXUSR)
108			&& !access_permissions.contains(AccessPermission::S_IXGRP)
109			&& !access_permissions.contains(AccessPermission::S_IXOTH)
110		{
111			return false;
112		}
113
114		true
115	}
116}
117
118bitflags! {
119	/// File status flags.
120	#[derive(Debug, Copy, Clone, Default)]
121	pub struct StatusFlags: i32 {
122		const O_APPEND = 0o2000;
123		const O_NONBLOCK = 0o4000;
124	}
125}
126
127bitflags! {
128	#[derive(Debug, Copy, Clone, Default)]
129	pub struct PollEvent: i16 {
130		const POLLIN = 0x1;
131		const POLLPRI = 0x2;
132		const POLLOUT = 0x4;
133		const POLLERR = 0x8;
134		const POLLHUP = 0x10;
135		const POLLNVAL = 0x20;
136		const POLLRDNORM = 0x040;
137		const POLLRDBAND = 0x080;
138		const POLLWRNORM = 0x0100;
139		const POLLWRBAND = 0x0200;
140		const POLLRDHUP = 0x2000;
141	}
142}
143
144#[repr(C)]
145#[derive(Debug, Default, Copy, Clone)]
146pub struct PollFd {
147	/// file descriptor
148	pub fd: i32,
149	/// events to look for
150	pub events: PollEvent,
151	/// events returned
152	pub revents: PollEvent,
153}
154
155bitflags! {
156	#[derive(Debug, Default, Copy, Clone)]
157	pub struct EventFlags: i16 {
158		const EFD_SEMAPHORE = 0o1;
159		const EFD_NONBLOCK = 0o4000;
160		const EFD_CLOEXEC = 0o40000;
161	}
162}
163
164bitflags! {
165	#[derive(Debug, Copy, Clone)]
166	pub struct AccessPermission: u32 {
167		const S_IFMT = 0o170_000;
168		const S_IFSOCK = 0o140_000;
169		const S_IFLNK = 0o120_000;
170		const S_IFREG = 0o100_000;
171		const S_IFBLK = 0o060_000;
172		const S_IFDIR = 0o040_000;
173		const S_IFCHR = 0o020_000;
174		const S_IFIFO = 0o010_000;
175		const S_IRUSR = 0o400;
176		const S_IWUSR = 0o200;
177		const S_IXUSR = 0o100;
178		const S_IRWXU = 0o700;
179		const S_IRGRP = 0o040;
180		const S_IWGRP = 0o020;
181		const S_IXGRP = 0o010;
182		const S_IRWXG = 0o070;
183		const S_IROTH = 0o004;
184		const S_IWOTH = 0o002;
185		const S_IXOTH = 0o001;
186		const S_IRWXO = 0o007;
187		// Allow bits unknown to us to be set externally. See bitflags documentation for further explanation.
188		const _ = !0;
189	}
190}
191
192impl Default for AccessPermission {
193	fn default() -> Self {
194		AccessPermission::from_bits(0o666).unwrap()
195	}
196}
197
198#[async_trait]
199pub(crate) trait ObjectInterface: Sync + Send + core::fmt::Debug {
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 [MaybeUninit<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 = "tcp", feature = "udp", feature = "vsock"))]
236	async fn accept(&self) -> io::Result<(Arc<dyn ObjectInterface>, Endpoint)> {
237		Err(Errno::Inval)
238	}
239
240	/// initiate a connection on a socket
241	#[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
242	async fn connect(&self, _endpoint: Endpoint) -> io::Result<()> {
243		Err(Errno::Inval)
244	}
245
246	/// `bind` a name to a socket
247	#[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
248	async fn bind(&self, _name: ListenEndpoint) -> io::Result<()> {
249		Err(Errno::Inval)
250	}
251
252	/// `listen` for connections on a socket
253	#[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
254	async fn listen(&self, _backlog: i32) -> io::Result<()> {
255		Err(Errno::Inval)
256	}
257
258	/// `setsockopt` sets options on sockets
259	#[cfg(any(feature = "tcp", feature = "udp", feature = "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 = "tcp", feature = "udp", feature = "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 = "tcp", feature = "udp", feature = "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 = "tcp", feature = "udp", feature = "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 = "tcp", feature = "udp", feature = "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 = "tcp", feature = "udp", feature = "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 = "tcp", feature = "udp", feature = "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(&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: FileDescriptor, buf: &mut [MaybeUninit<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(obj.read(buf), None)
341}
342
343pub(crate) fn lseek(fd: FileDescriptor, offset: isize, whence: SeekWhence) -> io::Result<isize> {
344	let obj = get_object(fd)?;
345
346	block_on(obj.lseek(offset, whence), None)
347}
348
349pub(crate) fn chmod(fd: FileDescriptor, mode: AccessPermission) -> io::Result<()> {
350	let obj = get_object(fd)?;
351
352	block_on(obj.chmod(mode), None)
353}
354
355pub(crate) fn write(fd: FileDescriptor, 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(obj.write(buf), None)
363}
364
365pub(crate) fn truncate(fd: FileDescriptor, length: usize) -> io::Result<()> {
366	let obj = get_object(fd)?;
367	block_on(obj.truncate(length), 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 i in &mut *fds {
375			let fd = i.fd;
376			i.revents = PollEvent::empty();
377			if let Ok(obj) = core_scheduler().get_object(fd) {
378				let mut pinned = core::pin::pin!(obj.poll(i.events));
379				if let Ready(Ok(e)) = pinned.as_mut().poll(cx)
380					&& !e.is_empty()
381				{
382					counter += 1;
383					i.revents = e;
384				}
385			}
386		}
387
388		if counter > 0 {
389			Ready(Ok(counter))
390		} else {
391			Pending
392		}
393	})
394	.await
395}
396
397/// Wait for some event on a file descriptor.
398///
399/// The unix-like `poll` waits for one of a set of file descriptors
400/// to become ready to perform I/O. The set of file descriptors to be
401/// monitored is specified in the `fds` argument, which is an array
402/// of structs of `PollFd`.
403pub fn poll(fds: &mut [PollFd], timeout: Option<Duration>) -> io::Result<u64> {
404	let result = block_on(poll_fds(fds), timeout);
405	if let Err(ref e) = result
406		&& timeout.is_some()
407	{
408		// A return value of zero indicates that the system call timed out
409		if *e == Errno::Again {
410			return Ok(0);
411		}
412	}
413
414	result
415}
416
417pub fn fstat(fd: FileDescriptor) -> io::Result<FileAttr> {
418	let obj = get_object(fd)?;
419	block_on(obj.fstat(), None)
420}
421
422/// Wait for some event on a file descriptor.
423///
424/// `eventfd` creates an linux-like "eventfd object" that can be used
425/// as an event wait/notify mechanism by user-space applications, and by
426/// the kernel to notify user-space applications of events. The
427/// object contains an unsigned 64-bit integer counter
428/// that is maintained by the kernel. This counter is initialized
429/// with the value specified in the argument `initval`.
430///
431/// As its return value, `eventfd` returns a new file descriptor that
432/// can be used to refer to the eventfd object.
433///
434/// The following values may be bitwise set in flags to change the
435/// behavior of `eventfd`:
436///
437/// `EFD_NONBLOCK`: Set the file descriptor in non-blocking mode
438/// `EFD_SEMAPHORE`: Provide semaphore-like semantics for reads
439/// from the new file descriptor.
440pub fn eventfd(initval: u64, flags: EventFlags) -> io::Result<FileDescriptor> {
441	let obj = self::eventfd::EventFd::new(initval, flags);
442
443	let fd = core_scheduler().insert_object(Arc::new(obj))?;
444
445	Ok(fd)
446}
447
448pub(crate) fn get_object(fd: FileDescriptor) -> io::Result<Arc<dyn ObjectInterface>> {
449	core_scheduler().get_object(fd)
450}
451
452pub(crate) fn insert_object(obj: Arc<dyn ObjectInterface>) -> io::Result<FileDescriptor> {
453	core_scheduler().insert_object(obj)
454}
455
456// The dup system call allocates a new file descriptor that refers
457// to the same open file description as the descriptor oldfd. The new
458// file descriptor number is guaranteed to be the lowest-numbered
459// file descriptor that was unused in the calling process.
460pub(crate) fn dup_object(fd: FileDescriptor) -> io::Result<FileDescriptor> {
461	core_scheduler().dup_object(fd)
462}
463
464pub(crate) fn dup_object2(fd1: FileDescriptor, fd2: FileDescriptor) -> io::Result<FileDescriptor> {
465	core_scheduler().dup_object2(fd1, fd2)
466}
467
468pub(crate) fn remove_object(fd: FileDescriptor) -> io::Result<Arc<dyn ObjectInterface>> {
469	core_scheduler().remove_object(fd)
470}
471
472pub(crate) fn isatty(fd: FileDescriptor) -> io::Result<bool> {
473	let obj = get_object(fd)?;
474	block_on(obj.isatty(), None)
475}