Skip to main content

abi_application/
lib.rs

1//! Host implementation of the native application C ABI.
2//!
3//! Core's native ELF handler installs the time manager from its executable
4//! context and discovers the entropy character device at
5//! `/devices/random/source` before launch. The first successful installation of
6//! each service is retained for the system. Native applications can run
7//! without an entropy device, in which case nonempty random fills return
8//! [`Status::Unavailable`].
9//!
10//! A native process is the Core task that runs a native entry on a stackful
11//! coroutine. The `XilaStartup.process` capability gives it its identity, its
12//! environment (the task's own), spawn and wait for children, and exit, with
13//! no table of its own: see [`Process`] and the crate README.
14
15#![no_std]
16#![deny(clippy::unwrap_used, clippy::expect_used)]
17
18extern crate alloc;
19
20mod directory;
21mod file;
22#[cfg(feature = "graphics")]
23mod graphics;
24mod iterator;
25mod metadata;
26#[cfg(feature = "network")]
27mod network;
28mod network_types;
29mod poll;
30mod process;
31mod registry;
32#[cfg(any(
33    all(
34        any(target_arch = "x86_64", target_arch = "aarch64"),
35        target_os = "linux"
36    ),
37    all(
38        any(
39            target_arch = "x86_64",
40            target_arch = "aarch64",
41            target_arch = "arm",
42            target_arch = "riscv32",
43            target_arch = "xtensa"
44        ),
45        target_os = "none"
46    )
47))]
48mod runner;
49mod startup;
50#[cfg(feature = "network")]
51pub use network::*;
52pub use network_types::*;
53mod random;
54mod status;
55mod threads;
56
57#[allow(dead_code)]
58mod guest_bindings {
59    include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
60}
61mod time;
62mod version;
63pub use threads::*;
64
65pub use directory::*;
66pub use file::*;
67#[cfg(feature = "graphics")]
68pub use graphics::xila_graphics_call;
69pub use iterator::*;
70pub use metadata::*;
71pub use poll::*;
72pub use process::*;
73pub use random::*;
74#[cfg(any(
75    all(
76        any(target_arch = "x86_64", target_arch = "aarch64"),
77        target_os = "linux"
78    ),
79    all(
80        any(
81            target_arch = "x86_64",
82            target_arch = "aarch64",
83            target_arch = "arm",
84            target_arch = "riscv32",
85            target_arch = "xtensa"
86        ),
87        target_os = "none"
88    )
89))]
90pub use runner::*;
91pub use startup::*;
92pub use status::*;
93pub use time::*;
94pub use version::*;
95
96mod api;
97mod heap;
98pub use api::{XILA_API, XilaApi};
99pub use heap::*;
100
101#[cfg(any(
102    all(
103        any(target_arch = "x86_64", target_arch = "aarch64"),
104        target_os = "linux"
105    ),
106    all(
107        any(
108            target_arch = "x86_64",
109            target_arch = "aarch64",
110            target_arch = "arm",
111            target_arch = "riscv32",
112            target_arch = "xtensa"
113        ),
114        target_os = "none"
115    )
116))]
117use stackful::{is_in_coroutine, suspend_on, suspend_on_cancellable};
118
119/// End the running coroutine with an exit status. Callers have checked
120/// `is_in_coroutine`.
121#[cfg(any(
122    all(
123        any(target_arch = "x86_64", target_arch = "aarch64"),
124        target_os = "linux"
125    ),
126    all(
127        any(
128            target_arch = "x86_64",
129            target_arch = "aarch64",
130            target_arch = "arm",
131            target_arch = "riscv32",
132            target_arch = "xtensa"
133        ),
134        target_os = "none"
135    )
136))]
137fn exit_coroutine(status: i32) -> ! {
138    // SAFETY: `xila_process_exit` released everything the process owns on this stack.
139    unsafe { stackful::exit(status) }
140}
141
142#[cfg(not(any(
143    all(
144        any(target_arch = "x86_64", target_arch = "aarch64"),
145        target_os = "linux"
146    ),
147    all(
148        any(
149            target_arch = "x86_64",
150            target_arch = "aarch64",
151            target_arch = "arm",
152            target_arch = "riscv32",
153            target_arch = "xtensa"
154        ),
155        target_os = "none"
156    )
157)))]
158use task::block_on as suspend_on;
159
160#[cfg(not(any(
161    all(
162        any(target_arch = "x86_64", target_arch = "aarch64"),
163        target_os = "linux"
164    ),
165    all(
166        any(
167            target_arch = "x86_64",
168            target_arch = "aarch64",
169            target_arch = "arm",
170            target_arch = "riscv32",
171            target_arch = "xtensa"
172        ),
173        target_os = "none"
174    )
175)))]
176use task::block_on as suspend_on_cancellable;
177
178#[cfg(not(any(
179    all(
180        any(target_arch = "x86_64", target_arch = "aarch64"),
181        target_os = "linux"
182    ),
183    all(
184        any(
185            target_arch = "x86_64",
186            target_arch = "aarch64",
187            target_arch = "arm",
188            target_arch = "riscv32",
189            target_arch = "xtensa"
190        ),
191        target_os = "none"
192    )
193)))]
194const fn is_in_coroutine() -> bool {
195    false
196}
197
198/// Targets without stack switching never reach this: they are never in a coroutine.
199#[cfg(not(any(
200    all(
201        any(target_arch = "x86_64", target_arch = "aarch64"),
202        target_os = "linux"
203    ),
204    all(
205        any(
206            target_arch = "x86_64",
207            target_arch = "aarch64",
208            target_arch = "arm",
209            target_arch = "riscv32",
210            target_arch = "xtensa"
211        ),
212        target_os = "none"
213    )
214)))]
215fn exit_coroutine(_: i32) -> ! {
216    unreachable!("exit outside a coroutine")
217}
218
219/// The one shared, non-generic `suspend_on` instantiation for unit-output futures.
220/// Sleep and random fill both go through it so the generic code exists once.
221#[inline(never)]
222fn suspend_dynamic(future: core::pin::Pin<&mut dyn core::future::Future<Output = ()>>) {
223    suspend_on(future)
224}
225
226/// Give every other ready task on the executor one turn, then resume.
227///
228/// Shared by `xila_thread_yield` and fallback-only polls. It reuses the non-generic
229/// [`suspend_dynamic`] so a yield adds no new copy of the suspension machinery.
230#[inline(never)]
231fn yield_once() {
232    let mut yielded = false;
233    suspend_dynamic(core::pin::pin!(core::future::poll_fn(|cx| {
234        if core::mem::replace(&mut yielded, true) {
235            core::task::Poll::Ready(())
236        } else {
237            cx.waker().wake_by_ref();
238            core::task::Poll::Pending
239        }
240    })));
241}
242
243#[cfg(test)]
244#[allow(clippy::unwrap_used)] // Fixture setup may report errors through Debug.
245mod tests {
246    extern crate std;
247    use super::*;
248    use alloc::{boxed::Box, vec, vec::Vec};
249    use core::ptr::{self, NonNull};
250    use file_system::{AccessFlags, CreateFlags, StateFlags};
251    testing::instantiate_global_allocator!();
252    #[test]
253    fn generated_header_and_sdk() {
254        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
255        let out = std::path::Path::new(env!("OUT_DIR"));
256        for (generated, committed) in [
257            ("application.h", "include/xila/application.h"),
258            ("stubs.h", "sdk/stubs.h"),
259            ("stubs.c", "sdk/stubs.c"),
260            // This snapshot pins both the symbol names and the slot order.
261            ("slots.tsv", "sdk/slots.tsv"),
262            ("bindings.rs", "sdk/rust/xila-sys/src/bindings.rs"),
263        ] {
264            let generated = std::fs::read(out.join(generated)).unwrap();
265            let committed = root.join(committed);
266            if std::env::var_os("XILA_UPDATE_HEADER").is_some() {
267                std::fs::write(&committed, &generated).unwrap();
268            }
269            assert!(
270                std::fs::read(&committed).unwrap() == generated,
271                "{} is stale; regenerate with XILA_UPDATE_HEADER=1",
272                committed.display()
273            );
274        }
275    }
276
277    #[cfg(not(feature = "graphics"))]
278    #[test]
279    fn disabled_graphics_keeps_its_slot() {
280        assert_eq!(
281            unsafe { (XILA_API.graphics_call)(ptr::null(), 0, ptr::null(), 0, ptr::null_mut()) },
282            Status::Unsupported
283        );
284    }
285
286    #[cfg(not(feature = "network"))]
287    #[test]
288    fn disabled_network_keeps_its_slots() {
289        assert_eq!(
290            unsafe { (XILA_API.network_close)(ptr::null_mut()) },
291            Status::Unsupported
292        );
293        assert_eq!(XILA_API.size as usize, core::mem::size_of::<XilaApi>());
294    }
295    #[test]
296    fn validation() {
297        for path in [
298            "/absolute",
299            "..",
300            "a/../b",
301            "x\0y",
302            "",
303            ".",
304            "./",
305            "./.",
306            "//",
307        ] {
308            assert_eq!(canonical("/root", path, true), Err(Status::InvalidArgument));
309        }
310        // Without `entry`, the capability itself may be named (directory open, statistics).
311        for path in ["", ".", "./"] {
312            assert_eq!(canonical("/root", path, false).unwrap().as_str(), "/root");
313        }
314        assert_eq!(
315            canonical("/root", "./a//./b/", true).unwrap().as_str(),
316            "/root/a/b"
317        );
318        assert_eq!(validate_rights(4), Err(Status::InvalidArgument));
319        for flags in [0, 8, 9, 128, u32::MAX, 1 | 16, 1 | 32] {
320            assert_eq!(open_flags(flags, 3), Err(Status::InvalidArgument));
321        }
322        assert_eq!(open_flags(1, 2), Err(Status::PermissionDenied));
323        for flags in [2, 5, 2 | 16, 2 | 32] {
324            assert_eq!(open_flags(flags, 1), Err(Status::PermissionDenied));
325        }
326        let flags = open_flags(127, 3).unwrap();
327        assert_eq!(flags.get_access(), AccessFlags::READ_WRITE);
328        assert_eq!(flags.get_create(), CreateFlags::all());
329        assert_eq!(
330            flags.get_state(),
331            StateFlags::Append | StateFlags::NonBlocking
332        );
333        let flags = open_flags(XILA_OPEN_READ, 1).unwrap();
334        assert_eq!(flags.get_access(), AccessFlags::Read);
335        assert_eq!(flags.get_create(), CreateFlags::empty());
336        assert_eq!(flags.get_state(), StateFlags::empty());
337        unsafe {
338            assert_eq!(
339                path_input([255u8].as_ptr().cast(), 1),
340                Err(Status::InvalidArgument)
341            );
342        }
343    }
344    #[test]
345    fn filesystem_validation() {
346        unsafe {
347            let mut stats = Statistics {
348                size: 72,
349                kind: 99,
350                ..Statistics::default()
351            };
352            assert_eq!(
353                xila_file_get_statistics(ptr::null_mut(), &mut stats),
354                Status::InvalidArgument
355            );
356            assert_eq!(stats.kind, 99);
357            assert_eq!(
358                xila_file_set_size(ptr::null_mut(), 0),
359                Status::InvalidArgument
360            );
361            assert_eq!(
362                xila_directory_get_statistics(ptr::null(), c"".as_ptr(), 0, 0, &mut stats),
363                Status::InvalidArgument
364            );
365            assert_eq!(
366                xila_directory_create(ptr::null(), c"a".as_ptr(), 1),
367                Status::InvalidArgument
368            );
369            assert_eq!(
370                xila_directory_remove(ptr::null(), c"a".as_ptr(), 1, 0),
371                Status::InvalidArgument
372            );
373            assert_eq!(
374                xila_directory_rename(ptr::null(), c"a".as_ptr(), 1, ptr::null(), c"b".as_ptr(), 1),
375                Status::InvalidArgument
376            );
377            assert_eq!(
378                xila_directory_iterator_open(ptr::null(), c"".as_ptr(), 0, ptr::null_mut()),
379                Status::InvalidArgument
380            );
381            assert_eq!(
382                xila_directory_iterator_next(
383                    ptr::null_mut(),
384                    ptr::null_mut(),
385                    0,
386                    ptr::null_mut(),
387                    ptr::null_mut()
388                ),
389                Status::InvalidArgument
390            );
391            assert_eq!(
392                xila_directory_iterator_rewind(ptr::null_mut()),
393                Status::InvalidArgument
394            );
395            assert_eq!(xila_directory_iterator_close(ptr::null_mut()), Status::Ok);
396            assert_eq!(crate::metadata::validate_output(&mut stats), Ok(()));
397            stats.size = 71;
398            assert_eq!(
399                crate::metadata::validate_output(&mut stats),
400                Err(Status::InvalidArgument)
401            );
402        }
403        assert_eq!(core::mem::size_of::<Statistics>(), 72);
404        assert_eq!(core::mem::offset_of!(Statistics, file_size), 24);
405        assert_eq!(core::mem::offset_of!(Statistics, access_nanoseconds), 48);
406        std::println!(
407            "File={} Directory={} DirectoryIterator={} Statistics={}",
408            core::mem::size_of::<File>(),
409            core::mem::size_of::<Directory>(),
410            core::mem::size_of::<DirectoryIterator>(),
411            core::mem::size_of::<Statistics>()
412        );
413    }
414    #[test]
415    fn kind_values_are_explicit() {
416        use file_system::Kind;
417        for (kind, value) in [
418            (Kind::File, XILA_KIND_FILE),
419            (Kind::Directory, XILA_KIND_DIRECTORY),
420            (Kind::BlockDevice, XILA_KIND_BLOCK_DEVICE),
421            (Kind::CharacterDevice, XILA_KIND_CHARACTER_DEVICE),
422            (Kind::Pipe, XILA_KIND_PIPE),
423            (Kind::Socket, XILA_KIND_SOCKET),
424            (Kind::SymbolicLink, XILA_KIND_SYMLINK),
425        ] {
426            assert_eq!(kind_value(kind), value);
427        }
428    }
429    #[test]
430    fn resolver_errors_report_the_status_of_their_kind() {
431        use file_system::io_error::ResolveError;
432        assert_eq!(
433            Status::from(ResolveError::NoAnswer),
434            Status::NameNotResolved
435        );
436        assert_eq!(Status::from(ResolveError::Failure), Status::ResolverFailure);
437        assert_eq!(
438            Status::from(ResolveError::InvalidName),
439            Status::InvalidDnsName
440        );
441        assert_eq!(Status::from(ResolveError::NoInterface), Status::Unavailable);
442        for &error in ResolveError::ALL {
443            assert_eq!(Status::from(error) as u32, u32::from(error.id()));
444            assert_eq!(Status::from(error), Status::from(error.kind()));
445        }
446    }
447
448    #[test]
449    fn status_and_kind_match_frozen_wire_table() {
450        use file_system::IoErrorKind as Kind;
451        let rows = [
452            (Kind::InvalidArgument, Status::InvalidArgument, 0x0101),
453            (Kind::InvalidData, Status::InvalidData, 0x0102),
454            (Kind::PermissionDenied, Status::PermissionDenied, 0x0103),
455            (
456                Kind::OperationNotPermitted,
457                Status::OperationNotPermitted,
458                0x0104,
459            ),
460            (Kind::InputOutput, Status::InputOutput, 0x0105),
461            (Kind::OutOfMemory, Status::OutOfMemory, 0x0106),
462            (Kind::WouldBlock, Status::WouldBlock, 0x0107),
463            (Kind::ResourceBusy, Status::ResourceBusy, 0x0108),
464            (Kind::Interrupted, Status::Interrupted, 0x0109),
465            (Kind::TimedOut, Status::TimedOut, 0x010A),
466            (Kind::Unsupported, Status::Unsupported, 0x010B),
467            (Kind::Overflow, Status::Overflow, 0x010C),
468            (Kind::WriteZero, Status::WriteZero, 0x010D),
469            (Kind::NoBuffers, Status::NoBuffers, 0x010E),
470            (Kind::NotFound, Status::NotFound, 0x010F),
471            (Kind::AlreadyExists, Status::AlreadyExists, 0x0110),
472            (Kind::InvalidFlags, Status::InvalidFlags, 0x0111),
473            (Kind::InvalidState, Status::InvalidState, 0x0112),
474            (Kind::NotImplemented, Status::NotImplemented, 0x0113),
475            (Kind::ExecFormat, Status::ExecFormat, 0x0114),
476            (Kind::NoChild, Status::NoChild, 0x0115),
477            (
478                Kind::ArgumentListTooLong,
479                Status::ArgumentListTooLong,
480                0x0116,
481            ),
482            (Kind::Deadlock, Status::Deadlock, 0x0117),
483            (Kind::BadDescriptor, Status::BadDescriptor, 0x0201),
484            (Kind::InvalidPath, Status::InvalidPath, 0x0202),
485            (
486                Kind::MissingPathComponent,
487                Status::MissingPathComponent,
488                0x0203,
489            ),
490            (Kind::MissingFinalEntry, Status::MissingFinalEntry, 0x0204),
491            (Kind::NameTooLong, Status::NameTooLong, 0x0205),
492            (Kind::SymlinkLoop, Status::SymlinkLoop, 0x0206),
493            (Kind::NotADirectory, Status::NotADirectory, 0x0207),
494            (Kind::IsADirectory, Status::IsADirectory, 0x0208),
495            (Kind::DirectoryNotEmpty, Status::DirectoryNotEmpty, 0x0209),
496            (Kind::NoSpace, Status::NoSpace, 0x020A),
497            (Kind::FileTooLarge, Status::FileTooLarge, 0x020B),
498            (Kind::ProcessFileLimit, Status::ProcessFileLimit, 0x020C),
499            (Kind::SystemFileLimit, Status::SystemFileLimit, 0x020D),
500            (Kind::CrossDevice, Status::CrossDevice, 0x020E),
501            (Kind::PathEscapesRoot, Status::PathEscapesRoot, 0x020F),
502            (Kind::CorruptData, Status::CorruptData, 0x0210),
503            (Kind::MissingAttribute, Status::MissingAttribute, 0x0211),
504            (Kind::StaleHandle, Status::StaleHandle, 0x0212),
505            (Kind::ReadOnlyFileSystem, Status::ReadOnlyFileSystem, 0x0213),
506            (Kind::InvalidSeek, Status::InvalidSeek, 0x0214),
507            (Kind::DeviceUnavailable, Status::Unavailable, 0x0301),
508            (Kind::NoSuchTask, Status::NoSuchTask, 0x0302),
509            (
510                Kind::InappropriateIoControl,
511                Status::InappropriateIoControl,
512                0x0303,
513            ),
514            (Kind::ConnectionRefused, Status::ConnectionRefused, 0x0401),
515            (Kind::ConnectionReset, Status::ConnectionReset, 0x0402),
516            (Kind::ConnectionAborted, Status::ConnectionAborted, 0x0403),
517            (Kind::NotConnected, Status::NotConnected, 0x0404),
518            (Kind::AlreadyConnected, Status::AlreadyConnected, 0x0405),
519            (Kind::AddressInUse, Status::AddressInUse, 0x0406),
520            (
521                Kind::AddressNotAvailable,
522                Status::AddressNotAvailable,
523                0x0407,
524            ),
525            (
526                Kind::DestinationRequired,
527                Status::DestinationRequired,
528                0x0408,
529            ),
530            (Kind::HostUnreachable, Status::HostUnreachable, 0x0409),
531            (Kind::NetworkUnreachable, Status::NetworkUnreachable, 0x040A),
532            (Kind::NetworkDown, Status::NetworkDown, 0x040B),
533            (Kind::BrokenPipe, Status::BrokenPipe, 0x040C),
534            (Kind::MessageTooLarge, Status::MessageTooLarge, 0x040D),
535            (Kind::DatagramTruncated, Status::DatagramTruncated, 0x040E),
536            (
537                Kind::SocketOperationUnsupported,
538                Status::SocketOperationUnsupported,
539                0x040F,
540            ),
541            (
542                Kind::ProtocolUnsupported,
543                Status::ProtocolUnsupported,
544                0x0410,
545            ),
546            (
547                Kind::AddressFamilyUnsupported,
548                Status::AddressFamilyUnsupported,
549                0x0411,
550            ),
551            (Kind::InProgress, Status::InProgress, 0x0412),
552            (Kind::AlreadyInProgress, Status::AlreadyInProgress, 0x0413),
553            (Kind::ProtocolError, Status::ProtocolError, 0x0414),
554            (Kind::NotASocket, Status::NotASocket, 0x0415),
555            (Kind::InvalidDnsName, Status::InvalidDnsName, 0x0501),
556            (
557                Kind::UnsupportedDnsQuery,
558                Status::UnsupportedDnsQuery,
559                0x0502,
560            ),
561            (Kind::NameNotResolved, Status::NameNotResolved, 0x0503),
562            (
563                Kind::ResolverTemporaryFailure,
564                Status::ResolverTemporaryFailure,
565                0x0504,
566            ),
567            (Kind::ResolverFailure, Status::ResolverFailure, 0x0505),
568        ];
569        assert_eq!(rows.len(), Kind::ALL.len());
570        for (kind, status, id) in rows {
571            assert_eq!(Status::from(kind), status);
572            assert_eq!(status.io_kind(), Some(kind));
573            assert_eq!(status as u32, id);
574        }
575        for (status, id) in [
576            (Status::Ok, 0),
577            (Status::End, 0x0701),
578            (Status::BufferTooSmall, 0x0702),
579        ] {
580            assert_eq!(status.io_kind(), None);
581            assert_eq!(status as u32, id);
582        }
583    }
584    #[test]
585    fn nulls_and_uninitialized_time() {
586        unsafe {
587            assert_eq!(
588                xila_file_open(ptr::null(), ptr::null(), 0, 1, ptr::null_mut()),
589                Status::InvalidArgument
590            );
591            assert_eq!(
592                xila_directory_open(ptr::null(), ptr::null(), 0, 1, ptr::null_mut()),
593                Status::InvalidArgument
594            );
595            assert_eq!(
596                xila_file_read(ptr::null_mut(), ptr::null_mut(), 0, ptr::null_mut()),
597                Status::InvalidArgument
598            );
599            assert_eq!(
600                xila_file_write(ptr::null_mut(), ptr::null(), 0, ptr::null_mut()),
601                Status::InvalidArgument
602            );
603            assert_eq!(
604                xila_file_seek(ptr::null_mut(), 0, 0, ptr::null_mut()),
605                Status::InvalidArgument
606            );
607            assert_eq!(xila_file_flush(ptr::null_mut()), Status::InvalidArgument);
608            assert_eq!(xila_file_close(ptr::null_mut()), Status::Ok);
609            xila_directory_close(ptr::null_mut());
610            let mut mono = 123;
611            let mut real = 456;
612            assert_eq!(xila_time_monotonic(&mut mono), Status::Unavailable);
613            assert_eq!(xila_time_realtime(&mut real), Status::Unavailable);
614            assert_eq!((mono, real), (123, 456));
615            assert_eq!(
616                xila_time_monotonic(ptr::null_mut()),
617                Status::InvalidArgument
618            );
619            assert_eq!(xila_time_realtime(ptr::null_mut()), Status::InvalidArgument);
620            // No clock is installed: resolution is unavailable, bad arguments still
621            // fail first, and the output is untouched.
622            let mut resolution = 789;
623            for clock in [XILA_CLOCK_MONOTONIC, XILA_CLOCK_REALTIME] {
624                assert_eq!(
625                    xila_time_resolution(clock, &mut resolution),
626                    Status::Unavailable
627                );
628                assert_eq!(
629                    xila_time_resolution(clock, ptr::null_mut()),
630                    Status::InvalidArgument
631                );
632            }
633            assert_eq!(
634                xila_time_resolution(2, &mut resolution),
635                Status::InvalidArgument
636            );
637            assert_eq!(resolution, 789);
638            // Sleeping needs the executor's timer, not the manager.
639            assert_eq!(xila_time_sleep(0), Status::Ok);
640            let clock = &::time::EmbassyClock;
641            let start = ::time::MonotonicClock::now(clock);
642            assert_eq!(xila_time_sleep(2_000_000), Status::Ok);
643            let elapsed = ::time::MonotonicClock::now(clock) - start;
644            assert!(elapsed >= core::time::Duration::from_millis(2));
645            // No entropy source is installed: only an empty fill can succeed.
646            let mut bytes = [0x5A_u8; 4];
647            assert_eq!(xila_random_fill(ptr::null_mut(), 0), Status::Ok);
648            assert_eq!(xila_random_fill(bytes.as_mut_ptr().cast(), 0), Status::Ok);
649            assert_eq!(
650                xila_random_fill(ptr::null_mut(), 1),
651                Status::InvalidArgument
652            );
653            assert_eq!(
654                xila_random_fill(bytes.as_mut_ptr().cast(), isize::MAX as usize + 1),
655                Status::InvalidArgument
656            );
657            assert_eq!(
658                xila_random_fill(bytes.as_mut_ptr().cast(), bytes.len()),
659                Status::Unavailable
660            );
661            assert_eq!(bytes, [0x5A; 4]);
662        }
663        std::println!(
664            "File={} Directory={}",
665            core::mem::size_of::<File>(),
666            core::mem::size_of::<Directory>()
667        );
668    }
669
670    /// A host that never starts a child: process identity and environment need no more.
671    struct NoSpawnHost(&'static task::Manager);
672    impl ProcessHost for NoSpawnHost {
673        fn task_manager(&self) -> &'static task::Manager {
674            self.0
675        }
676        fn virtual_file_system(&self) -> &'static virtual_file_system::VirtualFileSystem {
677            unreachable!("no home directory is granted")
678        }
679        fn spawn(&'static self, _: SpawnRequest) -> SpawnFuture {
680            Box::pin(async { Err(Status::Unsupported) })
681        }
682    }
683
684    std::thread_local! {
685        static EXPECTED: core::cell::Cell<(u32, u32)> = const { core::cell::Cell::new((0, 0)) };
686    }
687
688    macro_rules! check {
689        ($condition:expr) => {
690            if !$condition {
691                return line!() as i32;
692            }
693        };
694    }
695
696    /// Runs on a plain task, not a coroutine: calls that cannot suspend must say so.
697    unsafe extern "C" fn probe_entry(startup: *const XilaStartup) -> i32 {
698        let startup = unsafe { &*startup };
699        let api = unsafe { &*startup.api };
700        let process = startup.process;
701        check!(!process.is_null() && startup.home.is_null());
702        let (mut id, mut parent) = (u32::MAX, u32::MAX);
703        let mut length = 99;
704        let mut buffer = [b'#'; 8];
705        unsafe {
706            check!((api.process_id)(process, &mut id) == Status::Ok);
707            check!((api.process_parent_id)(process, &mut parent) == Status::Ok);
708            check!((id, parent) == EXPECTED.get());
709            // Only a process running on its own coroutine can exit.
710            check!((api.process_exit)(process, 3) == Status::Unsupported);
711            check!((api.process_exit)(ptr::null(), 3) == Status::InvalidArgument);
712            // A missing variable leaves the length untouched.
713            check!(
714                (api.env_get)(
715                    process,
716                    c"K".as_ptr(),
717                    1,
718                    buffer.as_mut_ptr().cast(),
719                    8,
720                    &mut length
721                ) == Status::NotFound
722            );
723            check!(length == 99);
724            check!((api.env_set)(process, c"K".as_ptr(), 1, c"value".as_ptr(), 5) == Status::Ok);
725            check!(
726                (api.env_get)(
727                    process,
728                    c"K".as_ptr(),
729                    1,
730                    buffer.as_mut_ptr().cast(),
731                    8,
732                    &mut length
733                ) == Status::Ok
734            );
735            check!(length == 5 && &buffer == b"value###");
736            check!(
737                (api.env_get)(
738                    process,
739                    c"K".as_ptr(),
740                    1,
741                    buffer.as_mut_ptr().cast(),
742                    4,
743                    &mut length
744                ) == Status::BufferTooSmall
745            );
746            check!(length == 5 && &buffer == b"value###");
747            // Enumeration uses byte counts and does not modify a short buffer.
748            check!(
749                (api.env_entry)(process, 0, ptr::null_mut(), 0, &mut length)
750                    == Status::BufferTooSmall
751            );
752            check!(length == 7);
753            check!(
754                (api.env_entry)(process, 0, buffer.as_mut_ptr().cast(), 6, &mut length)
755                    == Status::BufferTooSmall
756            );
757            check!(length == 7 && &buffer == b"value###");
758            check!(
759                (api.env_entry)(process, 0, buffer.as_mut_ptr().cast(), 7, &mut length)
760                    == Status::Ok
761            );
762            check!(length == 7 && &buffer == b"K=value#");
763
764            check!((api.env_set)(process, c"AB".as_ptr(), 2, c"".as_ptr(), 0) == Status::Ok);
765            check!(
766                (api.env_entry)(process, 1, buffer.as_mut_ptr().cast(), 8, &mut length)
767                    == Status::Ok
768            );
769            check!(length == 3 && &buffer[..3] == b"AB=");
770            check!(
771                (api.env_entry)(process, 2, ptr::null_mut(), 0, &mut length) == Status::NotFound
772            );
773            check!(length == 3 && &buffer[..3] == b"AB=");
774            check!(
775                (api.env_entry)(process, 0, ptr::null_mut(), 1, &mut length)
776                    == Status::InvalidArgument
777            );
778            check!(
779                (api.env_entry)(process, 0, ptr::null_mut(), 0, ptr::null_mut())
780                    == Status::InvalidArgument
781            );
782            check!(
783                (api.env_entry)(ptr::null(), 0, ptr::null_mut(), 0, &mut length)
784                    == Status::InvalidArgument
785            );
786            check!((api.env_remove)(process, c"AB".as_ptr(), 2) == Status::Ok);
787            // Invalid names and values.
788            for name in [&b""[..], b"A=B", b"A\0B", b"\xff"] {
789                check!(
790                    (api.env_set)(process, name.as_ptr().cast(), name.len(), c"v".as_ptr(), 1)
791                        == Status::InvalidArgument
792                );
793                check!(
794                    (api.env_get)(
795                        process,
796                        name.as_ptr().cast(),
797                        name.len(),
798                        ptr::null_mut(),
799                        0,
800                        &mut length
801                    ) == Status::InvalidArgument
802                );
803                check!(
804                    (api.env_remove)(process, name.as_ptr().cast(), name.len())
805                        == Status::InvalidArgument
806                );
807            }
808            check!(
809                (api.env_set)(process, c"K".as_ptr(), 1, c"a".as_ptr(), usize::MAX)
810                    == Status::InvalidArgument
811            );
812            check!(
813                (api.env_set)(process, c"K".as_ptr(), 1, ptr::null(), 1) == Status::InvalidArgument
814            );
815            check!((api.env_set)(process, c"K".as_ptr(), 1, ptr::null(), 0) == Status::Ok);
816            check!(
817                (api.env_get)(process, c"K".as_ptr(), 1, ptr::null_mut(), 0, &mut length)
818                    == Status::Ok
819            );
820            check!(length == 0);
821            check!((api.env_remove)(process, c"K".as_ptr(), 1) == Status::Ok);
822            check!((api.env_remove)(process, c"K".as_ptr(), 1) == Status::Ok);
823            check!(
824                (api.env_entry)(process, 0, ptr::null_mut(), 0, &mut length) == Status::NotFound
825            );
826            // Wait needs a child this process spawned.
827            check!(
828                (api.process_wait)(process, ptr::null_mut(), 0, ptr::null_mut())
829                    == Status::InvalidArgument
830            );
831            check!((api.process_child_close)(ptr::null_mut()) == Status::Ok);
832        }
833        0
834    }
835
836    unsafe extern "C" fn quiet_entry(startup: *const XilaStartup) -> i32 {
837        let startup = unsafe { &*startup };
838        let api = unsafe { &*startup.api };
839        let process = startup.process;
840        if !process.is_null() {
841            let mut id = 0;
842            let mut length = 0;
843            unsafe {
844                check!((api.process_id)(process, &mut id) == Status::Ok);
845                check!((api.process_parent_id)(process, &mut id) == Status::Ok);
846                check!(
847                    (api.env_get)(
848                        process,
849                        c"NAME".as_ptr(),
850                        4,
851                        ptr::null_mut(),
852                        0,
853                        &mut length
854                    ) == Status::NotFound
855                );
856                check!((api.env_remove)(process, c"NAME".as_ptr(), 4) == Status::Ok);
857            }
858        }
859        0
860    }
861
862    #[task::test]
863    async fn process_identity_and_environment_without_a_coroutine() {
864        let tasks = task::test_manager();
865        let task = tasks.get_current_task_identifier().await;
866        let host: &'static NoSpawnHost = Box::leak(Box::new(NoSpawnHost(tasks)));
867        EXPECTED.set((
868            identifier(task),
869            identifier(tasks.get_parent(task).await.unwrap()),
870        ));
871        let mut heap = Heap::new();
872        let mut state = HostState::new(Vec::new(), None, None, None);
873        let status = unsafe {
874            enter(
875                NonNull::from(&mut state),
876                probe_entry,
877                NonNull::from(&mut heap),
878                Some((host, task)),
879            )
880        };
881        assert_eq!(status, 0, "line of the failed check");
882        // A task that left no variables behind.
883        assert!(
884            tasks
885                .get_environment_variables(task)
886                .await
887                .unwrap()
888                .is_empty()
889        );
890    }
891
892    /// An empty environment and the process capability itself take no allocation:
893    /// the capability lives in the caller's host state, and the environment is the
894    /// task's own, empty until something sets a variable.
895    #[task::test]
896    async fn process_capability_and_empty_environment_allocate_nothing() {
897        let tasks = task::test_manager();
898        let task = tasks.get_current_task_identifier().await;
899        let host: &'static NoSpawnHost = Box::leak(Box::new(NoSpawnHost(tasks)));
900        let mut heap = Heap::new();
901        let mut state = HostState::new(Vec::new(), None, None, None);
902        let before = testing::MemoryManager::thread_allocations();
903        let status_with = unsafe {
904            enter(
905                NonNull::from(&mut state),
906                quiet_entry,
907                NonNull::from(&mut heap),
908                Some((host, task)),
909            )
910        };
911        let with = testing::MemoryManager::thread_allocations().since(before);
912        let before = testing::MemoryManager::thread_allocations();
913        let status_without = unsafe {
914            enter(
915                NonNull::from(&mut state),
916                quiet_entry,
917                NonNull::from(&mut heap),
918                None,
919            )
920        };
921        let without = testing::MemoryManager::thread_allocations().since(before);
922        assert_eq!((status_with, status_without), (0, 0));
923        assert_eq!(with.allocations(), 0);
924        assert_eq!(without.allocations(), 0);
925    }
926
927    unsafe extern "C" fn return_entry(startup: *const XilaStartup) -> i32 {
928        let startup = unsafe { &*startup };
929        let api = unsafe { &*startup.api };
930        check!(startup.argument_count == 1);
931        unsafe {
932            check!(
933                (api.env_set)(startup.process, c"NAME".as_ptr(), 4, c"v".as_ptr(), 1) == Status::Ok
934            )
935        };
936        4
937    }
938
939    unsafe extern "C" fn exit_entry(startup: *const XilaStartup) -> i32 {
940        let startup = unsafe { &*startup };
941        let api = unsafe { &*startup.api };
942        check!(startup.argument_count == 1);
943        unsafe {
944            check!(
945                (api.env_set)(startup.process, c"NAME".as_ptr(), 4, c"v".as_ptr(), 1) == Status::Ok
946            );
947            let _ = (api.process_exit)(startup.process, 5);
948        }
949        1 // Exit returned.
950    }
951
952    /// Leaving through `xila_process_exit` frees exactly what returning does: the
953    /// startup strings, the explicit environment and the coroutine stack.
954    #[cfg(all(
955        target_os = "linux",
956        any(target_arch = "x86_64", target_arch = "aarch64")
957    ))]
958    #[task::test]
959    async fn exit_and_return_release_the_same_memory() {
960        let tasks = task::test_manager();
961        let task = tasks.get_current_task_identifier().await;
962        let host: &'static NoSpawnHost = Box::leak(Box::new(NoSpawnHost(tasks)));
963        let run = async |entry: unsafe extern "C" fn(*const XilaStartup) -> i32| {
964            let before = testing::MemoryManager::thread_allocations();
965            let heap = Box::into_raw(Box::new(Heap::new()));
966            let state = Box::into_raw(Box::new(HostState::new(
967                vec!["argument".into()],
968                None,
969                None,
970                None,
971            )));
972            let launch = ProcessLaunch {
973                host,
974                environment: Some(vec![
975                    task::EnvironmentVariable::new("A", "1"),
976                    task::EnvironmentVariable::new("B", "2"),
977                ]),
978                home: None,
979                network: 0,
980            };
981            // SAFETY: the bounded entries fit the stack and never unwind, and the closure
982            // moves everything it owns into `run`.
983            let (handle, _) = unsafe {
984                stackful::spawn_with_result(
985                    tasks,
986                    task,
987                    "process",
988                    stackful::Stack::new(32 * 1024),
989                    move || {
990                        launch.run(
991                            NonNull::new_unchecked(state),
992                            entry,
993                            NonNull::new_unchecked(heap),
994                        )
995                    },
996                    |status| status as isize,
997                )
998                .await
999                .unwrap()
1000            };
1001            let status = handle.join().await;
1002            task::yield_now().await;
1003            drop(unsafe { Box::from_raw(state) });
1004            drop(unsafe { Box::from_raw(heap) });
1005            let delta = testing::MemoryManager::thread_allocations().since(before);
1006            (status, delta.net_bytes())
1007        };
1008        // The first runs grow the task manager's retained pool.
1009        run(return_entry).await;
1010        run(exit_entry).await;
1011        let (returned, returned_bytes) = run(return_entry).await;
1012        let (exited, exited_bytes) = run(exit_entry).await;
1013        assert_eq!((returned, exited), (4, 5));
1014        assert_eq!(returned_bytes, 0);
1015        assert_eq!(exited_bytes, returned_bytes);
1016    }
1017
1018    /// A process cancelled while it holds graphics objects must not leave the identity file
1019    /// pickers act with (the task of its last call) behind: a task identifier is reused, and
1020    /// whoever inherits it would act as the dead process.
1021    #[cfg(feature = "graphics")]
1022    #[task::test]
1023    async fn release_drops_the_graphics_state_with_its_task_identity() {
1024        let tasks = task::test_manager();
1025        let task = tasks.get_current_task_identifier().await;
1026        let users = Box::leak(Box::new(users::Manager::new()));
1027        let time = Box::leak(Box::new(
1028            ::time::Manager::new(&testing::TimeDevice).unwrap(),
1029        ));
1030        let vfs = Box::leak(Box::new(virtual_file_system::VirtualFileSystem::new(
1031            tasks,
1032            users,
1033            time,
1034            memory_file_system::FileSystem::new(),
1035        )));
1036        let mut state = HostState::new(Vec::new(), None, None, None);
1037        state.resources.graphics = Some(Box::new(::graphics::call::State::with_file_system(
1038            None, vfs, task,
1039        )));
1040        assert_eq!(
1041            state
1042                .resources
1043                .graphics
1044                .as_ref()
1045                .and_then(|graphics| graphics.file_system_task()),
1046            Some(task)
1047        );
1048        // SAFETY: nothing runs the program, and the state is where it ran.
1049        unsafe { HostState::release(NonNull::from(&mut state)) };
1050        assert!(state.resources.graphics.is_none(), "the identity is gone");
1051        // Releasing again does nothing.
1052        unsafe { HostState::release(NonNull::from(&mut state)) };
1053    }
1054
1055    std::thread_local! {
1056        /// Start and length of the host state under test.
1057        static HOST_STATE: core::cell::Cell<(usize, usize)> = const { core::cell::Cell::new((0, 0)) };
1058    }
1059
1060    /// Whether `address` lies in the host state, not on the calling coroutine's stack.
1061    fn in_host_state(address: usize) -> bool {
1062        let (start, length) = HOST_STATE.get();
1063        (start..start + length).contains(&address)
1064    }
1065
1066    unsafe fn startup_in_host_state(startup: *const XilaStartup) -> i32 {
1067        check!(in_host_state(startup as usize));
1068        let startup = unsafe { &*startup };
1069        check!(in_host_state(startup.process as usize));
1070        // The resources `xila_process_exit` empties are in the state, behind the capability.
1071        let resources = unsafe { (*startup.process).resources };
1072        check!(in_host_state(resources as usize));
1073        check!(in_host_state(ptr::from_ref(&startup.program_name) as usize));
1074        let name = unsafe { &(*resources).program_name };
1075        check!(in_host_state(ptr::from_ref(name) as usize));
1076        check!(name == "process");
1077        check!(startup.program_name.data == name.as_ptr().cast());
1078        check!(startup.program_name.length == name.len());
1079        0
1080    }
1081
1082    unsafe extern "C" fn located_return_entry(startup: *const XilaStartup) -> i32 {
1083        let failed = unsafe { startup_in_host_state(startup) };
1084        if failed != 0 { failed } else { 4 }
1085    }
1086
1087    unsafe extern "C" fn located_exit_entry(startup: *const XilaStartup) -> i32 {
1088        let failed = unsafe { startup_in_host_state(startup) };
1089        if failed != 0 {
1090            return failed;
1091        }
1092        let startup = unsafe { &*startup };
1093        let api = unsafe { &*startup.api };
1094        let _ = unsafe { (api.process_exit)(startup.process, 5) };
1095        1 // Exit returned.
1096    }
1097
1098    /// The startup block, the process capability and the resources it empties on exit
1099    /// belong to the host state the loader owns, whichever way the entry ends, so nothing
1100    /// the exit path or the SDK reads is stored in the coroutine's frames (#766). The
1101    /// standard streams, which need a file system to open, are checked in the C tests
1102    /// crate.
1103    #[cfg(all(
1104        target_os = "linux",
1105        any(target_arch = "x86_64", target_arch = "aarch64")
1106    ))]
1107    #[task::test]
1108    async fn startup_block_and_capability_stay_off_the_coroutine_stack() {
1109        let tasks = task::test_manager();
1110        let task = tasks.get_current_task_identifier().await;
1111        let host: &'static NoSpawnHost = Box::leak(Box::new(NoSpawnHost(tasks)));
1112        for (entry, expected) in [
1113            (
1114                located_return_entry as unsafe extern "C" fn(*const XilaStartup) -> i32,
1115                4,
1116            ),
1117            (located_exit_entry, 5),
1118        ] {
1119            let heap = Box::into_raw(Box::new(Heap::new()));
1120            let state = Box::into_raw(Box::new(HostState::new(Vec::new(), None, None, None)));
1121            HOST_STATE.set((state as usize, core::mem::size_of::<HostState>()));
1122            let launch = ProcessLaunch {
1123                host,
1124                environment: None,
1125                home: None,
1126                network: 0,
1127            };
1128            // SAFETY: the bounded entries fit the stack and never unwind, and the closure
1129            // holds only pointers to the state and heap, which outlive the run.
1130            let (handle, _) = unsafe {
1131                stackful::spawn_with_result(
1132                    tasks,
1133                    task,
1134                    "process",
1135                    stackful::Stack::new(32 * 1024),
1136                    move || {
1137                        launch.run(
1138                            NonNull::new_unchecked(state),
1139                            entry,
1140                            NonNull::new_unchecked(heap),
1141                        )
1142                    },
1143                    |status| status as isize,
1144                )
1145                .await
1146                .unwrap()
1147            };
1148            assert_eq!(handle.join().await, expected, "line of the failed check");
1149            task::yield_now().await;
1150            drop(unsafe { Box::from_raw(state) });
1151            drop(unsafe { Box::from_raw(heap) });
1152        }
1153    }
1154}