hermit/fd/
mod.rs

1use alloc::boxed::Box;
2use alloc::sync::Arc;
3use alloc::vec::Vec;
4use core::future::{self, Future};
5use core::mem::MaybeUninit;
6use core::task::Poll::{Pending, Ready};
7use core::time::Duration;
8
9use async_trait::async_trait;
10#[cfg(any(feature = "tcp", feature = "udp"))]
11use smoltcp::wire::{IpEndpoint, IpListenEndpoint};
12
13use crate::arch::kernel::core_local::core_scheduler;
14use crate::executor::block_on;
15use crate::fs::{DirectoryEntry, 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	}
68}
69
70bitflags! {
71	/// File status flags.
72	#[derive(Debug, Copy, Clone, Default)]
73	pub struct StatusFlags: i32 {
74		const O_APPEND = 0o2000;
75		const O_NONBLOCK = 0o4000;
76	}
77}
78
79bitflags! {
80	#[derive(Debug, Copy, Clone, Default)]
81	pub struct PollEvent: i16 {
82		const POLLIN = 0x1;
83		const POLLPRI = 0x2;
84		const POLLOUT = 0x4;
85		const POLLERR = 0x8;
86		const POLLHUP = 0x10;
87		const POLLNVAL = 0x20;
88		const POLLRDNORM = 0x040;
89		const POLLRDBAND = 0x080;
90		const POLLWRNORM = 0x0100;
91		const POLLWRBAND = 0x0200;
92		const POLLRDHUP = 0x2000;
93	}
94}
95
96#[repr(C)]
97#[derive(Debug, Default, Copy, Clone)]
98pub struct PollFd {
99	/// file descriptor
100	pub fd: i32,
101	/// events to look for
102	pub events: PollEvent,
103	/// events returned
104	pub revents: PollEvent,
105}
106
107bitflags! {
108	#[derive(Debug, Default, Copy, Clone)]
109	pub struct EventFlags: i16 {
110		const EFD_SEMAPHORE = 0o1;
111		const EFD_NONBLOCK = 0o4000;
112		const EFD_CLOEXEC = 0o40000;
113	}
114}
115
116bitflags! {
117	#[derive(Debug, Copy, Clone)]
118	pub struct AccessPermission: u32 {
119		const S_IFMT = 0o170_000;
120		const S_IFSOCK = 0o140_000;
121		const S_IFLNK = 0o120_000;
122		const S_IFREG = 0o100_000;
123		const S_IFBLK = 0o060_000;
124		const S_IFDIR = 0o040_000;
125		const S_IFCHR = 0o020_000;
126		const S_IFIFO = 0o010_000;
127		const S_IRUSR = 0o400;
128		const S_IWUSR = 0o200;
129		const S_IXUSR = 0o100;
130		const S_IRWXU = 0o700;
131		const S_IRGRP = 0o040;
132		const S_IWGRP = 0o020;
133		const S_IXGRP = 0o010;
134		const S_IRWXG = 0o070;
135		const S_IROTH = 0o004;
136		const S_IWOTH = 0o002;
137		const S_IXOTH = 0o001;
138		const S_IRWXO = 0o007;
139		// Allow bits unknown to us to be set externally. See bitflags documentation for further explanation.
140		const _ = !0;
141	}
142}
143
144impl Default for AccessPermission {
145	fn default() -> Self {
146		AccessPermission::from_bits(0o666).unwrap()
147	}
148}
149
150#[async_trait]
151pub(crate) trait ObjectInterface: Sync + Send + core::fmt::Debug {
152	/// check if an IO event is possible
153	async fn poll(&self, _event: PollEvent) -> io::Result<PollEvent> {
154		Ok(PollEvent::empty())
155	}
156
157	/// `async_read` attempts to read `len` bytes from the object references
158	/// by the descriptor
159	async fn read(&self, _buf: &mut [MaybeUninit<u8>]) -> io::Result<usize> {
160		Err(io::Error::ENOSYS)
161	}
162
163	/// `async_write` attempts to write `len` bytes to the object references
164	/// by the descriptor
165	async fn write(&self, _buf: &[u8]) -> io::Result<usize> {
166		Err(io::Error::ENOSYS)
167	}
168
169	/// `lseek` function repositions the offset of the file descriptor fildes
170	async fn lseek(&self, _offset: isize, _whence: SeekWhence) -> io::Result<isize> {
171		Err(io::Error::EINVAL)
172	}
173
174	/// `fstat`
175	async fn fstat(&self) -> io::Result<FileAttr> {
176		Err(io::Error::EINVAL)
177	}
178
179	/// 'readdir' returns a pointer to a dirent structure
180	/// representing the next directory entry in the directory stream
181	/// pointed to by the file descriptor
182	async fn readdir(&self) -> io::Result<Vec<DirectoryEntry>> {
183		Err(io::Error::EINVAL)
184	}
185
186	/// `accept` a connection on a socket
187	#[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
188	async fn accept(&self) -> io::Result<(Arc<dyn ObjectInterface>, Endpoint)> {
189		Err(io::Error::EINVAL)
190	}
191
192	/// initiate a connection on a socket
193	#[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
194	async fn connect(&self, _endpoint: Endpoint) -> io::Result<()> {
195		Err(io::Error::EINVAL)
196	}
197
198	/// `bind` a name to a socket
199	#[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
200	async fn bind(&self, _name: ListenEndpoint) -> io::Result<()> {
201		Err(io::Error::EINVAL)
202	}
203
204	/// `listen` for connections on a socket
205	#[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
206	async fn listen(&self, _backlog: i32) -> io::Result<()> {
207		Err(io::Error::EINVAL)
208	}
209
210	/// `setsockopt` sets options on sockets
211	#[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
212	async fn setsockopt(&self, _opt: SocketOption, _optval: bool) -> io::Result<()> {
213		Err(io::Error::ENOTSOCK)
214	}
215
216	/// `getsockopt` gets options on sockets
217	#[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
218	async fn getsockopt(&self, _opt: SocketOption) -> io::Result<bool> {
219		Err(io::Error::ENOTSOCK)
220	}
221
222	/// `getsockname` gets socket name
223	#[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
224	async fn getsockname(&self) -> io::Result<Option<Endpoint>> {
225		Ok(None)
226	}
227
228	/// `getpeername` get address of connected peer
229	#[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
230	#[allow(dead_code)]
231	async fn getpeername(&self) -> io::Result<Option<Endpoint>> {
232		Ok(None)
233	}
234
235	/// receive a message from a socket
236	#[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
237	async fn recvfrom(&self, _buffer: &mut [MaybeUninit<u8>]) -> io::Result<(usize, Endpoint)> {
238		Err(io::Error::ENOSYS)
239	}
240
241	/// send a message from a socket
242	///
243	/// The sendto() function shall send a message.
244	/// If the socket is a connectionless-mode socket, the message shall
245	/// If a peer address has been prespecified, either the message shall
246	/// be sent to the address specified by dest_addr (overriding the pre-specified peer
247	/// address).
248	#[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
249	async fn sendto(&self, _buffer: &[u8], _endpoint: Endpoint) -> io::Result<usize> {
250		Err(io::Error::ENOSYS)
251	}
252
253	/// shut down part of a full-duplex connection
254	#[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
255	async fn shutdown(&self, _how: i32) -> io::Result<()> {
256		Err(io::Error::ENOSYS)
257	}
258
259	/// Returns the file status flags.
260	async fn status_flags(&self) -> io::Result<StatusFlags> {
261		Err(io::Error::ENOSYS)
262	}
263
264	/// Sets the file status flags.
265	async fn set_status_flags(&self, _status_flags: StatusFlags) -> io::Result<()> {
266		Err(io::Error::ENOSYS)
267	}
268
269	/// `isatty` returns `true` for a terminal device
270	async fn isatty(&self) -> io::Result<bool> {
271		Ok(false)
272	}
273
274	// FIXME: remove once the ecosystem has migrated away from `AF_INET_OLD`
275	#[cfg(any(feature = "tcp", feature = "udp"))]
276	async fn inet_domain(&self) -> io::Result<i32> {
277		Err(io::Error::EINVAL)
278	}
279}
280
281pub(crate) fn read(fd: FileDescriptor, buf: &mut [MaybeUninit<u8>]) -> io::Result<usize> {
282	let obj = get_object(fd)?;
283
284	if buf.is_empty() {
285		return Ok(0);
286	}
287
288	block_on(obj.read(buf), None)
289}
290
291pub(crate) fn lseek(fd: FileDescriptor, offset: isize, whence: SeekWhence) -> io::Result<isize> {
292	let obj = get_object(fd)?;
293
294	block_on(obj.lseek(offset, whence), None)
295}
296
297pub(crate) fn write(fd: FileDescriptor, buf: &[u8]) -> io::Result<usize> {
298	let obj = get_object(fd)?;
299
300	if buf.is_empty() {
301		return Ok(0);
302	}
303
304	block_on(obj.write(buf), None)
305}
306
307async fn poll_fds(fds: &mut [PollFd]) -> io::Result<u64> {
308	future::poll_fn(|cx| {
309		let mut counter: u64 = 0;
310
311		for i in &mut *fds {
312			let fd = i.fd;
313			i.revents = PollEvent::empty();
314			let mut pinned_obj = core::pin::pin!(core_scheduler().get_object(fd));
315			if let Ready(Ok(obj)) = pinned_obj.as_mut().poll(cx) {
316				let mut pinned = core::pin::pin!(obj.poll(i.events));
317				if let Ready(Ok(e)) = pinned.as_mut().poll(cx) {
318					if !e.is_empty() {
319						counter += 1;
320						i.revents = e;
321					}
322				}
323			}
324		}
325
326		if counter > 0 {
327			Ready(Ok(counter))
328		} else {
329			Pending
330		}
331	})
332	.await
333}
334
335/// Wait for some event on a file descriptor.
336///
337/// The unix-like `poll` waits for one of a set of file descriptors
338/// to become ready to perform I/O. The set of file descriptors to be
339/// monitored is specified in the `fds` argument, which is an array
340/// of structs of `PollFd`.
341pub fn poll(fds: &mut [PollFd], timeout: Option<Duration>) -> io::Result<u64> {
342	let result = block_on(poll_fds(fds), timeout);
343	if let Err(ref e) = result {
344		if timeout.is_some() {
345			// A return value of zero indicates that the system call timed out
346			if *e == io::Error::EAGAIN {
347				return Ok(0);
348			}
349		}
350	}
351
352	result
353}
354
355pub fn fstat(fd: FileDescriptor) -> io::Result<FileAttr> {
356	let obj = get_object(fd)?;
357	block_on(obj.fstat(), None)
358}
359
360/// Wait for some event on a file descriptor.
361///
362/// `eventfd` creates an linux-like "eventfd object" that can be used
363/// as an event wait/notify mechanism by user-space applications, and by
364/// the kernel to notify user-space applications of events. The
365/// object contains an unsigned 64-bit integer counter
366/// that is maintained by the kernel. This counter is initialized
367/// with the value specified in the argument `initval`.
368///
369/// As its return value, `eventfd` returns a new file descriptor that
370/// can be used to refer to the eventfd object.
371///
372/// The following values may be bitwise set in flags to change the
373/// behavior of `eventfd`:
374///
375/// `EFD_NONBLOCK`: Set the file descriptor in non-blocking mode
376/// `EFD_SEMAPHORE`: Provide semaphore-like semantics for reads
377/// from the new file descriptor.
378pub fn eventfd(initval: u64, flags: EventFlags) -> io::Result<FileDescriptor> {
379	let obj = self::eventfd::EventFd::new(initval, flags);
380
381	let fd = block_on(core_scheduler().insert_object(Arc::new(obj)), None)?;
382
383	Ok(fd)
384}
385
386pub(crate) fn get_object(fd: FileDescriptor) -> io::Result<Arc<dyn ObjectInterface>> {
387	block_on(core_scheduler().get_object(fd), None)
388}
389
390pub(crate) fn insert_object(obj: Arc<dyn ObjectInterface>) -> io::Result<FileDescriptor> {
391	block_on(core_scheduler().insert_object(obj), None)
392}
393
394// The dup system call allocates a new file descriptor that refers
395// to the same open file description as the descriptor oldfd. The new
396// file descriptor number is guaranteed to be the lowest-numbered
397// file descriptor that was unused in the calling process.
398pub(crate) fn dup_object(fd: FileDescriptor) -> io::Result<FileDescriptor> {
399	block_on(core_scheduler().dup_object(fd), None)
400}
401
402pub(crate) fn dup_object2(fd1: FileDescriptor, fd2: FileDescriptor) -> io::Result<FileDescriptor> {
403	block_on(core_scheduler().dup_object2(fd1, fd2), None)
404}
405
406pub(crate) fn remove_object(fd: FileDescriptor) -> io::Result<Arc<dyn ObjectInterface>> {
407	block_on(core_scheduler().remove_object(fd), None)
408}
409
410pub(crate) fn isatty(fd: FileDescriptor) -> io::Result<bool> {
411	let obj = get_object(fd)?;
412	block_on(obj.isatty(), None)
413}